Merge inbound to m-c
authorWes Kocher <wkocher@mozilla.com>
Wed, 31 Jul 2013 17:31:45 -0700
changeset 153099 05d3797276d3d8c7d10ddc66e95c99352c2e3cc9
parent 153058 fd03bb4d1e48837adf025ae68e2ae09074a086d7 (current diff)
parent 153098 60d17705f2fc0b682ff510077f937d4d1487ca00 (diff)
child 153124 dba9ab6684dc807a975f628d30d366c7d1037745
child 153207 c482e61af458dacec258e6ee060d9d93aeec1ca1
child 153366 5d0f54a06a66c4e12f463c0c37ea7c2e99ad7a7e
child 170187 ad01ad77a4d177fa8af4f5fd2fe497f72e653bcc
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
05d3797276d3 / 25.0a1 / 20130801030223 / files
nightly linux64
05d3797276d3 / 25.0a1 / 20130801030223 / files
nightly mac
05d3797276d3 / 25.0a1 / 20130801030223 / files
nightly win32
05d3797276d3 / 25.0a1 / 20130801030223 / files
nightly win64
05d3797276d3 / 25.0a1 / 20130801030223 / 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
dom/indexedDB/nsIIDBDatabase.idl
dom/indexedDB/nsIIDBIndex.idl
dom/indexedDB/nsIIDBObjectStore.idl
dom/interfaces/base/nsIDOMGlobalObjectConstructor.idl
toolkit/mozapps/extensions/test/addons/test_bug463819_1/install.rdf
toolkit/mozapps/extensions/test/addons/test_bug463819_2/install.rdf
toolkit/mozapps/extensions/test/addons/test_bug463819_3/install.rdf
toolkit/mozapps/extensions/test/addons/test_bug463819_4/install.rdf
toolkit/mozapps/extensions/test/addons/test_bug463819_5/install.rdf
toolkit/mozapps/extensions/test/addons/test_bug463819_6/install.rdf
toolkit/mozapps/extensions/test/addons/test_bug463819_7/install.rdf
toolkit/mozapps/extensions/test/addons/test_bug463819_8/install.rdf
toolkit/mozapps/extensions/test/addons/test_bug463819_9/install.rdf
--- a/accessible/src/generic/DocAccessible.cpp
+++ b/accessible/src/generic/DocAccessible.cpp
@@ -1825,20 +1825,26 @@ DocAccessible::UpdateTree(Accessible* aC
 }
 
 uint32_t
 DocAccessible::UpdateTreeInternal(Accessible* aChild, bool aIsInsert,
                                   AccReorderEvent* aReorderEvent)
 {
   uint32_t updateFlags = eAccessible;
 
+  // If a focused node has been shown then it could mean its frame was recreated
+  // while the node stays focused and we need to fire focus event on
+  // the accessible we just created. If the queue contains a focus event for
+  // this node already then it will be suppressed by this one.
+  Accessible* focusedAcc = nullptr;
+
   nsINode* node = aChild->GetNode();
   if (aIsInsert) {
     // Create accessible tree for shown accessible.
-    CacheChildrenInSubtree(aChild);
+    CacheChildrenInSubtree(aChild, &focusedAcc);
 
   } else {
     // Fire menupopup end event before hide event if a menu goes away.
 
     // XXX: We don't look into children of hidden subtree to find hiding
     // menupopup (as we did prior bug 570275) because we don't do that when
     // menu is showing (and that's impossible until bug 606924 is fixed).
     // Nevertheless we should do this at least because layout coalesces
@@ -1865,57 +1871,59 @@ DocAccessible::UpdateTreeInternal(Access
       // Fire EVENT_MENUPOPUP_START if ARIA menu appears.
       FireDelayedEvent(nsIAccessibleEvent::EVENT_MENUPOPUP_START, aChild);
 
     } else if (ariaRole == roles::ALERT) {
       // Fire EVENT_ALERT if ARIA alert appears.
       updateFlags = eAlertAccessible;
       FireDelayedEvent(nsIAccessibleEvent::EVENT_ALERT, aChild);
     }
-
-    // If focused node has been shown then it means its frame was recreated
-    // while it's focused. Fire focus event on new focused accessible. If
-    // the queue contains focus event for this node then it's suppressed by
-    // this one.
-    // XXX: do we really want to send focus to focused DOM node not taking into
-    // account active item?
-    if (FocusMgr()->IsFocused(aChild))
-      FocusMgr()->DispatchFocusEvent(this, aChild);
-
   } else {
     // Update the tree for content removal.
     // The accessible parent may differ from container accessible if
     // the parent doesn't have own DOM node like list accessible for HTML
     // selects.
     Accessible* parent = aChild->Parent();
     NS_ASSERTION(parent, "No accessible parent?!");
     if (parent)
       parent->RemoveChild(aChild);
 
     UncacheChildrenInSubtree(aChild);
   }
 
+  // XXX: do we really want to send focus to focused DOM node not taking into
+  // account active item?
+  if (focusedAcc)
+    FocusMgr()->DispatchFocusEvent(this, focusedAcc);
+
   return updateFlags;
 }
 
 void
-DocAccessible::CacheChildrenInSubtree(Accessible* aRoot)
+DocAccessible::CacheChildrenInSubtree(Accessible* aRoot,
+                                      Accessible** aFocusedAcc)
 {
+  // If the accessible is focused then report a focus event after all related
+  // mutation events.
+  if (aFocusedAcc && !*aFocusedAcc &&
+      FocusMgr()->HasDOMFocus(aRoot->GetContent()))
+    *aFocusedAcc = aRoot;
+
   aRoot->EnsureChildren();
 
   // Make sure we create accessible tree defined in DOM only, i.e. if accessible
   // provides specific tree (like XUL trees) then tree creation is handled by
   // this accessible.
   uint32_t count = aRoot->ContentChildCount();
   for (uint32_t idx = 0; idx < count; idx++) {
     Accessible* child = aRoot->ContentChildAt(idx);
     NS_ASSERTION(child, "Illicit tree change while tree is created!");
     // Don't cross document boundaries.
     if (child && child->IsContent())
-      CacheChildrenInSubtree(child);
+      CacheChildrenInSubtree(child, aFocusedAcc);
   }
 
   // Fire document load complete on ARIA documents.
   // XXX: we should delay an event if the ARIA document has aria-busy.
   if (aRoot->HasARIARole() && !aRoot->IsDoc()) {
     a11y::role role = aRoot->ARIARole();
     if (role == roles::DIALOG || role == roles::DOCUMENT)
       FireDelayedEvent(nsIAccessibleEvent::EVENT_DOCUMENT_LOAD_COMPLETE, aRoot);
--- a/accessible/src/generic/DocAccessible.h
+++ b/accessible/src/generic/DocAccessible.h
@@ -444,18 +444,23 @@ protected:
     eAlertAccessible = 2
   };
 
   uint32_t UpdateTreeInternal(Accessible* aChild, bool aIsInsert,
                               AccReorderEvent* aReorderEvent);
 
   /**
    * Create accessible tree.
+   *
+   * @param aRoot       [in] a root of subtree to create
+   * @param aFocusedAcc [in, optional] a focused accessible under created
+   *                      subtree if any
    */
-  void CacheChildrenInSubtree(Accessible* aRoot);
+  void CacheChildrenInSubtree(Accessible* aRoot,
+                              Accessible** aFocusedAcc = nullptr);
 
   /**
    * Remove accessibles in subtree from node to accessible map.
    */
   void UncacheChildrenInSubtree(Accessible* aRoot);
 
   /**
    * Shutdown any cached accessible in the subtree.
--- a/addon-sdk/source/lib/sdk/indexed-db.js
+++ b/addon-sdk/source/lib/sdk/indexed-db.js
@@ -50,12 +50,9 @@ exports.indexedDB = Object.freeze({
   deleteDatabase: indexedDB.deleteForPrincipal.bind(indexedDB, principal),
   cmp: indexedDB.cmp
 });
 
 exports.IDBKeyRange = IDBKeyRange;
 exports.DOMException = Ci.nsIDOMDOMException;
 exports.IDBCursor = Ci.nsIIDBCursor;
 exports.IDBOpenDBRequest = Ci.nsIIDBOpenDBRequest;
-exports.IDBDatabase = Ci.nsIIDBDatabase;
-exports.IDBIndex = Ci.nsIIDBIndex;
-exports.IDBObjectStore = Ci.nsIIDBObjectStore;
 exports.IDBRequest = Ci.nsIIDBRequest;
--- a/addon-sdk/source/test/test-indexed-db.js
+++ b/addon-sdk/source/test/test-indexed-db.js
@@ -4,32 +4,31 @@
 
 "use strict";
 
 let xulApp = require("sdk/system/xul-app");
 if (xulApp.versionInRange(xulApp.platformVersion, "16.0a1", "*")) {
 new function tests() {
 
 const { indexedDB, IDBKeyRange, DOMException, IDBCursor,
-        IDBOpenDBRequest, IDBDatabase, IDBIndex, IDBObjectStore, IDBRequest
+        IDBOpenDBRequest, IDBRequest
       } = require("sdk/indexed-db");
 
 exports["test indexedDB is frozen"] = function(assert){
   let original = indexedDB.open;
   let f = function(){};
   assert.throws(function(){indexedDB.open = f});
   assert.equal(indexedDB.open,original);
   assert.notEqual(indexedDB.open,f);
 
 };
 
 exports["test db variables"] = function(assert) {
   [ indexedDB, IDBKeyRange, DOMException, IDBCursor,
-    IDBOpenDBRequest, IDBOpenDBRequest, IDBDatabase, IDBIndex,
-    IDBObjectStore, IDBRequest
+    IDBOpenDBRequest, IDBOpenDBRequest, IDBRequest
   ].forEach(function(value) {
     assert.notEqual(typeof(value), "undefined", "variable is defined");
   });
 }
 
 exports["test open"] = function(assert, done) {
   let request = indexedDB.open("MyTestDatabase");
   request.onerror = function(event) {
--- a/browser/base/content/browser.js
+++ b/browser/base/content/browser.js
@@ -6401,17 +6401,17 @@ var gIdentityHandler = {
       gNavigatorBundle.getString("identity.encrypted2");
     this._encryptionLabel[this.IDENTITY_MODE_IDENTIFIED] =
       gNavigatorBundle.getString("identity.encrypted2");
     this._encryptionLabel[this.IDENTITY_MODE_UNKNOWN] =
       gNavigatorBundle.getString("identity.unencrypted");
     this._encryptionLabel[this.IDENTITY_MODE_MIXED_DISPLAY_LOADED] =
       gNavigatorBundle.getString("identity.mixed_display_loaded");
     this._encryptionLabel[this.IDENTITY_MODE_MIXED_ACTIVE_LOADED] =
-      gNavigatorBundle.getString("identity.mixed_active_loaded");
+      gNavigatorBundle.getString("identity.mixed_active_loaded2");
     this._encryptionLabel[this.IDENTITY_MODE_MIXED_DISPLAY_LOADED_ACTIVE_BLOCKED] =
       gNavigatorBundle.getString("identity.mixed_display_loaded_active_blocked");
     return this._encryptionLabel;
   },
   get _identityPopup () {
     delete this._identityPopup;
     return this._identityPopup = document.getElementById("identity-popup");
   },
--- a/browser/locales/en-US/chrome/browser/browser.properties
+++ b/browser/locales/en-US/chrome/browser/browser.properties
@@ -255,17 +255,17 @@ indexedDB.usage=This website (%1$S) is a
 
 identity.identified.verifier=Verified by: %S
 identity.identified.verified_by_you=You have added a security exception for this site.
 identity.identified.state_and_country=%S, %S
 
 identity.encrypted2=The connection to this website is secure.
 identity.mixed_display_loaded=The connection to this website is not fully secure because it contains unencrypted elements (such as images).
 identity.mixed_display_loaded_active_blocked=Interactive content (such as script) that isn't encrypted has been blocked for your protection.
-identity.mixed_active_loaded=This website contains interactive content that isn't encrypted (such as scripts). Other people can view or modify the website's behavior.
+identity.mixed_active_loaded2=This website contains interactive content that isn't encrypted (such as scripts). Other people can view your information or modify the website's behavior.
 identity.unencrypted=Your connection to this website is not encrypted.
 
 identity.unknown.tooltip=This website does not supply identity information.
 
 identity.ownerUnknown2=(unknown)
 
 # LOCALIZATION NOTE (identity.chrome): %S is replaced with the brandShortName.
 identity.chrome=This is a secure %S page.
--- a/browser/themes/shared/identity-block.inc.css
+++ b/browser/themes/shared/identity-block.inc.css
@@ -81,8 +81,12 @@
 }
 
 #identity-popup-brandName {
   font-weight: bold;
   font-size: 1.25em;
   margin-top: .5em;
   margin-bottom: .5em;
 }
+
+#identity-popup-content-box {
+  max-width: 50ch;
+}
--- a/build/compare-mozconfig/compare-mozconfigs-wrapper.py
+++ b/build/compare-mozconfig/compare-mozconfigs-wrapper.py
@@ -1,25 +1,30 @@
 #!/usr/bin/python
 # 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/.
 
+from __future__ import unicode_literals
+
 import subprocess
 import sys
 from os import path
 from buildconfig import substs
 
+import logging
+log = logging.getLogger(__name__)
+
 def determine_platform():
     platform_mapping = {'WINNT': {'x86_64': 'win64',
-                                  'i386': 'win32'},
+                                  'i686': 'win32'},
                         'Darwin': {'x86_64': 'macosx-universal',
                                    'i386':'macosx-universal'},
                         'Linux': {'x86_64': 'linux64',
-                                  'i386': 'linux32'}}
+                                  'i686': 'linux32'}}
 
     os_type = substs['OS_TARGET']
     cpu_type = substs['TARGET_CPU']
     return platform_mapping.get(os_type, {}).get(cpu_type, None)
 
 def main():
     """ A wrapper script that calls compare-mozconfig.py
     based on the platform that the machine is building for"""
@@ -32,22 +37,27 @@ def main():
         # construct paths and args for compare-mozconfig
         browser_dir = path.join(topsrcdir, 'browser')
         script_path = path.join(topsrcdir, 'build/compare-mozconfig/compare-mozconfigs.py')
         whitelist_path = path.join(browser_dir, 'config/mozconfigs/whitelist')
         beta_mozconfig_path = path.join(browser_dir, 'config/mozconfigs', platform, 'beta')
         release_mozconfig_path = path.join(browser_dir, 'config/mozconfigs', platform, 'release')
         nightly_mozconfig_path = path.join(browser_dir, 'config/mozconfigs', platform, 'nightly')
 
-        # compare beta vs nightly
+        log.info("Comparing beta against nightly mozconfigs")
         ret_code = subprocess.call([python_exe, script_path, '--whitelist',
                                     whitelist_path, '--no-download',
                                     platform + ',' + beta_mozconfig_path +
                                     ',' + nightly_mozconfig_path])
 
         if ret_code > 0:
-            sys.exit(ret_code)
+            return ret_code
 
-        # compare release vs nightly
+        log.info("Comparing release against nightly mozconfigs")
         ret_code = subprocess.call([python_exe, script_path, '--whitelist',
                                     whitelist_path, '--no-download',
                                     platform + ',' + release_mozconfig_path +
                                     ',' + nightly_mozconfig_path])
+
+        return ret_code
+
+if __name__ == '__main__':
+    sys.exit(main())
--- a/build/compare-mozconfig/compare-mozconfigs.py
+++ b/build/compare-mozconfig/compare-mozconfigs.py
@@ -1,24 +1,121 @@
 #!/usr/bin/python
+# 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/.
+
+# originally from http://hg.mozilla.org/build/tools/file/4ab9c1a4e05b/scripts/release/compare-mozconfigs.py
+
+from __future__ import unicode_literals
+
 import logging
 import os
 import site
 import sys
 import urllib2
-
-site.addsitedir(os.path.join(os.path.dirname(__file__), "../../lib/python"))
-
-from release.sanity import verify_mozconfigs
-from release.info import readConfig
-from util.hg import make_hg_url
+import difflib
 
 FAILURE_CODE = 1
 SUCCESS_CODE = 0
 
+log = logging.getLogger(__name__)
+
+class ConfigError(Exception):
+    pass
+
+def make_hg_url(hgHost, repoPath, protocol='https', revision=None,
+                filename=None):
+    """construct a valid hg url from a base hg url (hg.mozilla.org),
+    repoPath, revision and possible filename"""
+    base = '%s://%s' % (protocol, hgHost)
+    repo = '/'.join(p.strip('/') for p in [base, repoPath])
+    if not filename:
+        if not revision:
+            return repo
+        else:
+            return '/'.join([p.strip('/') for p in [repo, 'rev', revision]])
+    else:
+        assert revision
+        return '/'.join([p.strip('/') for p in [repo, 'raw-file', revision,
+                         filename]])
+
+def readConfig(configfile, keys=[], required=[]):
+    c = {}
+    execfile(configfile, c)
+    for k in keys:
+        c = c[k]
+    items = c.keys()
+    err = False
+    for key in required:
+        if key not in items:
+            err = True
+            log.error("Required item `%s' missing from %s" % (key, c))
+    if err:
+        raise ConfigError("Missing at least one item in config, see above")
+    return c
+
+def verify_mozconfigs(mozconfig_pair, nightly_mozconfig_pair, platform,
+                      mozconfigWhitelist={}):
+    """Compares mozconfig to nightly_mozconfig and compare to an optional
+    whitelist of known differences. mozconfig_pair and nightly_mozconfig_pair
+    are pairs containing the mozconfig's identifier and the list of lines in
+    the mozconfig."""
+
+    # unpack the pairs to get the names, the names are just for
+    # identifying the mozconfigs when logging the error messages
+    mozconfig_name, mozconfig_lines = mozconfig_pair
+    nightly_mozconfig_name, nightly_mozconfig_lines = nightly_mozconfig_pair
+
+    missing_args = mozconfig_lines == [] or nightly_mozconfig_lines == []
+    if missing_args:
+        log.info("Missing mozconfigs to compare for %s" % platform)
+        return False
+
+    success = True
+
+    diff_instance = difflib.Differ()
+    diff_result = diff_instance.compare(mozconfig_lines, nightly_mozconfig_lines)
+    diff_list = list(diff_result)
+
+    for line in diff_list:
+        clean_line = line[1:].strip()
+        if (line[0] == '-' or line[0] == '+') and len(clean_line) > 1:
+            # skip comment lines
+            if clean_line.startswith('#'):
+                continue
+            # compare to whitelist
+            message = ""
+            if line[0] == '-':
+                if platform in mozconfigWhitelist.get('release', {}):
+                    if clean_line in \
+                            mozconfigWhitelist['release'][platform]:
+                        continue
+            elif line[0] == '+':
+                if platform in mozconfigWhitelist.get('nightly', {}):
+                    if clean_line in \
+                            mozconfigWhitelist['nightly'][platform]:
+                        continue
+                    else:
+                        log.warning("%s not in %s %s!" % (
+                            clean_line, platform,
+                            mozconfigWhitelist['nightly'][platform]))
+            else:
+                log.error("Skipping line %s!" % line)
+                continue
+            message = "found in %s but not in %s: %s"
+            if line[0] == '-':
+                log.error(message % (mozconfig_name,
+                                     nightly_mozconfig_name, clean_line))
+            else:
+                log.error(message % (nightly_mozconfig_name,
+                                     mozconfig_name, clean_line))
+            success = False
+    return success
+
 def get_mozconfig(path, options):
     """Consumes a path and returns a list of lines from
     the mozconfig file. If download is required, the path
     specified should be relative to the root of the hg
     repository e.g browser/config/mozconfigs/linux32/nightly"""
     if options.no_download:
         return open(path, 'r').readlines()
     else:
--- a/caps/src/nsSecurityManagerFactory.cpp
+++ b/caps/src/nsSecurityManagerFactory.cpp
@@ -72,17 +72,17 @@ nsSecurityNameSet::InitializeNameSet(nsI
 
     /*
      * Find Object.prototype's class by walking up the global object's
      * prototype chain.
      */
     JS::Rooted<JSObject*> obj(cx, global);
     JS::Rooted<JSObject*> proto(cx);
     for (;;) {
-        MOZ_ALWAYS_TRUE(JS_GetPrototype(cx, obj, proto.address()));
+        MOZ_ALWAYS_TRUE(JS_GetPrototype(cx, obj, &proto));
         if (!proto)
             break;
         obj = proto;
     }
     JSClass *objectClass = JS_GetClass(obj);
 
     JS::Rooted<JS::Value> v(cx);
     if (!JS_GetProperty(cx, global, "netscape", &v))
--- a/content/base/src/nsDocument.cpp
+++ b/content/base/src/nsDocument.cpp
@@ -5237,25 +5237,25 @@ nsDocument::Register(JSContext* aCx, con
     protoObject = aOptions.mPrototype;
     if (!JS_WrapObject(aCx, protoObject.address())) {
       rv.Throw(NS_ERROR_UNEXPECTED);
       return nullptr;
     }
 
     // Check the proto chain for HTMLElement prototype.
     JS::Rooted<JSObject*> protoProto(aCx);
-    if (!JS_GetPrototype(aCx, protoObject, protoProto.address())) {
+    if (!JS_GetPrototype(aCx, protoObject, &protoProto)) {
       rv.Throw(NS_ERROR_UNEXPECTED);
       return nullptr;
     }
     while (protoProto) {
       if (protoProto == htmlProto) {
         break;
       }
-      if (!JS_GetPrototype(aCx, protoProto, protoProto.address())) {
+      if (!JS_GetPrototype(aCx, protoProto, &protoProto)) {
         rv.Throw(NS_ERROR_UNEXPECTED);
         return nullptr;
       }
     }
 
     if (!protoProto) {
       rv.Throw(NS_ERROR_DOM_TYPE_MISMATCH_ERR);
       return nullptr;
--- a/content/base/src/nsObjectLoadingContent.cpp
+++ b/content/base/src/nsObjectLoadingContent.cpp
@@ -3152,17 +3152,17 @@ nsObjectLoadingContent::LegacyCall(JSCon
   if (!pi) {
     aRv.Throw(NS_ERROR_NOT_AVAILABLE);
     return JS::UndefinedValue();
   }
 
   JS::Rooted<JSObject*> pi_obj(aCx);
   JS::Rooted<JSObject*> pi_proto(aCx);
 
-  rv = GetPluginJSObject(aCx, obj, pi, pi_obj.address(), pi_proto.address());
+  rv = GetPluginJSObject(aCx, obj, pi, &pi_obj, &pi_proto);
   if (NS_FAILED(rv)) {
     aRv.Throw(rv);
     return JS::UndefinedValue();
   }
 
   if (!pi_obj) {
     aRv.Throw(NS_ERROR_NOT_AVAILABLE);
     return JS::UndefinedValue();
@@ -3218,17 +3218,17 @@ nsObjectLoadingContent::SetupProtoChain(
   if (!pi) {
     // No plugin around for this object.
     return;
   }
 
   JS::Rooted<JSObject*> pi_obj(aCx); // XPConnect-wrapped peer object, when we get it.
   JS::Rooted<JSObject*> pi_proto(aCx); // 'pi.__proto__'
 
-  rv = GetPluginJSObject(aCx, aObject, pi, pi_obj.address(), pi_proto.address());
+  rv = GetPluginJSObject(aCx, aObject, pi, &pi_obj, &pi_proto);
   if (NS_FAILED(rv)) {
     return;
   }
 
   if (!pi_obj) {
     // Didn't get a plugin instance JSObject, nothing we can do then.
     return;
   }
@@ -3305,31 +3305,28 @@ nsObjectLoadingContent::SetupProtoChain(
   //
 }
 
 // static
 nsresult
 nsObjectLoadingContent::GetPluginJSObject(JSContext *cx,
                                           JS::Handle<JSObject*> obj,
                                           nsNPAPIPluginInstance *plugin_inst,
-                                          JSObject **plugin_obj,
-                                          JSObject **plugin_proto)
+                                          JS::MutableHandle<JSObject*> plugin_obj,
+                                          JS::MutableHandle<JSObject*> plugin_proto)
 {
-  *plugin_obj = nullptr;
-  *plugin_proto = nullptr;
-
   // NB: We need an AutoEnterCompartment because we can be called from
   // nsObjectFrame when the plugin loads after the JS object for our content
   // node has been created.
   JSAutoCompartment ac(cx, obj);
 
   if (plugin_inst) {
-    plugin_inst->GetJSObject(cx, plugin_obj);
-    if (*plugin_obj) {
-      if (!::JS_GetPrototype(cx, *plugin_obj, plugin_proto)) {
+    plugin_inst->GetJSObject(cx, plugin_obj.address());
+    if (plugin_obj) {
+      if (!::JS_GetPrototype(cx, plugin_obj, plugin_proto)) {
         return NS_ERROR_UNEXPECTED;
       }
     }
   }
 
   return NS_OK;
 }
 
@@ -3347,27 +3344,27 @@ nsObjectLoadingContent::TeardownProtoCha
 
   JS::Rooted<JSObject*> proto(cx);
   JSAutoCompartment ac(cx, obj);
 
   // Loop over the DOM element's JS object prototype chain and remove
   // all JS objects of the class sNPObjectJSWrapperClass
   bool removed = false;
   while (obj) {
-    if (!::JS_GetPrototype(cx, obj, proto.address())) {
+    if (!::JS_GetPrototype(cx, obj, &proto)) {
       return;
     }
     if (!proto) {
       break;
     }
     // Unwrap while checking the jsclass - if the prototype is a wrapper for
     // an NP object, that counts too.
     if (JS_GetClass(js::UncheckedUnwrap(proto)) == &sNPObjectJSWrapperClass) {
       // We found an NPObject on the proto chain, get its prototype...
-      if (!::JS_GetPrototype(cx, proto, proto.address())) {
+      if (!::JS_GetPrototype(cx, proto, &proto)) {
         return;
       }
 
       MOZ_ASSERT(!removed, "more than one NPObject in prototype chain");
       removed = true;
 
       // ... and pull it out of the chain.
       ::JS_SetPrototype(cx, obj, proto);
--- a/content/base/src/nsObjectLoadingContent.h
+++ b/content/base/src/nsObjectLoadingContent.h
@@ -476,18 +476,18 @@ class nsObjectLoadingContent : public ns
     // Utility getter for getting our nsNPAPIPluginInstance in a safe way.
     nsresult ScriptRequestPluginInstance(JSContext* aCx,
                                          nsNPAPIPluginInstance** aResult);
 
     // Utility method for getting our plugin JSObject
     static nsresult GetPluginJSObject(JSContext *cx,
                                       JS::Handle<JSObject*> obj,
                                       nsNPAPIPluginInstance *plugin_inst,
-                                      JSObject **plugin_obj,
-                                      JSObject **plugin_proto);
+                                      JS::MutableHandle<JSObject*> plugin_obj,
+                                      JS::MutableHandle<JSObject*> plugin_proto);
 
     // The final listener for mChannel (uriloader, pluginstreamlistener, etc.)
     nsCOMPtr<nsIStreamListener> mFinalListener;
 
     // Frame loader, for content documents we load.
     nsRefPtr<nsFrameLoader>     mFrameLoader;
 
     // Track if we have a pending AsyncInstantiateEvent
--- a/content/svg/content/test/test_switch.xhtml
+++ b/content/svg/content/test/test_switch.xhtml
@@ -40,24 +40,22 @@ function checkWidth(element, x, y, w, h)
   var name = element.nodeName;
 
   is(bbox.width, w, test + " " + name + ".getBBox().width");
   ++test;
 }
 
 function run()
 {
-  netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
   // Set accept_languages to something we know
-  var prefService = Components.classes["@mozilla.org/preferences-service;1"]
-                               .getService(Components.interfaces.nsIPrefService);
-  var branch = prefService.getBranch("intl.");
-  var oldAcceptLanguages = branch.getCharPref("accept_languages");
-  branch.setCharPref("accept_languages", "en-gb,en,it");
+  SpecialPowers.pushPrefEnv({"set": [["intl.accept_languages", "en-gb,en,it"]]}, run1);
+}
 
+function run1()
+{
   try {
     var doc = $("svg").contentDocument;
     var s = doc.getElementById("s");
     var first = doc.getElementById("first");
     var second = doc.getElementById("second");
   
     /* test for an exact match */
     second.setAttribute("systemLanguage", "en-gb");
@@ -88,17 +86,16 @@ function run()
     checkWidth(s, 75, 100, 50, 50);
 
     /* test that we pick the best match */
     first.setAttribute("systemLanguage", "en");
     second.setAttribute("systemLanguage", "en-gb");
     checkWidth(s, 75, 100, 50, 50);
 
   } finally {
-    branch.setCharPref("accept_languages", oldAcceptLanguages);
     SimpleTest.finish();
   }
 }
 
 window.addEventListener("load", run, false);
 
 ]]>
 </script>
--- a/content/xbl/src/nsXBLBinding.cpp
+++ b/content/xbl/src/nsXBLBinding.cpp
@@ -760,17 +760,17 @@ nsXBLBinding::ChangeDocument(nsIDocument
           // that was...
 
           // Find the right prototype.
           JSAutoCompartment ac(cx, scriptObject);
 
           JS::Rooted<JSObject*> base(cx, scriptObject);
           JS::Rooted<JSObject*> proto(cx);
           for ( ; true; base = proto) { // Will break out on null proto
-            if (!JS_GetPrototype(cx, base, proto.address())) {
+            if (!JS_GetPrototype(cx, base, &proto)) {
               return;
             }
             if (!proto) {
               break;
             }
 
             JSClass* clazz = ::JS_GetClass(proto);
             if (!clazz ||
@@ -794,17 +794,17 @@ nsXBLBinding::ChangeDocument(nsIDocument
             if (JSVAL_TO_PRIVATE(protoBinding) != mPrototypeBinding) {
               // Not the right binding
               continue;
             }
 
             // Alright!  This is the right prototype.  Pull it out of the
             // proto chain.
             JS::Rooted<JSObject*> grandProto(cx);
-            if (!JS_GetPrototype(cx, proto, grandProto.address())) {
+            if (!JS_GetPrototype(cx, proto, &grandProto)) {
               return;
             }
             ::JS_SetPrototype(cx, base, grandProto);
             break;
           }
 
           mPrototypeBinding->UndefineFields(cx, scriptObject);
 
@@ -894,17 +894,17 @@ nsXBLBinding::DoInitJSClass(JSContext *c
   nsAutoCString xblKey(aClassName);
 
   JSAutoCompartment ac(cx, global);
 
   JS::Rooted<JSObject*> parent_proto(cx, nullptr);
   nsXBLJSClass* c = nullptr;
   if (obj) {
     // Retrieve the current prototype of obj.
-    if (!JS_GetPrototype(cx, obj, parent_proto.address())) {
+    if (!JS_GetPrototype(cx, obj, &parent_proto)) {
       return NS_ERROR_FAILURE;
     }
     if (parent_proto) {
       // We need to create a unique classname based on aClassName and
       // id.  Append a space (an invalid URI character) to ensure that
       // we don't have accidental collisions with the case when parent_proto is
       // null and aClassName ends in some bizarre numbers (yeah, it's unlikely).
       JS::Rooted<jsid> parent_proto_id(cx);
--- a/content/xbl/src/nsXBLDocumentInfo.cpp
+++ b/content/xbl/src/nsXBLDocumentInfo.cpp
@@ -99,17 +99,17 @@ nsXBLDocGlobalObject::doCheckAccess(JSCo
     ::JS_ReportError(cx, "Unable to verify access to a global object property.");
     return JS_FALSE;
   }
 
   // Make sure to actually operate on our object, and not some object further
   // down on the proto chain.
   JS::Rooted<JSObject*> base(cx, obj);
   while (JS_GetClass(base) != &nsXBLDocGlobalObject::gSharedGlobalClass) {
-    if (!::JS_GetPrototype(cx, base, base.address())) {
+    if (!::JS_GetPrototype(cx, base, &base)) {
       return JS_FALSE;
     }
     if (!base) {
       ::JS_ReportError(cx, "Invalid access to a global object property.");
       return JS_FALSE;
     }
   }
 
--- a/dom/base/nsDOMClassInfo.cpp
+++ b/dom/base/nsDOMClassInfo.cpp
@@ -198,21 +198,18 @@
 #include "nsDOMFile.h"
 
 #include "nsIEventListenerService.h"
 #include "nsIMessageManager.h"
 #include "mozilla/dom/Element.h"
 
 #include "mozilla/dom/indexedDB/IDBWrapperCache.h"
 #include "mozilla/dom/indexedDB/IDBRequest.h"
-#include "mozilla/dom/indexedDB/IDBDatabase.h"
-#include "mozilla/dom/indexedDB/IDBObjectStore.h"
 #include "mozilla/dom/indexedDB/IDBCursor.h"
 #include "mozilla/dom/indexedDB/IDBKeyRange.h"
-#include "mozilla/dom/indexedDB/IDBIndex.h"
 
 using mozilla::dom::indexedDB::IDBWrapperCache;
 using mozilla::dom::workers::ResolveWorkerClasses;
 
 #include "nsIDOMMediaQueryList.h"
 
 #include "mozilla/dom/Activity.h"
 
@@ -251,17 +248,16 @@ using mozilla::dom::workers::ResolveWork
 #include "BluetoothDevice.h"
 #endif
 
 #include "DOMCameraManager.h"
 #include "DOMCameraControl.h"
 #include "DOMCameraCapabilities.h"
 #include "nsIOpenWindowEventDetail.h"
 #include "nsIAsyncScrollEventDetail.h"
-#include "nsIDOMGlobalObjectConstructor.h"
 #include "nsIDOMCanvasRenderingContext2D.h"
 #include "LockedFile.h"
 #include "nsDebug.h"
 
 #include "mozilla/dom/BindingUtils.h"
 #include "mozilla/Likely.h"
 
 #ifdef MOZ_TIME_MANAGER
@@ -632,28 +628,22 @@ static nsDOMClassInfoData sClassInfoData
                                        nsIXPCScriptable::IS_GLOBAL_OBJECT)
   NS_DEFINE_CHROME_ONLY_CLASSINFO_DATA(ChromeMessageBroadcaster, nsDOMGenericSH,
                                        DOM_DEFAULT_SCRIPTABLE_FLAGS)
   NS_DEFINE_CHROME_ONLY_CLASSINFO_DATA(ChromeMessageSender, nsDOMGenericSH,
                                        DOM_DEFAULT_SCRIPTABLE_FLAGS)
 
   NS_DEFINE_CLASSINFO_DATA(IDBRequest, IDBEventTargetSH,
                            IDBEVENTTARGET_SCRIPTABLE_FLAGS)
-  NS_DEFINE_CLASSINFO_DATA(IDBDatabase, IDBEventTargetSH,
-                           IDBEVENTTARGET_SCRIPTABLE_FLAGS)
-  NS_DEFINE_CLASSINFO_DATA(IDBObjectStore, nsDOMGenericSH,
-                           DOM_DEFAULT_SCRIPTABLE_FLAGS)
   NS_DEFINE_CLASSINFO_DATA(IDBCursor, nsDOMGenericSH,
                            DOM_DEFAULT_SCRIPTABLE_FLAGS)
   NS_DEFINE_CLASSINFO_DATA(IDBCursorWithValue, nsDOMGenericSH,
                            DOM_DEFAULT_SCRIPTABLE_FLAGS)
   NS_DEFINE_CLASSINFO_DATA(IDBKeyRange, nsDOMGenericSH,
                            DOM_DEFAULT_SCRIPTABLE_FLAGS)
-  NS_DEFINE_CLASSINFO_DATA(IDBIndex, nsDOMGenericSH,
-                           DOM_DEFAULT_SCRIPTABLE_FLAGS)
   NS_DEFINE_CLASSINFO_DATA(IDBOpenDBRequest, IDBEventTargetSH,
                            IDBEVENTTARGET_SCRIPTABLE_FLAGS)
 
 
   NS_DEFINE_CLASSINFO_DATA(MozCSSKeyframeRule, nsDOMGenericSH,
                            DOM_DEFAULT_SCRIPTABLE_FLAGS)
   NS_DEFINE_CLASSINFO_DATA(MozCSSKeyframesRule, nsDOMGenericSH,
                            DOM_DEFAULT_SCRIPTABLE_FLAGS)
@@ -1537,42 +1527,29 @@ nsDOMClassInfo::Init()
     DOM_CLASSINFO_MAP_ENTRY(nsIMessageSender)
   DOM_CLASSINFO_MAP_END
 
   DOM_CLASSINFO_MAP_BEGIN(IDBRequest, nsIIDBRequest)
     DOM_CLASSINFO_MAP_ENTRY(nsIIDBRequest)
     DOM_CLASSINFO_MAP_ENTRY(nsIDOMEventTarget)
   DOM_CLASSINFO_MAP_END
 
-  DOM_CLASSINFO_MAP_BEGIN(IDBDatabase, nsIIDBDatabase)
-    DOM_CLASSINFO_MAP_ENTRY(nsIIDBDatabase)
-    DOM_CLASSINFO_MAP_ENTRY(nsIDOMEventTarget)
-  DOM_CLASSINFO_MAP_END
-
-  DOM_CLASSINFO_MAP_BEGIN(IDBObjectStore, nsIIDBObjectStore)
-    DOM_CLASSINFO_MAP_ENTRY(nsIIDBObjectStore)
-  DOM_CLASSINFO_MAP_END
-
   DOM_CLASSINFO_MAP_BEGIN(IDBCursor, nsIIDBCursor)
     DOM_CLASSINFO_MAP_ENTRY(nsIIDBCursor)
   DOM_CLASSINFO_MAP_END
 
   DOM_CLASSINFO_MAP_BEGIN(IDBCursorWithValue, nsIIDBCursorWithValue)
     DOM_CLASSINFO_MAP_ENTRY(nsIIDBCursor)
     DOM_CLASSINFO_MAP_ENTRY(nsIIDBCursorWithValue)
   DOM_CLASSINFO_MAP_END
 
   DOM_CLASSINFO_MAP_BEGIN(IDBKeyRange, nsIIDBKeyRange)
     DOM_CLASSINFO_MAP_ENTRY(nsIIDBKeyRange)
   DOM_CLASSINFO_MAP_END
 
-  DOM_CLASSINFO_MAP_BEGIN(IDBIndex, nsIIDBIndex)
-    DOM_CLASSINFO_MAP_ENTRY(nsIIDBIndex)
-  DOM_CLASSINFO_MAP_END
-
   DOM_CLASSINFO_MAP_BEGIN(IDBOpenDBRequest, nsIIDBOpenDBRequest)
     DOM_CLASSINFO_MAP_ENTRY(nsIIDBOpenDBRequest)
     DOM_CLASSINFO_MAP_ENTRY(nsIIDBRequest)
     DOM_CLASSINFO_MAP_ENTRY(nsIDOMEventTarget)
   DOM_CLASSINFO_MAP_END
 
   DOM_CLASSINFO_MAP_BEGIN(MozCSSKeyframeRule, nsIDOMMozCSSKeyframeRule)
     DOM_CLASSINFO_MAP_ENTRY(nsIDOMMozCSSKeyframeRule)
@@ -2173,17 +2150,17 @@ nsDOMClassInfo::PostCreatePrototype(JSCo
   if (!sObjectClass) {
     FindObjectClass(cx, proto);
     NS_ASSERTION(sObjectClass && !strcmp(sObjectClass->name, "Object"),
                  "Incorrect object class!");
   }
 
 #ifdef DEBUG
     JS::Rooted<JSObject*> proto2(cx);
-    JS_GetPrototype(cx, proto, proto2.address());
+    JS_GetPrototype(cx, proto, &proto2);
     NS_ASSERTION(proto2 && JS_GetClass(proto2) == sObjectClass,
                  "Hmm, somebody did something evil?");
 #endif
 
 #ifdef DEBUG
   if (mData->mHasClassInterface && mData->mProtoChainInterface &&
       mData->mProtoChainInterface != &NS_GET_IID(nsISupports)) {
     nsCOMPtr<nsIInterfaceInfoManager>
@@ -2506,17 +2483,17 @@ nsWindowSH::GlobalScopePolluterNewResolv
       }
 
       objp.set(obj);
       return true;
     }
   }
 
   JS::Rooted<JSObject*> proto(cx);
-  if (!::JS_GetPrototype(cx, obj, proto.address())) {
+  if (!::JS_GetPrototype(cx, obj, &proto)) {
     return JS_FALSE;
   }
   JSBool hasProp;
 
   if (!proto || !::JS_HasPropertyById(cx, proto, id, &hasProp) ||
       hasProp) {
     // No prototype, or the property exists on the prototype. Do
     // nothing.
@@ -2568,27 +2545,27 @@ nsWindowSH::GlobalScopePolluterNewResolv
 JSBool
 nsWindowSH::InvalidateGlobalScopePolluter(JSContext *cx,
                                           JS::Handle<JSObject*> aObj)
 {
   JS::Rooted<JSObject*> proto(cx);
   JS::Rooted<JSObject*> obj(cx, aObj);
 
   for (;;) {
-    if (!::JS_GetPrototype(cx, obj, proto.address())) {
+    if (!::JS_GetPrototype(cx, obj, &proto)) {
       return JS_FALSE;
     }
     if (!proto) {
       break;
     }
 
     if (JS_GetClass(proto) == &sGlobalScopePolluterClass) {
 
       JS::Rooted<JSObject*> proto_proto(cx);
-      if (!::JS_GetPrototype(cx, proto, proto_proto.address())) {
+      if (!::JS_GetPrototype(cx, proto, &proto_proto)) {
         return JS_FALSE;
       }
 
       // Pull the global scope polluter out of the prototype chain so
       // that it can be freed.
       ::JS_SplicePrototype(cx, obj, proto_proto);
 
       break;
@@ -2610,17 +2587,17 @@ nsWindowSH::InstallGlobalScopePolluter(J
   }
 
   JS::Rooted<JSObject*> o(cx, obj), proto(cx);
 
   // Find the place in the prototype chain where we want this global
   // scope polluter (right before Object.prototype).
 
   for (;;) {
-    if (!::JS_GetPrototype(cx, o, proto.address())) {
+    if (!::JS_GetPrototype(cx, o, &proto)) {
       return NS_ERROR_OUT_OF_MEMORY;
     }
     if (!proto) {
       break;
     }
     if (JS_GetClass(proto) == sObjectClass) {
       // Set the global scope polluters prototype to Object.prototype
       ::JS_SplicePrototype(cx, gsp, proto);
@@ -2724,86 +2701,32 @@ BaseStubConstructor(nsIWeakReference* aW
     native = do_CreateInstance(*name_struct->mData->mConstructorCID, &rv);
   }
   if (NS_FAILED(rv)) {
     NS_ERROR("Failed to create the object");
     return rv;
   }
 
   nsCOMPtr<nsIJSNativeInitializer> initializer(do_QueryInterface(native));
-  nsCOMPtr<nsIDOMGlobalObjectConstructor> constructor(do_QueryInterface(native));
-  if (initializer || constructor) {
+  if (initializer) {
     // Initialize object using the current inner window, but only if
     // the caller can access it.
     nsCOMPtr<nsPIDOMWindow> owner = do_QueryReferent(aWeakOwner);
     nsPIDOMWindow* outerWindow = owner ? owner->GetOuterWindow() : nullptr;
     nsPIDOMWindow* currentInner =
       outerWindow ? outerWindow->GetCurrentInnerWindow() : nullptr;
     if (!currentInner ||
         (owner != currentInner &&
          !nsContentUtils::CanCallerAccess(currentInner))) {
       return NS_ERROR_DOM_SECURITY_ERR;
     }
 
-    if (initializer) {
-      rv = initializer->Initialize(currentInner, cx, obj, args);
-      if (NS_FAILED(rv)) {
-        return rv;
-      }
-    } else {
-      nsCOMPtr<nsIXPConnectWrappedJS> wrappedJS = do_QueryInterface(native);
-
-      JS::Rooted<JSObject*> thisObject(cx, wrappedJS->GetJSObject());
-      if (!thisObject) {
-        return NS_ERROR_UNEXPECTED;
-      }
-
-      nsCxPusher pusher;
-      pusher.Push(cx);
-
-      JSAutoCompartment ac(cx, thisObject);
-
-      JS::Rooted<JS::Value> funval(cx);
-      if (!JS_GetProperty(cx, thisObject, "constructor", &funval) ||
-          !funval.isObject()) {
-        return NS_ERROR_UNEXPECTED;
-      }
-
-      // Check if the object is even callable.
-      NS_ENSURE_STATE(JS_ObjectIsCallable(cx, &funval.toObject()));
-      {
-        // wrap parameters in the target compartment
-        // we also pass in the calling window as the first argument
-        unsigned argc = args.length() + 1;
-        nsAutoArrayPtr<JS::Value> argv(new JS::Value[argc]);
-        JS::AutoArrayRooter rooter(cx, 0, argv);
-
-        nsCOMPtr<nsIXPConnectJSObjectHolder> holder;
-        nsCOMPtr<nsIDOMWindow> currentWin(do_GetInterface(currentInner));
-        rv = WrapNative(cx, obj, currentWin, &NS_GET_IID(nsIDOMWindow),
-                        true, &argv[0], getter_AddRefs(holder));
-        if (!JS_WrapValue(cx, &argv[0]))
-          return NS_ERROR_FAILURE;
-        rooter.changeLength(1);
-
-        for (size_t i = 1; i < argc; ++i) {
-          argv[i] = args[i - 1];
-          if (!JS_WrapValue(cx, &argv[i]))
-            return NS_ERROR_FAILURE;
-          rooter.changeLength(i + 1);
-        }
-
-        JS::Rooted<JS::Value> frval(cx);
-        bool ret = JS_CallFunctionValue(cx, thisObject, funval, argc, argv,
-                                        frval.address());
-
-        if (!ret) {
-          return NS_ERROR_FAILURE;
-        }
-      }
+    rv = initializer->Initialize(currentInner, cx, obj, args);
+    if (NS_FAILED(rv)) {
+      return rv;
     }
   }
 
   return WrapNative(cx, obj, native, true, args.rval().address());
 }
 
 static nsresult
 DefineInterfaceConstants(JSContext *cx, JS::Handle<JSObject*> obj, const nsIID *aIID)
@@ -3266,17 +3189,17 @@ nsDOMConstructor::HasInstance(nsIXPConne
     if (JSVAL_IS_PRIMITIVE(val)) {
       return NS_OK;
     }
 
     JS::Rooted<JSObject*> dot_prototype(cx, val.toObjectOrNull());
 
     JS::Rooted<JSObject*> proto(cx, dom_obj);
     for (;;) {
-      if (!JS_GetPrototype(cx, proto, proto.address())) {
+      if (!JS_GetPrototype(cx, proto, &proto)) {
         return NS_ERROR_UNEXPECTED;
       }
       if (!proto) {
         break;
       }
       if (proto == dot_prototype) {
         *bp = true;
         break;
@@ -3628,17 +3551,17 @@ ResolvePrototype(nsIXPConnect *aXPConnec
           proto = &val.toObject();
         }
       }
     }
 
     if (dot_prototype) {
       JSAutoCompartment ac(cx, dot_prototype);
       JS::Rooted<JSObject*> xpc_proto_proto(cx);
-      if (!::JS_GetPrototype(cx, dot_prototype, xpc_proto_proto.address())) {
+      if (!::JS_GetPrototype(cx, dot_prototype, &xpc_proto_proto)) {
         return NS_ERROR_UNEXPECTED;
       }
 
       if (proto &&
           (!xpc_proto_proto ||
            JS_GetClass(xpc_proto_proto) == sObjectClass)) {
         if (!JS_WrapObject(cx, proto.address()) ||
             !JS_SetPrototype(cx, dot_prototype, proto)) {
@@ -5250,17 +5173,17 @@ nsStorage2SH::NewResolve(nsIXPConnectWra
   // after converting id to a string if it's an integer.
 
   JS::Rooted<JSString*> jsstr(cx, IdToString(cx, id));
   if (!jsstr) {
     return NS_OK;
   }
 
   JS::Rooted<JSObject*> proto(cx);
-  if (!::JS_GetPrototype(cx, realObj, proto.address())) {
+  if (!::JS_GetPrototype(cx, realObj, &proto)) {
     return NS_ERROR_FAILURE;
   }
   JSBool hasProp;
 
   if (proto &&
       (::JS_HasPropertyById(cx, proto, id, &hasProp) &&
        hasProp)) {
     // We found the property we're resolving on the prototype,
--- a/dom/base/nsDOMClassInfoClasses.h
+++ b/dom/base/nsDOMClassInfoClasses.h
@@ -115,22 +115,19 @@ DOMCI_CLASS(DataTransfer)
 
 DOMCI_CLASS(EventListenerInfo)
 
 DOMCI_CLASS(ContentFrameMessageManager)
 DOMCI_CLASS(ChromeMessageBroadcaster)
 DOMCI_CLASS(ChromeMessageSender)
 
 DOMCI_CLASS(IDBRequest)
-DOMCI_CLASS(IDBDatabase)
-DOMCI_CLASS(IDBObjectStore)
 DOMCI_CLASS(IDBCursor)
 DOMCI_CLASS(IDBCursorWithValue)
 DOMCI_CLASS(IDBKeyRange)
-DOMCI_CLASS(IDBIndex)
 DOMCI_CLASS(IDBOpenDBRequest)
 
 
 DOMCI_CLASS(MozCSSKeyframeRule)
 DOMCI_CLASS(MozCSSKeyframesRule)
 
 DOMCI_CLASS(CSSPageRule)
 
--- a/dom/base/nsGlobalWindow.cpp
+++ b/dom/base/nsGlobalWindow.cpp
@@ -2068,19 +2068,19 @@ nsresult
 nsGlobalWindow::SetOuterObject(JSContext* aCx, JS::Handle<JSObject*> aOuterObject)
 {
   JSAutoCompartment ac(aCx, aOuterObject);
 
   // Indicate the default compartment object associated with this cx.
   js::SetDefaultObjectForContext(aCx, aOuterObject);
 
   // Set up the prototype for the outer object.
-  JSObject* inner = JS_GetParent(aOuterObject);
+  JS::Rooted<JSObject*> inner(aCx, JS_GetParent(aOuterObject));
   JS::Rooted<JSObject*> proto(aCx);
-  if (!JS_GetPrototype(aCx, inner, proto.address())) {
+  if (!JS_GetPrototype(aCx, inner, &proto)) {
     return NS_ERROR_FAILURE;
   }
   JS_SetPrototype(aCx, aOuterObject, proto);
 
   return NS_OK;
 }
 
 // We need certain special behavior for remote XUL whitelisted domains, but we
@@ -2462,27 +2462,29 @@ nsGlobalWindow::SetNewDocument(nsIDocume
 
   if (!aState && !reUseInnerWindow) {
     // Loading a new page and creating a new inner window, *not*
     // restoring from session history.
 
     // Now that both the the inner and outer windows are initialized
     // let the script context do its magic to hook them together.
 #ifdef DEBUG
-    JSObject* newInnerJSObject = newInnerWindow->FastGetGlobalJSObject();
+    JS::Rooted<JSObject*> newInnerJSObject(cx,
+        newInnerWindow->FastGetGlobalJSObject());
 #endif
 
     // Now that we're connecting the outer global to the inner one,
     // we must have transplanted it. The JS engine tries to maintain
     // the global object's compartment as its default compartment,
     // so update that now since it might have changed.
     js::SetDefaultObjectForContext(cx, mJSObject);
 #ifdef DEBUG
-    JSObject *proto1, *proto2;
-    JS_GetPrototype(cx, mJSObject, &proto1);
+    JS::Rooted<JSObject*> rootedJSObject(cx, mJSObject);
+    JS::Rooted<JSObject*> proto1(cx), proto2(cx);
+    JS_GetPrototype(cx, rootedJSObject, &proto1);
     JS_GetPrototype(cx, newInnerJSObject, &proto2);
     NS_ASSERTION(proto1 == proto2,
                  "outer and inner globals should have the same prototype");
 #endif
 
     nsCOMPtr<Element> frame = GetFrameElementInternal();
     if (frame) {
       nsPIDOMWindow* parentWindow = frame->OwnerDoc()->GetWindow();
@@ -6587,17 +6589,17 @@ nsGlobalWindow::CallerInnerWindow()
   // sandboxPrototype to make them appear as though they're running in the
   // scope of the page. So when a content script invokes postMessage, it expects
   // the |source| of the received message to be the window set as the
   // sandboxPrototype. This used to work incidentally for unrelated reasons, but
   // now we need to do some special handling to support it.
   {
     JSAutoCompartment ac(cx, scope);
     JS::Rooted<JSObject*> scopeProto(cx);
-    bool ok = JS_GetPrototype(cx, scope, scopeProto.address());
+    bool ok = JS_GetPrototype(cx, scope, &scopeProto);
     NS_ENSURE_TRUE(ok, nullptr);
     if (scopeProto && xpc::IsSandboxPrototypeProxy(scopeProto) &&
         (scopeProto = js::CheckedUnwrap(scopeProto, /* stopAtOuter = */ false)))
     {
       scope = scopeProto;
     }
   }
   JSAutoCompartment ac(cx, scope);
--- a/dom/bindings/BindingUtils.cpp
+++ b/dom/bindings/BindingUtils.cpp
@@ -1750,27 +1750,27 @@ InterfaceHasInstance(JSContext* cx, JS::
   DebugOnly<bool> ok = JS_GetProperty(cx, obj, "prototype", &protov);
   MOZ_ASSERT(ok, "Someone messed with our prototype property?");
 
   JS::Rooted<JSObject*> interfacePrototype(cx, &protov.toObject());
   MOZ_ASSERT(IsDOMIfaceAndProtoClass(js::GetObjectClass(interfacePrototype)),
              "Someone messed with our prototype property?");
 
   JS::Rooted<JSObject*> proto(cx);
-  if (!JS_GetPrototype(cx, instance, proto.address())) {
+  if (!JS_GetPrototype(cx, instance, &proto)) {
     return false;
   }
 
   while (proto) {
     if (proto == interfacePrototype) {
       *bp = true;
       return true;
     }
 
-    if (!JS_GetPrototype(cx, proto, proto.address())) {
+    if (!JS_GetPrototype(cx, proto, &proto)) {
       return false;
     }
   }
 
   *bp = false;
   return true;
 }
 
--- a/dom/bindings/Bindings.conf
+++ b/dom/bindings/Bindings.conf
@@ -533,24 +533,44 @@ DOMInterfaces = {
         'sheet'
     ]
 },
 
 'HTMLUListElement': {
     'nativeType' : 'mozilla::dom::HTMLSharedListElement'
 },
 
+'IDBDatabase': {
+    'nativeType': 'mozilla::dom::indexedDB::IDBDatabase',
+},
+
 'IDBFactory': {
     'nativeType': 'mozilla::dom::indexedDB::IDBFactory',
 },
 
 'IDBFileHandle': {
     'nativeType': 'mozilla::dom::indexedDB::IDBFileHandle',
 },
 
+'IDBIndex': {
+    'nativeType': 'mozilla::dom::indexedDB::IDBIndex',
+    'binaryNames': {
+        'mozGetAll': 'getAll',
+        'mozGetAllKeys': 'getAllKeys',
+    }
+},
+
+'IDBObjectStore': {
+    'nativeType': 'mozilla::dom::indexedDB::IDBObjectStore',
+    'implicitJSContext': [ 'createIndex' ],
+    'binaryNames': {
+        'mozGetAll': 'getAll'
+    }
+},
+
 'IDBTransaction': {
     'nativeType': 'mozilla::dom::indexedDB::IDBTransaction',
 },
 
 'IDBVersionChangeEvent': {
     'nativeType': 'mozilla::dom::indexedDB::IDBVersionChangeEvent',
     'headerFile': 'IDBEvents.h',
 },
@@ -1654,19 +1674,18 @@ addExternalIface('DeviceRotationRate', h
 addExternalIface('mozIDOMApplication', nativeType='mozIDOMApplication', headerFile='nsIDOMApplicationRegistry.h')
 addExternalIface('CSSRuleList')
 addExternalIface('DOMStringList')
 addExternalIface('RTCDataChannel', nativeType='nsIDOMDataChannel')
 addExternalIface('File')
 addExternalIface('FileCallback', nativeType='nsIFileCallback',
                  headerFile='nsIDOMHTMLCanvasElement.h')
 addExternalIface('HitRegionOptions', nativeType='nsISupports')
-addExternalIface('IDBDatabase', nativeType='nsIIDBDatabase')
-addExternalIface('IDBObjectStore', nativeType='nsIIDBObjectStore')
 addExternalIface('IDBOpenDBRequest', nativeType='nsIIDBOpenDBRequest')
+addExternalIface('IDBRequest', nativeType='nsIIDBRequest')
 addExternalIface('imgINotificationObserver', nativeType='imgINotificationObserver')
 addExternalIface('imgIRequest', nativeType='imgIRequest', notflattened=True)
 addExternalIface('LockedFile')
 addExternalIface('MediaList')
 addExternalIface('MenuBuilder', nativeType='nsIMenuBuilder', notflattened=True)
 addExternalIface('MozBluetoothManager', nativeType='nsIDOMBluetoothManager')
 addExternalIface('MozBoxObject', nativeType='nsIBoxObject')
 addExternalIface('MozCellBroadcast')
--- a/dom/bindings/DOMJSProxyHandler.cpp
+++ b/dom/bindings/DOMJSProxyHandler.cpp
@@ -225,17 +225,17 @@ DOMProxyHandler::delete_(JSContext* cx, 
   *bp = !!b;
   return true;
 }
 
 bool
 DOMProxyHandler::enumerate(JSContext* cx, JS::Handle<JSObject*> proxy, AutoIdVector& props)
 {
   JS::Rooted<JSObject*> proto(cx);
-  if (!JS_GetPrototype(cx, proxy, proto.address())) {
+  if (!JS_GetPrototype(cx, proxy, &proto))  {
     return false;
   }
   return getOwnPropertyNames(cx, proxy, props) &&
          (!proto || js::GetPropertyNames(cx, proto, 0, &props));
 }
 
 bool
 DOMProxyHandler::has(JSContext* cx, JS::Handle<JSObject*> proxy, JS::Handle<jsid> id, bool* bp)
--- a/dom/browser-element/BrowserElementPanning.js
+++ b/dom/browser-element/BrowserElementPanning.js
@@ -640,19 +640,16 @@ const KineticPanning = {
   target: null,
   start: function kp_start(target) {
     this.target = target;
 
     // Calculate the initial velocity of the movement based on user input
     let momentums = this.momentums;
     let flick = momentums[momentums.length - 1].time - momentums[0].time < 300;
 
-    // Calculate the panning based on the last moves.
-    momentums = momentums.slice(-kSamples);
-
     let distance = new Point(0, 0);
     momentums.forEach(function(momentum) {
       distance.add(momentum.dx, momentum.dy);
     });
 
     function clampFromZero(x, min, max) {
       if (x >= 0)
         return Math.max(min, Math.min(max, x));
@@ -702,16 +699,22 @@ const KineticPanning = {
     this.target.onKineticEnd();
     this.target = null;
   },
 
   momentums: [],
   record: function kp_record(delta, timestamp) {
     this.momentums.push({ 'time': this._getTime(timestamp),
                           'dx' : delta.x, 'dy' : delta.y });
+
+    // We only need to keep kSamples in this.momentums.
+    if (this.momentums.length > kSamples) {
+      this.momentums.shift();
+    }
+
     this.distance.add(delta.x, delta.y);
   },
 
   _getTime: function kp_getTime(time) {
     // Touch events generated by the platform or hand-made are defined in
     // microseconds instead of milliseconds. Bug 77992 will fix this at the
     // platform level.
     if (time > Date.now()) {
--- a/dom/indexedDB/AsyncConnectionHelper.cpp
+++ b/dom/indexedDB/AsyncConnectionHelper.cpp
@@ -168,17 +168,17 @@ AsyncConnectionHelper::~AsyncConnectionH
     mTransaction.forget(&transaction);
 
     nsCOMPtr<nsIThread> mainThread;
     NS_GetMainThread(getter_AddRefs(mainThread));
     NS_WARN_IF_FALSE(mainThread, "Couldn't get the main thread!");
 
     if (mainThread) {
       if (database) {
-        NS_ProxyRelease(mainThread, static_cast<nsIIDBDatabase*>(database));
+        NS_ProxyRelease(mainThread, static_cast<IDBWrapperCache*>(database));
       }
       if (transaction) {
         NS_ProxyRelease(mainThread, static_cast<IDBWrapperCache*>(transaction));
       }
     }
   }
 
   NS_ASSERTION(!mOldProgressHandler, "Should not have anything here!");
--- a/dom/indexedDB/IDBCursor.cpp
+++ b/dom/indexedDB/IDBCursor.cpp
@@ -268,36 +268,35 @@ IDBCursor::Create(IDBRequest* aRequest,
   cursor->mKey = aKey;
   cursor->mObjectKey = aObjectKey;
   cursor->mCloneReadInfo.Swap(aCloneReadInfo);
 
   return cursor.forget();
 }
 
 // static
-nsresult
-IDBCursor::ParseDirection(const nsAString& aDirection, Direction* aResult)
+IDBCursor::Direction
+IDBCursor::ConvertDirection(mozilla::dom::IDBCursorDirection aDirection)
 {
-  if (aDirection.EqualsLiteral("next")) {
-    *aResult = NEXT;
-  }
-  else if (aDirection.EqualsLiteral("nextunique")) {
-    *aResult = NEXT_UNIQUE;
+  switch (aDirection) {
+    case mozilla::dom::IDBCursorDirection::Next:
+      return NEXT;
+
+    case mozilla::dom::IDBCursorDirection::Nextunique:
+      return NEXT_UNIQUE;
+
+    case mozilla::dom::IDBCursorDirection::Prev:
+      return PREV;
+
+    case mozilla::dom::IDBCursorDirection::Prevunique:
+      return PREV_UNIQUE;
+
+    default:
+      MOZ_CRASH("Unknown direction!");
   }
-  else if (aDirection.EqualsLiteral("prev")) {
-    *aResult = PREV;
-  }
-  else if (aDirection.EqualsLiteral("prevunique")) {
-    *aResult = PREV_UNIQUE;
-  }
-  else {
-    return NS_ERROR_TYPE_ERR;
-  }
-  
-  return NS_OK;
 }
 
 // static
 already_AddRefed<IDBCursor>
 IDBCursor::CreateCommon(IDBRequest* aRequest,
                         IDBTransaction* aTransaction,
                         IDBObjectStore* aObjectStore,
                         Direction aDirection,
@@ -727,29 +726,35 @@ IDBCursor::Update(const jsval& aValue,
     if (NS_FAILED(rv)) {
       return rv;
     }
 
     if (key != objectKey) {
       return NS_ERROR_DOM_INDEXEDDB_DATA_ERR;
     }
 
-    rv = mObjectStore->Put(aValue, JSVAL_VOID, aCx, 0, getter_AddRefs(request));
-    if (NS_FAILED(rv)) {
-      return rv;
+    ErrorResult error;
+    JS::Rooted<JS::Value> value(aCx, aValue);
+    Optional<JS::Handle<JS::Value> > keyValue(aCx);
+    request = mObjectStore->Put(aCx, value, keyValue, error);
+    if (error.Failed()) {
+      return error.ErrorCode();
     }
   }
   else {
     JS::Rooted<JS::Value> keyVal(aCx);
     rv = objectKey.ToJSVal(aCx, &keyVal);
     NS_ENSURE_SUCCESS(rv, rv);
 
-    rv = mObjectStore->Put(aValue, keyVal, aCx, 1, getter_AddRefs(request));
-    if (NS_FAILED(rv)) {
-      return rv;
+    ErrorResult error;
+    JS::Rooted<JS::Value> value(aCx, aValue);
+    Optional<JS::Handle<JS::Value> > keyValue(aCx, keyVal);
+    request = mObjectStore->Put(aCx, value, keyValue, error);
+    if (error.Failed()) {
+      return error.ErrorCode();
     }
   }
 
 #ifdef IDB_PROFILER_USE_MARKS
   {
     uint64_t requestSerial =
       static_cast<IDBRequest*>(request.get())->GetSerialNumber();
     if (mType == OBJECTSTORE) {
@@ -808,20 +813,20 @@ IDBCursor::Delete(JSContext* aCx,
   NS_ASSERTION(!mKey.IsUnset() , "Bad key!");
 
   Key& objectKey = (mType == OBJECTSTORE) ? mKey : mObjectKey;
 
   JS::Rooted<JS::Value> key(aCx);
   nsresult rv = objectKey.ToJSVal(aCx, &key);
   NS_ENSURE_SUCCESS(rv, rv);
 
-  nsCOMPtr<nsIIDBRequest> request;
-  rv = mObjectStore->Delete(key, aCx, getter_AddRefs(request));
-  if (NS_FAILED(rv)) {
-    return rv;
+  ErrorResult error;
+  nsCOMPtr<nsIIDBRequest> request = mObjectStore->Delete(aCx, key, error);
+  if (error.Failed()) {
+    return error.ErrorCode();
   }
 
 #ifdef IDB_PROFILER_USE_MARKS
   {
     uint64_t requestSerial =
       static_cast<IDBRequest*>(request.get())->GetSerialNumber();
     if (mType == OBJECTSTORE) {
       IDB_PROFILER_MARK("IndexedDB Request %llu: "
--- a/dom/indexedDB/IDBCursor.h
+++ b/dom/indexedDB/IDBCursor.h
@@ -3,22 +3,25 @@
 /* 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/. */
 
 #ifndef mozilla_dom_indexeddb_idbcursor_h__
 #define mozilla_dom_indexeddb_idbcursor_h__
 
 #include "mozilla/dom/indexedDB/IndexedDatabase.h"
+
+#include "nsIIDBCursorWithValue.h"
+
+#include "mozilla/dom/IDBCursorBinding.h"
+#include "nsCycleCollectionParticipant.h"
+
 #include "mozilla/dom/indexedDB/IDBObjectStore.h"
 #include "mozilla/dom/indexedDB/Key.h"
 
-#include "nsIIDBCursorWithValue.h"
-
-#include "nsCycleCollectionParticipant.h"
 
 class nsIRunnable;
 class nsIScriptContext;
 class nsPIDOMWindow;
 
 BEGIN_INDEXEDDB_NAMESPACE
 
 class ContinueHelper;
@@ -108,18 +111,18 @@ public:
     return mTransaction;
   }
 
   IDBRequest* Request() const
   {
     return mRequest;
   }
 
-  static nsresult ParseDirection(const nsAString& aDirection,
-                                 Direction* aResult);
+  static Direction
+  ConvertDirection(IDBCursorDirection aDirection);
 
   void
   SetActor(IndexedDBCursorChild* aActorChild)
   {
     NS_ASSERTION(!aActorChild || !mActorChild, "Shouldn't have more than one!");
     mActorChild = aActorChild;
   }
 
--- a/dom/indexedDB/IDBDatabase.cpp
+++ b/dom/indexedDB/IDBDatabase.cpp
@@ -38,16 +38,17 @@
 
 #include "mozilla/dom/IDBDatabaseBinding.h"
 
 USING_INDEXEDDB_NAMESPACE
 using mozilla::dom::ContentParent;
 using mozilla::dom::quota::AssertIsOnIOThread;
 using mozilla::dom::quota::Client;
 using mozilla::dom::quota::QuotaManager;
+using mozilla::ErrorResult;
 using namespace mozilla::dom;
 
 namespace {
 
 class NoRequestDatabaseHelper : public AsyncConnectionHelper
 {
 public:
   NoRequestDatabaseHelper(IDBTransaction* aTransaction)
@@ -233,16 +234,18 @@ IDBDatabase::IDBDatabase()
   mActorParent(nullptr),
   mContentParent(nullptr),
   mInvalidated(false),
   mRegistered(false),
   mClosed(false),
   mRunningVersionChange(false)
 {
   NS_ASSERTION(NS_IsMainThread(), "Wrong thread!");
+
+  SetIsDOMBinding();
 }
 
 IDBDatabase::~IDBDatabase()
 {
   NS_ASSERTION(NS_IsMainThread(), "Wrong thread!");
 }
 
 void
@@ -396,422 +399,342 @@ IDBDatabase::OnUnlink()
   if (quotaManager) {
     quotaManager->UnregisterStorage(this);
 
     // Don't try to unregister again in the destructor.
     mRegistered = false;
   }
 }
 
-nsresult
+already_AddRefed<IDBObjectStore>
 IDBDatabase::CreateObjectStoreInternal(IDBTransaction* aTransaction,
                                        const ObjectStoreInfoGuts& aInfo,
-                                       IDBObjectStore** _retval)
+                                       ErrorResult& aRv)
 {
   NS_ASSERTION(NS_IsMainThread(), "Wrong thread!");
   NS_ASSERTION(aTransaction, "Null transaction!");
 
   DatabaseInfo* databaseInfo = aTransaction->DBInfo();
 
   nsRefPtr<ObjectStoreInfo> newInfo = new ObjectStoreInfo();
   *static_cast<ObjectStoreInfoGuts*>(newInfo.get()) = aInfo;
 
   newInfo->nextAutoIncrementId = aInfo.autoIncrement ? 1 : 0;
   newInfo->comittedAutoIncrementId = newInfo->nextAutoIncrementId;
 
   if (!databaseInfo->PutObjectStore(newInfo)) {
     NS_WARNING("Put failed!");
-    return NS_ERROR_DOM_INDEXEDDB_UNKNOWN_ERR;
+    aRv.Throw(NS_ERROR_DOM_INDEXEDDB_UNKNOWN_ERR);
+    return nullptr;
   }
 
   // Don't leave this in the hash if we fail below!
   AutoRemoveObjectStore autoRemove(databaseInfo, newInfo->name);
 
   nsRefPtr<IDBObjectStore> objectStore =
     aTransaction->GetOrCreateObjectStore(newInfo->name, newInfo, true);
-  NS_ENSURE_TRUE(objectStore, NS_ERROR_DOM_INDEXEDDB_UNKNOWN_ERR);
+  if (!objectStore) {
+    NS_WARNING("Failed to get objectStore!");
+    aRv.Throw(NS_ERROR_DOM_INDEXEDDB_UNKNOWN_ERR);
+    return nullptr;
+  }
 
   if (IndexedDatabaseManager::IsMainProcess()) {
     nsRefPtr<CreateObjectStoreHelper> helper =
       new CreateObjectStoreHelper(aTransaction, objectStore);
 
     nsresult rv = helper->DispatchToTransactionPool();
-    NS_ENSURE_SUCCESS(rv, NS_ERROR_DOM_INDEXEDDB_UNKNOWN_ERR);
+    if (NS_FAILED(rv)) {
+      NS_WARNING("Failed to dispatch!");
+      aRv.Throw(NS_ERROR_DOM_INDEXEDDB_UNKNOWN_ERR);
+      return nullptr;
+    }
   }
 
   autoRemove.forget();
 
   IDB_PROFILER_MARK("IndexedDB Pseudo-request: "
                     "database(%s).transaction(%s).createObjectStore(%s)",
                     "MT IDBDatabase.createObjectStore()",
                     IDB_PROFILER_STRING(this),
                     IDB_PROFILER_STRING(aTransaction),
                     IDB_PROFILER_STRING(objectStore));
 
-  objectStore.forget(_retval);
-
-  return NS_OK;
+  return objectStore.forget();
 }
 
 NS_IMPL_CYCLE_COLLECTION_TRAVERSE_BEGIN_INHERITED(IDBDatabase, IDBWrapperCache)
   NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mFactory)
 NS_IMPL_CYCLE_COLLECTION_TRAVERSE_END
 
 NS_IMPL_CYCLE_COLLECTION_UNLINK_BEGIN_INHERITED(IDBDatabase, IDBWrapperCache)
   // Don't unlink mFactory!
 
   // Do some cleanup.
   tmp->OnUnlink();
 NS_IMPL_CYCLE_COLLECTION_UNLINK_END
 
 NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION_INHERITED(IDBDatabase)
-  NS_INTERFACE_MAP_ENTRY(nsIIDBDatabase)
   NS_INTERFACE_MAP_ENTRY(nsIFileStorage)
   NS_INTERFACE_MAP_ENTRY(nsIOfflineStorage)
-  NS_DOM_INTERFACE_MAP_ENTRY_CLASSINFO(IDBDatabase)
 NS_INTERFACE_MAP_END_INHERITING(IDBWrapperCache)
 
 NS_IMPL_ADDREF_INHERITED(IDBDatabase, IDBWrapperCache)
 NS_IMPL_RELEASE_INHERITED(IDBDatabase, IDBWrapperCache)
 
-DOMCI_DATA(IDBDatabase, IDBDatabase)
-
-NS_IMPL_EVENT_HANDLER(IDBDatabase, abort)
-NS_IMPL_EVENT_HANDLER(IDBDatabase, error)
-NS_IMPL_EVENT_HANDLER(IDBDatabase, versionchange)
-
-NS_IMETHODIMP
-IDBDatabase::GetName(nsAString& aName)
+JSObject*
+IDBDatabase::WrapObject(JSContext* aCx, JS::Handle<JSObject*> aScope)
 {
-  NS_ASSERTION(NS_IsMainThread(), "Wrong thread!");
-  aName.Assign(mName);
-  return NS_OK;
+  return IDBDatabaseBinding::Wrap(aCx, aScope, this);
 }
 
-NS_IMETHODIMP
-IDBDatabase::GetVersion(uint64_t* aVersion)
+uint64_t
+IDBDatabase::Version() const
 {
   NS_ASSERTION(NS_IsMainThread(), "Wrong thread!");
-
   DatabaseInfo* info = Info();
-  *aVersion = info->version;
-
-  return NS_OK;
+  return info->version;
 }
 
-NS_IMETHODIMP
-IDBDatabase::GetObjectStoreNames(nsIDOMDOMStringList** aObjectStores)
+already_AddRefed<nsIDOMDOMStringList>
+IDBDatabase::GetObjectStoreNames(ErrorResult& aRv) const
 {
   NS_ASSERTION(NS_IsMainThread(), "Wrong thread!");
 
   DatabaseInfo* info = Info();
 
   nsAutoTArray<nsString, 10> objectStoreNames;
   if (!info->GetObjectStoreNames(objectStoreNames)) {
     NS_WARNING("Couldn't get names!");
-    return NS_ERROR_DOM_INDEXEDDB_UNKNOWN_ERR;
+    aRv.Throw(NS_ERROR_DOM_INDEXEDDB_UNKNOWN_ERR);
+    return nullptr;
   }
 
   nsRefPtr<nsDOMStringList> list(new nsDOMStringList());
   uint32_t count = objectStoreNames.Length();
   for (uint32_t index = 0; index < count; index++) {
-    NS_ENSURE_TRUE(list->Add(objectStoreNames[index]),
-                   NS_ERROR_DOM_INDEXEDDB_UNKNOWN_ERR);
+    if (!list->Add(objectStoreNames[index])) {
+      NS_WARNING("Failed to add element");
+      aRv.Throw(NS_ERROR_DOM_INDEXEDDB_UNKNOWN_ERR);
+      return nullptr;
+    }
   }
 
-  list.forget(aObjectStores);
-  return NS_OK;
+  return list.forget();
 }
 
-NS_IMETHODIMP
-IDBDatabase::CreateObjectStore(const nsAString& aName,
-                               const jsval& aOptions,
-                               JSContext* aCx,
-                               nsIIDBObjectStore** _retval)
+already_AddRefed<IDBObjectStore>
+IDBDatabase::CreateObjectStore(
+                            JSContext* aCx, const nsAString& aName,
+                            const IDBObjectStoreParameters& aOptionalParameters,
+                            ErrorResult& aRv)
 {
   NS_ASSERTION(NS_IsMainThread(), "Wrong thread!");
 
   IDBTransaction* transaction = AsyncConnectionHelper::GetCurrentTransaction();
 
   if (!transaction ||
       transaction->GetMode() != IDBTransaction::VERSION_CHANGE) {
-    return NS_ERROR_DOM_INDEXEDDB_NOT_ALLOWED_ERR;
+    aRv.Throw(NS_ERROR_DOM_INDEXEDDB_NOT_ALLOWED_ERR);
+    return nullptr;
   }
 
   DatabaseInfo* databaseInfo = transaction->DBInfo();
 
-  RootedDictionary<IDBObjectStoreParameters> params(aCx);
-  JS::Rooted<JS::Value> options(aCx, aOptions);
-  if (!params.Init(aCx, options)) {
-    return NS_ERROR_DOM_INDEXEDDB_UNKNOWN_ERR;
-  }
-
   KeyPath keyPath(0);
-  if (NS_FAILED(KeyPath::Parse(aCx, params.mKeyPath, &keyPath))) {
-    return NS_ERROR_DOM_SYNTAX_ERR;
+  if (NS_FAILED(KeyPath::Parse(aCx, aOptionalParameters.mKeyPath, &keyPath))) {
+    aRv.Throw(NS_ERROR_DOM_SYNTAX_ERR);
+    return nullptr;
   }
 
   if (databaseInfo->ContainsStoreName(aName)) {
-    return NS_ERROR_DOM_INDEXEDDB_CONSTRAINT_ERR;
+    aRv.Throw(NS_ERROR_DOM_INDEXEDDB_CONSTRAINT_ERR);
+    return nullptr;
   }
 
-  if (!keyPath.IsAllowedForObjectStore(params.mAutoIncrement)) {
-    return NS_ERROR_DOM_INVALID_ACCESS_ERR;
+  if (!keyPath.IsAllowedForObjectStore(aOptionalParameters.mAutoIncrement)) {
+    aRv.Throw(NS_ERROR_DOM_INVALID_ACCESS_ERR);
+    return nullptr;
   }
 
   ObjectStoreInfoGuts guts;
 
   guts.name = aName;
   guts.id = databaseInfo->nextObjectStoreId++;
   guts.keyPath = keyPath;
-  guts.autoIncrement = params.mAutoIncrement;
+  guts.autoIncrement = aOptionalParameters.mAutoIncrement;
 
-  nsRefPtr<IDBObjectStore> objectStore;
-  nsresult rv = CreateObjectStoreInternal(transaction, guts,
-                                          getter_AddRefs(objectStore));
-  NS_ENSURE_SUCCESS(rv, rv);
-
-  objectStore.forget(_retval);
-  return NS_OK;
+  return CreateObjectStoreInternal(transaction, guts, aRv);
 }
 
-NS_IMETHODIMP
-IDBDatabase::DeleteObjectStore(const nsAString& aName)
+void
+IDBDatabase::DeleteObjectStore(const nsAString& aName, ErrorResult& aRv)
 {
   NS_ASSERTION(NS_IsMainThread(), "Wrong thread!");
 
   IDBTransaction* transaction = AsyncConnectionHelper::GetCurrentTransaction();
 
   if (!transaction ||
       transaction->GetMode() != IDBTransaction::VERSION_CHANGE) {
-    return NS_ERROR_DOM_INDEXEDDB_NOT_ALLOWED_ERR;
+    aRv.Throw(NS_ERROR_DOM_INDEXEDDB_NOT_ALLOWED_ERR);
+    return;
   }
 
   DatabaseInfo* info = transaction->DBInfo();
   ObjectStoreInfo* objectStoreInfo = info->GetObjectStore(aName);
   if (!objectStoreInfo) {
-    return NS_ERROR_DOM_INDEXEDDB_NOT_FOUND_ERR;
+    aRv.Throw(NS_ERROR_DOM_INDEXEDDB_NOT_FOUND_ERR);
+    return;
   }
 
-  nsresult rv;
-
   if (IndexedDatabaseManager::IsMainProcess()) {
     nsRefPtr<DeleteObjectStoreHelper> helper =
       new DeleteObjectStoreHelper(transaction, objectStoreInfo->id);
 
-    rv = helper->DispatchToTransactionPool();
-    NS_ENSURE_SUCCESS(rv, NS_ERROR_DOM_INDEXEDDB_UNKNOWN_ERR);
+    nsresult rv = helper->DispatchToTransactionPool();
+    if (NS_FAILED(rv)) {
+      NS_WARNING("Failed to dispatch!");
+      aRv.Throw(NS_ERROR_DOM_INDEXEDDB_UNKNOWN_ERR);
+      return;
+    }
   }
   else {
     IndexedDBTransactionChild* actor = transaction->GetActorChild();
     NS_ASSERTION(actor, "Must have an actor here!");
 
     actor->SendDeleteObjectStore(nsString(aName));
   }
 
   transaction->RemoveObjectStore(aName);
 
   IDB_PROFILER_MARK("IndexedDB Pseudo-request: "
                     "database(%s).transaction(%s).deleteObjectStore(\"%s\")",
                     "MT IDBDatabase.deleteObjectStore()",
                     IDB_PROFILER_STRING(this),
                     IDB_PROFILER_STRING(transaction),
                     NS_ConvertUTF16toUTF8(aName).get());
-
-  return NS_OK;
 }
 
-NS_IMETHODIMP
-IDBDatabase::Transaction(const jsval& aStoreNames,
-                         const nsAString& aMode,
-                         JSContext* aCx,
-                         uint8_t aOptionalArgCount,
-                         nsISupports** _retval)
+already_AddRefed<indexedDB::IDBTransaction>
+IDBDatabase::Transaction(const Sequence<nsString>& aStoreNames,
+                         IDBTransactionMode aMode, ErrorResult& aRv)
 {
   NS_ASSERTION(NS_IsMainThread(), "Wrong thread!");
 
   if (QuotaManager::IsShuttingDown()) {
-    return NS_ERROR_DOM_INDEXEDDB_UNKNOWN_ERR;
+    aRv.Throw(NS_ERROR_DOM_INDEXEDDB_UNKNOWN_ERR);
+    return nullptr;
   }
 
   if (mClosed) {
-    return NS_ERROR_DOM_INDEXEDDB_NOT_ALLOWED_ERR;
+    aRv.Throw(NS_ERROR_DOM_INDEXEDDB_NOT_ALLOWED_ERR);
+    return nullptr;
   }
 
   if (mRunningVersionChange) {
-    return NS_ERROR_DOM_INDEXEDDB_NOT_ALLOWED_ERR;
+    aRv.Throw(NS_ERROR_DOM_INDEXEDDB_NOT_ALLOWED_ERR);
+    return nullptr;
+  }
+
+  if (aStoreNames.IsEmpty()) {
+    aRv.Throw(NS_ERROR_DOM_INVALID_ACCESS_ERR);
+    return nullptr;
   }
 
   IDBTransaction::Mode transactionMode = IDBTransaction::READ_ONLY;
-  if (aOptionalArgCount) {
-    if (aMode.EqualsLiteral("readwrite")) {
+  switch (aMode) {
+    case IDBTransactionMode::Readonly:
+      transactionMode = IDBTransaction::READ_ONLY;
+      break;
+    case IDBTransactionMode::Readwrite:
       transactionMode = IDBTransaction::READ_WRITE;
-    }
-    else if (!aMode.EqualsLiteral("readonly")) {
-      return NS_ERROR_TYPE_ERR;
-    }
-  }
-
-  nsresult rv;
-  nsTArray<nsString> storesToOpen;
-
-  if (!JSVAL_IS_PRIMITIVE(aStoreNames)) {
-    JS::Rooted<JSObject*> obj(aCx, JSVAL_TO_OBJECT(aStoreNames));
-
-    // See if this is a JS array.
-    if (JS_IsArrayObject(aCx, obj)) {
-      uint32_t length;
-      if (!JS_GetArrayLength(aCx, obj, &length)) {
-        return NS_ERROR_DOM_INDEXEDDB_UNKNOWN_ERR;
-      }
-
-      if (!length) {
-        return NS_ERROR_DOM_INVALID_ACCESS_ERR;
-      }
-
-      storesToOpen.SetCapacity(length);
-
-      for (uint32_t index = 0; index < length; index++) {
-        JS::Rooted<JS::Value> val(aCx);
-        JSString* jsstr;
-        nsDependentJSString str;
-        if (!JS_GetElement(aCx, obj, index, val.address()) ||
-            !(jsstr = JS_ValueToString(aCx, val)) ||
-            !str.init(aCx, jsstr)) {
-          return NS_ERROR_DOM_INDEXEDDB_UNKNOWN_ERR;
-        }
-
-        storesToOpen.AppendElement(str);
-      }
-
-      NS_ASSERTION(!storesToOpen.IsEmpty(),
-                   "Must have something here or else code below will "
-                   "misbehave!");
-    }
-    else {
-      // Perhaps some kind of wrapped object?
-      nsIXPConnect* xpc = nsContentUtils::XPConnect();
-      NS_ASSERTION(xpc, "This should never be null!");
-
-      nsCOMPtr<nsIXPConnectWrappedNative> wrapper;
-      rv = xpc->GetWrappedNativeOfJSObject(aCx, obj, getter_AddRefs(wrapper));
-      NS_ENSURE_SUCCESS(rv, NS_ERROR_DOM_INDEXEDDB_UNKNOWN_ERR);
-
-      if (wrapper) {
-        nsISupports* wrappedObject = wrapper->Native();
-        NS_ENSURE_TRUE(wrappedObject, NS_ERROR_DOM_INDEXEDDB_UNKNOWN_ERR);
-
-        // We only accept DOMStringList.
-        nsCOMPtr<nsIDOMDOMStringList> list = do_QueryInterface(wrappedObject);
-        if (list) {
-          uint32_t length;
-          rv = list->GetLength(&length);
-          NS_ENSURE_SUCCESS(rv, NS_ERROR_DOM_INDEXEDDB_UNKNOWN_ERR);
-
-          if (!length) {
-            return NS_ERROR_DOM_INVALID_ACCESS_ERR;
-          }
-
-          storesToOpen.SetCapacity(length);
-
-          for (uint32_t index = 0; index < length; index++) {
-            nsString* item = storesToOpen.AppendElement();
-            NS_ASSERTION(item, "This should never fail!");
-
-            rv = list->Item(index, *item);
-            NS_ENSURE_SUCCESS(rv, NS_ERROR_DOM_INDEXEDDB_UNKNOWN_ERR);
-          }
-
-          NS_ASSERTION(!storesToOpen.IsEmpty(),
-                       "Must have something here or else code below will "
-                       "misbehave!");
-        }
-      }
-    }
-  }
-
-  // If our list is empty here then the argument must have been an object that
-  // we don't support or a primitive. Either way we convert to a string.
-  if (storesToOpen.IsEmpty()) {
-    JSString* jsstr;
-    nsDependentJSString str;
-    if (!(jsstr = JS_ValueToString(aCx, aStoreNames)) ||
-        !str.init(aCx, jsstr)) {
-      return NS_ERROR_DOM_INDEXEDDB_UNKNOWN_ERR;
-    }
-
-    storesToOpen.AppendElement(str);
+      break;
+    case IDBTransactionMode::Versionchange:
+      transactionMode = IDBTransaction::VERSION_CHANGE;
+      break;
+    default:
+      MOZ_CRASH("Unknown mode!");
   }
 
   // Now check to make sure the object store names we collected actually exist.
   DatabaseInfo* info = Info();
-  for (uint32_t index = 0; index < storesToOpen.Length(); index++) {
-    if (!info->ContainsStoreName(storesToOpen[index])) {
-      return NS_ERROR_DOM_INDEXEDDB_NOT_FOUND_ERR;
+  for (uint32_t index = 0; index < aStoreNames.Length(); index++) {
+    if (!info->ContainsStoreName(aStoreNames[index])) {
+      aRv.Throw(NS_ERROR_DOM_INDEXEDDB_NOT_FOUND_ERR);
+      return nullptr;
     }
   }
 
   nsRefPtr<IDBTransaction> transaction =
-    IDBTransaction::Create(this, storesToOpen, transactionMode, false);
-  NS_ENSURE_TRUE(transaction, NS_ERROR_DOM_INDEXEDDB_UNKNOWN_ERR);
+    IDBTransaction::Create(this, aStoreNames, transactionMode, false);
+  if (!transaction) {
+    NS_WARNING("Failed to create the transaction!");
+    aRv.Throw(NS_ERROR_DOM_INDEXEDDB_UNKNOWN_ERR);
+    return nullptr;
+  }
 
   IDB_PROFILER_MARK("IndexedDB Transaction %llu: database(%s).transaction(%s)",
                     "IDBTransaction[%llu] MT Started",
                     transaction->GetSerialNumber(), IDB_PROFILER_STRING(this),
                     IDB_PROFILER_STRING(transaction));
 
-  nsRefPtr<IDBWrapperCache> tmp = transaction.get();
-  tmp.forget(_retval);
-  return NS_OK;
+  return transaction.forget();
 }
 
-NS_IMETHODIMP
+already_AddRefed<IDBRequest>
 IDBDatabase::MozCreateFileHandle(const nsAString& aName,
-                                 const nsAString& aType,
-                                 JSContext* aCx,
-                                 nsIIDBRequest** _retval)
+                                 const Optional<nsAString>& aType,
+                                 ErrorResult& aRv)
 {
   NS_ASSERTION(NS_IsMainThread(), "Wrong thread!");
 
   if (!IndexedDatabaseManager::IsMainProcess()) {
     NS_WARNING("Not supported yet!");
-    return NS_ERROR_DOM_INDEXEDDB_UNKNOWN_ERR;
+    aRv.Throw(NS_ERROR_DOM_INDEXEDDB_UNKNOWN_ERR);
+    return nullptr;
   }
 
   if (QuotaManager::IsShuttingDown()) {
-    return NS_ERROR_DOM_INDEXEDDB_UNKNOWN_ERR;
+    aRv.Throw(NS_ERROR_DOM_INDEXEDDB_UNKNOWN_ERR);
+    return nullptr;
   }
 
   if (mClosed) {
-    return NS_ERROR_DOM_INDEXEDDB_NOT_ALLOWED_ERR;
+    aRv.Throw(NS_ERROR_DOM_INDEXEDDB_NOT_ALLOWED_ERR);
+    return nullptr;
   }
 
   nsRefPtr<IDBRequest> request = IDBRequest::Create(nullptr, this, nullptr);
 
   nsRefPtr<CreateFileHelper> helper =
-    new CreateFileHelper(this, request, aName, aType);
+    new CreateFileHelper(this, request, aName,
+                         aType.WasPassed() ? aType.Value() : EmptyString());
 
   QuotaManager* quotaManager = QuotaManager::Get();
   NS_ASSERTION(quotaManager, "We should definitely have a manager here");
 
   nsresult rv = helper->Dispatch(quotaManager->IOThread());
-  NS_ENSURE_SUCCESS(rv, NS_ERROR_DOM_INDEXEDDB_UNKNOWN_ERR);
+  if (NS_FAILED(rv)) {
+    NS_WARNING("Failed to dispatch!");
+    aRv.Throw(NS_ERROR_DOM_INDEXEDDB_UNKNOWN_ERR);
+    return nullptr;
+  }
 
-  request.forget(_retval);
-  return NS_OK;
+  return request.forget();
 }
 
 NS_IMETHODIMP
 IDBDatabase::Close()
 {
   NS_ASSERTION(NS_IsMainThread(), "Wrong thread!");
 
   CloseInternal(false);
 
   NS_ASSERTION(mClosed, "Should have set the closed flag!");
+
   return NS_OK;
 }
 
 NS_IMETHODIMP_(nsIAtom*)
 IDBDatabase::Id()
 {
   return mDatabaseId;
 }
--- a/dom/indexedDB/IDBDatabase.h
+++ b/dom/indexedDB/IDBDatabase.h
@@ -2,27 +2,29 @@
 /* vim: set ts=2 et sw=2 tw=80: */
 /* 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/. */
 
 #ifndef mozilla_dom_indexeddb_idbdatabase_h__
 #define mozilla_dom_indexeddb_idbdatabase_h__
 
-#include "mozilla/Attributes.h"
 #include "mozilla/dom/indexedDB/IndexedDatabase.h"
 
 #include "nsIDocument.h"
 #include "nsIFileStorage.h"
-#include "nsIIDBDatabase.h"
 #include "nsIOfflineStorage.h"
 
+#include "mozilla/Attributes.h"
+#include "mozilla/dom/IDBObjectStoreBinding.h"
+#include "mozilla/dom/IDBTransactionBinding.h"
 #include "nsDOMEventTargetHelper.h"
 
 #include "mozilla/dom/indexedDB/FileManager.h"
+#include "mozilla/dom/indexedDB/IDBRequest.h"
 #include "mozilla/dom/indexedDB/IDBWrapperCache.h"
 
 class nsIScriptContext;
 class nsPIDOMWindow;
 
 namespace mozilla {
 namespace dom {
 class ContentParent;
@@ -41,28 +43,26 @@ class IDBIndex;
 class IDBObjectStore;
 class IDBTransaction;
 class IndexedDatabaseManager;
 class IndexedDBDatabaseChild;
 class IndexedDBDatabaseParent;
 struct ObjectStoreInfoGuts;
 
 class IDBDatabase : public IDBWrapperCache,
-                    public nsIIDBDatabase,
                     public nsIOfflineStorage
 {
   friend class AsyncConnectionHelper;
   friend class IndexedDatabaseManager;
   friend class IndexedDBDatabaseChild;
 
 public:
   NS_DECL_ISUPPORTS_INHERITED
-  NS_DECL_NSIIDBDATABASE
   NS_DECL_NSIFILESTORAGE
-  NS_DECL_NSIOFFLINESTORAGE_NOCLOSE
+  NS_DECL_NSIOFFLINESTORAGE
 
   NS_DECL_CYCLE_COLLECTION_CLASS_INHERITED(IDBDatabase, IDBWrapperCache)
 
   static already_AddRefed<IDBDatabase>
   Create(IDBWrapperCache* aOwnerCache,
          IDBFactory* aFactory,
          already_AddRefed<DatabaseInfo> aDatabaseInfo,
          const nsACString& aASCIIOrigin,
@@ -151,20 +151,73 @@ public:
   }
 
   mozilla::dom::ContentParent*
   GetContentParent() const
   {
     return mContentParent;
   }
 
-  nsresult
+  already_AddRefed<IDBObjectStore>
   CreateObjectStoreInternal(IDBTransaction* aTransaction,
                             const ObjectStoreInfoGuts& aInfo,
-                            IDBObjectStore** _retval);
+                            ErrorResult& aRv);
+
+  // nsWrapperCache
+  virtual JSObject*
+  WrapObject(JSContext* aCx, JS::Handle<JSObject*> aScope) MOZ_OVERRIDE;
+
+  // WebIDL
+  nsPIDOMWindow*
+  GetParentObject() const
+  {
+    return GetOwner();
+  }
+
+  void
+  GetName(nsString& aName) const
+  {
+    NS_ASSERTION(NS_IsMainThread(), "Wrong thread!");
+    aName.Assign(mName);
+  }
+
+  uint64_t
+  Version() const;
+
+  already_AddRefed<nsIDOMDOMStringList>
+  GetObjectStoreNames(ErrorResult& aRv) const;
+
+  already_AddRefed<IDBObjectStore>
+  CreateObjectStore(JSContext* aCx, const nsAString& aName,
+                    const IDBObjectStoreParameters& aOptionalParameters,
+                    ErrorResult& aRv);
+
+  void
+  DeleteObjectStore(const nsAString& name, ErrorResult& aRv);
+
+  already_AddRefed<indexedDB::IDBTransaction>
+  Transaction(const nsAString& aStoreName, IDBTransactionMode aMode,
+              ErrorResult& aRv)
+  {
+    Sequence<nsString> list;
+    list.AppendElement(aStoreName);
+    return Transaction(list, aMode, aRv);
+  }
+
+  already_AddRefed<indexedDB::IDBTransaction>
+  Transaction(const Sequence<nsString>& aStoreNames, IDBTransactionMode aMode,
+              ErrorResult& aRv);
+
+  IMPL_EVENT_HANDLER(abort)
+  IMPL_EVENT_HANDLER(error)
+  IMPL_EVENT_HANDLER(versionchange)
+
+  already_AddRefed<IDBRequest>
+  MozCreateFileHandle(const nsAString& aName, const Optional<nsAString>& aType,
+                      ErrorResult& aRv);
 
   virtual void LastRelease() MOZ_OVERRIDE;
 private:
   IDBDatabase();
   ~IDBDatabase();
 
   void OnUnlink();
 
--- a/dom/indexedDB/IDBFileHandle.cpp
+++ b/dom/indexedDB/IDBFileHandle.cpp
@@ -101,17 +101,17 @@ IDBFileHandle::CreateFileObject(mozilla:
                                 uint32_t aFileSize)
 {
   nsCOMPtr<nsIDOMFile> file = new mozilla::dom::file::File(
     mName, mType, aFileSize, mFile, aLockedFile, mFileInfo);
 
   return file.forget();
 }
 
-nsIIDBDatabase*
+IDBDatabase*
 IDBFileHandle::Database()
 {
   NS_ASSERTION(NS_IsMainThread(), "Wrong thread!");
 
   IDBDatabase* database = static_cast<IDBDatabase*>(mFileStorage.get());
   MOZ_ASSERT(database);
 
   return database;
--- a/dom/indexedDB/IDBFileHandle.h
+++ b/dom/indexedDB/IDBFileHandle.h
@@ -7,19 +7,19 @@
 #ifndef mozilla_dom_indexeddb_idbfilehandle_h__
 #define mozilla_dom_indexeddb_idbfilehandle_h__
 
 #include "IndexedDatabase.h"
 
 #include "mozilla/dom/file/FileHandle.h"
 #include "mozilla/dom/indexedDB/FileInfo.h"
 
-class nsIIDBDatabase;
+BEGIN_INDEXEDDB_NAMESPACE
 
-BEGIN_INDEXEDDB_NAMESPACE
+class IDBDatabase;
 
 class IDBFileHandle : public mozilla::dom::file::FileHandle
 {
 public:
   virtual JSObject*
   WrapObject(JSContext* aCx, JS::Handle<JSObject*> aScope) MOZ_OVERRIDE;
 
   NS_IMETHOD_(int64_t)
@@ -40,17 +40,18 @@ public:
 
   virtual already_AddRefed<nsISupports>
   CreateStream(nsIFile* aFile, bool aReadOnly);
 
   virtual already_AddRefed<nsIDOMFile>
   CreateFileObject(mozilla::dom::file::LockedFile* aLockedFile,
                    uint32_t aFileSize);
 
-  nsIIDBDatabase* Database();
+  IDBDatabase*
+  Database();
 
 private:
   IDBFileHandle()
   { }
 
   ~IDBFileHandle()
   { }
 
--- a/dom/indexedDB/IDBIndex.cpp
+++ b/dom/indexedDB/IDBIndex.cpp
@@ -10,17 +10,16 @@
 
 #include "nsIIDBKeyRange.h"
 
 #include "mozilla/dom/ContentChild.h"
 #include "mozilla/dom/ContentParent.h"
 #include "mozilla/dom/ipc/Blob.h"
 #include "mozilla/storage.h"
 #include "nsContentUtils.h"
-#include "nsDOMClassInfoID.h"
 #include "nsEventDispatcher.h"
 #include "nsThreadUtils.h"
 #include "xpcpublic.h"
 
 #include "AsyncConnectionHelper.h"
 #include "DatabaseInfo.h"
 #include "IDBCursor.h"
 #include "IDBEvents.h"
@@ -32,16 +31,17 @@
 #include "ipc/IndexedDBChild.h"
 #include "ipc/IndexedDBParent.h"
 
 #include "IndexedDatabaseInlines.h"
 
 USING_INDEXEDDB_NAMESPACE
 using namespace mozilla::dom;
 using namespace mozilla::dom::indexedDB::ipc;
+using mozilla::ErrorResult;
 
 namespace {
 
 class IndexHelper : public AsyncConnectionHelper
 {
 public:
   IndexHelper(IDBTransaction* aTransaction,
               IDBRequest* aRequest,
@@ -401,16 +401,18 @@ IDBIndex::IDBIndex()
   mCachedKeyPath(JSVAL_VOID),
   mActorChild(nullptr),
   mActorParent(nullptr),
   mUnique(false),
   mMultiEntry(false),
   mRooted(false)
 {
   NS_ASSERTION(NS_IsMainThread(), "Wrong thread!");
+
+  SetIsDOMBinding();
 }
 
 IDBIndex::~IDBIndex()
 {
   NS_ASSERTION(NS_IsMainThread(), "Wrong thread!");
   NS_ASSERTION(!mActorParent, "Actor parent owns us, how can we be dying?!");
 
   if (mRooted) {
@@ -420,239 +422,274 @@ IDBIndex::~IDBIndex()
 
   if (mActorChild) {
     NS_ASSERTION(!IndexedDatabaseManager::IsMainProcess(), "Wrong process!");
     mActorChild->Send__delete__(mActorChild);
     NS_ASSERTION(!mActorChild, "Should have cleared in Send__delete__!");
   }
 }
 
-nsresult
-IDBIndex::GetInternal(IDBKeyRange* aKeyRange,
-                      JSContext* aCx,
-                      IDBRequest** _retval)
+already_AddRefed<IDBRequest>
+IDBIndex::GetInternal(IDBKeyRange* aKeyRange, ErrorResult& aRv)
 {
   NS_ASSERTION(NS_IsMainThread(), "Wrong thread!");
 
   IDBTransaction* transaction = mObjectStore->Transaction();
   if (!transaction->IsOpen()) {
-    return NS_ERROR_DOM_INDEXEDDB_TRANSACTION_INACTIVE_ERR;
+    aRv.Throw(NS_ERROR_DOM_INDEXEDDB_TRANSACTION_INACTIVE_ERR);
+    return nullptr;
   }
 
   nsRefPtr<IDBRequest> request = GenerateRequest(this);
-  NS_ENSURE_TRUE(request, NS_ERROR_DOM_INDEXEDDB_UNKNOWN_ERR);
+  if (!request) {
+    NS_WARNING("Failed to generate request!");
+    aRv.Throw(NS_ERROR_DOM_INDEXEDDB_UNKNOWN_ERR);
+    return nullptr;
+  }
 
   nsRefPtr<GetHelper> helper =
     new GetHelper(transaction, request, this, aKeyRange);
 
   nsresult rv = helper->DispatchToTransactionPool();
-  NS_ENSURE_SUCCESS(rv, NS_ERROR_DOM_INDEXEDDB_UNKNOWN_ERR);
+  if (NS_FAILED(rv)) {
+    NS_WARNING("Failed to dispatch!");
+    aRv.Throw(NS_ERROR_DOM_INDEXEDDB_UNKNOWN_ERR);
+    return nullptr;
+  }
 
   IDB_PROFILER_MARK("IndexedDB Request %llu: "
                     "database(%s).transaction(%s).objectStore(%s).index(%s)."
                     "get(%s)",
                     "IDBRequest[%llu] MT IDBIndex.get()",
                     request->GetSerialNumber(),
                     IDB_PROFILER_STRING(ObjectStore()->Transaction()->
                                         Database()),
                     IDB_PROFILER_STRING(ObjectStore()->Transaction()),
                     IDB_PROFILER_STRING(ObjectStore()),
                     IDB_PROFILER_STRING(this), IDB_PROFILER_STRING(aKeyRange));
 
-  request.forget(_retval);
-  return NS_OK;
+  return request.forget();
 }
 
-nsresult
-IDBIndex::GetKeyInternal(IDBKeyRange* aKeyRange,
-                         JSContext* aCx,
-                         IDBRequest** _retval)
+already_AddRefed<IDBRequest>
+IDBIndex::GetKeyInternal(IDBKeyRange* aKeyRange, ErrorResult& aRv)
 {
   NS_ASSERTION(NS_IsMainThread(), "Wrong thread!");
 
   IDBTransaction* transaction = mObjectStore->Transaction();
   if (!transaction->IsOpen()) {
-    return NS_ERROR_DOM_INDEXEDDB_TRANSACTION_INACTIVE_ERR;
+    aRv.Throw(NS_ERROR_DOM_INDEXEDDB_TRANSACTION_INACTIVE_ERR);
+    return nullptr;
   }
 
   nsRefPtr<IDBRequest> request = GenerateRequest(this);
-  NS_ENSURE_TRUE(request, NS_ERROR_DOM_INDEXEDDB_UNKNOWN_ERR);
+  if (!request) {
+    NS_WARNING("Failed to generate request!");
+    aRv.Throw(NS_ERROR_DOM_INDEXEDDB_UNKNOWN_ERR);
+    return nullptr;
+  }
 
   nsRefPtr<GetKeyHelper> helper =
     new GetKeyHelper(transaction, request, this, aKeyRange);
 
   nsresult rv = helper->DispatchToTransactionPool();
-  NS_ENSURE_SUCCESS(rv, NS_ERROR_DOM_INDEXEDDB_UNKNOWN_ERR);
+  if (NS_FAILED(rv)) {
+    NS_WARNING("Failed to dispatch!");
+    aRv.Throw(NS_ERROR_DOM_INDEXEDDB_UNKNOWN_ERR);
+    return nullptr;
+  }
 
   IDB_PROFILER_MARK("IndexedDB Request %llu: "
                     "database(%s).transaction(%s).objectStore(%s).index(%s)."
                     "getKey(%s)",
                     "IDBRequest[%llu] MT IDBIndex.getKey()",
                     request->GetSerialNumber(),
                     IDB_PROFILER_STRING(ObjectStore()->Transaction()->
                                         Database()),
                     IDB_PROFILER_STRING(ObjectStore()->Transaction()),
                     IDB_PROFILER_STRING(ObjectStore()),
                     IDB_PROFILER_STRING(this), IDB_PROFILER_STRING(aKeyRange));
 
-  request.forget(_retval);
-  return NS_OK;
+  return request.forget();
 }
 
-nsresult
-IDBIndex::GetAllInternal(IDBKeyRange* aKeyRange,
-                         uint32_t aLimit,
-                         JSContext* aCx,
-                         IDBRequest** _retval)
+already_AddRefed<IDBRequest>
+IDBIndex::GetAllInternal(IDBKeyRange* aKeyRange, uint32_t aLimit,
+                         ErrorResult& aRv)
 {
   NS_ASSERTION(NS_IsMainThread(), "Wrong thread!");
 
   IDBTransaction* transaction = mObjectStore->Transaction();
   if (!transaction->IsOpen()) {
-    return NS_ERROR_DOM_INDEXEDDB_TRANSACTION_INACTIVE_ERR;
+    aRv.Throw(NS_ERROR_DOM_INDEXEDDB_TRANSACTION_INACTIVE_ERR);
+    return nullptr;
   }
 
   nsRefPtr<IDBRequest> request = GenerateRequest(this);
-  NS_ENSURE_TRUE(request, NS_ERROR_DOM_INDEXEDDB_UNKNOWN_ERR);
+  if (!request) {
+    NS_WARNING("Failed to generate request!");
+    aRv.Throw(NS_ERROR_DOM_INDEXEDDB_UNKNOWN_ERR);
+    return nullptr;
+  }
 
   nsRefPtr<GetAllHelper> helper =
     new GetAllHelper(transaction, request, this, aKeyRange, aLimit);
 
   nsresult rv = helper->DispatchToTransactionPool();
-  NS_ENSURE_SUCCESS(rv, NS_ERROR_DOM_INDEXEDDB_UNKNOWN_ERR);
+  if (NS_FAILED(rv)) {
+    NS_WARNING("Failed to dispatch!");
+    aRv.Throw(NS_ERROR_DOM_INDEXEDDB_UNKNOWN_ERR);
+    return nullptr;
+  }
 
   IDB_PROFILER_MARK("IndexedDB Request %llu: "
                     "database(%s).transaction(%s).objectStore(%s).index(%s)."
                     "getAll(%s, %lu)",
                     "IDBRequest[%llu] MT IDBIndex.getAll()",
                     request->GetSerialNumber(),
                     IDB_PROFILER_STRING(ObjectStore()->Transaction()->
                                         Database()),
                     IDB_PROFILER_STRING(ObjectStore()->Transaction()),
                     IDB_PROFILER_STRING(ObjectStore()),
                     IDB_PROFILER_STRING(this),
                     IDB_PROFILER_STRING(aKeyRange), aLimit);
 
-  request.forget(_retval);
-  return NS_OK;
+  return request.forget();
 }
 
-nsresult
-IDBIndex::GetAllKeysInternal(IDBKeyRange* aKeyRange,
-                             uint32_t aLimit,
-                             JSContext* aCx,
-                             IDBRequest** _retval)
+already_AddRefed<IDBRequest>
+IDBIndex::GetAllKeysInternal(IDBKeyRange* aKeyRange, uint32_t aLimit,
+                             ErrorResult& aRv)
 {
   NS_ASSERTION(NS_IsMainThread(), "Wrong thread!");
 
   IDBTransaction* transaction = mObjectStore->Transaction();
   if (!transaction->IsOpen()) {
-    return NS_ERROR_DOM_INDEXEDDB_TRANSACTION_INACTIVE_ERR;
+    aRv.Throw(NS_ERROR_DOM_INDEXEDDB_TRANSACTION_INACTIVE_ERR);
   }
 
   nsRefPtr<IDBRequest> request = GenerateRequest(this);
-  NS_ENSURE_TRUE(request, NS_ERROR_DOM_INDEXEDDB_UNKNOWN_ERR);
+  if (!request) {
+    NS_WARNING("Failed to generate request!");
+    aRv.Throw(NS_ERROR_DOM_INDEXEDDB_UNKNOWN_ERR);
+    return nullptr;
+  }
 
   nsRefPtr<GetAllKeysHelper> helper =
     new GetAllKeysHelper(transaction, request, this, aKeyRange, aLimit);
 
   nsresult rv = helper->DispatchToTransactionPool();
-  NS_ENSURE_SUCCESS(rv, NS_ERROR_DOM_INDEXEDDB_UNKNOWN_ERR);
+  if (NS_FAILED(rv)) {
+    NS_WARNING("Failed to dispatch!");
+    aRv.Throw(NS_ERROR_DOM_INDEXEDDB_UNKNOWN_ERR);
+    return nullptr;
+  }
 
   IDB_PROFILER_MARK("IndexedDB Request %llu: "
                     "database(%s).transaction(%s).objectStore(%s).index(%s)."
                     "getAllKeys(%s, %lu)",
                     "IDBRequest[%llu] MT IDBIndex.getAllKeys()",
                     request->GetSerialNumber(),
                     IDB_PROFILER_STRING(ObjectStore()->Transaction()->
                                         Database()),
                     IDB_PROFILER_STRING(ObjectStore()->Transaction()),
                     IDB_PROFILER_STRING(ObjectStore()),
                     IDB_PROFILER_STRING(this), IDB_PROFILER_STRING(aKeyRange),
                     aLimit);
 
-  request.forget(_retval);
-  return NS_OK;
+  return request.forget();
 }
 
-nsresult
-IDBIndex::CountInternal(IDBKeyRange* aKeyRange,
-                        JSContext* aCx,
-                        IDBRequest** _retval)
+already_AddRefed<IDBRequest>
+IDBIndex::CountInternal(IDBKeyRange* aKeyRange, ErrorResult& aRv)
 {
   NS_ASSERTION(NS_IsMainThread(), "Wrong thread!");
 
   IDBTransaction* transaction = mObjectStore->Transaction();
   if (!transaction->IsOpen()) {
-    return NS_ERROR_DOM_INDEXEDDB_TRANSACTION_INACTIVE_ERR;
+    aRv.Throw(NS_ERROR_DOM_INDEXEDDB_TRANSACTION_INACTIVE_ERR);
+    return nullptr;
   }
 
   nsRefPtr<IDBRequest> request = GenerateRequest(this);
-  NS_ENSURE_TRUE(request, NS_ERROR_DOM_INDEXEDDB_UNKNOWN_ERR);
+  if (!request) {
+    NS_WARNING("Failed to generate request!");
+    aRv.Throw(NS_ERROR_DOM_INDEXEDDB_UNKNOWN_ERR);
+    return nullptr;
+  }
 
   nsRefPtr<CountHelper> helper =
     new CountHelper(transaction, request, this, aKeyRange);
 
   nsresult rv = helper->DispatchToTransactionPool();
-  NS_ENSURE_SUCCESS(rv, NS_ERROR_DOM_INDEXEDDB_UNKNOWN_ERR);
+  if (NS_FAILED(rv)) {
+    NS_WARNING("Failed to dispatch!");
+    aRv.Throw(NS_ERROR_DOM_INDEXEDDB_UNKNOWN_ERR);
+    return nullptr;
+  }
 
   IDB_PROFILER_MARK("IndexedDB Request %llu: "
                     "database(%s).transaction(%s).objectStore(%s).index(%s)."
                     "count(%s)",
                     "IDBRequest[%llu] MT IDBIndex.count()",
                     request->GetSerialNumber(),
                     IDB_PROFILER_STRING(ObjectStore()->Transaction()->
                                         Database()),
                     IDB_PROFILER_STRING(ObjectStore()->Transaction()),
                     IDB_PROFILER_STRING(ObjectStore()),
                     IDB_PROFILER_STRING(this), IDB_PROFILER_STRING(aKeyRange));
 
-  request.forget(_retval);
-  return NS_OK;
+  return request.forget();
 }
 
-nsresult
-IDBIndex::OpenKeyCursorInternal(IDBKeyRange* aKeyRange,
-                                size_t aDirection,
-                                JSContext* aCx,
-                                IDBRequest** _retval)
+already_AddRefed<IDBRequest>
+IDBIndex::OpenKeyCursorInternal(IDBKeyRange* aKeyRange, size_t aDirection,
+                                ErrorResult& aRv)
 {
   NS_ASSERTION(NS_IsMainThread(), "Wrong thread!");
 
   IDBTransaction* transaction = mObjectStore->Transaction();
   if (!transaction->IsOpen()) {
-    return NS_ERROR_DOM_INDEXEDDB_TRANSACTION_INACTIVE_ERR;
+    aRv.Throw(NS_ERROR_DOM_INDEXEDDB_TRANSACTION_INACTIVE_ERR);
+    return nullptr;
   }
 
   IDBCursor::Direction direction =
     static_cast<IDBCursor::Direction>(aDirection);
 
   nsRefPtr<IDBRequest> request = GenerateRequest(this);
-  NS_ENSURE_TRUE(request, NS_ERROR_DOM_INDEXEDDB_UNKNOWN_ERR);
+  if (!request) {
+    NS_WARNING("Failed to generate request!");
+    aRv.Throw(NS_ERROR_DOM_INDEXEDDB_UNKNOWN_ERR);
+    return nullptr;
+  }
 
   nsRefPtr<OpenKeyCursorHelper> helper =
     new OpenKeyCursorHelper(transaction, request, this, aKeyRange, direction);
 
   nsresult rv = helper->DispatchToTransactionPool();
-  NS_ENSURE_SUCCESS(rv, NS_ERROR_DOM_INDEXEDDB_UNKNOWN_ERR);
+  if (NS_FAILED(rv)) {
+    NS_WARNING("Failed to dispatch!");
+    aRv.Throw(NS_ERROR_DOM_INDEXEDDB_UNKNOWN_ERR);
+    return nullptr;
+  }
 
   IDB_PROFILER_MARK("IndexedDB Request %llu: "
                     "database(%s).transaction(%s).objectStore(%s).index(%s)."
                     "openKeyCursor(%s)",
                     "IDBRequest[%llu] MT IDBIndex.openKeyCursor()",
                     request->GetSerialNumber(),
                     IDB_PROFILER_STRING(ObjectStore()->Transaction()->
                                         Database()),
                     IDB_PROFILER_STRING(ObjectStore()->Transaction()),
                     IDB_PROFILER_STRING(ObjectStore()),
                     IDB_PROFILER_STRING(this), IDB_PROFILER_STRING(aKeyRange),
                     IDB_PROFILER_STRING(direction));
 
-  request.forget(_retval);
-  return NS_OK;
+  return request.forget();
 }
 
 nsresult
 IDBIndex::OpenCursorInternal(IDBKeyRange* aKeyRange,
                              size_t aDirection,
                              IDBRequest** _retval)
 {
   NS_ASSERTION(NS_IsMainThread(), "Wrong thread!");
@@ -746,345 +783,255 @@ IDBIndex::OpenCursorFromChildProcess(
 
   NS_ASSERTION(!cloneInfo.mCloneBuffer.data(), "Should have swapped!");
 
   cursor.forget(_retval);
   return NS_OK;
 }
 
 NS_IMPL_CYCLE_COLLECTION_TRACE_BEGIN(IDBIndex)
+  NS_IMPL_CYCLE_COLLECTION_TRACE_PRESERVED_WRAPPER
   NS_IMPL_CYCLE_COLLECTION_TRACE_JSVAL_MEMBER_CALLBACK(mCachedKeyPath)
 NS_IMPL_CYCLE_COLLECTION_TRACE_END
 
 NS_IMPL_CYCLE_COLLECTION_TRAVERSE_BEGIN(IDBIndex)
   NS_IMPL_CYCLE_COLLECTION_TRAVERSE_SCRIPT_OBJECTS
   NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mObjectStore)
 NS_IMPL_CYCLE_COLLECTION_TRAVERSE_END
 
 NS_IMPL_CYCLE_COLLECTION_UNLINK_BEGIN(IDBIndex)
+  NS_IMPL_CYCLE_COLLECTION_UNLINK_PRESERVED_WRAPPER
+
   // Don't unlink mObjectStore!
 
   tmp->mCachedKeyPath = JSVAL_VOID;
 
   if (tmp->mRooted) {
     NS_DROP_JS_OBJECTS(tmp, IDBIndex);
     tmp->mRooted = false;
   }
 NS_IMPL_CYCLE_COLLECTION_UNLINK_END
 
 NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION(IDBIndex)
-  NS_INTERFACE_MAP_ENTRY(nsIIDBIndex)
-  NS_DOM_INTERFACE_MAP_ENTRY_CLASSINFO(IDBIndex)
+  NS_WRAPPERCACHE_INTERFACE_MAP_ENTRY
   NS_INTERFACE_MAP_ENTRY(nsISupports)
 NS_INTERFACE_MAP_END
 
 NS_IMPL_CYCLE_COLLECTING_ADDREF(IDBIndex)
 NS_IMPL_CYCLE_COLLECTING_RELEASE(IDBIndex)
 
-DOMCI_DATA(IDBIndex, IDBIndex)
-
-NS_IMETHODIMP
-IDBIndex::GetName(nsAString& aName)
+JSObject*
+IDBIndex::WrapObject(JSContext* aCx, JS::Handle<JSObject*> aScope)
 {
-  NS_ASSERTION(NS_IsMainThread(), "Wrong thread!");
-
-  aName.Assign(mName);
-  return NS_OK;
+  return IDBIndexBinding::Wrap(aCx, aScope, this);
 }
 
-NS_IMETHODIMP
-IDBIndex::GetStoreName(nsAString& aStoreName)
-{
-  NS_ASSERTION(NS_IsMainThread(), "Wrong thread!");
-
-  return mObjectStore->GetName(aStoreName);
-}
-
-NS_IMETHODIMP
-IDBIndex::GetKeyPath(JSContext* aCx,
-                     jsval* aVal)
+JS::Value
+IDBIndex::GetKeyPath(JSContext* aCx, ErrorResult& aRv)
 {
   NS_ASSERTION(NS_IsMainThread(), "Wrong thread!");
 
   if (!JSVAL_IS_VOID(mCachedKeyPath)) {
-    *aVal = mCachedKeyPath;
-    return NS_OK;
+    return mCachedKeyPath;
   }
 
-  nsresult rv = GetKeyPath().ToJSVal(aCx, mCachedKeyPath);
-  NS_ENSURE_SUCCESS(rv, rv);
+  aRv = GetKeyPath().ToJSVal(aCx, mCachedKeyPath);
+  ENSURE_SUCCESS(aRv, JSVAL_VOID);
 
   if (JSVAL_IS_GCTHING(mCachedKeyPath)) {
     NS_HOLD_JS_OBJECTS(this, IDBIndex);
     mRooted = true;
   }
 
-  *aVal = mCachedKeyPath;
-  return NS_OK;
-}
-
-NS_IMETHODIMP
-IDBIndex::GetUnique(bool* aUnique)
-{
-  NS_ASSERTION(NS_IsMainThread(), "Wrong thread!");
-
-  *aUnique = mUnique;
-  return NS_OK;
+  return mCachedKeyPath;
 }
 
-NS_IMETHODIMP
-IDBIndex::GetMultiEntry(bool* aMultiEntry)
-{
-  NS_ASSERTION(NS_IsMainThread(), "Wrong thread!");
-
-  *aMultiEntry = mMultiEntry;
-  return NS_OK;
-}
-
-NS_IMETHODIMP
-IDBIndex::GetObjectStore(nsIIDBObjectStore** aObjectStore)
-{
-  NS_ASSERTION(NS_IsMainThread(), "Wrong thread!");
-
-  nsCOMPtr<nsIIDBObjectStore> objectStore(mObjectStore);
-  objectStore.forget(aObjectStore);
-  return NS_OK;
-}
-
-NS_IMETHODIMP
-IDBIndex::Get(const jsval& aKey,
-              JSContext* aCx,
-              nsIIDBRequest** _retval)
+already_AddRefed<IDBRequest>
+IDBIndex::Get(JSContext* aCx, JS::Handle<JS::Value> aKey, ErrorResult& aRv)
 {
   NS_ASSERTION(NS_IsMainThread(), "Wrong thread!");
 
   IDBTransaction* transaction = mObjectStore->Transaction();
   if (!transaction->IsOpen()) {
-    return NS_ERROR_DOM_INDEXEDDB_TRANSACTION_INACTIVE_ERR;
+    aRv.Throw(NS_ERROR_DOM_INDEXEDDB_TRANSACTION_INACTIVE_ERR);
+    return nullptr;
   }
 
   nsRefPtr<IDBKeyRange> keyRange;
-  nsresult rv = IDBKeyRange::FromJSVal(aCx, aKey, getter_AddRefs(keyRange));
-  NS_ENSURE_SUCCESS(rv, rv);
+  aRv = IDBKeyRange::FromJSVal(aCx, aKey, getter_AddRefs(keyRange));
+  ENSURE_SUCCESS(aRv, nullptr);
 
   if (!keyRange) {
-    // Must specify a key or keyRange for get().
-    return NS_ERROR_DOM_INDEXEDDB_DATA_ERR;
+    // Must specify a key or keyRange for getKey().
+    aRv.Throw(NS_ERROR_DOM_INDEXEDDB_DATA_ERR);
+    return nullptr;
   }
 
-  nsRefPtr<IDBRequest> request;
-  rv = GetInternal(keyRange, aCx, getter_AddRefs(request));
-  NS_ENSURE_SUCCESS(rv, rv);
-
-  request.forget(_retval);
-  return NS_OK;
+  return GetInternal(keyRange, aRv);
 }
 
-NS_IMETHODIMP
-IDBIndex::GetKey(const jsval& aKey,
-                 JSContext* aCx,
-                 nsIIDBRequest** _retval)
+already_AddRefed<IDBRequest>
+IDBIndex::GetKey(JSContext* aCx, JS::Handle<JS::Value> aKey, ErrorResult& aRv)
 {
   NS_ASSERTION(NS_IsMainThread(), "Wrong thread!");
 
   IDBTransaction* transaction = mObjectStore->Transaction();
   if (!transaction->IsOpen()) {
-    return NS_ERROR_DOM_INDEXEDDB_TRANSACTION_INACTIVE_ERR;
+    aRv.Throw(NS_ERROR_DOM_INDEXEDDB_TRANSACTION_INACTIVE_ERR);
+    return nullptr;
   }
 
   nsRefPtr<IDBKeyRange> keyRange;
-  nsresult rv = IDBKeyRange::FromJSVal(aCx, aKey, getter_AddRefs(keyRange));
-  NS_ENSURE_SUCCESS(rv, rv);
+  aRv = IDBKeyRange::FromJSVal(aCx, aKey, getter_AddRefs(keyRange));
+  ENSURE_SUCCESS(aRv, nullptr);
 
   if (!keyRange) {
     // Must specify a key or keyRange for get().
-    return NS_ERROR_DOM_INDEXEDDB_DATA_ERR;
+    aRv.Throw(NS_ERROR_DOM_INDEXEDDB_DATA_ERR);
+    return nullptr;
   }
 
-  nsRefPtr<IDBRequest> request;
-  rv = GetKeyInternal(keyRange, aCx, getter_AddRefs(request));
-  NS_ENSURE_SUCCESS(rv, rv);
-
-  request.forget(_retval);
-  return NS_OK;
+  return GetKeyInternal(keyRange, aRv);
 }
 
-NS_IMETHODIMP
-IDBIndex::GetAll(const jsval& aKey,
-                 uint32_t aLimit,
-                 JSContext* aCx,
-                 uint8_t aOptionalArgCount,
-                 nsIIDBRequest** _retval)
+already_AddRefed<IDBRequest>
+IDBIndex::GetAll(JSContext* aCx, const Optional<JS::Handle<JS::Value> >& aKey,
+                 const Optional<uint32_t>& aLimit, ErrorResult& aRv)
 {
   NS_ASSERTION(NS_IsMainThread(), "Wrong thread!");
 
   IDBTransaction* transaction = mObjectStore->Transaction();
   if (!transaction->IsOpen()) {
-    return NS_ERROR_DOM_INDEXEDDB_TRANSACTION_INACTIVE_ERR;
+    aRv.Throw(NS_ERROR_DOM_INDEXEDDB_TRANSACTION_INACTIVE_ERR);
+    return nullptr;
   }
 
-  nsresult rv;
-
   nsRefPtr<IDBKeyRange> keyRange;
-  if (aOptionalArgCount) {
-    rv = IDBKeyRange::FromJSVal(aCx, aKey, getter_AddRefs(keyRange));
-    NS_ENSURE_SUCCESS(rv, rv);
+  if (aKey.WasPassed()) {
+    aRv = IDBKeyRange::FromJSVal(aCx, aKey.Value(), getter_AddRefs(keyRange));
+    ENSURE_SUCCESS(aRv, nullptr);
   }
 
-  if (aOptionalArgCount < 2 || aLimit == 0) {
-    aLimit = UINT32_MAX;
+  uint32_t limit = UINT32_MAX;
+  if (aLimit.WasPassed() && aLimit.Value() > 0) {
+    limit = aLimit.Value();
   }
 
-  nsRefPtr<IDBRequest> request;
-  rv = GetAllInternal(keyRange, aLimit, aCx, getter_AddRefs(request));
-  NS_ENSURE_SUCCESS(rv, rv);
-
-  request.forget(_retval);
-  return NS_OK;
+  return GetAllInternal(keyRange, limit, aRv);
 }
 
-NS_IMETHODIMP
-IDBIndex::GetAllKeys(const jsval& aKey,
-                     uint32_t aLimit,
-                     JSContext* aCx,
-                     uint8_t aOptionalArgCount,
-                     nsIIDBRequest** _retval)
+already_AddRefed<IDBRequest>
+IDBIndex::GetAllKeys(JSContext* aCx,
+                     const Optional<JS::Handle<JS::Value> >& aKey,
+                     const Optional<uint32_t>& aLimit, ErrorResult& aRv)
 {
   NS_ASSERTION(NS_IsMainThread(), "Wrong thread!");
 
   IDBTransaction* transaction = mObjectStore->Transaction();
   if (!transaction->IsOpen()) {
-    return NS_ERROR_DOM_INDEXEDDB_TRANSACTION_INACTIVE_ERR;
+    aRv.Throw(NS_ERROR_DOM_INDEXEDDB_TRANSACTION_INACTIVE_ERR);
+    return nullptr;
   }
 
-  nsresult rv;
-
   nsRefPtr<IDBKeyRange> keyRange;
-  if (aOptionalArgCount) {
-    rv = IDBKeyRange::FromJSVal(aCx, aKey, getter_AddRefs(keyRange));
-    NS_ENSURE_SUCCESS(rv, rv);
+  if (aKey.WasPassed()) {
+    aRv = IDBKeyRange::FromJSVal(aCx, aKey.Value(), getter_AddRefs(keyRange));
+    ENSURE_SUCCESS(aRv, nullptr);
   }
 
-  if (aOptionalArgCount < 2 || aLimit == 0) {
-    aLimit = UINT32_MAX;
+  uint32_t limit = UINT32_MAX;
+  if (aLimit.WasPassed() && aLimit.Value() > 0) {
+    limit = aLimit.Value();
   }
 
-  nsRefPtr<IDBRequest> request;
-  rv = GetAllKeysInternal(keyRange, aLimit, aCx, getter_AddRefs(request));
-  NS_ENSURE_SUCCESS(rv, rv);
-
-  request.forget(_retval);
-  return NS_OK;
+  return GetAllKeysInternal(keyRange, limit, aRv);
 }
 
-NS_IMETHODIMP
-IDBIndex::OpenCursor(const jsval& aKey,
-                     const nsAString& aDirection,
-                     JSContext* aCx,
-                     uint8_t aOptionalArgCount,
-                     nsIIDBRequest** _retval)
+already_AddRefed<IDBRequest>
+IDBIndex::OpenCursor(JSContext* aCx,
+                     const Optional<JS::Handle<JS::Value> >& aRange,
+                     IDBCursorDirection aDirection, ErrorResult& aRv)
 {
   NS_ASSERTION(NS_IsMainThread(), "Wrong thread!");
 
   IDBTransaction* transaction = mObjectStore->Transaction();
   if (!transaction->IsOpen()) {
-    return NS_ERROR_DOM_INDEXEDDB_TRANSACTION_INACTIVE_ERR;
+    aRv.Throw(NS_ERROR_DOM_INDEXEDDB_TRANSACTION_INACTIVE_ERR);
+    return nullptr;
   }
 
-  nsresult rv;
-
-  IDBCursor::Direction direction = IDBCursor::NEXT;
-
   nsRefPtr<IDBKeyRange> keyRange;
-  if (aOptionalArgCount) {
-    rv = IDBKeyRange::FromJSVal(aCx, aKey, getter_AddRefs(keyRange));
-    NS_ENSURE_SUCCESS(rv, rv);
-
-    if (aOptionalArgCount >= 2) {
-      rv = IDBCursor::ParseDirection(aDirection, &direction);
-      NS_ENSURE_SUCCESS(rv, rv);
-    }
+  if (aRange.WasPassed()) {
+    aRv = IDBKeyRange::FromJSVal(aCx, aRange.Value(), getter_AddRefs(keyRange));
+    ENSURE_SUCCESS(aRv, nullptr);
   }
 
+  IDBCursor::Direction direction = IDBCursor::ConvertDirection(aDirection);
+
   nsRefPtr<IDBRequest> request = GenerateRequest(this);
-  NS_ENSURE_TRUE(request, NS_ERROR_DOM_INDEXEDDB_UNKNOWN_ERR);
+  if (!request) {
+    NS_WARNING("Failed to generate request!");
+    aRv.Throw(NS_ERROR_DOM_INDEXEDDB_UNKNOWN_ERR);
+    return nullptr;
+  }
 
   nsRefPtr<OpenCursorHelper> helper =
     new OpenCursorHelper(transaction, request, this, keyRange, direction);
 
-  rv = helper->DispatchToTransactionPool();
-  NS_ENSURE_SUCCESS(rv, NS_ERROR_DOM_INDEXEDDB_UNKNOWN_ERR);
-
-  request.forget(_retval);
-  return NS_OK;
+  nsresult rv = helper->DispatchToTransactionPool();
+  if (NS_FAILED(rv)) {
+    NS_WARNING("Failed to dispatch!");
+    aRv.Throw(NS_ERROR_DOM_INDEXEDDB_UNKNOWN_ERR);
+    return nullptr;
+  }
+
+  return request.forget();
 }
 
-NS_IMETHODIMP
-IDBIndex::OpenKeyCursor(const jsval& aKey,
-                        const nsAString& aDirection,
-                        JSContext* aCx,
-                        uint8_t aOptionalArgCount,
-                        nsIIDBRequest** _retval)
+already_AddRefed<IDBRequest>
+IDBIndex::OpenKeyCursor(JSContext* aCx,
+                        const Optional<JS::Handle<JS::Value> >& aRange,
+                        IDBCursorDirection aDirection, ErrorResult& aRv)
 {
   NS_ASSERTION(NS_IsMainThread(), "Wrong thread!");
 
   IDBTransaction* transaction = mObjectStore->Transaction();
   if (!transaction->IsOpen()) {
-    return NS_ERROR_DOM_INDEXEDDB_TRANSACTION_INACTIVE_ERR;
+    aRv.Throw(NS_ERROR_DOM_INDEXEDDB_TRANSACTION_INACTIVE_ERR);
+    return nullptr;
   }
 
-  nsresult rv;
-
-  IDBCursor::Direction direction = IDBCursor::NEXT;
-
   nsRefPtr<IDBKeyRange> keyRange;
-  if (aOptionalArgCount) {
-    rv = IDBKeyRange::FromJSVal(aCx, aKey, getter_AddRefs(keyRange));
-    NS_ENSURE_SUCCESS(rv, rv);
-
-    if (aOptionalArgCount >= 2) {
-      rv = IDBCursor::ParseDirection(aDirection, &direction);
-      NS_ENSURE_SUCCESS(rv, rv);
-    }
+  if (aRange.WasPassed()) {
+    aRv = IDBKeyRange::FromJSVal(aCx, aRange.Value(), getter_AddRefs(keyRange));
+    ENSURE_SUCCESS(aRv, nullptr);
   }
 
-  nsRefPtr<IDBRequest> request;
-  rv = OpenKeyCursorInternal(keyRange, direction, aCx,
-                             getter_AddRefs(request));
-  NS_ENSURE_SUCCESS(rv, rv);
-
-  request.forget(_retval);
-  return NS_OK;
+  IDBCursor::Direction direction = IDBCursor::ConvertDirection(aDirection);
+
+  return OpenKeyCursorInternal(keyRange, direction, aRv);
 }
 
-NS_IMETHODIMP
-IDBIndex::Count(const jsval& aKey,
-                JSContext* aCx,
-                uint8_t aOptionalArgCount,
-                nsIIDBRequest** _retval)
+already_AddRefed<IDBRequest>
+IDBIndex::Count(JSContext* aCx, const Optional<JS::Handle<JS::Value> >& aKey,
+                ErrorResult& aRv)
 {
   IDBTransaction* transaction = mObjectStore->Transaction();
   if (!transaction->IsOpen()) {
-    return NS_ERROR_DOM_INDEXEDDB_TRANSACTION_INACTIVE_ERR;
+    aRv.Throw(NS_ERROR_DOM_INDEXEDDB_TRANSACTION_INACTIVE_ERR);
+    return nullptr;
   }
 
-  nsresult rv;
-
   nsRefPtr<IDBKeyRange> keyRange;
-  if (aOptionalArgCount) {
-    rv = IDBKeyRange::FromJSVal(aCx, aKey, getter_AddRefs(keyRange));
-    NS_ENSURE_SUCCESS(rv, rv);
+  if (aKey.WasPassed()) {
+    aRv = IDBKeyRange::FromJSVal(aCx, aKey.Value(), getter_AddRefs(keyRange));
+    ENSURE_SUCCESS(aRv, nullptr);
   }
 
-  nsRefPtr<IDBRequest> request;
-  rv = CountInternal(keyRange, aCx, getter_AddRefs(request));
-  NS_ENSURE_SUCCESS(rv, rv);
-
-  request.forget(_retval);
-  return NS_OK;
+  return CountInternal(keyRange, aRv);
 }
 
 void
 IndexHelper::ReleaseMainThreadObjects()
 {
   mIndex = nullptr;
   AsyncConnectionHelper::ReleaseMainThreadObjects();
 }
--- a/dom/indexedDB/IDBIndex.h
+++ b/dom/indexedDB/IDBIndex.h
@@ -3,21 +3,26 @@
 /* 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/. */
 
 #ifndef mozilla_dom_indexeddb_idbindex_h__
 #define mozilla_dom_indexeddb_idbindex_h__
 
 #include "mozilla/dom/indexedDB/IndexedDatabase.h"
-#include "mozilla/dom/indexedDB/KeyPath.h"
 
-#include "nsIIDBIndex.h"
+#include "mozilla/Attributes.h"
+#include "mozilla/dom/IDBCursorBinding.h"
+#include "mozilla/ErrorResult.h"
+#include "nsCycleCollectionParticipant.h"
+#include "nsWrapperCache.h"
 
-#include "nsCycleCollectionParticipant.h"
+#include "mozilla/dom/indexedDB/IDBObjectStore.h"
+#include "mozilla/dom/indexedDB/IDBRequest.h"
+#include "mozilla/dom/indexedDB/KeyPath.h"
 
 class nsIScriptContext;
 class nsPIDOMWindow;
 
 BEGIN_INDEXEDDB_NAMESPACE
 
 class AsyncConnectionHelper;
 class IDBCursor;
@@ -25,22 +30,21 @@ class IDBKeyRange;
 class IDBObjectStore;
 class IDBRequest;
 class IndexedDBIndexChild;
 class IndexedDBIndexParent;
 class Key;
 
 struct IndexInfo;
 
-class IDBIndex MOZ_FINAL : public nsIIDBIndex
+class IDBIndex MOZ_FINAL : public nsISupports,
+                           public nsWrapperCache
 {
 public:
   NS_DECL_CYCLE_COLLECTING_ISUPPORTS
-  NS_DECL_NSIIDBINDEX
-
   NS_DECL_CYCLE_COLLECTION_SCRIPT_HOLDER_CLASS(IDBIndex)
 
   static already_AddRefed<IDBIndex>
   Create(IDBObjectStore* aObjectStore,
          const IndexInfo* aIndexInfo,
          bool aCreating);
 
   IDBObjectStore* ObjectStore()
@@ -95,63 +99,138 @@ public:
   }
 
   IndexedDBIndexParent*
   GetActorParent() const
   {
     return mActorParent;
   }
 
-  nsresult GetInternal(IDBKeyRange* aKeyRange,
-                       JSContext* aCx,
-                       IDBRequest** _retval);
+  already_AddRefed<IDBRequest>
+  GetInternal(IDBKeyRange* aKeyRange,
+              ErrorResult& aRv);
 
-  nsresult GetKeyInternal(IDBKeyRange* aKeyRange,
-                          JSContext* aCx,
-                          IDBRequest** _retval);
+  already_AddRefed<IDBRequest>
+  GetKeyInternal(IDBKeyRange* aKeyRange,
+                 ErrorResult& aRv);
 
-  nsresult GetAllInternal(IDBKeyRange* aKeyRange,
-                          uint32_t aLimit,
-                          JSContext* aCx,
-                          IDBRequest** _retval);
+  already_AddRefed<IDBRequest>
+  GetAllInternal(IDBKeyRange* aKeyRange,
+                 uint32_t aLimit,
+                 ErrorResult& aRv);
 
-  nsresult GetAllKeysInternal(IDBKeyRange* aKeyRange,
-                              uint32_t aLimit,
-                              JSContext* aCx,
-                              IDBRequest** _retval);
+  already_AddRefed<IDBRequest>
+  GetAllKeysInternal(IDBKeyRange* aKeyRange,
+                     uint32_t aLimit,
+                     ErrorResult& aRv);
 
-  nsresult CountInternal(IDBKeyRange* aKeyRange,
-                         JSContext* aCx,
-                         IDBRequest** _retval);
+  already_AddRefed<IDBRequest>
+  CountInternal(IDBKeyRange* aKeyRange,
+                ErrorResult& aRv);
 
   nsresult OpenCursorFromChildProcess(
                             IDBRequest* aRequest,
                             size_t aDirection,
                             const Key& aKey,
                             const Key& aObjectKey,
                             IDBCursor** _retval);
 
-  nsresult OpenKeyCursorInternal(IDBKeyRange* aKeyRange,
-                                 size_t aDirection,
-                                 JSContext* aCx,
-                                 IDBRequest** _retval);
+  already_AddRefed<IDBRequest>
+  OpenKeyCursorInternal(IDBKeyRange* aKeyRange,
+                        size_t aDirection,
+                        ErrorResult& aRv);
 
   nsresult OpenCursorInternal(IDBKeyRange* aKeyRange,
                               size_t aDirection,
                               IDBRequest** _retval);
 
   nsresult OpenCursorFromChildProcess(
                             IDBRequest* aRequest,
                             size_t aDirection,
                             const Key& aKey,
                             const Key& aObjectKey,
                             const SerializedStructuredCloneReadInfo& aCloneInfo,
                             nsTArray<StructuredCloneFile>& aBlobs,
                             IDBCursor** _retval);
 
+  // nsWrapperCache
+  virtual JSObject*
+  WrapObject(JSContext* aCx, JS::Handle<JSObject*> aScope) MOZ_OVERRIDE;
+
+  // WebIDL
+  IDBObjectStore*
+  GetParentObject() const
+  {
+    return mObjectStore;
+  }
+
+  void
+  GetName(nsString& aName) const
+  {
+    NS_ASSERTION(NS_IsMainThread(), "Wrong thread!");
+    aName.Assign(mName);
+  }
+
+  IDBObjectStore*
+  ObjectStore() const
+  {
+    NS_ASSERTION(NS_IsMainThread(), "Wrong thread!");
+    return mObjectStore;
+  }
+
+  JS::Value
+  GetKeyPath(JSContext* aCx, ErrorResult& aRv);
+
+  bool
+  MultiEntry() const
+  {
+    NS_ASSERTION(NS_IsMainThread(), "Wrong thread!");
+    return mMultiEntry;
+  }
+
+  bool
+  Unique() const
+  {
+    NS_ASSERTION(NS_IsMainThread(), "Wrong thread!");
+    return mUnique;
+  }
+
+  already_AddRefed<IDBRequest>
+  OpenCursor(JSContext* aCx, const Optional<JS::Handle<JS::Value> >& aRange,
+             IDBCursorDirection aDirection, ErrorResult& aRv);
+
+  already_AddRefed<IDBRequest>
+  OpenKeyCursor(JSContext* aCx, const Optional<JS::Handle<JS::Value> >& aRange,
+                IDBCursorDirection aDirection, ErrorResult& aRv);
+
+  already_AddRefed<IDBRequest>
+  Get(JSContext* aCx, JS::Handle<JS::Value> aKey, ErrorResult& aRv);
+
+  already_AddRefed<IDBRequest>
+  GetKey(JSContext* aCx, JS::Handle<JS::Value> aKey, ErrorResult& aRv);
+
+  already_AddRefed<IDBRequest>
+  Count(JSContext* aCx, const Optional<JS::Handle<JS::Value> >& aKey,
+         ErrorResult& aRv);
+
+  void
+  GetStoreName(nsString& aStoreName) const
+  {
+    NS_ASSERTION(NS_IsMainThread(), "Wrong thread!");
+    mObjectStore->GetName(aStoreName);
+  }
+
+  already_AddRefed<IDBRequest>
+  GetAll(JSContext* aCx, const Optional<JS::Handle<JS::Value> >& aKey,
+         const Optional<uint32_t>& aLimit, ErrorResult& aRv);
+
+  already_AddRefed<IDBRequest>
+  GetAllKeys(JSContext* aCx, const Optional<JS::Handle<JS::Value> >& aKey,
+             const Optional<uint32_t>& aLimit, ErrorResult& aRv);
+
 private:
   IDBIndex();
   ~IDBIndex();
 
   nsRefPtr<IDBObjectStore> mObjectStore;
 
   int64_t mId;
   nsString mName;
--- a/dom/indexedDB/IDBObjectStore.cpp
+++ b/dom/indexedDB/IDBObjectStore.cpp
@@ -47,16 +47,17 @@
 #include "IndexedDatabaseInlines.h"
 
 #define FILE_COPY_BUFFER_SIZE 32768
 
 USING_INDEXEDDB_NAMESPACE
 using namespace mozilla::dom;
 using namespace mozilla::dom::indexedDB::ipc;
 using mozilla::dom::quota::FileOutputStream;
+using mozilla::ErrorResult;
 
 BEGIN_INDEXEDDB_NAMESPACE
 
 struct FileHandleData
 {
   nsString type;
   nsString name;
 };
@@ -1725,16 +1726,18 @@ IDBObjectStore::IDBObjectStore()
   mKeyPath(0),
   mCachedKeyPath(JSVAL_VOID),
   mRooted(false),
   mAutoIncrement(false),
   mActorChild(nullptr),
   mActorParent(nullptr)
 {
   NS_ASSERTION(NS_IsMainThread(), "Wrong thread!");
+
+  SetIsDOMBinding();
 }
 
 IDBObjectStore::~IDBObjectStore()
 {
   NS_ASSERTION(NS_IsMainThread(), "Wrong thread!");
   NS_ASSERTION(!mActorParent, "Actor parent owns us, how can we be dying?!");
   if (mActorChild) {
     NS_ASSERTION(!IndexedDatabaseManager::IsMainProcess(), "Wrong process!");
@@ -1808,57 +1811,63 @@ IDBObjectStore::GetAddInfo(JSContext* aC
   }
   else {
     rv = GetAddInfoCallback(aCx, &data);
   }
 
   return rv;
 }
 
-nsresult
-IDBObjectStore::AddOrPut(const jsval& aValue,
-                         const jsval& aKey,
-                         JSContext* aCx,
-                         uint8_t aOptionalArgCount,
-                         bool aOverwrite,
-                         IDBRequest** _retval)
+already_AddRefed<IDBRequest>
+IDBObjectStore::AddOrPut(JSContext* aCx, JS::Handle<JS::Value> aValue,
+                         const Optional<JS::Handle<JS::Value> >& aKey,
+                         bool aOverwrite, ErrorResult& aRv)
 {
   NS_ASSERTION(NS_IsMainThread(), "Wrong thread!");
 
   if (!mTransaction->IsOpen()) {
-    return NS_ERROR_DOM_INDEXEDDB_TRANSACTION_INACTIVE_ERR;
+    aRv.Throw(NS_ERROR_DOM_INDEXEDDB_TRANSACTION_INACTIVE_ERR);
+    return nullptr;
   }
 
   if (!IsWriteAllowed()) {
-    return NS_ERROR_DOM_INDEXEDDB_READ_ONLY_ERR;
+    aRv.Throw(NS_ERROR_DOM_INDEXEDDB_READ_ONLY_ERR);
+    return nullptr;
   }
 
-  JS::Rooted<JS::Value> keyval(aCx,
-    (aOptionalArgCount >= 1) ? aKey : JSVAL_VOID);
+  JS::Rooted<JS::Value> keyval(aCx, aKey.WasPassed() ? aKey.Value()
+                                                     : JSVAL_VOID);
 
   StructuredCloneWriteInfo cloneWriteInfo;
   Key key;
   nsTArray<IndexUpdateInfo> updateInfo;
 
   JS::Rooted<JS::Value> value(aCx, aValue);
-  nsresult rv = GetAddInfo(aCx, value, keyval, cloneWriteInfo, key,
-                           updateInfo);
-  if (NS_FAILED(rv)) {
-    return rv;
+  aRv = GetAddInfo(aCx, value, keyval, cloneWriteInfo, key, updateInfo);
+  if (aRv.Failed()) {
+    return nullptr;
   }
 
   nsRefPtr<IDBRequest> request = GenerateRequest(this);
-  NS_ENSURE_TRUE(request, NS_ERROR_DOM_INDEXEDDB_UNKNOWN_ERR);
+  if (!request) {
+    NS_WARNING("Failed to generate request!");
+    aRv.Throw(NS_ERROR_DOM_INDEXEDDB_UNKNOWN_ERR);
+    return nullptr;
+  }
 
   nsRefPtr<AddHelper> helper =
     new AddHelper(mTransaction, request, this, cloneWriteInfo, key,
                   aOverwrite, updateInfo);
 
-  rv = helper->DispatchToTransactionPool();
-  NS_ENSURE_SUCCESS(rv, NS_ERROR_DOM_INDEXEDDB_UNKNOWN_ERR);
+  nsresult rv = helper->DispatchToTransactionPool();
+  if (NS_FAILED(rv)) {
+    NS_WARNING("Failed to dispatch!");
+    aRv.Throw(NS_ERROR_DOM_INDEXEDDB_UNKNOWN_ERR);
+    return nullptr;
+  }
 
 #ifdef IDB_PROFILER_USE_MARKS
   if (aOverwrite) {
     IDB_PROFILER_MARK("IndexedDB Request %llu: "
                       "database(%s).transaction(%s).objectStore(%s).%s(%s)",
                       "IDBRequest[%llu] MT IDBObjectStore.put()",
                       request->GetSerialNumber(),
                       IDB_PROFILER_STRING(Transaction()->Database()),
@@ -1873,18 +1882,17 @@ IDBObjectStore::AddOrPut(const jsval& aV
                       request->GetSerialNumber(),
                       IDB_PROFILER_STRING(Transaction()->Database()),
                       IDB_PROFILER_STRING(Transaction()),
                       IDB_PROFILER_STRING(this),
                       key.IsUnset() ? "" : IDB_PROFILER_STRING(key));
   }
 #endif
 
-  request.forget(_retval);
-  return NS_OK;
+  return request.forget();
 }
 
 nsresult
 IDBObjectStore::AddOrPutInternal(
                       const SerializedStructuredCloneWriteInfo& aCloneWriteInfo,
                       const Key& aKey,
                       const InfallibleTArray<IndexUpdateInfo>& aUpdateInfoArray,
                       const nsTArray<nsCOMPtr<nsIDOMBlob> >& aBlobs,
@@ -1986,222 +1994,262 @@ IDBObjectStore::AddOrPutInternal(
                       key.IsUnset() ? "" : IDB_PROFILER_STRING(key));
   }
 #endif
 
   request.forget(_retval);
   return NS_OK;
 }
 
-nsresult
-IDBObjectStore::GetInternal(IDBKeyRange* aKeyRange,
-                            JSContext* aCx,
-                            IDBRequest** _retval)
+already_AddRefed<IDBRequest>
+IDBObjectStore::GetInternal(IDBKeyRange* aKeyRange, ErrorResult& aRv)
 {
   NS_ASSERTION(NS_IsMainThread(), "Wrong thread!");
   NS_ASSERTION(aKeyRange, "Null pointer!");
 
   if (!mTransaction->IsOpen()) {
-    return NS_ERROR_DOM_INDEXEDDB_TRANSACTION_INACTIVE_ERR;
+    aRv.Throw(NS_ERROR_DOM_INDEXEDDB_TRANSACTION_INACTIVE_ERR);
+    return nullptr;
   }
 
   nsRefPtr<IDBRequest> request = GenerateRequest(this);
-  NS_ENSURE_TRUE(request, NS_ERROR_DOM_INDEXEDDB_UNKNOWN_ERR);
+  if (!request) {
+    NS_WARNING("Failed to generate request!");
+    aRv.Throw(NS_ERROR_DOM_INDEXEDDB_UNKNOWN_ERR);
+    return nullptr;
+  }
 
   nsRefPtr<GetHelper> helper =
     new GetHelper(mTransaction, request, this, aKeyRange);
 
   nsresult rv = helper->DispatchToTransactionPool();
-  NS_ENSURE_SUCCESS(rv, NS_ERROR_DOM_INDEXEDDB_UNKNOWN_ERR);
+  if (NS_FAILED(rv)) {
+    NS_WARNING("Failed to dispatch!");
+    aRv.Throw(NS_ERROR_DOM_INDEXEDDB_UNKNOWN_ERR);
+    return nullptr;
+  }
 
   IDB_PROFILER_MARK("IndexedDB Request %llu: "
                     "database(%s).transaction(%s).objectStore(%s).get(%s)",
                     "IDBRequest[%llu] MT IDBObjectStore.get()",
                     request->GetSerialNumber(),
                     IDB_PROFILER_STRING(Transaction()->Database()),
                     IDB_PROFILER_STRING(Transaction()),
                     IDB_PROFILER_STRING(this), IDB_PROFILER_STRING(aKeyRange));
 
-  request.forget(_retval);
-  return NS_OK;
+  return request.forget();
 }
 
-nsresult
+already_AddRefed<IDBRequest>
 IDBObjectStore::GetAllInternal(IDBKeyRange* aKeyRange,
-                               uint32_t aLimit,
-                               JSContext* aCx,
-                               IDBRequest** _retval)
+                               uint32_t aLimit, ErrorResult& aRv)
 {
   NS_ASSERTION(NS_IsMainThread(), "Wrong thread!");
 
   if (!mTransaction->IsOpen()) {
-    return NS_ERROR_DOM_INDEXEDDB_TRANSACTION_INACTIVE_ERR;
+    aRv.Throw(NS_ERROR_DOM_INDEXEDDB_TRANSACTION_INACTIVE_ERR);
+    return nullptr;
   }
 
   nsRefPtr<IDBRequest> request = GenerateRequest(this);
-  NS_ENSURE_TRUE(request, NS_ERROR_DOM_INDEXEDDB_UNKNOWN_ERR);
+  if (!request) {
+    NS_WARNING("Failed to generate request!");
+    aRv.Throw(NS_ERROR_DOM_INDEXEDDB_UNKNOWN_ERR);
+    return nullptr;
+  }
 
   nsRefPtr<GetAllHelper> helper =
     new GetAllHelper(mTransaction, request, this, aKeyRange, aLimit);
 
   nsresult rv = helper->DispatchToTransactionPool();
-  NS_ENSURE_SUCCESS(rv, NS_ERROR_DOM_INDEXEDDB_UNKNOWN_ERR);
+  if (NS_FAILED(rv)) {
+    NS_WARNING("Failed to dispatch!");
+    aRv.Throw(NS_ERROR_DOM_INDEXEDDB_UNKNOWN_ERR);
+    return nullptr;
+  }
 
   IDB_PROFILER_MARK("IndexedDB Request %llu: "
                     "database(%s).transaction(%s).objectStore(%s)."
                     "getAll(%s, %lu)",
                     "IDBRequest[%llu] MT IDBObjectStore.getAll()",
                     request->GetSerialNumber(),
                     IDB_PROFILER_STRING(Transaction()->Database()),
                     IDB_PROFILER_STRING(Transaction()),
                     IDB_PROFILER_STRING(this), IDB_PROFILER_STRING(aKeyRange),
                     aLimit);
 
-  request.forget(_retval);
-  return NS_OK;
+  return request.forget();
 }
 
-nsresult
+already_AddRefed<IDBRequest>
 IDBObjectStore::DeleteInternal(IDBKeyRange* aKeyRange,
-                               JSContext* aCx,
-                               IDBRequest** _retval)
+                               ErrorResult& aRv)
 {
   NS_ASSERTION(NS_IsMainThread(), "Wrong thread!");
   NS_ASSERTION(aKeyRange, "Null key range!");
 
   if (!mTransaction->IsOpen()) {
-    return NS_ERROR_DOM_INDEXEDDB_TRANSACTION_INACTIVE_ERR;
+    aRv.Throw(NS_ERROR_DOM_INDEXEDDB_TRANSACTION_INACTIVE_ERR);
+    return nullptr;
   }
 
   if (!IsWriteAllowed()) {
-    return NS_ERROR_DOM_INDEXEDDB_READ_ONLY_ERR;
+    aRv.Throw(NS_ERROR_DOM_INDEXEDDB_READ_ONLY_ERR);
+    return nullptr;
   }
 
   nsRefPtr<IDBRequest> request = GenerateRequest(this);
-  NS_ENSURE_TRUE(request, NS_ERROR_DOM_INDEXEDDB_UNKNOWN_ERR);
+  if (!request) {
+    NS_WARNING("Failed to generate request!");
+    aRv.Throw(NS_ERROR_DOM_INDEXEDDB_UNKNOWN_ERR);
+    return nullptr;
+  }
 
   nsRefPtr<DeleteHelper> helper =
     new DeleteHelper(mTransaction, request, this, aKeyRange);
 
   nsresult rv = helper->DispatchToTransactionPool();
-  NS_ENSURE_SUCCESS(rv, NS_ERROR_DOM_INDEXEDDB_UNKNOWN_ERR);
+  if (NS_FAILED(rv)) {
+    NS_WARNING("Failed to dispatch!");
+    aRv.Throw(NS_ERROR_DOM_INDEXEDDB_UNKNOWN_ERR);
+    return nullptr;
+  }
 
   IDB_PROFILER_MARK("IndexedDB Request %llu: "
                     "database(%s).transaction(%s).objectStore(%s).delete(%s)",
                     "IDBRequest[%llu] MT IDBObjectStore.delete()",
                     request->GetSerialNumber(),
                     IDB_PROFILER_STRING(Transaction()->Database()),
                     IDB_PROFILER_STRING(Transaction()),
                     IDB_PROFILER_STRING(this), IDB_PROFILER_STRING(aKeyRange));
 
-  request.forget(_retval);
-  return NS_OK;
+  return request.forget();
 }
 
-nsresult
-IDBObjectStore::ClearInternal(JSContext* aCx,
-                              IDBRequest** _retval)
+already_AddRefed<IDBRequest>
+IDBObjectStore::Clear(ErrorResult& aRv)
 {
   NS_ASSERTION(NS_IsMainThread(), "Wrong thread!");
 
   if (!mTransaction->IsOpen()) {
-    return NS_ERROR_DOM_INDEXEDDB_TRANSACTION_INACTIVE_ERR;
+    aRv.Throw(NS_ERROR_DOM_INDEXEDDB_TRANSACTION_INACTIVE_ERR);
+    return nullptr;
   }
 
   if (!IsWriteAllowed()) {
-    return NS_ERROR_DOM_INDEXEDDB_READ_ONLY_ERR;
+    aRv.Throw(NS_ERROR_DOM_INDEXEDDB_READ_ONLY_ERR);
+    return nullptr;
   }
 
   nsRefPtr<IDBRequest> request = GenerateRequest(this);
-  NS_ENSURE_TRUE(request, NS_ERROR_DOM_INDEXEDDB_UNKNOWN_ERR);
+  if (!request) {
+    NS_WARNING("Failed to generate request!");
+    aRv.Throw(NS_ERROR_DOM_INDEXEDDB_UNKNOWN_ERR);
+    return nullptr;
+  }
 
   nsRefPtr<ClearHelper> helper(new ClearHelper(mTransaction, request, this));
 
   nsresult rv = helper->DispatchToTransactionPool();
-  NS_ENSURE_SUCCESS(rv, NS_ERROR_DOM_INDEXEDDB_UNKNOWN_ERR);
+  if (NS_FAILED(rv)) {
+    NS_WARNING("Failed to dispatch!");
+    aRv.Throw(NS_ERROR_DOM_INDEXEDDB_UNKNOWN_ERR);
+    return nullptr;
+  }
 
   IDB_PROFILER_MARK("IndexedDB Request %llu: "
                     "database(%s).transaction(%s).objectStore(%s).clear()",
                     "IDBRequest[%llu] MT IDBObjectStore.clear()",
                     request->GetSerialNumber(),
                     IDB_PROFILER_STRING(Transaction()->Database()),
                     IDB_PROFILER_STRING(Transaction()),
                     IDB_PROFILER_STRING(this));
 
-  request.forget(_retval);
-  return NS_OK;
+  return request.forget();
 }
 
-nsresult
-IDBObjectStore::CountInternal(IDBKeyRange* aKeyRange,
-                              JSContext* aCx,
-                              IDBRequest** _retval)
+already_AddRefed<IDBRequest>
+IDBObjectStore::CountInternal(IDBKeyRange* aKeyRange, ErrorResult& aRv)
 {
   NS_ASSERTION(NS_IsMainThread(), "Wrong thread!");
 
   if (!mTransaction->IsOpen()) {
-    return NS_ERROR_DOM_INDEXEDDB_TRANSACTION_INACTIVE_ERR;
+    aRv.Throw(NS_ERROR_DOM_INDEXEDDB_TRANSACTION_INACTIVE_ERR);
+    return nullptr;
   }
 
   nsRefPtr<IDBRequest> request = GenerateRequest(this);
-  NS_ENSURE_TRUE(request, NS_ERROR_DOM_INDEXEDDB_UNKNOWN_ERR);
+  if (!request) {
+    NS_WARNING("Failed to generate request!");
+    aRv.Throw(NS_ERROR_DOM_INDEXEDDB_UNKNOWN_ERR);
+    return nullptr;
+  }
 
   nsRefPtr<CountHelper> helper =
     new CountHelper(mTransaction, request, this, aKeyRange);
   nsresult rv = helper->DispatchToTransactionPool();
-  NS_ENSURE_SUCCESS(rv, NS_ERROR_DOM_INDEXEDDB_UNKNOWN_ERR);
+  if (NS_FAILED(rv)) {
+    NS_WARNING("Failed to dispatch!");
+    aRv.Throw(NS_ERROR_DOM_INDEXEDDB_UNKNOWN_ERR);
+    return nullptr;
+  }
 
   IDB_PROFILER_MARK("IndexedDB Request %llu: "
                     "database(%s).transaction(%s).objectStore(%s).count(%s)",
                     "IDBRequest[%llu] MT IDBObjectStore.count()",
                     request->GetSerialNumber(),
                     IDB_PROFILER_STRING(Transaction()->Database()),
                     IDB_PROFILER_STRING(Transaction()),
                     IDB_PROFILER_STRING(this), IDB_PROFILER_STRING(aKeyRange));
 
-  request.forget(_retval);
-  return NS_OK;
+  return request.forget();
 }
 
-nsresult
+already_AddRefed<IDBRequest>
 IDBObjectStore::OpenCursorInternal(IDBKeyRange* aKeyRange,
-                                   size_t aDirection,
-                                   JSContext* aCx,
-                                   IDBRequest** _retval)
+                                   size_t aDirection, ErrorResult& aRv)
 {
   NS_ASSERTION(NS_IsMainThread(), "Wrong thread!");
 
   if (!mTransaction->IsOpen()) {
-    return NS_ERROR_DOM_INDEXEDDB_TRANSACTION_INACTIVE_ERR;
+    aRv.Throw(NS_ERROR_DOM_INDEXEDDB_TRANSACTION_INACTIVE_ERR);
+    return nullptr;
   }
 
   IDBCursor::Direction direction =
     static_cast<IDBCursor::Direction>(aDirection);
 
   nsRefPtr<IDBRequest> request = GenerateRequest(this);
-  NS_ENSURE_TRUE(request, NS_ERROR_DOM_INDEXEDDB_UNKNOWN_ERR);
+  if (!request) {
+    NS_WARNING("Failed to generate request!");
+    aRv.Throw(NS_ERROR_DOM_INDEXEDDB_UNKNOWN_ERR);
+    return nullptr;
+  }
 
   nsRefPtr<OpenCursorHelper> helper =
     new OpenCursorHelper(mTransaction, request, this, aKeyRange, direction);
 
   nsresult rv = helper->DispatchToTransactionPool();
-  NS_ENSURE_SUCCESS(rv, NS_ERROR_DOM_INDEXEDDB_UNKNOWN_ERR);
+  if (NS_FAILED(rv)) {
+    NS_WARNING("Failed to dispatch!");
+    aRv.Throw(NS_ERROR_DOM_INDEXEDDB_UNKNOWN_ERR);
+    return nullptr;
+  }
 
   IDB_PROFILER_MARK("IndexedDB Request %llu: "
                     "database(%s).transaction(%s).objectStore(%s)."
                     "openCursor(%s, %s)",
                     "IDBRequest[%llu] MT IDBObjectStore.openCursor()",
                     request->GetSerialNumber(),
                     IDB_PROFILER_STRING(Transaction()->Database()),
                     IDB_PROFILER_STRING(Transaction()),
                     IDB_PROFILER_STRING(this), IDB_PROFILER_STRING(aKeyRange),
                     IDB_PROFILER_STRING(direction));
 
-  request.forget(_retval);
-  return NS_OK;
+  return request.forget();
 }
 
 nsresult
 IDBObjectStore::OpenCursorFromChildProcess(
                             IDBRequest* aRequest,
                             size_t aDirection,
                             const Key& aKey,
                             const SerializedStructuredCloneReadInfo& aCloneInfo,
@@ -2240,19 +2288,18 @@ void
 IDBObjectStore::SetInfo(ObjectStoreInfo* aInfo)
 {
   NS_ASSERTION(NS_IsMainThread(), "Wrong thread");
   NS_ASSERTION(aInfo != mInfo, "This is nonsense");
 
   mInfo = aInfo;
 }
 
-nsresult
-IDBObjectStore::CreateIndexInternal(const IndexInfo& aInfo,
-                                    IDBIndex** _retval)
+already_AddRefed<IDBIndex>
+IDBObjectStore::CreateIndexInternal(const IndexInfo& aInfo, ErrorResult& aRv)
 {
   NS_ASSERTION(NS_IsMainThread(), "Wrong thread!");
 
   IndexInfo* indexInfo = mInfo->indexes.AppendElement();
 
   indexInfo->name = aInfo.name;
   indexInfo->id = aInfo.id;
   indexInfo->keyPath = aInfo.keyPath;
@@ -2266,521 +2313,416 @@ IDBObjectStore::CreateIndexInternal(cons
 
   mCreatedIndexes.AppendElement(index);
 
   if (IndexedDatabaseManager::IsMainProcess()) {
     nsRefPtr<CreateIndexHelper> helper =
       new CreateIndexHelper(mTransaction, index);
 
     nsresult rv = helper->DispatchToTransactionPool();
-    NS_ENSURE_SUCCESS(rv, NS_ERROR_DOM_INDEXEDDB_UNKNOWN_ERR);
+    if (NS_FAILED(rv)) {
+      NS_WARNING("Failed to dispatch!");
+      aRv.Throw(NS_ERROR_DOM_INDEXEDDB_UNKNOWN_ERR);
+      return nullptr;
+    }
   }
 
   autoRemove.forget();
 
   IDB_PROFILER_MARK("IndexedDB Pseudo-request: "
                     "database(%s).transaction(%s).objectStore(%s)."
                     "createIndex(%s)",
                     "MT IDBObjectStore.createIndex()",
                     IDB_PROFILER_STRING(Transaction()->Database()),
                     IDB_PROFILER_STRING(Transaction()),
                     IDB_PROFILER_STRING(this), IDB_PROFILER_STRING(index));
 
-  index.forget(_retval);
-  return NS_OK;
+  return index.forget();
 }
 
-nsresult
-IDBObjectStore::IndexInternal(const nsAString& aName,
-                              IDBIndex** _retval)
+already_AddRefed<IDBIndex>
+IDBObjectStore::Index(const nsAString& aName, ErrorResult &aRv)
 {
   NS_ASSERTION(NS_IsMainThread(), "Wrong thread!");
 
   if (mTransaction->IsFinished()) {
-    return NS_ERROR_DOM_INDEXEDDB_TRANSACTION_INACTIVE_ERR;
+    aRv.Throw(NS_ERROR_DOM_INDEXEDDB_TRANSACTION_INACTIVE_ERR);
+    return nullptr;
   }
 
   IndexInfo* indexInfo = nullptr;
   uint32_t indexCount = mInfo->indexes.Length();
   for (uint32_t index = 0; index < indexCount; index++) {
     if (mInfo->indexes[index].name == aName) {
       indexInfo = &(mInfo->indexes[index]);
       break;
     }
   }
 
   if (!indexInfo) {
-    return NS_ERROR_DOM_INDEXEDDB_NOT_FOUND_ERR;
+    aRv.Throw(NS_ERROR_DOM_INDEXEDDB_NOT_FOUND_ERR);
+    return nullptr;
   }
 
   nsRefPtr<IDBIndex> retval;
   for (uint32_t i = 0; i < mCreatedIndexes.Length(); i++) {
     nsRefPtr<IDBIndex>& index = mCreatedIndexes[i];
     if (index->Name() == aName) {
       retval = index;
       break;
     }
   }
 
   if (!retval) {
     retval = IDBIndex::Create(this, indexInfo, false);
-    NS_ENSURE_TRUE(retval, NS_ERROR_DOM_INDEXEDDB_UNKNOWN_ERR);
+    if (!retval) {
+      NS_WARNING("Failed to create index!");
+      aRv.Throw(NS_ERROR_DOM_INDEXEDDB_UNKNOWN_ERR);
+      return nullptr;
+    }
 
     if (!mCreatedIndexes.AppendElement(retval)) {
       NS_WARNING("Out of memory!");
-      return NS_ERROR_DOM_INDEXEDDB_UNKNOWN_ERR;
+      aRv.Throw(NS_ERROR_DOM_INDEXEDDB_UNKNOWN_ERR);
+      return nullptr;
     }
   }
 
-  retval.forget(_retval);
-  return NS_OK;
+  return retval.forget();
 }
 
 NS_IMPL_CYCLE_COLLECTION_TRACE_BEGIN(IDBObjectStore)
+  NS_IMPL_CYCLE_COLLECTION_TRACE_PRESERVED_WRAPPER
   NS_IMPL_CYCLE_COLLECTION_TRACE_JSVAL_MEMBER_CALLBACK(mCachedKeyPath)
 NS_IMPL_CYCLE_COLLECTION_TRACE_END
 
 NS_IMPL_CYCLE_COLLECTION_TRAVERSE_BEGIN(IDBObjectStore)
   NS_IMPL_CYCLE_COLLECTION_TRAVERSE_SCRIPT_OBJECTS
   NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mTransaction)
 
   for (uint32_t i = 0; i < tmp->mCreatedIndexes.Length(); i++) {
     NS_CYCLE_COLLECTION_NOTE_EDGE_NAME(cb, "mCreatedIndexes[i]");
-    cb.NoteXPCOMChild(static_cast<nsIIDBIndex*>(tmp->mCreatedIndexes[i].get()));
+    cb.NoteXPCOMChild(static_cast<nsISupports*>(tmp->mCreatedIndexes[i].get()));
   }
 NS_IMPL_CYCLE_COLLECTION_TRAVERSE_END
 
 NS_IMPL_CYCLE_COLLECTION_UNLINK_BEGIN(IDBObjectStore)
+  NS_IMPL_CYCLE_COLLECTION_UNLINK_PRESERVED_WRAPPER
+
   // Don't unlink mTransaction!
 
   tmp->mCreatedIndexes.Clear();
 
   tmp->mCachedKeyPath = JSVAL_VOID;
 
   if (tmp->mRooted) {
     NS_DROP_JS_OBJECTS(tmp, IDBObjectStore);
     tmp->mRooted = false;
   }
 NS_IMPL_CYCLE_COLLECTION_UNLINK_END
 
 NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION(IDBObjectStore)
-  NS_INTERFACE_MAP_ENTRY(nsIIDBObjectStore)
-  NS_DOM_INTERFACE_MAP_ENTRY_CLASSINFO(IDBObjectStore)
+  NS_WRAPPERCACHE_INTERFACE_MAP_ENTRY
   NS_INTERFACE_MAP_ENTRY(nsISupports)
 NS_INTERFACE_MAP_END
 
 NS_IMPL_CYCLE_COLLECTING_ADDREF(IDBObjectStore)
 NS_IMPL_CYCLE_COLLECTING_RELEASE(IDBObjectStore)
 
-DOMCI_DATA(IDBObjectStore, IDBObjectStore)
-
-NS_IMETHODIMP
-IDBObjectStore::GetName(nsAString& aName)
+JSObject*
+IDBObjectStore::WrapObject(JSContext* aCx, JS::Handle<JSObject*> aScope)
 {
-  NS_ASSERTION(NS_IsMainThread(), "Wrong thread!");
-
-  aName.Assign(mName);
-  return NS_OK;
+  return IDBObjectStoreBinding::Wrap(aCx, aScope, this);
 }
 
-NS_IMETHODIMP
-IDBObjectStore::GetKeyPath(JSContext* aCx,
-                           jsval* aVal)
+JS::Value
+IDBObjectStore::GetKeyPath(JSContext* aCx, ErrorResult& aRv)
 {
   NS_ASSERTION(NS_IsMainThread(), "Wrong thread!");
 
   if (!JSVAL_IS_VOID(mCachedKeyPath)) {
-    *aVal = mCachedKeyPath;
-    return NS_OK;
+    return mCachedKeyPath;
   }
 
-  nsresult rv = GetKeyPath().ToJSVal(aCx, mCachedKeyPath);
-  NS_ENSURE_SUCCESS(rv, rv);
+  aRv = GetKeyPath().ToJSVal(aCx, mCachedKeyPath);
+  ENSURE_SUCCESS(aRv, JSVAL_VOID);
 
   if (JSVAL_IS_GCTHING(mCachedKeyPath)) {
     NS_HOLD_JS_OBJECTS(this, IDBObjectStore);
     mRooted = true;
   }
 
-  *aVal = mCachedKeyPath;
-  return NS_OK;
-}
-
-NS_IMETHODIMP
-IDBObjectStore::GetTransaction(nsISupports** aTransaction)
-{
-  NS_ASSERTION(NS_IsMainThread(), "Wrong thread!");
-
-  nsRefPtr<IDBWrapperCache> transaction(mTransaction);
-  transaction.forget(aTransaction);
-  return NS_OK;
+  return mCachedKeyPath;
 }
 
-NS_IMETHODIMP
-IDBObjectStore::GetAutoIncrement(bool* aAutoIncrement)
-{
-  NS_ASSERTION(NS_IsMainThread(), "Wrong thread!");
-
-  *aAutoIncrement = mAutoIncrement;
-  return NS_OK;
-}
-
-NS_IMETHODIMP
-IDBObjectStore::GetIndexNames(nsIDOMDOMStringList** aIndexNames)
+already_AddRefed<nsIDOMDOMStringList>
+IDBObjectStore::GetIndexNames(ErrorResult& aRv)
 {
   NS_ASSERTION(NS_IsMainThread(), "Wrong thread!");
 
   nsRefPtr<nsDOMStringList> list(new nsDOMStringList());
 
   nsAutoTArray<nsString, 10> names;
   uint32_t count = mInfo->indexes.Length();
   names.SetCapacity(count);
 
   for (uint32_t index = 0; index < count; index++) {
     names.InsertElementSorted(mInfo->indexes[index].name);
   }
 
   for (uint32_t index = 0; index < count; index++) {
-    NS_ENSURE_TRUE(list->Add(names[index]),
-                   NS_ERROR_DOM_INDEXEDDB_UNKNOWN_ERR);
+    if (!list->Add(names[index])) {
+      NS_WARNING("Failed to add element!");
+      aRv.Throw(NS_ERROR_DOM_INDEXEDDB_UNKNOWN_ERR);
+      return nullptr;
+    }
   }
 
-  list.forget(aIndexNames);
-  return NS_OK;
+  return list.forget();
 }
 
-NS_IMETHODIMP
-IDBObjectStore::Get(const jsval& aKey,
-                    JSContext* aCx,
-                    nsIIDBRequest** _retval)
+already_AddRefed<IDBRequest>
+IDBObjectStore::Get(JSContext* aCx, JS::Handle<JS::Value> aKey,
+                    ErrorResult& aRv)
 {
   NS_ASSERTION(NS_IsMainThread(), "Wrong thread!");
 
   if (!mTransaction->IsOpen()) {
-    return NS_ERROR_DOM_INDEXEDDB_TRANSACTION_INACTIVE_ERR;
+    aRv.Throw(NS_ERROR_DOM_INDEXEDDB_TRANSACTION_INACTIVE_ERR);
+    return nullptr;
   }
 
   nsRefPtr<IDBKeyRange> keyRange;
-  nsresult rv = IDBKeyRange::FromJSVal(aCx, aKey, getter_AddRefs(keyRange));
-  NS_ENSURE_SUCCESS(rv, rv);
+  aRv = IDBKeyRange::FromJSVal(aCx, aKey, getter_AddRefs(keyRange));
+  ENSURE_SUCCESS(aRv, nullptr);
 
   if (!keyRange) {
     // Must specify a key or keyRange for get().
-    return NS_ERROR_DOM_INDEXEDDB_DATA_ERR;
+    aRv.Throw(NS_ERROR_DOM_INDEXEDDB_DATA_ERR);
+    return nullptr;
   }
 
-  nsRefPtr<IDBRequest> request;
-  rv = GetInternal(keyRange, aCx, getter_AddRefs(request));
-  if (NS_FAILED(rv)) {
-    return rv;
+  return GetInternal(keyRange, aRv);
+}
+
+already_AddRefed<IDBRequest>
+IDBObjectStore::GetAll(JSContext* aCx,
+                       const Optional<JS::Handle<JS::Value> >& aKey,
+                       const Optional<uint32_t>& aLimit, ErrorResult& aRv)
+{
+  NS_ASSERTION(NS_IsMainThread(), "Wrong thread!");
+
+  if (!mTransaction->IsOpen()) {
+    aRv.Throw(NS_ERROR_DOM_INDEXEDDB_TRANSACTION_INACTIVE_ERR);
+    return nullptr;
   }
 
-  request.forget(_retval);
-  return NS_OK;
+  nsRefPtr<IDBKeyRange> keyRange;
+  if (aKey.WasPassed()) {
+    aRv = IDBKeyRange::FromJSVal(aCx, aKey.Value(), getter_AddRefs(keyRange));
+    ENSURE_SUCCESS(aRv, nullptr);
+  }
+
+  uint32_t limit = UINT32_MAX;
+  if (aLimit.WasPassed() && aLimit.Value() != 0) {
+    limit = aLimit.Value();
+  }
+
+  return GetAllInternal(keyRange, limit, aRv);
 }
 
-NS_IMETHODIMP
-IDBObjectStore::GetAll(const jsval& aKey,
-                       uint32_t aLimit,
-                       JSContext* aCx,
-                       uint8_t aOptionalArgCount,
-                       nsIIDBRequest** _retval)
+already_AddRefed<IDBRequest>
+IDBObjectStore::Delete(JSContext* aCx, JS::Handle<JS::Value> aKey,
+                       ErrorResult& aRv)
 {
   NS_ASSERTION(NS_IsMainThread(), "Wrong thread!");
 
   if (!mTransaction->IsOpen()) {
-    return NS_ERROR_DOM_INDEXEDDB_TRANSACTION_INACTIVE_ERR;
+    aRv.Throw(NS_ERROR_DOM_INDEXEDDB_TRANSACTION_INACTIVE_ERR);
+    return nullptr;
   }
 
-  nsresult rv;
+  if (!IsWriteAllowed()) {
+    aRv.Throw(NS_ERROR_DOM_INDEXEDDB_READ_ONLY_ERR);
+    return nullptr;
+  }
 
   nsRefPtr<IDBKeyRange> keyRange;
-  if (aOptionalArgCount) {
-    rv = IDBKeyRange::FromJSVal(aCx, aKey, getter_AddRefs(keyRange));
-    NS_ENSURE_SUCCESS(rv, rv);
-  }
-
-  if (aOptionalArgCount < 2 || aLimit == 0) {
-    aLimit = UINT32_MAX;
+  aRv = IDBKeyRange::FromJSVal(aCx, aKey, getter_AddRefs(keyRange));
+  ENSURE_SUCCESS(aRv, nullptr);
+
+  if (!keyRange) {
+    // Must specify a key or keyRange for delete().
+    aRv.Throw(NS_ERROR_DOM_INDEXEDDB_DATA_ERR);
+    return nullptr;
   }
 
-  nsRefPtr<IDBRequest> request;
-  rv = GetAllInternal(keyRange, aLimit, aCx, getter_AddRefs(request));
-  if (NS_FAILED(rv)) {
-    return rv;
-  }
-
-  request.forget(_retval);
-  return NS_OK;
+  return DeleteInternal(keyRange, aRv);
 }
 
-NS_IMETHODIMP
-IDBObjectStore::Add(const jsval& aValue,
-                    const jsval& aKey,
-                    JSContext* aCx,
-                    uint8_t aOptionalArgCount,
-                    nsIIDBRequest** _retval)
-{
-  NS_ASSERTION(NS_IsMainThread(), "Wrong thread!");
-
-  nsRefPtr<IDBRequest> request;
-  nsresult rv = AddOrPut(aValue, aKey, aCx, aOptionalArgCount, false,
-                         getter_AddRefs(request));
-  if (NS_FAILED(rv)) {
-    return rv;
-  }
-
-  request.forget(_retval);
-  return NS_OK;
-}
-
-NS_IMETHODIMP
-IDBObjectStore::Put(const jsval& aValue,
-                    const jsval& aKey,
-                    JSContext* aCx,
-                    uint8_t aOptionalArgCount,
-                    nsIIDBRequest** _retval)
-{
-  NS_ASSERTION(NS_IsMainThread(), "Wrong thread!");
-
-  nsRefPtr<IDBRequest> request;
-  nsresult rv = AddOrPut(aValue, aKey, aCx, aOptionalArgCount, true,
-                         getter_AddRefs(request));
-  if (NS_FAILED(rv)) {
-    return rv;
-  }
-
-  request.forget(_retval);
-  return NS_OK;
-}
-
-NS_IMETHODIMP
-IDBObjectStore::Delete(const jsval& aKey,
-                       JSContext* aCx,
-                       nsIIDBRequest** _retval)
+already_AddRefed<IDBRequest>
+IDBObjectStore::OpenCursor(JSContext* aCx,
+                           const Optional<JS::Handle<JS::Value> >& aRange,
+                           IDBCursorDirection aDirection, ErrorResult& aRv)
 {
   NS_ASSERTION(NS_IsMainThread(), "Wrong thread!");
 
   if (!mTransaction->IsOpen()) {
-    return NS_ERROR_DOM_INDEXEDDB_TRANSACTION_INACTIVE_ERR;
-  }
-
-  if (!IsWriteAllowed()) {
-    return NS_ERROR_DOM_INDEXEDDB_READ_ONLY_ERR;
+    aRv.Throw(NS_ERROR_DOM_INDEXEDDB_TRANSACTION_INACTIVE_ERR);
+    return nullptr;
   }
 
   nsRefPtr<IDBKeyRange> keyRange;
-  nsresult rv = IDBKeyRange::FromJSVal(aCx, aKey, getter_AddRefs(keyRange));
-  if (NS_FAILED(rv)) {
-    return rv;
-  }
-
-  if (!keyRange) {
-    // Must specify a key or keyRange for delete().
-    return NS_ERROR_DOM_INDEXEDDB_DATA_ERR;
+  if (aRange.WasPassed()) {
+    aRv = IDBKeyRange::FromJSVal(aCx, aRange.Value(), getter_AddRefs(keyRange));
+    ENSURE_SUCCESS(aRv, nullptr);
   }
 
-  nsRefPtr<IDBRequest> request;
-  rv = DeleteInternal(keyRange, aCx, getter_AddRefs(request));
-  if (NS_FAILED(rv)) {
-    return rv;
-  }
-
-  request.forget(_retval);
-  return NS_OK;
+  IDBCursor::Direction direction = IDBCursor::ConvertDirection(aDirection);
+  size_t argDirection = static_cast<size_t>(direction);
+
+  return OpenCursorInternal(keyRange, argDirection, aRv);
 }
 
-NS_IMETHODIMP
-IDBObjectStore::Clear(JSContext* aCx, nsIIDBRequest** _retval)
+already_AddRefed<IDBIndex>
+IDBObjectStore::CreateIndex(JSContext* aCx, const nsAString& aName,
+                            const nsAString& aKeyPath,
+                            const IDBIndexParameters& aOptionalParameters,
+                            ErrorResult& aRv)
 {
   NS_ASSERTION(NS_IsMainThread(), "Wrong thread!");
 
-  nsRefPtr<IDBRequest> request;
-  nsresult rv = ClearInternal(aCx, getter_AddRefs(request));
-  if (NS_FAILED(rv)) {
-    return rv;
-  }
-
-  request.forget(_retval);
-  return NS_OK;
-}
-
-NS_IMETHODIMP
-IDBObjectStore::OpenCursor(const jsval& aKey,
-                           const nsAString& aDirection,
-                           JSContext* aCx,
-                           uint8_t aOptionalArgCount,
-                           nsIIDBRequest** _retval)
-{
-  NS_ASSERTION(NS_IsMainThread(), "Wrong thread!");
-
-  if (!mTransaction->IsOpen()) {
-    return NS_ERROR_DOM_INDEXEDDB_TRANSACTION_INACTIVE_ERR;
-  }
-
-  nsresult rv;
-
-  IDBCursor::Direction direction = IDBCursor::NEXT;
-
-  nsRefPtr<IDBKeyRange> keyRange;
-  if (aOptionalArgCount) {
-    rv = IDBKeyRange::FromJSVal(aCx, aKey, getter_AddRefs(keyRange));
-    NS_ENSURE_SUCCESS(rv, rv);
-
-    if (aOptionalArgCount >= 2) {
-      rv = IDBCursor::ParseDirection(aDirection, &direction);
-      NS_ENSURE_SUCCESS(rv, rv);
-    }
-  }
-
-  size_t argDirection = static_cast<size_t>(direction);
-
-  nsRefPtr<IDBRequest> request;
-  rv = OpenCursorInternal(keyRange, argDirection, aCx,
-                          getter_AddRefs(request));
-  if (NS_FAILED(rv)) {
-    return rv;
-  }
-
-  request.forget(_retval);
-  return NS_OK;
-}
-
-NS_IMETHODIMP
-IDBObjectStore::CreateIndex(const nsAString& aName,
-                            const jsval& aKeyPath,
-                            const jsval& aOptions,
-                            JSContext* aCx,
-                            nsIIDBIndex** _retval)
-{
-  NS_PRECONDITION(NS_IsMainThread(), "Wrong thread!");
-
   KeyPath keyPath(0);
   if (NS_FAILED(KeyPath::Parse(aCx, aKeyPath, &keyPath)) ||
       !keyPath.IsValid()) {
-    return NS_ERROR_DOM_SYNTAX_ERR;
+    aRv.Throw(NS_ERROR_DOM_SYNTAX_ERR);
+    return nullptr;
   }
 
+  return CreateIndex(aCx, aName, keyPath, aOptionalParameters, aRv);
+}
+
+already_AddRefed<IDBIndex>
+IDBObjectStore::CreateIndex(JSContext* aCx, const nsAString& aName,
+                            const Sequence<nsString >& aKeyPath,
+                            const IDBIndexParameters& aOptionalParameters,
+                            ErrorResult& aRv)
+{
+  NS_PRECONDITION(NS_IsMainThread(), "Wrong thread!");
+
+  if (!aKeyPath.Length()) {
+    aRv.Throw(NS_ERROR_DOM_SYNTAX_ERR);
+    return nullptr;
+  }
+
+  KeyPath keyPath(0);
+  if (NS_FAILED(KeyPath::Parse(aCx, aKeyPath, &keyPath))) {
+    aRv.Throw(NS_ERROR_DOM_SYNTAX_ERR);
+    return nullptr;
+  }
+
+  return CreateIndex(aCx, aName, keyPath, aOptionalParameters, aRv);
+}
+
+already_AddRefed<IDBIndex>
+IDBObjectStore::CreateIndex(JSContext* aCx, const nsAString& aName,
+                            KeyPath& aKeyPath,
+                            const IDBIndexParameters& aOptionalParameters,
+                            ErrorResult& aRv)
+{
   // Check name and current mode
   IDBTransaction* transaction = AsyncConnectionHelper::GetCurrentTransaction();
 
   if (!transaction ||
       transaction != mTransaction ||
       mTransaction->GetMode() != IDBTransaction::VERSION_CHANGE) {
-    return NS_ERROR_DOM_INDEXEDDB_NOT_ALLOWED_ERR;
+    aRv.Throw(NS_ERROR_DOM_INDEXEDDB_NOT_ALLOWED_ERR);
+    return nullptr;
   }
 
   bool found = false;
   uint32_t indexCount = mInfo->indexes.Length();
   for (uint32_t index = 0; index < indexCount; index++) {
     if (mInfo->indexes[index].name == aName) {
       found = true;
       break;
     }
   }
 
   if (found) {
-    return NS_ERROR_DOM_INDEXEDDB_CONSTRAINT_ERR;
+    aRv.Throw(NS_ERROR_DOM_INDEXEDDB_CONSTRAINT_ERR);
+    return nullptr;
   }
 
   NS_ASSERTION(mTransaction->IsOpen(), "Impossible!");
 
 #ifdef DEBUG
   for (uint32_t index = 0; index < mCreatedIndexes.Length(); index++) {
     if (mCreatedIndexes[index]->Name() == aName) {
       NS_ERROR("Already created this one!");
     }
   }
 #endif
 
-  nsresult rv;
-  mozilla::idl::IDBIndexParameters params;
-
-  // Get optional arguments.
-  if (!JSVAL_IS_VOID(aOptions) && !JSVAL_IS_NULL(aOptions)) {
-    rv = params.Init(aCx, &aOptions);
-    if (NS_FAILED(rv)) {
-      return rv;
-    }
-  }
-
-  if (params.multiEntry && keyPath.IsArray()) {
-    return NS_ERROR_DOM_INVALID_ACCESS_ERR;
+  if (aOptionalParameters.mMultiEntry && aKeyPath.IsArray()) {
+    aRv.Throw(NS_ERROR_DOM_INVALID_ACCESS_ERR);
+    return nullptr;
   }
 
   DatabaseInfo* databaseInfo = mTransaction->DBInfo();
 
   IndexInfo info;
 
   info.name = aName;
   info.id = databaseInfo->nextIndexId++;
-  info.keyPath = keyPath;
-  info.unique = params.unique;
-  info.multiEntry = params.multiEntry;
-
-  nsRefPtr<IDBIndex> index;
-  rv = CreateIndexInternal(info, getter_AddRefs(index));
-  if (NS_FAILED(rv)) {
-    return rv;
-  }
-
-  index.forget(_retval);
-  return NS_OK;
+  info.keyPath = aKeyPath;
+  info.unique = aOptionalParameters.mUnique;
+  info.multiEntry = aOptionalParameters.mMultiEntry;
+
+  return CreateIndexInternal(info, aRv);
 }
 
-NS_IMETHODIMP
-IDBObjectStore::Index(const nsAString& aName,
-                      nsIIDBIndex** _retval)
-{
-  NS_ASSERTION(NS_IsMainThread(), "Wrong thread!");
-
-  nsRefPtr<IDBIndex> index;
-  nsresult rv = IndexInternal(aName, getter_AddRefs(index));
-  if (NS_FAILED(rv)) {
-    return rv;
-  }
-
-  index.forget(_retval);
-  return NS_OK;
-}
-
-NS_IMETHODIMP
-IDBObjectStore::DeleteIndex(const nsAString& aName)
+void
+IDBObjectStore::DeleteIndex(const nsAString& aName, ErrorResult& aRv)
 {
   NS_ASSERTION(NS_IsMainThread(), "Wrong thread!");
 
   IDBTransaction* transaction = AsyncConnectionHelper::GetCurrentTransaction();
 
   if (!transaction ||
       transaction != mTransaction ||
       mTransaction->GetMode() != IDBTransaction::VERSION_CHANGE) {
-    return NS_ERROR_DOM_INDEXEDDB_NOT_ALLOWED_ERR;
+    aRv.Throw(NS_ERROR_DOM_INDEXEDDB_NOT_ALLOWED_ERR);
+    return;
   }
 
   NS_ASSERTION(mTransaction->IsOpen(), "Impossible!");
 
   uint32_t index = 0;
   for (; index < mInfo->indexes.Length(); index++) {
     if (mInfo->indexes[index].name == aName) {
       break;
     }
   }
 
   if (index == mInfo->indexes.Length()) {
-    return NS_ERROR_DOM_INDEXEDDB_NOT_FOUND_ERR;
+    aRv.Throw(NS_ERROR_DOM_INDEXEDDB_NOT_FOUND_ERR);
+    return;
   }
 
-  nsresult rv;
-
   if (IndexedDatabaseManager::IsMainProcess()) {
     nsRefPtr<DeleteIndexHelper> helper =
       new DeleteIndexHelper(mTransaction, this, aName);
 
-    rv = helper->DispatchToTransactionPool();
-    NS_ENSURE_SUCCESS(rv, NS_ERROR_DOM_INDEXEDDB_UNKNOWN_ERR);
+    nsresult rv = helper->DispatchToTransactionPool();
+    if (NS_FAILED(rv)) {
+      NS_WARNING("Failed to dispatch!");
+      aRv.Throw(NS_ERROR_DOM_INDEXEDDB_UNKNOWN_ERR);
+      return;
+    }
   }
   else {
     NS_ASSERTION(mActorChild, "Must have an actor here!");
 
     mActorChild->SendDeleteIndex(nsString(aName));
   }
 
   mInfo->indexes.RemoveElementAt(index);
@@ -2795,46 +2737,35 @@ IDBObjectStore::DeleteIndex(const nsAStr
   IDB_PROFILER_MARK("IndexedDB Pseudo-request: "
                     "database(%s).transaction(%s).objectStore(%s)."
                     "deleteIndex(\"%s\")",
                     "MT IDBObjectStore.deleteIndex()",
                     IDB_PROFILER_STRING(Transaction()->Database()),
                     IDB_PROFILER_STRING(Transaction()),
                     IDB_PROFILER_STRING(this),
                     NS_ConvertUTF16toUTF8(aName).get());
-
-  return NS_OK;
 }
 
-NS_IMETHODIMP
-IDBObjectStore::Count(const jsval& aKey,
-                      JSContext* aCx,
-                      uint8_t aOptionalArgCount,
-                      nsIIDBRequest** _retval)
+already_AddRefed<IDBRequest>
+IDBObjectStore::Count(JSContext* aCx,
+                      const Optional<JS::Handle<JS::Value> >& aKey,
+                      ErrorResult& aRv)
 {
   if (!mTransaction->IsOpen()) {
-    return NS_ERROR_DOM_INDEXEDDB_TRANSACTION_INACTIVE_ERR;
+    aRv.Throw(NS_ERROR_DOM_INDEXEDDB_TRANSACTION_INACTIVE_ERR);
+    return nullptr;
   }
 
-  nsresult rv;
-
   nsRefPtr<IDBKeyRange> keyRange;
-  if (aOptionalArgCount) {
-    rv = IDBKeyRange::FromJSVal(aCx, aKey, getter_AddRefs(keyRange));
-    NS_ENSURE_SUCCESS(rv, rv);
+  if (aKey.WasPassed()) {
+    aRv = IDBKeyRange::FromJSVal(aCx, aKey.Value(), getter_AddRefs(keyRange));
+    ENSURE_SUCCESS(aRv, nullptr);
   }
 
-  nsRefPtr<IDBRequest> request;
-  rv = CountInternal(keyRange, aCx, getter_AddRefs(request));
-  if (NS_FAILED(rv)) {
-    return rv;
-  }
-
-  request.forget(_retval);
-  return NS_OK;
+  return CountInternal(keyRange, aRv);
 }
 
 inline nsresult
 CopyData(nsIInputStream* aInputStream, nsIOutputStream* aOutputStream)
 {
   NS_ASSERTION(!NS_IsMainThread(), "Wrong thread!");
   NS_ASSERTION(IndexedDatabaseManager::IsMainProcess(), "Wrong process!");
 
--- a/dom/indexedDB/IDBObjectStore.h
+++ b/dom/indexedDB/IDBObjectStore.h
@@ -4,20 +4,22 @@
  * 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/. */
 
 #ifndef mozilla_dom_indexeddb_idbobjectstore_h__
 #define mozilla_dom_indexeddb_idbobjectstore_h__
 
 #include "mozilla/dom/indexedDB/IndexedDatabase.h"
 
-#include "nsIIDBObjectStore.h"
-
+#include "mozilla/dom/IDBCursorBinding.h"
+#include "mozilla/dom/IDBIndexBinding.h"
+#include "mozilla/dom/IDBObjectStoreBinding.h"
 #include "nsCycleCollectionParticipant.h"
 
+#include "mozilla/dom/indexedDB/IDBRequest.h"
 #include "mozilla/dom/indexedDB/IDBTransaction.h"
 #include "mozilla/dom/indexedDB/KeyPath.h"
 
 class nsIDOMBlob;
 class nsIScriptContext;
 class nsPIDOMWindow;
 
 namespace mozilla {
@@ -41,22 +43,21 @@ class Key;
 
 struct IndexInfo;
 struct IndexUpdateInfo;
 struct ObjectStoreInfo;
 
 struct FileHandleData;
 struct BlobOrFileData;
 
-class IDBObjectStore MOZ_FINAL : public nsIIDBObjectStore
+class IDBObjectStore MOZ_FINAL : public nsISupports,
+                                 public nsWrapperCache
 {
 public:
   NS_DECL_CYCLE_COLLECTING_ISUPPORTS
-  NS_DECL_NSIIDBOBJECTSTORE
-
   NS_DECL_CYCLE_COLLECTION_SCRIPT_HOLDER_CLASS(IDBObjectStore)
 
   static already_AddRefed<IDBObjectStore>
   Create(IDBTransaction* aTransaction,
          ObjectStoreInfo* aInfo,
          nsIAtom* aDatabaseId,
          bool aCreating);
 
@@ -192,87 +193,172 @@ public:
   }
 
   IndexedDBObjectStoreParent*
   GetActorParent() const
   {
     return mActorParent;
   }
 
-  nsresult
+  already_AddRefed<IDBIndex>
   CreateIndexInternal(const IndexInfo& aInfo,
-                      IDBIndex** _retval);
-
-  nsresult
-  IndexInternal(const nsAString& aName,
-                IDBIndex** _retval);
+                      ErrorResult& aRv);
 
   nsresult AddOrPutInternal(
                       const SerializedStructuredCloneWriteInfo& aCloneWriteInfo,
                       const Key& aKey,
                       const InfallibleTArray<IndexUpdateInfo>& aUpdateInfoArray,
                       const nsTArray<nsCOMPtr<nsIDOMBlob> >& aBlobs,
                       bool aOverwrite,
                       IDBRequest** _retval);
 
-  nsresult GetInternal(IDBKeyRange* aKeyRange,
-                       JSContext* aCx,
-                       IDBRequest** _retval);
+  already_AddRefed<IDBRequest>
+  GetInternal(IDBKeyRange* aKeyRange,
+              ErrorResult& aRv);
 
-  nsresult GetAllInternal(IDBKeyRange* aKeyRange,
-                          uint32_t aLimit,
-                          JSContext* aCx,
-                          IDBRequest** _retval);
+  already_AddRefed<IDBRequest>
+  GetAllInternal(IDBKeyRange* aKeyRange,
+                 uint32_t aLimit,
+                 ErrorResult& aRv);
 
-  nsresult DeleteInternal(IDBKeyRange* aKeyRange,
-                          JSContext* aCx,
-                          IDBRequest** _retval);
-
-  nsresult ClearInternal(JSContext* aCx,
-                         IDBRequest** _retval);
+  already_AddRefed<IDBRequest>
+  DeleteInternal(IDBKeyRange* aKeyRange,
+                 ErrorResult& aRv);
 
-  nsresult CountInternal(IDBKeyRange* aKeyRange,
-                         JSContext* aCx,
-                         IDBRequest** _retval);
+  already_AddRefed<IDBRequest>
+  CountInternal(IDBKeyRange* aKeyRange,
+                ErrorResult& aRv);
 
-  nsresult OpenCursorInternal(IDBKeyRange* aKeyRange,
-                              size_t aDirection,
-                              JSContext* aCx,
-                              IDBRequest** _retval);
+  already_AddRefed<IDBRequest>
+  OpenCursorInternal(IDBKeyRange* aKeyRange,
+                     size_t aDirection,
+                     ErrorResult& aRv);
 
   nsresult OpenCursorFromChildProcess(
                             IDBRequest* aRequest,
                             size_t aDirection,
                             const Key& aKey,
                             const SerializedStructuredCloneReadInfo& aCloneInfo,
                             nsTArray<StructuredCloneFile>& aBlobs,
                             IDBCursor** _retval);
 
   void
   SetInfo(ObjectStoreInfo* aInfo);
 
   static JSClass sDummyPropJSClass;
 
+  // nsWrapperCache
+  virtual JSObject*
+  WrapObject(JSContext* aCx, JS::Handle<JSObject*> aScope) MOZ_OVERRIDE;
+
+  // WebIDL
+  IDBTransaction*
+  GetParentObject() const
+  {
+    return mTransaction;
+  }
+
+  void
+  GetName(nsString& aName) const
+  {
+    NS_ASSERTION(NS_IsMainThread(), "Wrong thread!");
+    aName.Assign(mName);
+  }
+
+  JS::Value
+  GetKeyPath(JSContext* aCx, ErrorResult& aRv);
+
+  already_AddRefed<nsIDOMDOMStringList>
+  GetIndexNames(ErrorResult& aRv);
+
+  IDBTransaction*
+  Transaction() const
+  {
+    NS_ASSERTION(NS_IsMainThread(), "Wrong thread!");
+    return mTransaction;
+  }
+
+  bool
+  AutoIncrement() const
+  {
+    NS_ASSERTION(NS_IsMainThread(), "Wrong thread!");
+    return mAutoIncrement;
+  }
+
+  already_AddRefed<IDBRequest>
+  Put(JSContext* aCx, JS::Handle<JS::Value> aValue,
+      const Optional<JS::Handle<JS::Value> >& aKey, ErrorResult& aRv)
+  {
+    NS_ASSERTION(NS_IsMainThread(), "Wrong thread!");
+    return AddOrPut(aCx, aValue, aKey, true, aRv);
+  }
+
+  already_AddRefed<IDBRequest>
+  Add(JSContext* aCx, JS::Handle<JS::Value> aValue,
+      const Optional<JS::Handle<JS::Value> >& aKey, ErrorResult& aRv)
+  {
+    NS_ASSERTION(NS_IsMainThread(), "Wrong thread!");
+    return AddOrPut(aCx, aValue, aKey, false, aRv);
+  }
+
+  already_AddRefed<IDBRequest>
+  Delete(JSContext* aCx, JS::Handle<JS::Value> aKey, ErrorResult& aRv);
+
+  already_AddRefed<IDBRequest>
+  Get(JSContext* aCx, JS::Handle<JS::Value> aKey, ErrorResult& aRv);
+
+  already_AddRefed<IDBRequest>
+  Clear(ErrorResult& aRv);
+
+  already_AddRefed<IDBRequest>
+  OpenCursor(JSContext* aCx, const Optional<JS::Handle<JS::Value> >& aRange,
+             IDBCursorDirection aDirection, ErrorResult& aRv);
+
+  already_AddRefed<IDBIndex>
+  CreateIndex(JSContext* aCx, const nsAString& aName, const nsAString& aKeyPath,
+              const IDBIndexParameters& aOptionalParameters, ErrorResult& aRv);
+
+  already_AddRefed<IDBIndex>
+  CreateIndex(JSContext* aCx, const nsAString& aName,
+              const Sequence<nsString >& aKeyPath,
+              const IDBIndexParameters& aOptionalParameters, ErrorResult& aRv);
+
+  already_AddRefed<IDBIndex>
+  Index(const nsAString& aName, ErrorResult &aRv);
+
+  void
+  DeleteIndex(const nsAString& aIndexName, ErrorResult& aRv);
+
+  already_AddRefed<IDBRequest>
+  Count(JSContext* aCx, const Optional<JS::Handle<JS::Value> >& aKey,
+        ErrorResult& aRv);
+
+  already_AddRefed<IDBRequest>
+  GetAll(JSContext* aCx, const Optional<JS::Handle<JS::Value> >& aKey,
+         const Optional<uint32_t >& aLimit, ErrorResult& aRv);
+
 protected:
   IDBObjectStore();
   ~IDBObjectStore();
 
   nsresult GetAddInfo(JSContext* aCx,
                       JS::Handle<JS::Value> aValue,
                       JS::Handle<JS::Value> aKeyVal,
                       StructuredCloneWriteInfo& aCloneWriteInfo,
                       Key& aKey,
                       nsTArray<IndexUpdateInfo>& aUpdateInfoArray);
 
-  nsresult AddOrPut(const jsval& aValue,
-                    const jsval& aKey,
-                    JSContext* aCx,
-                    uint8_t aOptionalArgCount,
-                    bool aOverwrite,
-                    IDBRequest** _retval);
+  already_AddRefed<IDBRequest>
+  AddOrPut(JSContext* aCx, JS::Handle<JS::Value> aValue,
+           const Optional<JS::Handle<JS::Value> >& aKey, bool aOverwrite,
+           ErrorResult& aRv);
+
+  already_AddRefed<IDBIndex>
+  CreateIndex(JSContext* aCx, const nsAString& aName, KeyPath& aKeyPath,
+              const IDBIndexParameters& aOptionalParameters, ErrorResult& aRv);
 
   static void
   ClearStructuredCloneBuffer(JSAutoStructuredCloneBuffer& aBuffer);
 
   static bool
   ReadFileHandle(JSStructuredCloneReader* aReader,
                  FileHandleData* aRetval);
 
--- a/dom/indexedDB/IDBTransaction.cpp
+++ b/dom/indexedDB/IDBTransaction.cpp
@@ -87,17 +87,17 @@ NS_IMETHODIMP_(nsrefcnt) StartTransactio
 NS_IMPL_QUERY_INTERFACE1(StartTransactionRunnable, nsIRunnable)
 
 } // anonymous namespace
 
 
 // static
 already_AddRefed<IDBTransaction>
 IDBTransaction::CreateInternal(IDBDatabase* aDatabase,
-                               nsTArray<nsString>& aObjectStoreNames,
+                               const Sequence<nsString>& aObjectStoreNames,
                                Mode aMode,
                                bool aDispatchDelayed,
                                bool aIsVersionChangeTransactionChild)
 {
   NS_ASSERTION(NS_IsMainThread(), "Wrong thread!");
   NS_ASSERTION(IndexedDatabaseManager::IsMainProcess() || !aDispatchDelayed,
                "No support for delayed-dispatch transactions in child "
                "process!");
@@ -694,17 +694,17 @@ IDBTransaction::GetObjectStoreNames(Erro
       aRv.Throw(NS_ERROR_DOM_INDEXEDDB_UNKNOWN_ERR);
       return nullptr;
     }
   }
 
   return list.forget();
 }
 
-already_AddRefed<nsIIDBObjectStore>
+already_AddRefed<IDBObjectStore>
 IDBTransaction::ObjectStore(const nsAString& aName, ErrorResult& aRv)
 {
   NS_ASSERTION(NS_IsMainThread(), "Wrong thread!");
 
   if (IsFinished()) {
     aRv.Throw(NS_ERROR_DOM_INDEXEDDB_NOT_ALLOWED_ERR);
     return nullptr;
   }
--- a/dom/indexedDB/IDBTransaction.h
+++ b/dom/indexedDB/IDBTransaction.h
@@ -84,17 +84,17 @@ public:
     INITIAL = 0,
     LOADING,
     COMMITTING,
     DONE
   };
 
   static already_AddRefed<IDBTransaction>
   Create(IDBDatabase* aDatabase,
-         nsTArray<nsString>& aObjectStoreNames,
+         const Sequence<nsString>& aObjectStoreNames,
          Mode aMode,
          bool aDispatchDelayed)
   {
     return CreateInternal(aDatabase, aObjectStoreNames, aMode, aDispatchDelayed,
                           false);
   }
 
   // nsIDOMEventTarget
@@ -225,27 +225,27 @@ public:
   GetParentObject() const
   {
     return GetOwner();
   }
 
   IDBTransactionMode
   GetMode(ErrorResult& aRv) const;
 
-  nsIIDBDatabase*
+  IDBDatabase*
   Db() const
   {
     NS_ASSERTION(NS_IsMainThread(), "Wrong thread!");
     return mDatabase;
   }
 
   DOMError*
   GetError(ErrorResult& aRv);
 
-  already_AddRefed<nsIIDBObjectStore>
+  already_AddRefed<IDBObjectStore>
   ObjectStore(const nsAString& aName, ErrorResult& aRv);
 
   void
   Abort(ErrorResult& aRv)
   {
     NS_ASSERTION(NS_IsMainThread(), "Wrong thread!");
     aRv = AbortInternal(NS_ERROR_DOM_INDEXEDDB_ABORT_ERR, nullptr);
   }
@@ -260,17 +260,17 @@ public:
 private:
   nsresult
   AbortInternal(nsresult aAbortCode,
                 already_AddRefed<mozilla::dom::DOMError> aError);
 
   // Should only be called directly through IndexedDBDatabaseChild.
   static already_AddRefed<IDBTransaction>
   CreateInternal(IDBDatabase* aDatabase,
-                 nsTArray<nsString>& aObjectStoreNames,
+                 const Sequence<nsString>& aObjectStoreNames,
                  Mode aMode,
                  bool aDispatchDelayed,
                  bool aIsVersionChangeTransactionChild);
 
   IDBTransaction();
   ~IDBTransaction();
 
   nsresult CommitOrRollback();
--- a/dom/indexedDB/KeyPath.cpp
+++ b/dom/indexedDB/KeyPath.cpp
@@ -7,16 +7,18 @@
 #include "KeyPath.h"
 #include "IDBObjectStore.h"
 #include "Key.h"
 
 #include "nsCharSeparatedTokenizer.h"
 #include "nsJSUtils.h"
 #include "xpcpublic.h"
 
+#include "mozilla/dom/BindingDeclarations.h"
+
 USING_INDEXEDDB_NAMESPACE
 
 namespace {
 
 inline
 bool
 IgnoreWhitespace(PRUnichar c)
 {
@@ -217,16 +219,49 @@ GetJSValFromKeyPathString(JSContext* aCx
   NS_ENSURE_SUCCESS(rv, rv);
   return rv;
 }
 
 } // anonymous namespace
 
 // static
 nsresult
+KeyPath::Parse(JSContext* aCx, const nsAString& aString, KeyPath* aKeyPath)
+{
+  KeyPath keyPath(0);
+  keyPath.SetType(STRING);
+
+  if (!keyPath.AppendStringWithValidation(aCx, aString)) {
+    return NS_ERROR_FAILURE;
+  }
+
+  *aKeyPath = keyPath;
+  return NS_OK;
+}
+
+//static
+nsresult
+KeyPath::Parse(JSContext* aCx, const mozilla::dom::Sequence<nsString>& aStrings,
+               KeyPath* aKeyPath)
+{
+  KeyPath keyPath(0);
+  keyPath.SetType(ARRAY);
+
+  for (uint32_t i = 0; i < aStrings.Length(); ++i) {
+    if (!keyPath.AppendStringWithValidation(aCx, aStrings[i])) {
+      return NS_ERROR_FAILURE;
+    }
+  }
+
+  *aKeyPath = keyPath;
+  return NS_OK;
+}
+
+// static
+nsresult
 KeyPath::Parse(JSContext* aCx, const JS::Value& aValue, KeyPath* aKeyPath)
 {
   KeyPath keyPath(0);
 
   aKeyPath->SetType(NONEXISTENT);
 
   // See if this is a JS array.
   if (!JSVAL_IS_PRIMITIVE(aValue) &&
--- a/dom/indexedDB/KeyPath.h
+++ b/dom/indexedDB/KeyPath.h
@@ -4,16 +4,18 @@
  * 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/. */
 
 #ifndef mozilla_dom_indexeddb_keypath_h__
 #define mozilla_dom_indexeddb_keypath_h__
 
 #include "mozilla/dom/indexedDB/IndexedDatabase.h"
 
+#include "mozilla/dom/BindingDeclarations.h"
+
 BEGIN_INDEXEDDB_NAMESPACE
 
 class Key;
 
 class KeyPath
 {
 public:
   enum KeyPathType {
@@ -41,16 +43,22 @@ public:
   }
 
   ~KeyPath()
   {
     MOZ_COUNT_DTOR(KeyPath);
   }
 
   static nsresult
+  Parse(JSContext* aCx, const nsAString& aString, KeyPath* aKeyPath);
+
+  static nsresult
+  Parse(JSContext* aCx, const Sequence<nsString>& aStrings, KeyPath* aKeyPath);
+
+  static nsresult
   Parse(JSContext* aCx, const JS::Value& aValue, KeyPath* aKeyPath);
 
   nsresult
   ExtractKey(JSContext* aCx, const JS::Value& aValue, Key& aKey) const;
 
   nsresult
   ExtractKeyAsJSVal(JSContext* aCx, const JS::Value& aValue,
                     JS::Value* aOutVal) const;
--- a/dom/indexedDB/OpenDatabaseHelper.cpp
+++ b/dom/indexedDB/OpenDatabaseHelper.cpp
@@ -2054,17 +2054,17 @@ OpenDatabaseHelper::StartSetVersion()
   NS_ASSERTION(mState == eSetVersionPending, "Why are we here?");
 
   // In case we fail, fire error events
   mState = eFiringEvents;
 
   nsresult rv = EnsureSuccessResult();
   NS_ENSURE_SUCCESS(rv, rv);
 
-  nsTArray<nsString> storesToOpen;
+  Sequence<nsString> storesToOpen;
   nsRefPtr<IDBTransaction> transaction =
     IDBTransaction::Create(mDatabase, storesToOpen,
                            IDBTransaction::VERSION_CHANGE, true);
   NS_ENSURE_TRUE(transaction, NS_ERROR_DOM_INDEXEDDB_UNKNOWN_ERR);
 
   nsRefPtr<SetVersionHelper> helper =
     new SetVersionHelper(transaction, mOpenDBRequest, this, mRequestedVersion,
                          mCurrentVersion);
--- a/dom/indexedDB/ipc/IndexedDBChild.cpp
+++ b/dom/indexedDB/ipc/IndexedDBChild.cpp
@@ -503,17 +503,17 @@ IndexedDBDatabaseChild::RecvPIndexedDBTr
 
   if (!EnsureDatabase(mRequest, dbInfo, osInfo)) {
     return false;
   }
 
   nsRefPtr<IPCOpenDatabaseHelper> helper =
     new IPCOpenDatabaseHelper(mDatabase, mRequest);
 
-  nsTArray<nsString> storesToOpen;
+  Sequence<nsString> storesToOpen;
   nsRefPtr<IDBTransaction> transaction =
     IDBTransaction::CreateInternal(mDatabase, storesToOpen,
                                    IDBTransaction::VERSION_CHANGE, false, true);
   NS_ENSURE_TRUE(transaction, false);
 
   nsRefPtr<IPCSetVersionHelper> versionHelper =
     new IPCSetVersionHelper(transaction, mRequest, oldVersion, mVersion);
 
--- a/dom/indexedDB/ipc/IndexedDBParent.cpp
+++ b/dom/indexedDB/ipc/IndexedDBParent.cpp
@@ -1,36 +1,40 @@
 /* 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/. */
 
+
 #include "IndexedDBParent.h"
 
-#include "AsyncConnectionHelper.h"
+#include "nsIDOMEvent.h"
+#include "nsIDOMFile.h"
+#include "nsIXPConnect.h"
+
 #include "mozilla/AppProcessChecker.h"
 #include "mozilla/Assertions.h"
 #include "mozilla/Attributes.h"
 #include "mozilla/dom/ContentParent.h"
-#include "mozilla/dom/indexedDB/DatabaseInfo.h"
-#include "mozilla/dom/indexedDB/IDBDatabase.h"
-#include "mozilla/dom/indexedDB/IDBEvents.h"
-#include "mozilla/dom/indexedDB/IDBFactory.h"
-#include "mozilla/dom/indexedDB/IDBIndex.h"
-#include "mozilla/dom/indexedDB/IDBKeyRange.h"
-#include "mozilla/dom/indexedDB/IDBObjectStore.h"
-#include "mozilla/dom/indexedDB/IDBTransaction.h"
+#include "mozilla/dom/IDBDatabaseBinding.h"
 #include "mozilla/dom/ipc/Blob.h"
 #include "mozilla/dom/TabParent.h"
 #include "mozilla/unused.h"
 #include "mozilla/Util.h"
 #include "nsContentUtils.h"
 #include "nsCxPusher.h"
-#include "nsIDOMEvent.h"
-#include "nsIDOMFile.h"
-#include "nsIXPConnect.h"
+
+#include "AsyncConnectionHelper.h"
+#include "DatabaseInfo.h"
+#include "IDBDatabase.h"
+#include "IDBEvents.h"
+#include "IDBFactory.h"
+#include "IDBIndex.h"
+#include "IDBKeyRange.h"
+#include "IDBObjectStore.h"
+#include "IDBTransaction.h"
 
 #define CHROME_ORIGIN "chrome"
 #define PERMISSION_PREFIX "indexedDB-chrome-"
 #define PERMISSION_SUFFIX_READ "-read"
 #define PERMISSION_SUFFIX_WRITE "-write"
 
 USING_INDEXEDDB_NAMESPACE
 
@@ -372,41 +376,32 @@ IndexedDBDatabaseParent::HandleRequestEv
 
     if (!SendBlocked(oldVersion)) {
       return NS_ERROR_FAILURE;
     }
 
     return NS_OK;
   }
 
-  nsIXPConnect* xpc = nsContentUtils::XPConnect();
-  MOZ_ASSERT(xpc);
-
   AutoSafeJSContext cx;
 
   JS::Rooted<JS::Value> result(cx);
   rv = mOpenRequest->GetResult(result.address());
   NS_ENSURE_SUCCESS(rv, rv);
 
   MOZ_ASSERT(!JSVAL_IS_PRIMITIVE(result));
 
-  nsCOMPtr<nsIXPConnectWrappedNative> wrapper;
-  rv = xpc->GetWrappedNativeOfJSObject(cx, JSVAL_TO_OBJECT(result),
-                                       getter_AddRefs(wrapper));
-  NS_ENSURE_SUCCESS(rv, rv);
-
-  nsCOMPtr<nsIIDBDatabase> database;
-  if (!wrapper || !(database = do_QueryInterface(wrapper->Native()))) {
+  IDBDatabase *database;
+  rv = UnwrapObject<IDBDatabase>(cx, &result.toObject(), database);
+  if (NS_FAILED(rv)) {
     NS_WARNING("Didn't get the object we expected!");
-    return NS_ERROR_FAILURE;
+    return rv;
   }
 
-  IDBDatabase* databaseConcrete = static_cast<IDBDatabase*>(database.get());
-
-  DatabaseInfo* dbInfo = databaseConcrete->Info();
+  DatabaseInfo* dbInfo = database->Info();
   MOZ_ASSERT(dbInfo);
 
   nsAutoTArray<nsString, 20> objectStoreNames;
   if (!dbInfo->GetObjectStoreNames(objectStoreNames)) {
     MOZ_CRASH("This should never fail!");
   }
 
   InfallibleTArray<ObjectStoreInfoGuts> objectStoreInfos;
@@ -422,18 +417,17 @@ IndexedDBDatabaseParent::HandleRequestEv
       objectStoreInfos.AppendElement(*osInfo);
     }
   }
 
   if (aType.EqualsLiteral(SUCCESS_EVT_STR)) {
     nsRefPtr<IDBOpenDBRequest> request;
     mOpenRequest.swap(request);
 
-    EventTarget* target =
-      static_cast<EventTarget*>(databaseConcrete);
+    EventTarget* target = static_cast<EventTarget*>(database);
 
 #ifdef DEBUG
     {
       nsresult rvDEBUG =
         target->AddEventListener(NS_LITERAL_STRING(ERROR_EVT_STR),
                                  mEventListener, false);
       NS_WARN_IF_FALSE(NS_SUCCEEDED(rvDEBUG), "Failed to add error listener!");
     }
@@ -442,34 +436,34 @@ IndexedDBDatabaseParent::HandleRequestEv
     NS_NAMED_LITERAL_STRING(versionChange, VERSIONCHANGE_EVT_STR);
     rv = target->AddEventListener(versionChange, mEventListener, false);
     NS_ENSURE_SUCCESS(rv, rv);
 
     if (!SendSuccess(*dbInfo, objectStoreInfos)) {
       return NS_ERROR_FAILURE;
     }
 
-    MOZ_ASSERT(!mDatabase || mDatabase == databaseConcrete);
+    MOZ_ASSERT(!mDatabase || mDatabase == database);
 
     if (!mDatabase) {
-      databaseConcrete->SetActor(this);
-      mDatabase = databaseConcrete;
+      database->SetActor(this);
+      mDatabase = database;
     }
 
     return NS_OK;
   }
 
   if (aType.EqualsLiteral(UPGRADENEEDED_EVT_STR)) {
     MOZ_ASSERT(!mDatabase);
 
     IDBTransaction* transaction =
       AsyncConnectionHelper::GetCurrentTransaction();
     MOZ_ASSERT(transaction);
 
-    if (!CheckWritePermission(databaseConcrete->Name())) {
+    if (!CheckWritePermission(database->Name())) {
       // If we get here then the child process is either dead or in the process
       // of being killed. Abort the transaction now to prevent any changes to
       // the database.
       ErrorResult rv;
       transaction->Abort(rv);
       if (rv.Failed()) {
         NS_WARNING("Failed to abort transaction!");
       }
@@ -492,18 +486,18 @@ IndexedDBDatabaseParent::HandleRequestEv
     versionChangeParams.osInfo() = objectStoreInfos;
     versionChangeParams.oldVersion() = oldVersion;
 
     if (!SendPIndexedDBTransactionConstructor(actor.forget(),
                                               versionChangeParams)) {
       return NS_ERROR_FAILURE;
     }
 
-    databaseConcrete->SetActor(this);
-    mDatabase = databaseConcrete;
+    database->SetActor(this);
+    mDatabase = database;
 
     return NS_OK;
   }
 
   MOZ_CRASH("Unexpected message type!");
 }
 
 nsresult
@@ -595,17 +589,17 @@ IndexedDBDatabaseParent::RecvPIndexedDBT
     return false;
   }
 
   if (mDatabase->IsClosed()) {
     // If the window was navigated then we won't be able to do anything here.
     return true;
   }
 
-  nsTArray<nsString> storesToOpen;
+  Sequence<nsString> storesToOpen;
   storesToOpen.AppendElements(params.names());
 
   nsRefPtr<IDBTransaction> transaction =
     IDBTransaction::Create(mDatabase, storesToOpen, params.mode(), false);
   NS_ENSURE_TRUE(transaction, false);
 
   nsresult rv = actor->SetTransaction(transaction);
   NS_ENSURE_SUCCESS(rv, false);
@@ -791,23 +785,19 @@ IndexedDBTransactionParent::RecvPIndexed
     const nsString& name = params.name();
 
     nsRefPtr<IDBObjectStore> objectStore;
 
     {
       AutoSetCurrentTransaction asct(mTransaction);
 
       ErrorResult rv;
-      nsCOMPtr<nsIIDBObjectStore> store = mTransaction->ObjectStore(name, rv);
-      if (rv.Failed()) {
-        NS_WARNING("Failed to get object store!");
-        return false;
-      }
-
-      objectStore = static_cast<IDBObjectStore*>(store.get());
+      objectStore = mTransaction->ObjectStore(name, rv);
+      ENSURE_SUCCESS(rv, false);
+
       actor->SetObjectStore(objectStore);
     }
 
     objectStore->SetActor(actor);
     return true;
   }
 
   if (aParams.type() ==
@@ -869,26 +859,24 @@ IndexedDBVersionChangeTransactionParent:
     // If we've invalidated this database in the parent then we should bail out
     // now to avoid logic problems that could force-kill the child.
     return true;
   }
 
   IDBDatabase* db = mTransaction->Database();
   MOZ_ASSERT(db);
 
-  nsresult rv;
+  ErrorResult rv;
 
   {
     AutoSetCurrentTransaction asct(mTransaction);
-
-    rv = db->DeleteObjectStore(aName);
+    db->DeleteObjectStore(aName, rv);
   }
 
-  NS_ENSURE_SUCCESS(rv, false);
-
+  ENSURE_SUCCESS(rv, false);
   return true;
 }
 
 bool
 IndexedDBVersionChangeTransactionParent::RecvPIndexedDBObjectStoreConstructor(
                                     PIndexedDBObjectStoreParent* aActor,
                                     const ObjectStoreConstructorParams& aParams)
 {
@@ -919,26 +907,25 @@ IndexedDBVersionChangeTransactionParent:
 
     const ObjectStoreInfoGuts& info = params.info();
 
     IDBDatabase* db = mTransaction->Database();
     MOZ_ASSERT(db);
 
     nsRefPtr<IDBObjectStore> objectStore;
 
-    nsresult rv;
+    ErrorResult rv;
 
     {
       AutoSetCurrentTransaction asct(mTransaction);
 
-      rv = db->CreateObjectStoreInternal(mTransaction, info,
-                                         getter_AddRefs(objectStore));
+      objectStore = db->CreateObjectStoreInternal(mTransaction, info, rv);
     }
 
-    NS_ENSURE_SUCCESS(rv, false);
+    ENSURE_SUCCESS(rv, false);
 
     actor->SetObjectStore(objectStore);
     objectStore->SetActor(actor);
     return true;
   }
 
   return
     IndexedDBTransactionParent::RecvPIndexedDBObjectStoreConstructor(aActor,
@@ -1148,18 +1135,19 @@ IndexedDBObjectStoreParent::RecvPIndexed
     const GetIndexParams& params = aParams.get_GetIndexParams();
     const nsString& name = params.name();
 
     nsRefPtr<IDBIndex> index;
 
     {
       AutoSetCurrentTransaction asct(mObjectStore->Transaction());
 
-      nsresult rv = mObjectStore->IndexInternal(name, getter_AddRefs(index));
-      NS_ENSURE_SUCCESS(rv, false);
+      ErrorResult rv;
+      index = mObjectStore->Index(name, rv);
+      ENSURE_SUCCESS(rv, false);
 
       actor->SetIndex(index);
     }
 
     index->SetActor(actor);
     return true;
   }
 
@@ -1248,26 +1236,25 @@ IndexedDBVersionChangeObjectStoreParent:
   }
 
   if (mObjectStore->Transaction()->Database()->IsInvalidated()) {
     // If we've invalidated this database in the parent then we should bail out
     // now to avoid logic problems that could force-kill the child.
     return true;
   }
 
-  nsresult rv;
+  ErrorResult rv;
 
   {
     AutoSetCurrentTransaction asct(mObjectStore->Transaction());
 
-    rv = mObjectStore->DeleteIndex(aName);
+    mObjectStore->DeleteIndex(aName, rv);
   }
 
-  NS_ENSURE_SUCCESS(rv, false);
-
+  ENSURE_SUCCESS(rv, false);
   return true;
 }
 
 bool
 IndexedDBVersionChangeObjectStoreParent::RecvPIndexedDBIndexConstructor(
                                           PIndexedDBIndexParent* aActor,
                                           const IndexConstructorParams& aParams)
 {
@@ -1292,26 +1279,24 @@ IndexedDBVersionChangeObjectStoreParent:
     MOZ_ASSERT(mObjectStore->Transaction()->GetMode() ==
                IDBTransaction::VERSION_CHANGE);
 
     const CreateIndexParams& params = aParams.get_CreateIndexParams();
     const IndexInfo& info = params.info();
 
     nsRefPtr<IDBIndex> index;
 
-    nsresult rv;
-
     {
       AutoSetCurrentTransaction asct(mObjectStore->Transaction());
 
-      rv = mObjectStore->CreateIndexInternal(info, getter_AddRefs(index));
+      ErrorResult rv;
+      index = mObjectStore->CreateIndexInternal(info, rv);
+      ENSURE_SUCCESS(rv, false);
     }
 
-    NS_ENSURE_SUCCESS(rv, false);
-
     actor->SetIndex(index);
     index->SetActor(actor);
     return true;
   }
 
   return IndexedDBObjectStoreParent::RecvPIndexedDBIndexConstructor(aActor,
                                                                     aParams);
 }
@@ -1508,19 +1493,19 @@ IndexedDBObjectStoreRequestParent::Get(c
 
   nsRefPtr<IDBKeyRange> keyRange =
     IDBKeyRange::FromSerializedKeyRange(aParams.keyRange());
   MOZ_ASSERT(keyRange);
 
   {
     AutoSetCurrentTransaction asct(mObjectStore->Transaction());
 
-    nsresult rv = mObjectStore->GetInternal(keyRange, nullptr,
-                                            getter_AddRefs(request));
-    NS_ENSURE_SUCCESS(rv, false);
+    ErrorResult rv;
+    request = mObjectStore->GetInternal(keyRange, rv);
+    ENSURE_SUCCESS(rv, false);
   }
 
   request->SetActor(this);
   mRequest.swap(request);
 
   return true;
 }
 
@@ -1548,20 +1533,19 @@ IndexedDBObjectStoreRequestParent::GetAl
 
     default:
       MOZ_CRASH("Unknown param type!");
   }
 
   {
     AutoSetCurrentTransaction asct(mObjectStore->Transaction());
 
-    nsresult rv = mObjectStore->GetAllInternal(keyRange, aParams.limit(),
-                                               nullptr,
-                                               getter_AddRefs(request));
-    NS_ENSURE_SUCCESS(rv, false);
+    ErrorResult rv;
+    request = mObjectStore->GetAllInternal(keyRange, aParams.limit(), rv);
+    ENSURE_SUCCESS(rv, false);
   }
 
   request->SetActor(this);
   mRequest.swap(request);
   return true;
 }
 
 bool
@@ -1630,19 +1614,19 @@ IndexedDBObjectStoreRequestParent::Delet
 
   nsRefPtr<IDBKeyRange> keyRange =
     IDBKeyRange::FromSerializedKeyRange(aParams.keyRange());
   MOZ_ASSERT(keyRange);
 
   {
     AutoSetCurrentTransaction asct(mObjectStore->Transaction());
 
-    nsresult rv =
-      mObjectStore->DeleteInternal(keyRange, nullptr, getter_AddRefs(request));
-    NS_ENSURE_SUCCESS(rv, false);
+    ErrorResult rv;
+    request = mObjectStore->DeleteInternal(keyRange, rv);
+    ENSURE_SUCCESS(rv, false);
   }
 
   request->SetActor(this);
   mRequest.swap(request);
   return true;
 }
 
 bool
@@ -1651,18 +1635,19 @@ IndexedDBObjectStoreRequestParent::Clear
   MOZ_ASSERT(mRequestType == ParamsUnionType::TClearParams);
   MOZ_ASSERT(mObjectStore);
 
   nsRefPtr<IDBRequest> request;
 
   {
     AutoSetCurrentTransaction asct(mObjectStore->Transaction());
 
-    nsresult rv = mObjectStore->ClearInternal(nullptr, getter_AddRefs(request));
-    NS_ENSURE_SUCCESS(rv, false);
+    ErrorResult rv;
+    request = mObjectStore->Clear(rv);
+    ENSURE_SUCCESS(rv, false);
   }
 
   request->SetActor(this);
   mRequest.swap(request);
   return true;
 }
 
 bool
@@ -1689,19 +1674,19 @@ IndexedDBObjectStoreRequestParent::Count
       MOZ_CRASH("Unknown param type!");
   }
 
   nsRefPtr<IDBRequest> request;
 
   {
     AutoSetCurrentTransaction asct(mObjectStore->Transaction());
 
-    nsresult rv =
-      mObjectStore->CountInternal(keyRange, nullptr, getter_AddRefs(request));
-    NS_ENSURE_SUCCESS(rv, false);
+    ErrorResult rv;
+    request = mObjectStore->CountInternal(keyRange, rv);
+    ENSURE_SUCCESS(rv, false);
   }
 
   request->SetActor(this);
   mRequest.swap(request);
   return true;
 }
 
 bool
@@ -1730,20 +1715,19 @@ IndexedDBObjectStoreRequestParent::OpenC
 
   size_t direction = static_cast<size_t>(aParams.direction());
 
   nsRefPtr<IDBRequest> request;
 
   {
     AutoSetCurrentTransaction asct(mObjectStore->Transaction());
 
-    nsresult rv =
-      mObjectStore->OpenCursorInternal(keyRange, direction, nullptr,
-                                       getter_AddRefs(request));
-    NS_ENSURE_SUCCESS(rv, false);
+    ErrorResult rv;
+    request = mObjectStore->OpenCursorInternal(keyRange, direction, rv);
+    ENSURE_SUCCESS(rv, false);
   }
 
   request->SetActor(this);
   mRequest.swap(request);
   return true;
 }
 
 /*******************************************************************************
@@ -1784,19 +1768,19 @@ IndexedDBIndexRequestParent::Get(const G
 
   nsRefPtr<IDBKeyRange> keyRange =
     IDBKeyRange::FromSerializedKeyRange(aParams.keyRange());
   MOZ_ASSERT(keyRange);
 
   {
     AutoSetCurrentTransaction asct(mIndex->ObjectStore()->Transaction());
 
-    nsresult rv = mIndex->GetInternal(keyRange, nullptr,
-                                      getter_AddRefs(request));
-    NS_ENSURE_SUCCESS(rv, false);
+    ErrorResult rv;
+    request = mIndex->GetInternal(keyRange, rv);
+    ENSURE_SUCCESS(rv, false);
   }
 
   request->SetActor(this);
   mRequest.swap(request);
   return true;
 }
 
 bool
@@ -1809,19 +1793,19 @@ IndexedDBIndexRequestParent::GetKey(cons
 
   nsRefPtr<IDBKeyRange> keyRange =
     IDBKeyRange::FromSerializedKeyRange(aParams.keyRange());
   MOZ_ASSERT(keyRange);
 
   {
     AutoSetCurrentTransaction asct(mIndex->ObjectStore()->Transaction());
 
-    nsresult rv = mIndex->GetKeyInternal(keyRange, nullptr,
-                                         getter_AddRefs(request));
-    NS_ENSURE_SUCCESS(rv, false);
+    ErrorResult rv;
+    request = mIndex->GetKeyInternal(keyRange, rv);
+    ENSURE_SUCCESS(rv, false);
   }
 
   request->SetActor(this);
   mRequest.swap(request);
   return true;
 }
 
 bool
@@ -1848,19 +1832,19 @@ IndexedDBIndexRequestParent::GetAll(cons
 
     default:
       MOZ_CRASH("Unknown param type!");
   }
 
   {
     AutoSetCurrentTransaction asct(mIndex->ObjectStore()->Transaction());
 
-    nsresult rv = mIndex->GetAllInternal(keyRange, aParams.limit(), nullptr,
-                                         getter_AddRefs(request));
-    NS_ENSURE_SUCCESS(rv, false);
+    ErrorResult rv;
+    request = mIndex->GetAllInternal(keyRange, aParams.limit(), rv);
+    ENSURE_SUCCESS(rv, false);
   }
 
   request->SetActor(this);
   mRequest.swap(request);
   return true;
 }
 
 bool
@@ -1887,19 +1871,19 @@ IndexedDBIndexRequestParent::GetAllKeys(
 
     default:
       MOZ_CRASH("Unknown param type!");
   }
 
   {
     AutoSetCurrentTransaction asct(mIndex->ObjectStore()->Transaction());
 
-    nsresult rv = mIndex->GetAllKeysInternal(keyRange, aParams.limit(), nullptr,
-                                             getter_AddRefs(request));
-    NS_ENSURE_SUCCESS(rv, false);
+    ErrorResult rv;
+    request = mIndex->GetAllKeysInternal(keyRange, aParams.limit(), rv);
+    ENSURE_SUCCESS(rv, false);
   }
 
   request->SetActor(this);
   mRequest.swap(request);
   return true;
 }
 
 bool
@@ -1926,19 +1910,19 @@ IndexedDBIndexRequestParent::Count(const
       MOZ_CRASH("Unknown param type!");
   }
 
   nsRefPtr<IDBRequest> request;
 
   {
     AutoSetCurrentTransaction asct(mIndex->ObjectStore()->Transaction());
 
-    nsresult rv = mIndex->CountInternal(keyRange, nullptr,
-                                        getter_AddRefs(request));
-    NS_ENSURE_SUCCESS(rv, false);
+    ErrorResult rv;
+    request = mIndex->CountInternal(keyRange, rv);
+    ENSURE_SUCCESS(rv, false);
   }
 
   request->SetActor(this);
   mRequest.swap(request);
   return true;
 }
 
 bool
@@ -2008,20 +1992,19 @@ IndexedDBIndexRequestParent::OpenKeyCurs
 
   size_t direction = static_cast<size_t>(aParams.direction());
 
   nsRefPtr<IDBRequest> request;
 
   {
     AutoSetCurrentTransaction asct(mIndex->ObjectStore()->Transaction());
 
-    nsresult rv =
-      mIndex->OpenKeyCursorInternal(keyRange, direction, nullptr,
-                                    getter_AddRefs(request));
-    NS_ENSURE_SUCCESS(rv, false);
+    ErrorResult rv;
+    request = mIndex->OpenKeyCursorInternal(keyRange, direction, rv);
+    ENSURE_SUCCESS(rv, false);
   }
 
   request->SetActor(this);
   mRequest.swap(request);
   return true;
 }
 
 /*******************************************************************************
--- a/dom/indexedDB/moz.build
+++ b/dom/indexedDB/moz.build
@@ -5,20 +5,17 @@
 # file, You can obtain one at http://mozilla.org/MPL/2.0/.
 
 DIRS += ['ipc']
 TEST_DIRS += ['test']
 
 XPIDL_SOURCES += [
     'nsIIDBCursor.idl',
     'nsIIDBCursorWithValue.idl',
-    'nsIIDBDatabase.idl',
-    'nsIIDBIndex.idl',
     'nsIIDBKeyRange.idl',
-    'nsIIDBObjectStore.idl',
     'nsIIDBOpenDBRequest.idl',
     'nsIIDBRequest.idl',
     'nsIIndexedDatabaseManager.idl',
 ]
 
 XPIDL_MODULE = 'dom_indexeddb'
 
 XPIDL_FLAGS += [
deleted file mode 100644
--- a/dom/indexedDB/nsIIDBDatabase.idl
+++ /dev/null
@@ -1,56 +0,0 @@
-/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
-/* vim: set ts=2 et sw=2 tw=80: */
-/* 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/. */
-
-#include "nsISupports.idl"
-
-interface nsIIDBObjectStore;
-interface nsIIDBRequest;
-interface nsIDOMDOMStringList;
-interface nsIDOMEventListener;
-
-/**
- * IDBDatabase interface.  See
- * http://dvcs.w3.org/hg/IndexedDB/raw-file/tip/Overview.html#idl-def-IDBDatabase
- * for more information.
- */
-[scriptable, builtinclass, uuid(89299bf8-e078-4ebc-abda-d97fe5618602)]
-interface nsIIDBDatabase : nsISupports
-{
-  readonly attribute DOMString name;
-
-  readonly attribute unsigned long long version;
-
-  readonly attribute nsIDOMDOMStringList objectStoreNames;
-
-  [implicit_jscontext]
-  nsIIDBObjectStore
-  createObjectStore([Null(Stringify)] in DOMString name,
-                    /* IDBObjectStoreParameters */
-                    [optional /* none */] in jsval options);
-
-  void
-  deleteObjectStore([Null(Stringify)] in DOMString name);
-
-  // mode can be either "readonly" or "readwrite"
-  [optional_argc, implicit_jscontext]
-  nsISupports
-  transaction(in jsval storeNames, // js array of strings
-              [optional /* "readonly" */] in DOMString mode);
-
-  [implicit_jscontext]
-  nsIIDBRequest
-  mozCreateFileHandle(in DOMString name,
-                      [optional] in DOMString type);
-
-  void
-  close();
-
-  [implicit_jscontext] attribute jsval onabort;
-
-  [implicit_jscontext] attribute jsval onerror;
-
-  [implicit_jscontext] attribute jsval onversionchange;
-};
deleted file mode 100644
--- a/dom/indexedDB/nsIIDBIndex.idl
+++ /dev/null
@@ -1,67 +0,0 @@
-/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
-/* vim: set ts=2 et sw=2 tw=80: */
-/* 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/. */
-
-#include "nsISupports.idl"
-
-interface nsIIDBObjectStore;
-interface nsIIDBRequest;
-
-/**
- * IDBIndex interface.  See
- * http://dev.w3.org/2006/webapi/WebSimpleDB/#idl-def-IDBIndex for more
- * information.
- */
-[scriptable, builtinclass, uuid(a859747a-0f05-4dfb-8f42-05c61415d4e4)]
-interface nsIIDBIndex : nsISupports
-{
-  readonly attribute DOMString name;
-
-  readonly attribute DOMString storeName;
-
-  [implicit_jscontext]
-  readonly attribute jsval keyPath;
-
-  readonly attribute boolean unique;
-
-  readonly attribute boolean multiEntry;
-
-  readonly attribute nsIIDBObjectStore objectStore;
-
-  [implicit_jscontext]
-  nsIIDBRequest
-  get(in jsval key);
-
-  [implicit_jscontext]
-  nsIIDBRequest
-  getKey(in jsval key);
-
-  [implicit_jscontext, optional_argc, binaryname(GetAll)]
-  nsIIDBRequest
-  mozGetAll([optional /* null */] in jsval key,
-            [optional /* unlimited */] in unsigned long limit);
-
-  [implicit_jscontext, optional_argc, binaryname(GetAllKeys)]
-  nsIIDBRequest
-  mozGetAllKeys([optional /* null */] in jsval key,
-                [optional /* unlimited */] in unsigned long limit);
-
-  // direction can be "next", "nextunique", "prev" or "prevunique"
-  [implicit_jscontext, optional_argc]
-  nsIIDBRequest
-  openCursor([optional /* null */] in jsval key,
-             [optional /* "next" */] in DOMString direction);
-
-  // direction can be "next", "nextunique", "prev" or "prevunique"
-  [implicit_jscontext, optional_argc]
-  nsIIDBRequest
-  openKeyCursor([optional /* null */] in jsval key,
-                [optional /* "next" */] in DOMString direction);
-
-  // Accepts null, a key value, or a nsIIDBKeyRange object.
-  [implicit_jscontext, optional_argc]
-  nsIIDBRequest
-  count([optional] in jsval key);
-};
deleted file mode 100644
--- a/dom/indexedDB/nsIIDBObjectStore.idl
+++ /dev/null
@@ -1,99 +0,0 @@
-/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
-/* vim: set ts=2 et sw=2 tw=80: */
-/* 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/. */
-
-#include "nsISupports.idl"
-
-interface nsIIDBIndex;
-interface nsIIDBKeyRange;
-interface nsIIDBRequest;
-interface nsIDOMDOMStringList;
-
-dictionary IDBIndexParameters
-{
-  boolean unique;
-  boolean multiEntry;
-};
-
-/**
- * nsIIDBObjectStore interface.  See
- * http://dev.w3.org/2006/webapi/WebSimpleDB/#idl-def-nsIIDBObjectStore
- * for more information.
- */
-[scriptable, builtinclass, uuid(dd189afd-e1b7-4496-bf8d-629c58709595)]
-interface nsIIDBObjectStore : nsISupports
-{
-  readonly attribute DOMString name;
-
-  [implicit_jscontext]
-  readonly attribute jsval keyPath;
-
-  readonly attribute nsIDOMDOMStringList indexNames;
-
-  // IDBTransaction
-  readonly attribute nsISupports transaction;
-
-  readonly attribute boolean autoIncrement;
-
-  // Success fires IDBTransactionEvent, result == value for key
-  [implicit_jscontext]
-  nsIIDBRequest
-  get(in jsval key);
-
-  // Success fires IDBTransactionEvent, result == array of values for given keys
-  [implicit_jscontext, optional_argc, binaryname(GetAll)]
-  nsIIDBRequest
-  mozGetAll([optional /* null */] in jsval key,
-            [optional /* unlimited */] in unsigned long limit);
-
-  // Success fires IDBTransactionEvent, result == key
-  [implicit_jscontext, optional_argc]
-  nsIIDBRequest
-  add(in jsval value,
-      [optional /* undefined */] in jsval key);
-
-  // Success fires IDBTransactionEvent, result == key
-  [implicit_jscontext, optional_argc]
-  nsIIDBRequest
-  put(in jsval value,
-      [optional /* undefined */] in jsval key);
-
-  // Success fires IDBTransactionEvent, result == null
-  [implicit_jscontext]
-  nsIIDBRequest
-  delete(in jsval key);
-
-  // Success fires IDBTransactionEvent, result == null
-  [implicit_jscontext]
-  nsIIDBRequest
-  clear();
-
-  // Success fires IDBTransactionEvent, result == IDBCursor or result == null if
-  // no match.
-  // direction can be "next", "nextunique", "prev" or "prevunique"
-  [implicit_jscontext, optional_argc]
-  nsIIDBRequest
-  openCursor([optional /* null */] in jsval range,
-             [optional /* "next" */] in DOMString direction);
-
-  [implicit_jscontext]
-  nsIIDBIndex
-  createIndex([Null(Stringify)] in DOMString name,
-              in jsval keyPath,
-              /* nsIIDBIndexParameters */
-              [optional /* none */] in jsval options);
-
-  // Returns object immediately
-  nsIIDBIndex
-  index([Null(Stringify)] in DOMString name);
-
-  void
-  deleteIndex([Null(Stringify)] in DOMString name);
-
-  // Accepts null, a key value, or a nsIIDBKeyRange object.
-  [implicit_jscontext, optional_argc]
-  nsIIDBRequest
-  count([optional] in jsval key);
-};
--- a/dom/indexedDB/test/browser_permissionsPromptAllow.js
+++ b/dom/indexedDB/test/browser_permissionsPromptAllow.js
@@ -19,17 +19,17 @@ function test1()
 {
   info("creating tab");
   gBrowser.selectedTab = gBrowser.addTab();
 
   gBrowser.selectedBrowser.addEventListener("load", function () {
     gBrowser.selectedBrowser.removeEventListener("load", arguments.callee, true);
 
     setFinishedCallback(function(result, exception) {
-      ok(result instanceof Components.interfaces.nsIIDBDatabase,
+      ok(result instanceof IDBDatabase,
          "First database creation was successful");
       ok(!exception, "No exception");
       is(getPermission(testPageURL, "indexedDB"),
          Components.interfaces.nsIPermissionManager.UNKNOWN_ACTION,
          "Correct permission set");
       gBrowser.removeCurrentTab();
       executeSoon(test2);
     });
@@ -55,17 +55,17 @@ function test2()
 {
   info("creating tab");
   gBrowser.selectedTab = gBrowser.addTab();
 
   gBrowser.selectedBrowser.addEventListener("load", function () {
     gBrowser.selectedBrowser.removeEventListener("load", arguments.callee, true);
 
     setFinishedCallback(function(result, exception) {
-      ok(result instanceof Components.interfaces.nsIIDBDatabase,
+      ok(result instanceof IDBDatabase,
          "First database creation was successful");
       ok(!exception, "No exception");
       is(getPermission(testPageURL, "indexedDB"),
          Components.interfaces.nsIPermissionManager.UNKNOWN_ACTION,
          "Correct permission set");
       gBrowser.removeCurrentTab();
       unregisterAllPopupEventHandlers();
       removePermission(testPageURL, "indexedDB");
--- a/dom/indexedDB/test/browser_perwindow_privateBrowsing.js
+++ b/dom/indexedDB/test/browser_perwindow_privateBrowsing.js
@@ -15,17 +15,17 @@ function test()
 
 function test1()
 {
   gBrowser.selectedTab = gBrowser.addTab();
   gBrowser.selectedBrowser.addEventListener("load", function () {
     gBrowser.selectedBrowser.removeEventListener("load", arguments.callee, true);
 
     setFinishedCallback(function(result, exception) {
-      ok(result instanceof Components.interfaces.nsIIDBDatabase,
+      ok(result instanceof IDBDatabase,
          "First database creation was successful");
       ok(!exception, "No exception");
       gBrowser.removeCurrentTab();
 
       executeSoon(test2);
     });
   }, true);
   content.location = testPageURL;
--- a/dom/indexedDB/test/unit/head.js
+++ b/dom/indexedDB/test/unit/head.js
@@ -3,19 +3,16 @@
  * http://creativecommons.org/publicdomain/zero/1.0/
  */
 
 const { 'classes': Cc, 'interfaces': Ci } = Components;
 
 const DOMException = Ci.nsIDOMDOMException;
 const IDBCursor = Ci.nsIIDBCursor;
 const IDBOpenDBRequest = Ci.nsIIDBOpenDBRequest;
-const IDBDatabase = Ci.nsIIDBDatabase
-const IDBIndex = Ci.nsIIDBIndex
-const IDBObjectStore = Ci.nsIIDBObjectStore
 const IDBRequest = Ci.nsIIDBRequest
 
 function is(a, b, msg) {
   dump("is(" + a + ", " + b + ", \"" + msg + "\")");
   do_check_eq(a, b, Components.stack.caller);
 }
 
 function ok(cond, msg) {
--- a/dom/indexedDB/test/unit/test_complex_keyPaths.js
+++ b/dom/indexedDB/test/unit/test_complex_keyPaths.js
@@ -2,18 +2,16 @@
  * Any copyright is dedicated to the Public Domain.
  * http://creativecommons.org/publicdomain/zero/1.0/
  */
 
 var testGenerator = testSteps();
 
 function testSteps()
 {
-  const nsIIDBObjectStore = Components.interfaces.nsIIDBObjectStore;
-
   // Test object stores
 
   const name = "test_complex_keyPaths";
   const keyPaths = [
     { keyPath: "id",      value: { id: 5 },                      key: 5 },
     { keyPath: "id",      value: { id: "14", iid: 12 },          key: "14" },
     { keyPath: "id",      value: { iid: "14", id: 12 },          key: 12 },
     { keyPath: "id",      value: {} },
--- a/dom/indexedDB/test/unit/test_objectStore_inline_autoincrement_key_added_on_put.js
+++ b/dom/indexedDB/test/unit/test_objectStore_inline_autoincrement_key_added_on_put.js
@@ -2,17 +2,16 @@
  * Any copyright is dedicated to the Public Domain.
  * http://creativecommons.org/publicdomain/zero/1.0/
  */
 
 var testGenerator = testSteps();
 
 function testSteps()
 {
-  const IDBObjectStore = Components.interfaces.nsIIDBObjectStore;
   const name = this.window ? window.location.pathname : "Splendid Test";
 
   var request = indexedDB.open(name, 1);
   request.onerror = errorHandler;
   request.onupgradeneeded = grabEventAndContinueHandler;
   var event = yield undefined;
 
   var db = event.target.result;
--- a/dom/indexedDB/test/unit/test_objectStore_remove_values.js
+++ b/dom/indexedDB/test/unit/test_objectStore_remove_values.js
@@ -2,17 +2,16 @@
  * Any copyright is dedicated to the Public Domain.
  * http://creativecommons.org/publicdomain/zero/1.0/
  */
 
 var testGenerator = testSteps();
 
 function testSteps()
 {
-  const IDBObjectStore = Components.interfaces.nsIIDBObjectStore;
   const name = this.window ? window.location.pathname : "Splendid Test";
 
   var data = [
     { name: "inline key; key generator",
       autoIncrement: true,
       storedObject: {name: "Lincoln"},
       keyName: "id",
       keyValue: undefined,
--- a/dom/indexedDB/test/unit/test_open_objectStore.js
+++ b/dom/indexedDB/test/unit/test_open_objectStore.js
@@ -2,17 +2,16 @@
  * Any copyright is dedicated to the Public Domain.
  * http://creativecommons.org/publicdomain/zero/1.0/
  */
 
 var testGenerator = testSteps();
 
 function testSteps()
 {
-  const nsIIDBObjectStore = Components.interfaces.nsIIDBObjectStore;
   const name = this.window ? window.location.pathname : "Splendid Test";
   const objectStoreName = "Objects";
 
   let request = indexedDB.open(name, 1);
   request.onerror = errorHandler;
   request.onupgradeneeded = grabEventAndContinueHandler;
   request.onsuccess = grabEventAndContinueHandler;
   let event = yield undefined;
--- a/dom/indexedDB/test/unit/test_remove_index.js
+++ b/dom/indexedDB/test/unit/test_remove_index.js
@@ -2,18 +2,16 @@
  * Any copyright is dedicated to the Public Domain.
  * http://creativecommons.org/publicdomain/zero/1.0/
  */
 
 var testGenerator = testSteps();
 
 function testSteps()
 {
-  const nsIIDBObjectStore = Components.interfaces.nsIIDBObjectStore;
-
   const name = this.window ? window.location.pathname : "Splendid Test";
   const indexName = "My Test Index";
 
   let request = indexedDB.open(name, 1);
   request.onerror = errorHandler;
   request.onupgradeneeded = grabEventAndContinueHandler;
   let event = yield undefined;
 
--- a/dom/indexedDB/test/unit/test_remove_objectStore.js
+++ b/dom/indexedDB/test/unit/test_remove_objectStore.js
@@ -2,18 +2,16 @@
  * Any copyright is dedicated to the Public Domain.
  * http://creativecommons.org/publicdomain/zero/1.0/
  */
 
 var testGenerator = testSteps();
 
 function testSteps()
 {
-  const nsIIDBObjectStore = Components.interfaces.nsIIDBObjectStore;
-
   const name = this.window ? window.location.pathname : "Splendid Test";
   const objectStoreName = "Objects";
 
   let request = indexedDB.open(name, 1);
   request.onerror = errorHandler;
   request.onupgradeneeded = grabEventAndContinueHandler;
   let event = yield undefined;
 
--- a/dom/interfaces/base/moz.build
+++ b/dom/interfaces/base/moz.build
@@ -11,17 +11,16 @@ XPIDL_SOURCES += [
     'nsIContentPrefService.idl',
     'nsIContentPrefService2.idl',
     'nsIContentURIGrouper.idl',
     'nsIDOMCRMFObject.idl',
     'nsIDOMChromeWindow.idl',
     'nsIDOMClientRect.idl',
     'nsIDOMClientRectList.idl',
     'nsIDOMConstructor.idl',
-    'nsIDOMGlobalObjectConstructor.idl',
     'nsIDOMGlobalPropertyInitializer.idl',
     'nsIDOMHistory.idl',
     'nsIDOMJSWindow.idl',
     'nsIDOMLocation.idl',
     'nsIDOMMediaQueryList.idl',
     'nsIDOMModalContentWindow.idl',
     'nsIDOMNavigator.idl',
     'nsIDOMPkcs11.idl',
deleted file mode 100644
--- a/dom/interfaces/base/nsIDOMGlobalObjectConstructor.idl
+++ /dev/null
@@ -1,19 +0,0 @@
-/* -*- Mode: IDL; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-#include "domstubs.idl"
-
-[scriptable, uuid(cb439c73-0129-4289-a349-c5216e6b912a)]
-interface nsIDOMGlobalObjectConstructor : nsISupports
-{
-  /*
-   * JS use only
-   *
-   * The constructor() method will be called with any parameters passed
-   * to the object constructor.
-   * If the JS implementation returns a value, it will be ignored.
-   */
-  void constructor();
-};
--- a/dom/plugins/base/nsJSNPRuntime.cpp
+++ b/dom/plugins/base/nsJSNPRuntime.cpp
@@ -1080,17 +1080,17 @@ GetNPObjectWrapper(JSContext *cx, JSObje
   JS::Rooted<JSObject*> obj(cx, aObj);
   while (obj && (obj = js::CheckedUnwrap(obj))) {
     if (JS_GetClass(obj) == &sNPObjectJSWrapperClass) {
       if (wrapResult && !JS_WrapObject(cx, obj.address())) {
         return NULL;
       }
       return obj;
     }
-    if (!::JS_GetPrototype(cx, obj, obj.address())) {
+    if (!::JS_GetPrototype(cx, obj, &obj)) {
       return NULL;
     }
   }
   return NULL;
 }
 
 static NPObject *
 GetNPObject(JSContext *cx, JSObject *obj)
--- a/dom/quota/nsIOfflineStorage.h
+++ b/dom/quota/nsIOfflineStorage.h
@@ -68,25 +68,9 @@ NS_DEFINE_STATIC_IID_ACCESSOR(nsIOffline
   Close() MOZ_OVERRIDE;                                                        \
                                                                                \
   NS_IMETHOD_(bool)                                                            \
   IsClosed() MOZ_OVERRIDE;                                                     \
                                                                                \
   NS_IMETHOD_(void)                                                            \
   Invalidate() MOZ_OVERRIDE;
 
-#define NS_DECL_NSIOFFLINESTORAGE_NOCLOSE                                      \
-  NS_IMETHOD_(Client*)                                                         \
-  GetClient() MOZ_OVERRIDE;                                                    \
-                                                                               \
-  NS_IMETHOD_(bool)                                                            \
-  IsOwned(nsPIDOMWindow* aOwner) MOZ_OVERRIDE;                                 \
-                                                                               \
-  NS_IMETHOD_(const nsACString&)                                               \
-  Origin() MOZ_OVERRIDE;                                                       \
-                                                                               \
-  NS_IMETHOD_(bool)                                                            \
-  IsClosed() MOZ_OVERRIDE;                                                     \
-                                                                               \
-  NS_IMETHOD_(void)                                                            \
-  Invalidate() MOZ_OVERRIDE;
-
 #endif // nsIOfflineStorage_h__
--- a/dom/system/NetworkGeolocationProvider.js
+++ b/dom/system/NetworkGeolocationProvider.js
@@ -180,17 +180,17 @@ WifiGeoPositionProvider.prototype = {
     };
 
     xhr.onload = function() {  
         LOG("gls returned status: " + xhr.status + " --> " +  JSON.stringify(xhr.response));
         if (xhr.status != 200) {
             return;
         }
 
-        if (!xhr.response.location) {
+        if (!xhr.response || !xhr.response.location) {
             return;
         }
 
         let newLocation = new WifiGeoPositionObject(xhr.response.location.lat,
                                                     xhr.response.location.lng,
                                                     xhr.response.accuracy);
         
         Cc["@mozilla.org/geolocation/service;1"].getService(Ci.nsIGeolocationUpdate)
--- a/dom/webidl/DummyBinding.webidl
+++ b/dom/webidl/DummyBinding.webidl
@@ -13,17 +13,16 @@ interface DummyInterface {
   InspectorRGBTriple rgbTriple();
   Function getFunction();
   void funcSocketsDict(optional SocketsDict arg);
   void funcHttpConnDict(optional HttpConnDict arg);
   void funcWebSocketDict(optional WebSocketDict arg);
   void funcDNSCacheDict(optional DNSCacheDict arg);
   void funcConnStatusDict(optional ConnStatusDict arg);
   void frameRequestCallback(FrameRequestCallback arg);
-  void idbObjectStoreParams(optional IDBObjectStoreParameters arg);
   void CameraPictureOptions(optional CameraPictureOptions arg);
   void MmsParameters(optional MmsParameters arg);
   void MmsAttachment(optional MmsAttachment arg);
 };
 
 interface DummyInterfaceWorkers {
   BlobPropertyBag blobBag();
 };
new file mode 100644
--- /dev/null
+++ b/dom/webidl/IDBCursor.webidl
@@ -0,0 +1,15 @@
+/* -*- Mode: IDL; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/.
+ *
+ * The origin of this IDL file is
+ * https://dvcs.w3.org/hg/IndexedDB/raw-file/tip/Overview.html#idl-def-IDBCursorDirection
+ */
+
+enum IDBCursorDirection {
+    "next",
+    "nextunique",
+    "prev",
+    "prevunique"
+};
--- a/dom/webidl/IDBDatabase.webidl
+++ b/dom/webidl/IDBDatabase.webidl
@@ -5,16 +5,45 @@
  *
  * The origin of this IDL file is
  * https://dvcs.w3.org/hg/IndexedDB/raw-file/tip/Overview.html#idl-def-IDBObjectStoreParameters
  *
  * Copyright © 2012 W3C® (MIT, ERCIM, Keio), All Rights Reserved. W3C
  * liability, trademark and document use rules apply.
  */
 
-dictionary IDBObjectStoreParameters {
-  // XXXbz this should be "(DOMString or sequence<DOMString>)?", but
-  // we don't support unions in dictionaries yet.  See bug 767926.
-  any keyPath = null;
-  boolean autoIncrement = false;
+interface IDBDatabase : EventTarget {
+    readonly    attribute DOMString          name;
+    readonly    attribute unsigned long long version;
+
+    [Throws]
+    readonly    attribute DOMStringList      objectStoreNames;
+
+    [Throws]
+    IDBObjectStore createObjectStore (DOMString name, optional IDBObjectStoreParameters optionalParameters);
+
+    [Throws]
+    void           deleteObjectStore (DOMString name);
+
+    // This should be:
+    // IDBTransaction transaction ((DOMString or sequence<DOMString>) storeNames, optional IDBTransactionMode mode = "readonly");
+    // but unions are not currently supported.
+
+    [Throws]
+    IDBTransaction transaction (DOMString storeName, optional IDBTransactionMode mode = "readonly");
+
+    [Throws]
+    IDBTransaction transaction (sequence<DOMString> storeNames, optional IDBTransactionMode mode = "readonly");
+
+    void           close ();
+
+    [SetterThrows]
+                attribute EventHandler       onabort;
+    [SetterThrows]
+                attribute EventHandler       onerror;
+    [SetterThrows]
+                attribute EventHandler       onversionchange;
 };
 
-// If we start using IDBObjectStoreParameters here, remove it from DummyBinding.
+partial interface IDBDatabase {
+    [Throws]
+    IDBRequest mozCreateFileHandle (DOMString name, optional DOMString type);
+};
--- a/dom/webidl/IDBFileHandle.webidl
+++ b/dom/webidl/IDBFileHandle.webidl
@@ -1,10 +1,8 @@
 /* -*- Mode: IDL; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
-interface IDBDatabase;
-
 interface IDBFileHandle : FileHandle {
   readonly attribute IDBDatabase database;
 };
new file mode 100644
--- /dev/null
+++ b/dom/webidl/IDBIndex.webidl
@@ -0,0 +1,49 @@
+/* -*- Mode: IDL; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/.
+ *
+ * The origin of this IDL file is
+ * https://dvcs.w3.org/hg/IndexedDB/raw-file/tip/Overview.html#idl-def-IDBIndexParameters
+ */
+
+dictionary IDBIndexParameters {
+    boolean unique = false;
+    boolean multiEntry = false;
+};
+
+interface IDBIndex {
+    readonly    attribute DOMString      name;
+    readonly    attribute IDBObjectStore objectStore;
+
+    [Throws]
+    readonly    attribute any            keyPath;
+
+    readonly    attribute boolean        multiEntry;
+    readonly    attribute boolean        unique;
+
+    [Throws]
+    IDBRequest openCursor (optional any range, optional IDBCursorDirection direction = "next");
+
+    [Throws]
+    IDBRequest openKeyCursor (optional any range, optional IDBCursorDirection direction = "next");
+
+    [Throws]
+    IDBRequest get (any key);
+
+    [Throws]
+    IDBRequest getKey (any key);
+
+    [Throws]
+    IDBRequest count (optional any key);
+};
+
+partial interface IDBIndex {
+    readonly attribute DOMString storeName;
+
+    [Throws]
+    IDBRequest mozGetAll (optional any key, optional unsigned long limit);
+
+    [Throws]
+    IDBRequest mozGetAllKeys (optional any key, optional unsigned long limit);
+};
new file mode 100644
--- /dev/null
+++ b/dom/webidl/IDBObjectStore.webidl
@@ -0,0 +1,70 @@
+/* -*- Mode: IDL; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/.
+ *
+ * The origin of this IDL file is
+ * https://dvcs.w3.org/hg/IndexedDB/raw-file/tip/Overview.html#idl-def-IDBObjectStore
+ */
+
+interface IDBRequest;
+
+dictionary IDBObjectStoreParameters {
+    // TODO (DOMString or sequence<DOMString>)? keyPath = null;
+    any                                         keyPath = null;
+    boolean                             autoIncrement = false;
+};
+
+interface IDBObjectStore {
+    readonly    attribute DOMString      name;
+
+    [Throws]
+    readonly    attribute any            keyPath;
+
+    [Throws]
+    readonly    attribute DOMStringList  indexNames;
+    readonly    attribute IDBTransaction transaction;
+    readonly    attribute boolean        autoIncrement;
+
+    [Throws]
+    IDBRequest put (any value, optional any key);
+
+    [Throws]
+    IDBRequest add (any value, optional any key);
+
+    [Throws]
+    IDBRequest delete (any key);
+
+    [Throws]
+    IDBRequest get (any key);
+
+    [Throws]
+    IDBRequest clear ();
+
+    [Throws]
+    IDBRequest openCursor (optional any range, optional IDBCursorDirection direction = "next");
+
+    // Bug 899972
+    // IDBIndex   createIndex (DOMString name, (DOMString or sequence<DOMString>) keyPath, optional IDBIndexParameters optionalParameters);
+
+    [Throws]
+    IDBIndex   createIndex (DOMString name, DOMString keyPath, optional IDBIndexParameters optionalParameters);
+
+    [Throws]
+    IDBIndex   createIndex (DOMString name, sequence<DOMString> keyPath, optional IDBIndexParameters optionalParameters);
+
+    [Throws]
+    IDBIndex   index (DOMString name);
+
+    [Throws]
+    void       deleteIndex (DOMString indexName);
+
+    [Throws]
+    IDBRequest count (optional any key);
+};
+
+partial interface IDBObjectStore {
+    // Success fires IDBTransactionEvent, result == array of values for given keys
+    [Throws]
+    IDBRequest mozGetAll (optional any key, optional unsigned long limit);
+};
--- a/dom/webidl/IDBTransaction.webidl
+++ b/dom/webidl/IDBTransaction.webidl
@@ -3,18 +3,16 @@
  * License, v. 2.0. If a copy of the MPL was not distributed with this file,
  * You can obtain one at http://mozilla.org/MPL/2.0/.
  *
  * The origin of this IDL file is
  * https://dvcs.w3.org/hg/IndexedDB/raw-file/tip/Overview.html#idl-def-IDBTransaction
  * https://dvcs.w3.org/hg/IndexedDB/raw-file/tip/Overview.html#idl-def-IDBTransactionMode
  */
 
-interface IDBObjectStore;
-
 enum IDBTransactionMode {
     "readonly",
     "readwrite",
     "versionchange"
 };
 
 interface IDBTransaction : EventTarget {
     [Throws]
--- a/dom/webidl/WebIDL.mk
+++ b/dom/webidl/WebIDL.mk
@@ -159,19 +159,22 @@ webidl_files = \
   HTMLTableSectionElement.webidl \
   HTMLTemplateElement.webidl \
   HTMLTextAreaElement.webidl \
   HTMLTimeElement.webidl \
   HTMLTitleElement.webidl \
   HTMLTrackElement.webidl \
   HTMLUListElement.webidl \
   HTMLVideoElement.webidl \
+  IDBCursor.webidl \
   IDBDatabase.webidl \
   IDBFactory.webidl \
   IDBFileHandle.webidl \
+  IDBIndex.webidl \
+  IDBObjectStore.webidl \
   IDBTransaction.webidl \
   IDBVersionChangeEvent.webidl \
   ImageData.webidl \
   ImageDocument.webidl \
   InspectorUtils.webidl \
   KeyboardEvent.webidl \
   KeyEvent.webidl \
   LinkStyle.webidl \
--- a/dom/workers/WorkerScope.cpp
+++ b/dom/workers/WorkerScope.cpp
@@ -974,24 +974,24 @@ CreateDedicatedWorkerGlobalScope(JSConte
   //          -> Object
 
   JS::Rooted<JSObject*> eventTargetProto(aCx,
     EventTargetBinding_workers::GetProtoObject(aCx, global));
   if (!eventTargetProto) {
     return NULL;
   }
 
-  JSObject* scopeProto =
-    WorkerGlobalScope::InitClass(aCx, global, eventTargetProto);
+  JS::Rooted<JSObject*> scopeProto(aCx,
+    WorkerGlobalScope::InitClass(aCx, global, eventTargetProto));
   if (!scopeProto) {
     return NULL;
   }
 
-  JSObject* dedicatedScopeProto =
-    DedicatedWorkerGlobalScope::InitClass(aCx, global, scopeProto);
+  JS::Rooted<JSObject*> dedicatedScopeProto(aCx,
+    DedicatedWorkerGlobalScope::InitClass(aCx, global, scopeProto));
   if (!dedicatedScopeProto) {
     return NULL;
   }
 
   if (!JS_SetPrototype(aCx, global, dedicatedScopeProto)) {
     return NULL;
   }
 
--- a/gfx/layers/TiledLayerBuffer.h
+++ b/gfx/layers/TiledLayerBuffer.h
@@ -106,26 +106,21 @@ public:
   bool RemoveTile(const nsIntPoint& aTileOrigin, Tile& aRemovedTile);
 
   // This operates the same as GetTile(x, y), but will also replace the
   // specified tile with the placeholder tile. This does not call ReleaseTile
   // on the removed tile.
   bool RemoveTile(int x, int y, Tile& aRemovedTile);
 
   uint16_t GetTileLength() const { return TILEDLAYERBUFFER_TILE_SIZE; }
-  uint32_t GetScaledTileLength() const {
-    // volatile variables to help investigate bug 881018
-    volatile float resolution = mResolution;
-    volatile float fScaledLength = TILEDLAYERBUFFER_TILE_SIZE / mResolution;
-    volatile uint32_t uiScaledLength = TILEDLAYERBUFFER_TILE_SIZE / mResolution;
-    if (!uiScaledLength) {
-        MOZ_CRASH();
-    }
-    return uiScaledLength;
-  }
+
+#ifdef MOZ_WIDGET_ANDROID
+  MOZ_NEVER_INLINE // bug 881018 causes wrong results when GetScaledTileLength is inlined
+#endif
+  uint32_t GetScaledTileLength() const { return TILEDLAYERBUFFER_TILE_SIZE / mResolution; }
 
   unsigned int GetTileCount() const { return mRetainedTiles.Length(); }
 
   const nsIntRegion& GetValidRegion() const { return mValidRegion; }
   const nsIntRegion& GetPaintedRegion() const { return mPaintedRegion; }
   void ClearPaintedRegion() { mPaintedRegion.SetEmpty(); }
 
   // Given a position i, this function returns the position inside the current tile.
--- a/gfx/thebes/gfxASurface.cpp
+++ b/gfx/thebes/gfxASurface.cpp
@@ -108,17 +108,17 @@ gfxASurface::SurfaceDestroyFunc(void *da
     // fprintf (stderr, "Deleting wrapper for %p (wrapper: %p)\n", surf->mSurface, data);
     delete surf;
 }
 
 gfxASurface*
 gfxASurface::GetSurfaceWrapper(cairo_surface_t *csurf)
 {
     if (!csurf)
-        return NULL;
+        return nullptr;
     return (gfxASurface*) cairo_surface_get_user_data(csurf, &gfxasurface_pointer_key);
 }
 
 void
 gfxASurface::SetSurfaceWrapper(cairo_surface_t *csurf, gfxASurface *asurf)
 {
     if (!csurf)
         return;
@@ -276,17 +276,17 @@ gfxASurface::SetData(const cairo_user_da
         return;
     cairo_surface_set_user_data(mSurface, key, user_data, destroy);
 }
 
 void *
 gfxASurface::GetData(const cairo_user_data_key_t *key)
 {
     if (!mSurfaceValid)
-        return NULL;
+        return nullptr;
     return cairo_surface_get_user_data(mSurface, key);
 }
 
 void
 gfxASurface::Finish()
 {
     // null surfaces are allowed here
     cairo_surface_finish(mSurface);
--- a/gfx/thebes/gfxAndroidPlatform.cpp
+++ b/gfx/thebes/gfxAndroidPlatform.cpp
@@ -22,17 +22,17 @@
 #include "ft2build.h"
 #include FT_FREETYPE_H
 #include FT_MODULE_H
 
 using namespace mozilla;
 using namespace mozilla::dom;
 using namespace mozilla::gfx;
 
-static FT_Library gPlatformFTLibrary = NULL;
+static FT_Library gPlatformFTLibrary = nullptr;
 
 static int64_t sFreetypeMemoryUsed;
 static FT_MemoryRec_ sFreetypeMemoryRecord;
 
 static int64_t
 GetFreetypeSize()
 {
     return sFreetypeMemoryUsed;
@@ -109,17 +109,17 @@ gfxAndroidPlatform::gfxAndroidPlatform()
 
 }
 
 gfxAndroidPlatform::~gfxAndroidPlatform()
 {
     cairo_debug_reset_static_data();
 
     FT_Done_Library(gPlatformFTLibrary);
-    gPlatformFTLibrary = NULL;
+    gPlatformFTLibrary = nullptr;
 }
 
 already_AddRefed<gfxASurface>
 gfxAndroidPlatform::CreateOffscreenSurface(const gfxIntSize& size,
                                       gfxASurface::gfxContentType contentType)
 {
     nsRefPtr<gfxASurface> newSurface;
     newSurface = new gfxImageSurface(size, OptimalFormatForContent(contentType));
--- a/gfx/thebes/gfxBlur.h
+++ b/gfx/thebes/gfxBlur.h
@@ -47,22 +47,23 @@ public:
      * @param aRect The coordinates of the surface to create in device units.
      *
      * @param aBlurRadius The blur radius in pixels.  This is the radius of
      *   the entire (triple) kernel function.  Each individual box blur has
      *   radius approximately 1/3 this value, or diameter approximately 2/3
      *   this value.  This parameter should nearly always be computed using
      *   CalculateBlurRadius, below.
      *
-     * @param aDirtyRect A pointer to a dirty rect, measured in device units, if available.
-     *  This will be used for optimizing the blur operation. It is safe to pass NULL here.
+     * @param aDirtyRect A pointer to a dirty rect, measured in device units,
+     *  if available. This will be used for optimizing the blur operation. It
+     *  is safe to pass nullptr here.
      *
-     * @param aSkipRect A pointer to a rect, measured in device units, that represents an area
-     *  where blurring is unnecessary and shouldn't be done for speed reasons. It is safe to
-     *  pass NULL here.
+     * @param aSkipRect A pointer to a rect, measured in device units, that
+     *  represents an area where blurring is unnecessary and shouldn't be done
+     *  for speed reasons. It is safe to pass nullptr here.
      */
     gfxContext* Init(const gfxRect& aRect,
                      const gfxIntSize& aSpreadRadius,
                      const gfxIntSize& aBlurRadius,
                      const gfxRect* aDirtyRect,
                      const gfxRect* aSkipRect);
 
     /**
--- a/gfx/thebes/gfxContext.cpp
+++ b/gfx/thebes/gfxContext.cpp
@@ -31,17 +31,17 @@ using namespace mozilla;
 using namespace mozilla::gfx;
 
 /* This class lives on the stack and allows gfxContext users to easily, and
  * performantly get a gfx::Pattern to use for drawing in their current context.
  */
 class GeneralPattern
 {
 public:    
-  GeneralPattern(gfxContext *aContext) : mContext(aContext), mPattern(NULL) {}
+  GeneralPattern(gfxContext *aContext) : mContext(aContext), mPattern(nullptr) {}
   ~GeneralPattern() { if (mPattern) { mPattern->~Pattern(); } }
 
   operator mozilla::gfx::Pattern&()
   {
     gfxContext::AzureState &state = mContext->CurrentState();
 
     if (state.pattern) {
       return *state.pattern->GetPattern(mContext->mDT, state.patternTransformChanged ? &state.patternTransform : nullptr);
@@ -71,17 +71,17 @@ private:
     mozilla::AlignedStorage2<mozilla::gfx::SurfacePattern> mSurfacePattern;
   };
 
   gfxContext *mContext;
   Pattern *mPattern;
 };
 
 gfxContext::gfxContext(gfxASurface *surface)
-  : mRefCairo(NULL)
+  : mRefCairo(nullptr)
   , mSurface(surface)
 {
   MOZ_COUNT_CTOR(gfxContext);
 
   mCairo = cairo_create(surface->CairoSurface());
   mFlags = surface->GetDefaultContextFlags();
   if (mSurface->GetRotateForLandscape()) {
     // Rotate page 90 degrees to draw landscape page on portrait paper
@@ -92,19 +92,19 @@ gfxContext::gfxContext(gfxASurface *surf
                       0,  0);
     Multiply(matrix);
   }
 }
 
 gfxContext::gfxContext(DrawTarget *aTarget)
   : mPathIsRect(false)
   , mTransformChanged(false)
-  , mCairo(NULL)
-  , mRefCairo(NULL)
-  , mSurface(NULL)
+  , mCairo(nullptr)
+  , mRefCairo(nullptr)
+  , mSurface(nullptr)
   , mFlags(0)
   , mDT(aTarget)
   , mOriginalDT(aTarget)
 {
   MOZ_COUNT_CTOR(gfxContext);
 
   mStateStack.SetLength(1);
   CurrentState().drawTarget = mDT;
@@ -219,18 +219,18 @@ gfxContext::Restore()
 
 // drawing
 void
 gfxContext::NewPath()
 {
   if (mCairo) {
     cairo_new_path(mCairo);
   } else {
-    mPath = NULL;
-    mPathBuilder = NULL;
+    mPath = nullptr;
+    mPathBuilder = nullptr;
     mPathIsRect = false;
     mTransformChanged = false;
   }
 }
 
 void
 gfxContext::ClosePath()
 {
@@ -929,17 +929,18 @@ gfxContext::SetDash(gfxFloat *dashes, in
     AzureState &state = CurrentState();
 
     state.dashPattern.SetLength(ndash);
     for (int i = 0; i < ndash; i++) {
       state.dashPattern[i] = Float(dashes[i]);
     }
     state.strokeOptions.mDashLength = ndash;
     state.strokeOptions.mDashOffset = Float(offset);
-    state.strokeOptions.mDashPattern = ndash ? state.dashPattern.Elements() : NULL;
+    state.strokeOptions.mDashPattern = ndash ? state.dashPattern.Elements()
+                                             : nullptr;
   }
 }
 
 bool
 gfxContext::CurrentDash(FallibleTArray<gfxFloat>& dashes, gfxFloat* offset) const
 {
   if (mCairo) {
     int count = cairo_get_dash_count(mCairo);
@@ -969,17 +970,17 @@ gfxContext::CurrentDash(FallibleTArray<g
 gfxFloat
 gfxContext::CurrentDashOffset() const
 {
   if (mCairo) {
     if (cairo_get_dash_count(mCairo) <= 0) {
         return 0.0;
     }
     gfxFloat offset;
-    cairo_get_dash(mCairo, NULL, &offset);
+    cairo_get_dash(mCairo, nullptr, &offset);
     return offset;
   } else {
     return CurrentState().strokeOptions.mDashOffset;
   }
 }
 
 void
 gfxContext::SetLineWidth(gfxFloat width)
@@ -1117,33 +1118,33 @@ gfxContext::CurrentFillRule() const
 void
 gfxContext::Clip(const gfxRect& rect)
 {
   if (mCairo) {
     cairo_new_path(mCairo);
     cairo_rectangle(mCairo, rect.X(), rect.Y(), rect.Width(), rect.Height());
     cairo_clip(mCairo);
   } else {
-    AzureState::PushedClip clip = { NULL, ToRect(rect), mTransform };
+    AzureState::PushedClip clip = { nullptr, ToRect(rect), mTransform };
     CurrentState().pushedClips.AppendElement(clip);
     mDT->PushClipRect(ToRect(rect));
     NewPath();
   }
 }
 
 void
 gfxContext::Clip()
 {
   if (mCairo) {
     cairo_clip_preserve(mCairo);
   } else {
     if (mPathIsRect) {
       MOZ_ASSERT(!mTransformChanged);
 
-      AzureState::PushedClip clip = { NULL, mRect, mTransform };
+      AzureState::PushedClip clip = { nullptr, mRect, mTransform };
       CurrentState().pushedClips.AppendElement(clip);
       mDT->PushClipRect(mRect);
     } else {
       EnsurePath();
       mDT->PushClip(mPath);
       AzureState::PushedClip clip = { mPath, Rect(), mTransform };
       CurrentState().pushedClips.AppendElement(clip);
     }
@@ -1274,19 +1275,19 @@ gfxContext::SetColor(const gfxRGBA& c)
 
         // Use the original alpha to avoid unnecessary float->byte->float
         // conversion errors
         cairo_set_source_rgba(mCairo, cms.r, cms.g, cms.b, c.a);
     }
     else
         cairo_set_source_rgba(mCairo, c.r, c.g, c.b, c.a);
   } else {
-    CurrentState().pattern = NULL;
-    CurrentState().sourceSurfCairo = NULL;
-    CurrentState().sourceSurface = NULL;
+    CurrentState().pattern = nullptr;
+    CurrentState().sourceSurfCairo = nullptr;
+    CurrentState().sourceSurface = nullptr;
 
     if (gfxPlatform::GetCMSMode() == eCMSMode_All) {
 
         gfxRGBA cms;
         qcms_transform *transform = gfxPlatform::GetCMSRGBTransform();
         if (transform)
           gfxPlatform::TransformPixel(c, cms, transform);
 
@@ -1300,19 +1301,19 @@ gfxContext::SetColor(const gfxRGBA& c)
 }
 
 void
 gfxContext::SetDeviceColor(const gfxRGBA& c)
 {
   if (mCairo) {
     cairo_set_source_rgba(mCairo, c.r, c.g, c.b, c.a);
   } else {
-    CurrentState().pattern = NULL;
-    CurrentState().sourceSurfCairo = NULL;
-    CurrentState().sourceSurface = NULL;
+    CurrentState().pattern = nullptr;
+    CurrentState().sourceSurfCairo = nullptr;
+    CurrentState().sourceSurface = nullptr;
     CurrentState().color = ToColor(c);
   }
 }
 
 bool
 gfxContext::GetDeviceColor(gfxRGBA& c)
 {
   if (mCairo) {
@@ -1338,34 +1339,34 @@ gfxContext::GetDeviceColor(gfxRGBA& c)
 void
 gfxContext::SetSource(gfxASurface *surface, const gfxPoint& offset)
 {
   if (mCairo) {
     NS_ASSERTION(surface->GetAllowUseAsSource(), "Surface not allowed to be used as source!");
     cairo_set_source_surface(mCairo, surface->CairoSurface(), offset.x, offset.y);
   } else {
     CurrentState().surfTransform = Matrix(1.0f, 0, 0, 1.0f, Float(offset.x), Float(offset.y));
-    CurrentState().pattern = NULL;
+    CurrentState().pattern = nullptr;
     CurrentState().patternTransformChanged = false;
     // Keep the underlying cairo surface around while we keep the
     // sourceSurface.
     CurrentState().sourceSurfCairo = surface;
     CurrentState().sourceSurface =
       gfxPlatform::GetPlatform()->GetSourceSurfaceForSurface(mDT, surface);
   }
 }
 
 void
 gfxContext::SetPattern(gfxPattern *pattern)
 {
   if (mCairo) {
     cairo_set_source(mCairo, pattern->CairoPattern());
   } else {
-    CurrentState().sourceSurfCairo = NULL;
-    CurrentState().sourceSurface = NULL;
+    CurrentState().sourceSurfCairo = nullptr;
+    CurrentState().sourceSurface = nullptr;
     CurrentState().patternTransformChanged = false;
     CurrentState().pattern = pattern;
   }
 }
 
 already_AddRefed<gfxPattern>
 gfxContext::GetPattern()
 {
@@ -1616,19 +1617,19 @@ void
 gfxContext::PopGroupToSource()
 {
   if (mCairo) {
     cairo_pop_group_to_source(mCairo);
   } else {
     RefPtr<SourceSurface> src = mDT->Snapshot();
     Point deviceOffset = CurrentState().deviceOffset;
     Restore();
-    CurrentState().sourceSurfCairo = NULL;
+    CurrentState().sourceSurfCairo = nullptr;
     CurrentState().sourceSurface = src;
-    CurrentState().pattern = NULL;
+    CurrentState().pattern = nullptr;
     CurrentState().patternTransformChanged = false;
 
     Matrix mat = mTransform;
     mat.Invert();
 
     Matrix deviceOffsetTranslation;
     deviceOffsetTranslation.Translate(deviceOffset.x, deviceOffset.y);
     CurrentState().surfTransform = deviceOffsetTranslation * mat;
@@ -1947,58 +1948,58 @@ gfxContext::CopyAsDataURL()
 }
 #endif
 
 void
 gfxContext::EnsurePath()
 {
   if (mPathBuilder) {
     mPath = mPathBuilder->Finish();
-    mPathBuilder = NULL;
+    mPathBuilder = nullptr;
   }
 
   if (mPath) {
     if (mTransformChanged) {
       Matrix mat = mTransform;
       mat.Invert();
       mat = mPathTransform * mat;
       mPathBuilder = mPath->TransformedCopyToBuilder(mat, CurrentState().fillRule);
       mPath = mPathBuilder->Finish();
-      mPathBuilder = NULL;
+      mPathBuilder = nullptr;
 
       mTransformChanged = false;
     }
 
     if (CurrentState().fillRule == mPath->GetFillRule()) {
       return;
     }
 
     mPathBuilder = mPath->CopyToBuilder(CurrentState().fillRule);
 
     mPath = mPathBuilder->Finish();
-    mPathBuilder = NULL;
+    mPathBuilder = nullptr;
     return;
   }
 
   EnsurePathBuilder();
   mPath = mPathBuilder->Finish();
-  mPathBuilder = NULL;
+  mPathBuilder = nullptr;
 }
 
 void
 gfxContext::EnsurePathBuilder()
 {
   if (mPathBuilder && !mTransformChanged) {
     return;
   }
 
   if (mPath) {
     if (!mTransformChanged) {
       mPathBuilder = mPath->CopyToBuilder(CurrentState().fillRule);
-      mPath = NULL;
+      mPath = nullptr;
     } else {
       Matrix invTransform = mTransform;
       invTransform.Invert();
       Matrix toNewUS = mPathTransform * invTransform;
       mPathBuilder = mPath->TransformedCopyToBuilder(toNewUS, CurrentState().fillRule);
     }
     return;
   }
@@ -2014,18 +2015,18 @@ gfxContext::EnsurePathBuilder()
       mPathBuilder->LineTo(mRect.BottomRight());
       mPathBuilder->LineTo(mRect.BottomLeft());
       mPathBuilder->Close();
     }
   }
 
   if (mTransformChanged) {
     // This could be an else if since this should never happen when
-    // mPathBuilder is NULL and mPath is NULL. But this way we can assert
-    // if all the state is as expected.
+    // mPathBuilder is nullptr and mPath is nullptr. But this way we can
+    // assert if all the state is as expected.
     MOZ_ASSERT(oldPath);
     MOZ_ASSERT(!mPathIsRect);
 
     Matrix invTransform = mTransform;
     invTransform.Invert();
     Matrix toNewUS = mPathTransform * invTransform;
 
     RefPtr<Path> path = mPathBuilder->Finish();
--- a/gfx/thebes/gfxContext.h
+++ b/gfx/thebes/gfxContext.h
@@ -62,17 +62,17 @@ public:
     /**
      * Return the current transparency group target, if any, along
      * with its device offsets from the top.  If no group is
      * active, returns the surface the gfxContext was created with,
      * and 0,0 in dx,dy.
      */
     already_AddRefed<gfxASurface> CurrentSurface(gfxFloat *dx, gfxFloat *dy);
     already_AddRefed<gfxASurface> CurrentSurface() {
-        return CurrentSurface(NULL, NULL);
+        return CurrentSurface(nullptr, nullptr);
     }
 
     /**
      * Return the raw cairo_t object.
      * XXX this should go away at some point.
      */
     cairo_t *GetCairo();
 
@@ -448,17 +448,17 @@ public:
         gfxLineSolid,
         gfxLineDashed,
         gfxLineDotted
     } gfxLineType;
 
     void SetDash(gfxLineType ltype);
     void SetDash(gfxFloat *dashes, int ndash, gfxFloat offset);
     // Return true if dashing is set, false if it's not enabled or the
-    // context is in an error state.  |offset| can be NULL to mean
+    // context is in an error state.  |offset| can be nullptr to mean
     // "don't care".
     bool CurrentDash(FallibleTArray<gfxFloat>& dashes, gfxFloat* offset) const;
     // Returns 0.0 if dashing isn't enabled.
     gfxFloat CurrentDashOffset() const;
 
     /**
      * Sets the line width that's used for line drawing.
      */
--- a/gfx/thebes/gfxCoreTextShaper.cpp
+++ b/gfx/thebes/gfxCoreTextShaper.cpp
@@ -27,26 +27,26 @@
 #include "gfxUserFontSet.h"
 
 #include "nsUnicodeRange.h"
 #include <algorithm>
 
 using namespace mozilla;
 
 // standard font descriptors that we construct the first time they're needed
-CTFontDescriptorRef gfxCoreTextShaper::sDefaultFeaturesDescriptor = NULL;
-CTFontDescriptorRef gfxCoreTextShaper::sDisableLigaturesDescriptor = NULL;
+CTFontDescriptorRef gfxCoreTextShaper::sDefaultFeaturesDescriptor = nullptr;
+CTFontDescriptorRef gfxCoreTextShaper::sDisableLigaturesDescriptor = nullptr;
 
 gfxCoreTextShaper::gfxCoreTextShaper(gfxMacFont *aFont)
     : gfxFontShaper(aFont)
 {
     // Create our CTFontRef
     mCTFont = ::CTFontCreateWithGraphicsFont(aFont->GetCGFontRef(),
                                              aFont->GetAdjustedSize(),
-                                             NULL,
+                                             nullptr,
                                              GetDefaultFeaturesDescriptor());
 
     // Set up the default attribute dictionary that we will need each time we create a CFAttributedString
     mAttributesDict = ::CFDictionaryCreate(kCFAllocatorDefault,
                                            (const void**) &kCTFontAttributeName,
                                            (const void**) &mCTFont,
                                            1, // count of attributes
                                            &kCFTypeDictionaryKeyCallBacks,
@@ -209,19 +209,19 @@ gfxCoreTextShaper::SetGlyphsFromRun(gfxS
         stringRange.location - aStringOffset >= wordLength) {
         return NS_OK;
     }
 
     // retrieve the laid-out glyph data from the CTRun
     nsAutoArrayPtr<CGGlyph> glyphsArray;
     nsAutoArrayPtr<CGPoint> positionsArray;
     nsAutoArrayPtr<CFIndex> glyphToCharArray;
-    const CGGlyph* glyphs = NULL;
-    const CGPoint* positions = NULL;
-    const CFIndex* glyphToChar = NULL;
+    const CGGlyph* glyphs = nullptr;
+    const CGPoint* positions = nullptr;
+    const CFIndex* glyphToChar = nullptr;
 
     // Testing indicates that CTRunGetGlyphsPtr (almost?) always succeeds,
     // and so allocating a new array and copying data with CTRunGetGlyphs
     // will be extremely rare.
     // If this were not the case, we could use an nsAutoTArray<> to
     // try and avoid the heap allocation for small runs.
     // It's possible that some future change to CoreText will mean that
     // CTRunGetGlyphsPtr fails more often; if this happens, nsAutoTArray<>
@@ -255,17 +255,17 @@ gfxCoreTextShaper::SetGlyphsFromRun(gfxS
         if (!glyphToCharArray) {
             return NS_ERROR_OUT_OF_MEMORY;
         }
         ::CTRunGetStringIndices(aCTRun, ::CFRangeMake(0, 0), glyphToCharArray.get());
         glyphToChar = glyphToCharArray.get();
     }
 
     double runWidth = ::CTRunGetTypographicBounds(aCTRun, ::CFRangeMake(0, 0),
-                                                  NULL, NULL, NULL);
+                                                  nullptr, nullptr, nullptr);
 
     nsAutoTArray<gfxShapedText::DetailedGlyph,1> detailedGlyphs;
     gfxShapedText::CompressedGlyph g;
     gfxShapedText::CompressedGlyph *charGlyphs =
         aShapedText->GetCharacterGlyphs() + aOffset;
 
     // CoreText gives us the glyphindex-to-charindex mapping, which relates each glyph
     // to a source text character; we also need the charindex-to-glyphindex mapping to
@@ -508,17 +508,17 @@ gfxCoreTextShaper::SetGlyphsFromRun(gfxS
 }
 
 // Construct the font attribute descriptor that we'll apply by default when creating a CTFontRef.
 // This will turn off line-edge swashes by default, because we don't know the actual line breaks
 // when doing glyph shaping.
 void
 gfxCoreTextShaper::CreateDefaultFeaturesDescriptor()
 {
-    if (sDefaultFeaturesDescriptor != NULL) {
+    if (sDefaultFeaturesDescriptor != nullptr) {
         return;
     }
 
     SInt16 val = kSmartSwashType;
     CFNumberRef swashesType =
         ::CFNumberCreate(kCFAllocatorDefault,
                          kCFNumberSInt16Type,
                          &val);
@@ -581,17 +581,17 @@ gfxCoreTextShaper::CreateDefaultFeatures
         ::CTFontDescriptorCreateWithAttributes(attributesDict);
     ::CFRelease(attributesDict);
 }
 
 // Create a CTFontRef, with the Common Ligatures feature disabled
 CTFontRef
 gfxCoreTextShaper::CreateCTFontWithDisabledLigatures(CGFloat aSize)
 {
-    if (sDisableLigaturesDescriptor == NULL) {
+    if (sDisableLigaturesDescriptor == nullptr) {
         // initialize cached descriptor to turn off the Common Ligatures feature
         SInt16 val = kLigaturesType;
         CFNumberRef ligaturesType =
             ::CFNumberCreate(kCFAllocatorDefault,
                              kCFNumberSInt16Type,
                              &val);
         val = kCommonLigaturesOffSelector;
         CFNumberRef commonLigaturesOffSelector =
@@ -631,24 +631,24 @@ gfxCoreTextShaper::CreateCTFontWithDisab
 
         sDisableLigaturesDescriptor =
             ::CTFontDescriptorCreateCopyWithAttributes(GetDefaultFeaturesDescriptor(),
                                                        attributesDict);
         ::CFRelease(attributesDict);
     }
 
     gfxMacFont *f = static_cast<gfxMacFont*>(mFont);
-    return ::CTFontCreateWithGraphicsFont(f->GetCGFontRef(), aSize, NULL,
+    return ::CTFontCreateWithGraphicsFont(f->GetCGFontRef(), aSize, nullptr,
                                           sDisableLigaturesDescriptor);
 }
 
 void
 gfxCoreTextShaper::Shutdown() // [static]
 {
-    if (sDisableLigaturesDescriptor != NULL) {
+    if (sDisableLigaturesDescriptor != nullptr) {
         ::CFRelease(sDisableLigaturesDescriptor);
-        sDisableLigaturesDescriptor = NULL;
+        sDisableLigaturesDescriptor = nullptr;
     }        
-    if (sDefaultFeaturesDescriptor != NULL) {
+    if (sDefaultFeaturesDescriptor != nullptr) {
         ::CFRelease(sDefaultFeaturesDescriptor);
-        sDefaultFeaturesDescriptor = NULL;
+        sDefaultFeaturesDescriptor = nullptr;
     }
 }
--- a/gfx/thebes/gfxCoreTextShaper.h
+++ b/gfx/thebes/gfxCoreTextShaper.h
@@ -42,17 +42,17 @@ protected:
                               CTRunRef       aCTRun,
                               int32_t        aStringOffset);
 
     CTFontRef CreateCTFontWithDisabledLigatures(CGFloat aSize);
 
     static void CreateDefaultFeaturesDescriptor();
 
     static CTFontDescriptorRef GetDefaultFeaturesDescriptor() {
-        if (sDefaultFeaturesDescriptor == NULL) {
+        if (sDefaultFeaturesDescriptor == nullptr) {
             CreateDefaultFeaturesDescriptor();
         }
         return sDefaultFeaturesDescriptor;
     }
 
     // cached font descriptor, created the first time it's needed
     static CTFontDescriptorRef    sDefaultFeaturesDescriptor;
 
--- a/gfx/thebes/gfxD2DSurface.cpp
+++ b/gfx/thebes/gfxD2DSurface.cpp
@@ -78,17 +78,17 @@ gfxD2DSurface::GetDC(bool aRetainContent
 {
     return cairo_d2d_get_dc(CairoSurface(), aRetainContents);
 }
 
 void
 gfxD2DSurface::ReleaseDC(const nsIntRect *aUpdatedRect)
 {
     if (!aUpdatedRect) {
-        return cairo_d2d_release_dc(CairoSurface(), NULL);
+        return cairo_d2d_release_dc(CairoSurface(), nullptr);
     }
 
     cairo_rectangle_int_t rect;
     rect.x = aUpdatedRect->x;
     rect.y = aUpdatedRect->y;
     rect.width = aUpdatedRect->width;
     rect.height = aUpdatedRect->height;
     cairo_d2d_release_dc(CairoSurface(), &rect);
--- a/gfx/thebes/gfxDWriteCommon.cpp
+++ b/gfx/thebes/gfxDWriteCommon.cpp
@@ -1,16 +1,16 @@
 /* -*- Mode: C++; tab-width: 20; indent-tabs-mode: nil; c-basic-offset: 4 -*-
  * 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/. */
 
 #include "gfxDWriteCommon.h"
 
-IDWriteFontFileLoader* gfxDWriteFontFileLoader::mInstance = NULL;
+IDWriteFontFileLoader* gfxDWriteFontFileLoader::mInstance = nullptr;
 
 HRESULT STDMETHODCALLTYPE
 gfxDWriteFontFileLoader::CreateStreamFromKey(const void *fontFileReferenceKey, 
                                              UINT32 fontFileReferenceKeySize, 
                                              IDWriteFontFileStream **fontFileStream)
 {
     if (!fontFileReferenceKey || !fontFileStream) {
         return E_POINTER;
@@ -56,16 +56,16 @@ gfxDWriteFontFileStream::ReadFileFragmen
                                           void **fragmentContext)
 {
     // We are required to do bounds checking.
     if (fileOffset + fragmentSize > (UINT64)mData.Length()) {
         return E_FAIL;
     }
     // We should be alive for the duration of this.
     *fragmentStart = &mData[fileOffset];
-    *fragmentContext = NULL;
+    *fragmentContext = nullptr;
     return S_OK;
 }
 
 void STDMETHODCALLTYPE
 gfxDWriteFontFileStream::ReleaseFileFragment(void *fragmentContext)
 {
 }
--- a/gfx/thebes/gfxDWriteFontList.cpp
+++ b/gfx/thebes/gfxDWriteFontList.cpp
@@ -285,17 +285,17 @@ gfxDWriteFontEntry::CopyFontTable(uint32
             return NS_ERROR_FAILURE;
 
         AutoDC dc;
         AutoSelectFont font(dc.GetDC(), &logfont);
         if (font.IsValid()) {
             uint32_t tableSize =
                 ::GetFontData(dc.GetDC(),
                               NativeEndian::swapToBigEndian(aTableTag), 0,
-                              NULL, 0);
+                              nullptr, 0);
             if (tableSize != GDI_ERROR) {
                 if (aBuffer.SetLength(tableSize)) {
                     ::GetFontData(dc.GetDC(),
                                   NativeEndian::swapToBigEndian(aTableTag), 0,
                                   aBuffer.Elements(), aBuffer.Length());
                     return NS_OK;
                 }
                 return NS_ERROR_OUT_OF_MEMORY;
@@ -307,17 +307,17 @@ gfxDWriteFontEntry::CopyFontTable(uint32
     nsRefPtr<IDWriteFontFace> fontFace;
     nsresult rv = CreateFontFace(getter_AddRefs(fontFace));
     if (NS_FAILED(rv)) {
         return rv;
     }
 
     uint8_t *tableData;
     uint32_t len;
-    void *tableContext = NULL;
+    void *tableContext = nullptr;
     BOOL exists;
     HRESULT hr =
         fontFace->TryGetFontTable(NativeEndian::swapToBigEndian(aTableTag),
                                   (const void**)&tableData, &len,
                                   &tableContext, &exists);
     if (FAILED(hr) || !exists) {
         return NS_ERROR_FAILURE;
     }
@@ -476,17 +476,17 @@ gfxDWriteFontEntry::CreateFontFace(IDWri
 
     // check whether we need to add a DWrite simulated style
     if ((aSimulations & DWRITE_FONT_SIMULATIONS_BOLD) &&
         !(mFontFace->GetSimulations() & DWRITE_FONT_SIMULATIONS_BOLD)) {
         // if so, we need to return not mFontFace itself but a version that
         // has the Bold simulation - unfortunately, DWrite doesn't provide
         // a simple API for this
         UINT32 numberOfFiles = 0;
-        if (FAILED(mFontFace->GetFiles(&numberOfFiles, NULL))) {
+        if (FAILED(mFontFace->GetFiles(&numberOfFiles, nullptr))) {
             return NS_ERROR_FAILURE;
         }
         nsAutoTArray<IDWriteFontFile*,1> files;
         files.AppendElements(numberOfFiles);
         if (FAILED(mFontFace->GetFiles(&numberOfFiles, files.Elements()))) {
             return NS_ERROR_FAILURE;
         }
         HRESULT hr = gfxWindowsPlatform::GetPlatform()->GetDWriteFactory()->
@@ -748,18 +748,18 @@ gfxDWriteFontList::InitFontList()
 
     LARGE_INTEGER frequency;        // ticks per second
     LARGE_INTEGER t1, t2, t3;           // ticks
     double elapsedTime, upTime;
     char nowTime[256], nowDate[256];
 
     if (LOG_FONTINIT_ENABLED()) {    
         GetTimeFormat(LOCALE_INVARIANT, TIME_FORCE24HOURFORMAT, 
-                      NULL, NULL, nowTime, 256);
-        GetDateFormat(LOCALE_INVARIANT, 0, NULL, NULL, nowDate, 256);
+                      nullptr, nullptr, nowTime, 256);
+        GetDateFormat(LOCALE_INVARIANT, 0, nullptr, nullptr, nowDate, 256);
     }
     upTime = (double) GetTickCount();
     QueryPerformanceFrequency(&frequency);
     QueryPerformanceCounter(&t1);
 
     HRESULT hr;
     gfxFontCache *fc = gfxFontCache::GetCache();
     if (fc) {
@@ -816,18 +816,18 @@ gfxDWriteFontList::DelayedInitFontList()
 
     LARGE_INTEGER frequency;        // ticks per second
     LARGE_INTEGER t1, t2, t3;           // ticks
     double elapsedTime, upTime;
     char nowTime[256], nowDate[256];
 
     if (LOG_FONTINIT_ENABLED()) {    
         GetTimeFormat(LOCALE_INVARIANT, TIME_FORCE24HOURFORMAT, 
-                      NULL, NULL, nowTime, 256);
-        GetDateFormat(LOCALE_INVARIANT, 0, NULL, NULL, nowDate, 256);
+                      nullptr, nullptr, nowTime, 256);
+        GetDateFormat(LOCALE_INVARIANT, 0, nullptr, nullptr, nowDate, 256);
     }
 
     upTime = (double) GetTickCount();
     QueryPerformanceFrequency(&frequency);
     QueryPerformanceCounter(&t1);
 
     HRESULT hr;
 
@@ -1089,17 +1089,17 @@ gfxDWriteFontList::GetFontSubstitutes()
         return NS_ERROR_FAILURE;
     }
 
     for (i = 0, rv = ERROR_SUCCESS; rv != ERROR_NO_MORE_ITEMS; i++) {
         aliasName[0] = 0;
         lenAlias = ArrayLength(aliasName);
         actualName[0] = 0;
         lenActual = sizeof(actualName);
-        rv = RegEnumValueW(hKey, i, aliasName, &lenAlias, NULL, &valueType, 
+        rv = RegEnumValueW(hKey, i, aliasName, &lenAlias, nullptr, &valueType,
                 (LPBYTE)actualName, &lenActual);
 
         if (rv != ERROR_SUCCESS || valueType != REG_SZ || lenAlias == 0) {
             continue;
         }
 
         if (aliasName[0] == WCHAR('@')) {
             continue;
@@ -1366,17 +1366,17 @@ gfxDWriteFontList::GlobalFontFallback(co
 
     // initialize fallback renderer
     if (!mFallbackRenderer) {
         mFallbackRenderer = new FontFallbackRenderer(dwFactory);
     }
 
     // initialize text format
     if (!mFallbackFormat) {
-        hr = dwFactory->CreateTextFormat(L"Arial", NULL,
+        hr = dwFactory->CreateTextFormat(L"Arial", nullptr,
                                          DWRITE_FONT_WEIGHT_REGULAR,
                                          DWRITE_FONT_STYLE_NORMAL,
                                          DWRITE_FONT_STRETCH_NORMAL,
                                          72.0f, L"en-us",
                                          getter_AddRefs(mFallbackFormat));
         if (FAILED(hr)) {
             return nullptr;
         }
@@ -1404,17 +1404,17 @@ gfxDWriteFontList::GlobalFontFallback(co
                                      200.0f, 200.0f,
                                      getter_AddRefs(fallbackLayout));
     if (FAILED(hr)) {
         return nullptr;
     }
 
     // call the draw method to invoke the DirectWrite layout functions
     // which determine the fallback font
-    hr = fallbackLayout->Draw(NULL, mFallbackRenderer, 50.0f, 50.0f);
+    hr = fallbackLayout->Draw(nullptr, mFallbackRenderer, 50.0f, 50.0f);
     if (FAILED(hr)) {
         return nullptr;
     }
 
     gfxFontFamily *family = FindFamily(mFallbackRenderer->FallbackFamilyName());
     if (family) {
         gfxFontEntry *fontEntry;
         bool needsBold;  // ignored in the system fallback case
--- a/gfx/thebes/gfxDWriteFontList.h
+++ b/gfx/thebes/gfxDWriteFontList.h
@@ -308,17 +308,17 @@ public:
     {
         if (__uuidof(IDWriteTextRenderer) == riid) {
             *ppvObject = this;
         } else if (__uuidof(IDWritePixelSnapping) == riid) {
             *ppvObject = this;
         } else if (__uuidof(IUnknown) == riid) {
             *ppvObject = this;
         } else {
-            *ppvObject = NULL;
+            *ppvObject = nullptr;
             return E_FAIL;
         }
 
         this->AddRef();
         return S_OK;
     }
 
     const nsString& FallbackFamilyName() { return mFamilyName; }
--- a/gfx/thebes/gfxDWriteFonts.cpp
+++ b/gfx/thebes/gfxDWriteFonts.cpp
@@ -486,17 +486,17 @@ gfxDWriteFont::SetupCairoFont(gfxContext
     }
     cairo_set_scaled_font(aContext->GetCairo(), scaledFont);
     return true;
 }
 
 bool
 gfxDWriteFont::IsValid()
 {
-    return mFontFace != NULL;
+    return mFontFace != nullptr;
 }
 
 IDWriteFontFace*
 gfxDWriteFont::GetFontFace()
 {
     return  mFontFace.get();
 }
 
--- a/gfx/thebes/gfxDWriteShaper.cpp
+++ b/gfx/thebes/gfxDWriteShaper.cpp
@@ -40,17 +40,17 @@ gfxDWriteShaper::ShapeText(gfxContext   
 
     /**
      * There's an internal 16-bit limit on some things inside the analyzer,
      * but we never attempt to shape a word longer than 32K characters
      * in a single call, so we cannot exceed that limit.
      */
     UINT32 length = aLength;
 
-    TextAnalysis analysis(aText, length, NULL, readingDirection);
+    TextAnalysis analysis(aText, length, nullptr, readingDirection);
     TextAnalysis::Run *runHead;
     hr = analysis.GenerateResults(analyzer, &runHead);
 
     if (FAILED(hr)) {
         NS_WARNING("Analyzer failed to generate results.");
         return false;
     }
 
@@ -78,17 +78,17 @@ trymoreglyphs:
         return false;
     }
 
     UINT32 actualGlyphs;
 
     hr = analyzer->GetGlyphs(aText, length,
             font->GetFontFace(), FALSE, 
             readingDirection == DWRITE_READING_DIRECTION_RIGHT_TO_LEFT,
-            &runHead->mScript, NULL, NULL, NULL, NULL, 0,
+            &runHead->mScript, nullptr, nullptr, nullptr, nullptr, 0,
             maxGlyphs, clusters.Elements(), textProperties.Elements(),
             indices.Elements(), glyphProperties.Elements(), &actualGlyphs);
 
     if (hr == HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER)) {
         // We increase the amount of glyphs and try again.
         goto trymoreglyphs;
     }
     if (FAILED(hr)) {
@@ -117,38 +117,38 @@ trymoreglyphs:
                                           font->GetFontFace(),
                                           font->GetAdjustedSize(),
                                           1.0,
                                           nullptr,
                                           FALSE,
                                           FALSE,
                                           FALSE,
                                           &runHead->mScript,
-                                          NULL,
-                                          NULL,
-                                          NULL,
+                                          nullptr,
+                                          nullptr,
+                                          nullptr,
                                           0,
                                           advances.Elements(),
                                           glyphOffsets.Elements());
     } else {
         hr = analyzer->GetGlyphPlacements(aText,
                                           clusters.Elements(),
                                           textProperties.Elements(),
                                           length,
                                           indices.Elements(),
                                           glyphProperties.Elements(),
                                           actualGlyphs,
                                           font->GetFontFace(),
                                           font->GetAdjustedSize(),
                                           FALSE,
                                           FALSE,
                                           &runHead->mScript,
-                                          NULL,
-                                          NULL,
-                                          NULL,
+                                          nullptr,
+                                          nullptr,
+                                          nullptr,
                                           0,
                                           advances.Elements(),
                                           glyphOffsets.Elements());
     }
     if (FAILED(hr)) {
         NS_WARNING("Analyzer failed to get glyph placements.");
         return false;
     }
--- a/gfx/thebes/gfxDWriteTextAnalysis.cpp
+++ b/gfx/thebes/gfxDWriteTextAnalysis.cpp
@@ -8,17 +8,17 @@
 TextAnalysis::TextAnalysis(const wchar_t* text,
                            UINT32 textLength,
                            const wchar_t* localeName,
                            DWRITE_READING_DIRECTION readingDirection)
   : mText(text)
   , mTextLength(textLength)
   , mLocaleName(localeName)
   , mReadingDirection(readingDirection)
-  , mCurrentRun(NULL)
+  , mCurrentRun(nullptr)
 {
 }
 
 TextAnalysis::~TextAnalysis()
 {
     // delete runs, except mRunHead which is part of the TextAnalysis object
     for (Run *run = mRunHead.nextRun; run;) {
         Run *origRun = run;
@@ -37,17 +37,17 @@ TextAnalysis::GenerateResults(IDWriteTex
     HRESULT hr = S_OK;
 
     // Initially start out with one result that covers the entire range.
     // This result will be subdivided by the analysis processes.
     mRunHead.mTextStart = 0;
     mRunHead.mTextLength = mTextLength;
     mRunHead.mBidiLevel = 
         (mReadingDirection == DWRITE_READING_DIRECTION_RIGHT_TO_LEFT);
-    mRunHead.nextRun = NULL;
+    mRunHead.nextRun = nullptr;
     mCurrentRun = &mRunHead;
 
     // Call each of the analyzers in sequence, recording their results.
     if (SUCCEEDED(hr = textAnalyzer->AnalyzeScript(this,
                                                    0,
                                                    mTextLength,
                                                    this))) {
         *runHead = &mRunHead;
@@ -62,17 +62,17 @@ TextAnalysis::GenerateResults(IDWriteTex
 
 IFACEMETHODIMP 
 TextAnalysis::GetTextAtPosition(UINT32 textPosition,
                                 OUT WCHAR const** textString,
                                 OUT UINT32* textLength)
 {
     if (textPosition >= mTextLength) {
         // No text at this position, valid query though.
-        *textString = NULL;
+        *textString = nullptr;
         *textLength = 0;
     } else {
         *textString = mText + textPosition;
         *textLength = mTextLength - textPosition;
     }
     return S_OK;
 }
 
@@ -80,17 +80,17 @@ TextAnalysis::GetTextAtPosition(UINT32 t
 IFACEMETHODIMP 
 TextAnalysis::GetTextBeforePosition(UINT32 textPosition,
                                     OUT WCHAR const** textString,
                                     OUT UINT32* textLength)
 {
     if (textPosition == 0 || textPosition > mTextLength) {
         // Either there is no text before here (== 0), or this
         // is an invalid position. The query is considered valid thouh.
-        *textString = NULL;
+        *textString = nullptr;
         *textLength = 0;
     } else {
         *textString = mText;
         *textLength = textPosition;
     }
     return S_OK;
 }
 
@@ -117,17 +117,17 @@ TextAnalysis::GetLocaleName(UINT32 textP
 
 
 IFACEMETHODIMP 
 TextAnalysis::GetNumberSubstitution(UINT32 textPosition,
                                     OUT UINT32* textLength,
                                     OUT IDWriteNumberSubstitution** numberSubstitution)
 {
     // We do not support number substitution.
-    *numberSubstitution = NULL;
+    *numberSubstitution = nullptr;
     *textLength = mTextLength - textPosition;
 
     return S_OK;
 }
 
 
 ////////////////////////////////////////////////////////////////////////////////
 // IDWriteTextAnalysisSink implementation
--- a/gfx/thebes/gfxFT2FontBase.cpp
+++ b/gfx/thebes/gfxFT2FontBase.cpp
@@ -86,17 +86,17 @@ gfxFT2FontBase::GetGlyph(uint32_t aCharC
     }
 
     return slot->mGlyphIndex;
 }
 
 void
 gfxFT2FontBase::GetGlyphExtents(uint32_t aGlyph, cairo_text_extents_t* aExtents)
 {
-    NS_PRECONDITION(aExtents != NULL, "aExtents must not be NULL");
+    NS_PRECONDITION(aExtents != nullptr, "aExtents must not be NULL");
 
     cairo_glyph_t glyphs[1];
     glyphs[0].index = aGlyph;
     glyphs[0].x = 0.0;
     glyphs[0].y = 0.0;
     // cairo does some caching for us here but perhaps a small gain could be
     // made by caching more.  It is usually only the advance that is needed,
     // so caching only the advance could allow many requests to be cached with
--- a/gfx/thebes/gfxFT2FontList.cpp
+++ b/gfx/thebes/gfxFT2FontList.cpp
@@ -595,17 +595,17 @@ public:
         mOps = (PLDHashTableOps) {
             PL_DHashAllocTable,
             PL_DHashFreeTable,
             StringHash,
             HashMatchEntry,
             MoveEntry,
             PL_DHashClearEntryStub,
             PL_DHashFinalizeStub,
-            NULL
+            nullptr
         };
 
         if (!PL_DHashTableInit(&mMap, &mOps, nullptr,
                                sizeof(FNCMapEntry), 0))
         {
             mMap.ops = nullptr;
             LOG(("initializing the map failed"));
         }
@@ -654,22 +654,22 @@ public:
             if (!(end = strchr(beginning, ';'))) {
                 break;
             }
             nsCString faceList(beginning, end - beginning);
             beginning = end + 1;
             if (!(end = strchr(beginning, ';'))) {
                 break;
             }
-            uint32_t timestamp = strtoul(beginning, NULL, 10);
+            uint32_t timestamp = strtoul(beginning, nullptr, 10);
             beginning = end + 1;
             if (!(end = strchr(beginning, ';'))) {
                 break;
             }
-            uint32_t filesize = strtoul(beginning, NULL, 10);
+            uint32_t filesize = strtoul(beginning, nullptr, 10);
 
             FNCMapEntry* mapEntry =
                 static_cast<FNCMapEntry*>
                 (PL_DHashTableOperate(&mMap, filename.get(), PL_DHASH_ADD));
             if (mapEntry) {
                 mapEntry->mFilename.Assign(filename);
                 mapEntry->mTimestamp = timestamp;
                 mapEntry->mFilesize = filesize;
@@ -824,32 +824,32 @@ gfxFT2FontList::AppendFacesFromCachedFac
             break;
         }
         nsString faceName =
             NS_ConvertUTF8toUTF16(beginning, end - beginning);
         beginning = end + 1;
         if (!(end = strchr(beginning, ','))) {
             break;
         }
-        uint32_t index = strtoul(beginning, NULL, 10);
+        uint32_t index = strtoul(beginning, nullptr, 10);
         beginning = end + 1;
         if (!(end = strchr(beginning, ','))) {
             break;
         }
         bool italic = (*beginning != '0');
         beginning = end + 1;
         if (!(end = strchr(beginning, ','))) {
             break;
         }
-        uint32_t weight = strtoul(beginning, NULL, 10);
+        uint32_t weight = strtoul(beginning, nullptr, 10);
         beginning = end + 1;
         if (!(end = strchr(beginning, ','))) {
             break;
         }
-        int32_t stretch = strtol(beginning, NULL, 10);
+        int32_t stretch = strtol(beginning, nullptr, 10);
 
         FontListEntry fle(familyName, faceName, aFileName,
                           weight, stretch, italic, index);
         AppendFaceFromFontListEntry(fle, aStdFile);
 
         beginning = end + 1;
         end = strchr(beginning, ',');
     }
@@ -1152,17 +1152,17 @@ gfxFT2FontList::FindFonts()
         const nsString& path(searchPaths[i]);
         for (uint32_t j = 0; j < fontPatterns.Length(); j++) { 
             nsAutoString pattern(path);
             pattern.Append(fontPatterns[j]);
             HANDLE handle = FindFirstFileExW(pattern.get(),
                                              FindExInfoStandard,
                                              &results,
                                              FindExSearchNameMatch,
-                                             NULL,
+                                             nullptr,
                                              0);
             bool moreFiles = handle != INVALID_HANDLE_VALUE;
             while (moreFiles) {
                 nsAutoString filePath(path);
                 filePath.AppendLiteral("\\");
                 filePath.Append(results.cFileName);
                 AppendFacesFromFontFile(NS_ConvertUTF16toUTF8(filePath));
                 moreFiles = FindNextFile(handle, &results);
@@ -1271,18 +1271,18 @@ gfxFT2FontList::FindFontsInDir(const nsC
         "DroidSansFallback.ttf"
     };
 
     DIR *d = opendir(aDir.get());
     if (!d) {
         return;
     }
 
-    struct dirent *ent = NULL;
-    while ((ent = readdir(d)) != NULL) {
+    struct dirent *ent = nullptr;
+    while ((ent = readdir(d)) != nullptr) {
         int namelen = strlen(ent->d_name);
         if (namelen <= 4) {
             // cannot be a usable font filename
             continue;
         }
         const char *ext = ent->d_name + namelen - 4;
         if (strcasecmp(ext, ".ttf") == 0 ||
             strcasecmp(ext, ".otf") == 0 ||
--- a/gfx/thebes/gfxFT2FontList.h
+++ b/gfx/thebes/gfxFT2FontList.h
@@ -50,17 +50,17 @@ public:
     // create a font entry representing an installed font, identified by
     // a FontListEntry; the freetype and cairo faces will not be instantiated
     // until actually needed
     static FT2FontEntry*
     CreateFontEntry(const FontListEntry& aFLE);
 
     // Create a font entry for a given freetype face; if it is an installed font,
     // also record the filename and index.
-    // aFontData (if non-NULL) is NS_Malloc'ed data that aFace depends on,
+    // aFontData (if non-nullptr) is NS_Malloc'ed data that aFace depends on,
     // to be freed after the face is destroyed
     static FT2FontEntry* 
     CreateFontEntry(FT_Face aFace,
                     const char *aFilename, uint8_t aIndex,
                     const nsAString& aName,
                     const uint8_t *aFontData = nullptr);
 
     virtual gfxFont *CreateFontInstance(const gfxFontStyle *aFontStyle,
--- a/gfx/thebes/gfxFT2Fonts.cpp
+++ b/gfx/thebes/gfxFT2Fonts.cpp
@@ -281,17 +281,17 @@ void gfxFT2FontGroup::GetCJKPrefFonts(ns
         switch (::GetACP()) {
             case 932: GetPrefFonts(nsGkAtoms::Japanese, aFontEntryList); break;
             case 936: GetPrefFonts(nsGkAtoms::zh_cn, aFontEntryList); break;
             case 949: GetPrefFonts(nsGkAtoms::ko, aFontEntryList); break;
             // XXX Don't we need to append nsGkAtoms::zh_hk if the codepage is 950?
             case 950: GetPrefFonts(nsGkAtoms::zh_tw, aFontEntryList); break;
         }
 #else
-        const char *ctype = setlocale(LC_CTYPE, NULL);
+        const char *ctype = setlocale(LC_CTYPE, nullptr);
         if (ctype) {
             if (!PL_strncasecmp(ctype, "ja", 2)) {
                 GetPrefFonts(nsGkAtoms::Japanese, aFontEntryList);
             } else if (!PL_strncasecmp(ctype, "zh_cn", 5)) {
                 GetPrefFonts(nsGkAtoms::zh_cn, aFontEntryList);
             } else if (!PL_strncasecmp(ctype, "zh_hk", 5)) {
                 GetPrefFonts(nsGkAtoms::zh_hk, aFontEntryList);
             } else if (!PL_strncasecmp(ctype, "zh_tw", 5)) {
--- a/gfx/thebes/gfxFT2Utils.cpp
+++ b/gfx/thebes/gfxFT2Utils.cpp
@@ -42,18 +42,18 @@ SnapLineToPixels(gfxFloat& aOffset, gfxF
     aOffset = floor(offset + 0.5);
     aSize = snappedSize;
 }
 
 void
 gfxFT2LockedFace::GetMetrics(gfxFont::Metrics* aMetrics,
                              uint32_t* aSpaceGlyph)
 {
-    NS_PRECONDITION(aMetrics != NULL, "aMetrics must not be NULL");
-    NS_PRECONDITION(aSpaceGlyph != NULL, "aSpaceGlyph must not be NULL");
+    NS_PRECONDITION(aMetrics != nullptr, "aMetrics must not be NULL");
+    NS_PRECONDITION(aSpaceGlyph != nullptr, "aSpaceGlyph must not be NULL");
 
     if (MOZ_UNLIKELY(!mFace)) {
         // No face.  This unfortunate situation might happen if the font
         // file is (re)moved at the wrong time.
         aMetrics->emHeight = mGfxFont->GetStyle()->size;
         aMetrics->emAscent = 0.8 * aMetrics->emHeight;
         aMetrics->emDescent = 0.2 * aMetrics->emHeight;
         aMetrics->maxAscent = aMetrics->emAscent;
@@ -318,17 +318,17 @@ gfxFT2LockedFace::GetUVSGlyph(uint32_t a
 #endif
 
     return (*sGetCharVariantPtr)(mFace, aCharCode, aVariantSelector);
 }
 
 uint32_t
 gfxFT2LockedFace::GetCharExtents(char aChar, cairo_text_extents_t* aExtents)
 {
-    NS_PRECONDITION(aExtents != NULL, "aExtents must not be NULL");
+    NS_PRECONDITION(aExtents != nullptr, "aExtents must not be NULL");
 
     if (!mFace)
         return 0;
 
     FT_UInt gid = mGfxFont->GetGlyph(aChar);
     if (gid) {
         mGfxFont->GetGlyphExtents(gid, aExtents);
     }
--- a/gfx/thebes/gfxFont.cpp
+++ b/gfx/thebes/gfxFont.cpp
@@ -701,17 +701,17 @@ gfxFontFamily::FindFontForStyle(const gf
         return fe;
     }
 
     bool wantItalic = (aFontStyle.style &
                        (NS_FONT_STYLE_ITALIC | NS_FONT_STYLE_OBLIQUE)) != 0;
 
     // Most families are "simple", having just Regular/Bold/Italic/BoldItalic,
     // or some subset of these. In this case, we have exactly 4 entries in mAvailableFonts,
-    // stored in the above order; note that some of the entries may be NULL.
+    // stored in the above order; note that some of the entries may be nullptr.
     // We can then pick the required entry based on whether the request is for
     // bold or non-bold, italic or non-italic, without running the more complex
     // matching algorithm used for larger families with many weights and/or widths.
 
     if (mIsSimpleFamily) {
         // Family has no more than the "standard" 4 faces, at fixed indexes;
         // calculate which one we want.
         // Note that we cannot simply return it as not all 4 faces are necessarily present.
@@ -880,17 +880,17 @@ gfxFontFamily::FindWeightsForStyle(gfxFo
                                    bool anItalic, int16_t aStretch)
 {
     uint32_t foundWeights = 0;
     uint32_t bestMatchDistance = 0xffffffff;
 
     uint32_t count = mAvailableFonts.Length();
     for (uint32_t i = 0; i < count; i++) {
         // this is not called for "simple" families, and therefore it does not
-        // need to check the mAvailableFonts entries for NULL
+        // need to check the mAvailableFonts entries for nullptr.
         gfxFontEntry *fe = mAvailableFonts[i];
         uint32_t distance = StyleDistance(fe, anItalic, aStretch);
         if (distance <= bestMatchDistance) {
             int8_t wt = fe->mWeight / 100;
             NS_ASSERTION(wt >= 1 && wt < 10, "invalid weight in fontEntry");
             if (!aFontsForWeights[wt]) {
                 // record this as a possible candidate for weight matching
                 aFontsForWeights[wt] = fe;
@@ -2521,18 +2521,18 @@ gfxFont::Draw(gfxTextRun *aTextRun, uint
       }
 
       GlyphBufferAzure glyphs;
       Glyph *glyph;
 
       Matrix mat, matInv;
       Matrix oldMat = dt->GetTransform();
 
-      // This is NULL when we have inverse-transformed glyphs and we need to
-      // transform the Brush inside flush.
+      // This is nullptr when we have inverse-transformed glyphs and we need
+      // to transform the Brush inside flush.
       Matrix *passedInvMatrix = nullptr;
 
       RefPtr<GlyphRenderingOptions> renderingOptions =
         GetGlyphRenderingOptions();
 
       DrawOptions drawOptions;
       drawOptions.mAntialiasMode = Get2DAAMode(mAntialiasOption);
 
--- a/gfx/thebes/gfxFont.h
+++ b/gfx/thebes/gfxFont.h
@@ -345,22 +345,22 @@ public:
     // reference to a shared system font cache.
     //
     // The default implementation uses CopyFontTable to get the data
     // into a byte array, and maintains a cache of loaded tables.
     //
     // Subclasses should override this if they can provide more efficient
     // access than copying table data into our own buffers.
     //
-    // Get blob that encapsulates a specific font table, or NULL if
+    // Get blob that encapsulates a specific font table, or nullptr if
     // the table doesn't exist in the font.
     //
     // Caller is responsible to call hb_blob_destroy() on the returned blob
-    // (if non-NULL) when no longer required. For transient access to a table,
-    // use of AutoTable (below) is generally preferred.
+    // (if non-nullptr) when no longer required. For transient access to a
+    // table, use of AutoTable (below) is generally preferred.
     virtual hb_blob_t *GetFontTable(uint32_t aTag);
 
     // Stack-based utility to return a specified table, automatically releasing
     // the blob when the AutoTable goes out of scope.
     class AutoTable {
     public:
         AutoTable(gfxFontEntry* aFontEntry, uint32_t aTag)
         {
@@ -390,18 +390,18 @@ public:
     // if it is more efficient to get the table from the OS at that level.
     bool GetExistingFontTable(uint32_t aTag, hb_blob_t** aBlob);
 
     // Elements of aTable are transferred (not copied) to and returned in a
     // new hb_blob_t which is registered on the gfxFontEntry, but the initial
     // reference is owned by the caller.  Removing the last reference
     // unregisters the table from the font entry.
     //
-    // Pass NULL for aBuffer to indicate that the table is not present and
-    // NULL will be returned.  Also returns NULL on OOM.
+    // Pass nullptr for aBuffer to indicate that the table is not present and
+    // nullptr will be returned.  Also returns nullptr on OOM.
     hb_blob_t *ShareFontTableAndGetBlob(uint32_t aTag,
                                         FallibleTArray<uint8_t>* aTable);
 
     // Shaper face accessors:
     // NOTE that harfbuzz and graphite handle ownership/lifetime of the face
     // object in completely different ways.
 
     // Get HarfBuzz face corresponding to this font file.
@@ -1543,17 +1543,17 @@ public:
      * units, really!
      * @param aSpacing spacing to insert before and after characters (for RTL
      * glyphs, before-spacing is inserted to the right of characters). There
      * are aEnd - aStart elements in this array, unless it's null to indicate
      * that there is no spacing.
      * @param aDrawMode specifies whether the fill or stroke of the glyph should be
      * drawn, or if it should be drawn into the current path
      * @param aObjectPaint information about how to construct the fill and
-     * stroke pattern. Can be NULL if we are not stroking the text, which
+     * stroke pattern. Can be nullptr if we are not stroking the text, which
      * indicates that the current source from aContext should be used for filling
      * 
      * Callers guarantee:
      * -- aStart and aEnd are aligned to cluster and ligature boundaries
      * -- all glyphs use this font
      * 
      * The default implementation builds a cairo glyph array and
      * calls cairo_show_glyphs or cairo_glyph_path.
--- a/gfx/thebes/gfxFontconfigUtils.cpp
+++ b/gfx/thebes/gfxFontconfigUtils.cpp
@@ -303,17 +303,17 @@ gfxFontconfigUtils::NewPattern(const nsT
             AddWeakString(pattern, FC_FAMILY, family.get());
         }
     }
 
     return pattern.out();
 }
 
 gfxFontconfigUtils::gfxFontconfigUtils()
-    : mLastConfig(NULL)
+    : mLastConfig(nullptr)
 {
     mFontsByFamily.Init(50);
     mFontsByFullname.Init(50);
     mLangSupportTable.Init(20);
     UpdateFontListInternal();
 }
 
 nsresult
@@ -472,54 +472,54 @@ gfxFontconfigUtils::GetSampleLangForGrou
 
                     if (*pos == '\0')
                         break;
 
                     languages = pos + 1;
                 }
             }
         }
-        const char *ctype = setlocale(LC_CTYPE, NULL);
+        const char *ctype = setlocale(LC_CTYPE, nullptr);
         if (ctype &&
             TryLangForGroup(nsDependentCString(ctype), aLangGroup, aFcLang))
             return;
     }
 
     if (langGroup->defaultLang) {
         aFcLang->Assign(langGroup->defaultLang);
     } else {
         aFcLang->Truncate();
     }
 }
 
 nsresult
 gfxFontconfigUtils::GetFontListInternal(nsTArray<nsCString>& aListOfFonts,
                                         nsIAtom *aLangGroup)
 {
-    FcPattern *pat = NULL;
-    FcObjectSet *os = NULL;
-    FcFontSet *fs = NULL;
+    FcPattern *pat = nullptr;
+    FcObjectSet *os = nullptr;
+    FcFontSet *fs = nullptr;
     nsresult rv = NS_ERROR_FAILURE;
 
     aListOfFonts.Clear();
 
     pat = FcPatternCreate();
     if (!pat)
         goto end;
 
-    os = FcObjectSetBuild(FC_FAMILY, NULL);
+    os = FcObjectSetBuild(FC_FAMILY, nullptr);
     if (!os)
         goto end;
 
     // take the pattern and add the lang group to it
     if (aLangGroup) {
         AddLangGroup(pat, aLangGroup);
     }
 
-    fs = FcFontList(NULL, pat, os);
+    fs = FcFontList(nullptr, pat, os);
     if (!fs)
         goto end;
 
     for (int i = 0; i < fs->nfont; i++) {
         char *family;
 
         if (FcPatternGetString(fs->fonts[i], FC_FAMILY, 0,
                                (FcChar8 **) &family) != FcResultMatch)
@@ -559,18 +559,18 @@ gfxFontconfigUtils::UpdateFontList()
 
 nsresult
 gfxFontconfigUtils::UpdateFontListInternal(bool aForce)
 {
     if (!aForce) {
         // This checks periodically according to fontconfig's configured
         // <rescan> interval.
         FcInitBringUptoDate();
-    } else if (!FcConfigUptoDate(NULL)) { // check now with aForce
-        mLastConfig = NULL;
+    } else if (!FcConfigUptoDate(nullptr)) { // check now with aForce
+        mLastConfig = nullptr;
         FcInitReinitialize();
     }
 
     // FcInitReinitialize() (used by FcInitBringUptoDate) creates a new config
     // before destroying the old config, so the only way that we'd miss an
     // update is if fontconfig did more than one update and the memory for the
     // most recent config happened to be at the same location as the original
     // config.
@@ -664,34 +664,34 @@ gfxFontconfigUtils::GetStandardFamilyNam
         return rv;
 
     NS_ConvertUTF16toUTF8 fontname(aFontName);
 
     // return empty string if no such family exists
     if (!IsExistingFamily(fontname))
         return NS_OK;
 
-    FcPattern *pat = NULL;
-    FcObjectSet *os = NULL;
-    FcFontSet *givenFS = NULL;
+    FcPattern *pat = nullptr;
+    FcObjectSet *os = nullptr;
+    FcFontSet *givenFS = nullptr;
     nsTArray<nsCString> candidates;
-    FcFontSet *candidateFS = NULL;
+    FcFontSet *candidateFS = nullptr;
     rv = NS_ERROR_FAILURE;
 
     pat = FcPatternCreate();
     if (!pat)
         goto end;
 
     FcPatternAddString(pat, FC_FAMILY, (FcChar8 *)fontname.get());
 
-    os = FcObjectSetBuild(FC_FAMILY, FC_FILE, FC_INDEX, NULL);
+    os = FcObjectSetBuild(FC_FAMILY, FC_FILE, FC_INDEX, nullptr);
     if (!os)
         goto end;
 
-    givenFS = FcFontList(NULL, pat, os);
+    givenFS = FcFontList(nullptr, pat, os);
     if (!givenFS)
         goto end;
 
     // The first value associated with a FC_FAMILY property is the family
     // returned by GetFontList(), so use this value if appropriate.
 
     // See if there is a font face with first family equal to the given family.
     for (int i = 0; i < givenFS->nfont; ++i) {
@@ -713,17 +713,17 @@ gfxFontconfigUtils::GetStandardFamilyNam
     }
 
     // See if any of the first family names represent the same set of font
     // faces as the given family.
     for (uint32_t j = 0; j < candidates.Length(); ++j) {
         FcPatternDel(pat, FC_FAMILY);
         FcPatternAddString(pat, FC_FAMILY, (FcChar8 *)candidates[j].get());
 
-        candidateFS = FcFontList(NULL, pat, os);
+        candidateFS = FcFontList(nullptr, pat, os);
         if (!candidateFS)
             goto end;
 
         if (candidateFS->nfont != givenFS->nfont)
             continue;
 
         bool equal = true;
         for (int i = 0; i < givenFS->nfont; ++i) {
@@ -829,50 +829,51 @@ gfxFontconfigUtils::GetFullnameFromFamil
 
     return true;
 }
 
 bool
 gfxFontconfigUtils::FontsByFullnameEntry::KeyEquals(KeyTypePointer aKey) const
 {
     const FcChar8 *key = mKey;
-    // If mKey is NULL, key comes from the style and family of the first font.
+    // If mKey is nullptr, key comes from the style and family of the first
+    // font.
     nsAutoCString fullname;
     if (!key) {
         NS_ASSERTION(mFonts.Length(), "No font in FontsByFullnameEntry!");
         GetFullnameFromFamilyAndStyle(mFonts[0], &fullname);
 
         key = ToFcChar8(fullname);
     }
 
     return FcStrCmpIgnoreCase(aKey, key) == 0;
 }
 
 void
 gfxFontconfigUtils::AddFullnameEntries()
 {
     // This FcFontSet is owned by fontconfig
-    FcFontSet *fontSet = FcConfigGetFonts(NULL, FcSetSystem);
+    FcFontSet *fontSet = FcConfigGetFonts(nullptr, FcSetSystem);
 
     // Record the existing font families
     for (int f = 0; f < fontSet->nfont; ++f) {
         FcPattern *font = fontSet->fonts[f];
 
         int v = 0;
         FcChar8 *fullname;
         while (FcPatternGetString(font,
                                   FC_FULLNAME, v, &fullname) == FcResultMatch) {
             FontsByFullnameEntry *entry = mFontsByFullname.PutEntry(fullname);
             if (entry) {
                 // entry always has space for one font, so the first AddFont
                 // will always succeed, and so the entry will always have a
                 // font from which to obtain the key.
                 bool added = entry->AddFont(font);
-                // The key may be NULL either if this is the first font, or if
-                // the first font does not have a fullname property, and so
+                // The key may be nullptr either if this is the first font, or
+                // if the first font does not have a fullname property, and so
                 // the key is obtained from the font.  Set the key in both
                 // cases.  The check that AddFont succeeded is required for
                 // the second case.
                 if (!entry->mKey && added) {
                     entry->mKey = fullname;
                 }
             }
 
@@ -885,18 +886,18 @@ gfxFontconfigUtils::AddFullnameEntries()
             if (!GetFullnameFromFamilyAndStyle(font, &name))
                 continue;
 
             FontsByFullnameEntry *entry =
                 mFontsByFullname.PutEntry(ToFcChar8(name));
             if (entry) {
                 entry->AddFont(font);
                 // Either entry->mKey has been set for a previous font or it
-                // remains NULL to indicate that the key is obtained from the
-                // first font.
+                // remains nullptr to indicate that the key is obtained from
+                // the first font.
             }
         }
     }
 }
 
 const nsTArray< nsCountedRef<FcPattern> >&
 gfxFontconfigUtils::GetFontsForFullname(const FcChar8 *aFullname)
 {
@@ -1003,17 +1004,17 @@ gfxFontconfigUtils::GetLangSupportEntry(
         best = entry->mSupport;
         // If there is support for this language, an empty font list indicates
         // that the list hasn't been initialized yet.
         if (best == FcLangDifferentLang || entry->mFonts.Length() > 0)
             return entry;
     }
 
     // This FcFontSet is owned by fontconfig
-    FcFontSet *fontSet = FcConfigGetFonts(NULL, FcSetSystem);
+    FcFontSet *fontSet = FcConfigGetFonts(nullptr, FcSetSystem);
 
     nsAutoTArray<FcPattern*,100> fonts;
 
     for (int f = 0; f < fontSet->nfont; ++f) {
         FcPattern *font = fontSet->fonts[f];
 
         FcLangResult support = GetLangSupport(font, aLang);
 
@@ -1041,17 +1042,17 @@ gfxFontconfigUtils::GetLangSupportEntry(
         if (fonts.Length() != 0) {
             entry->mFonts.AppendElements(fonts.Elements(), fonts.Length());
         } else if (best != FcLangDifferentLang) {
             // Previously there was a font that supported this language at the
             // level of entry->mSupport, but it has now disappeared.  At least
             // entry->mSupport needs to be recalculated, but this is an
             // indication that the set of installed fonts has changed, so
             // update all caches.
-            mLastConfig = NULL; // invalidates caches
+            mLastConfig = nullptr; // invalidates caches
             UpdateFontListInternal(true);
             return GetLangSupportEntry(aLang, aWithFonts);
         }
     }
 
     return entry;
 }
 
--- a/gfx/thebes/gfxFontconfigUtils.h
+++ b/gfx/thebes/gfxFontconfigUtils.h
@@ -176,21 +176,21 @@ public:
     // Hash entry with a dependent const FcChar8* pointer to an external
     // string for a key (and no data).  The user must ensure that the string
     // associated with the pointer is not destroyed.  This entry type is
     // useful for family name keys as the family name string is held in the
     // font pattern.
     class DepFcStrEntry : public FcStrEntryBase {
     public:
         // When constructing a new entry in the hashtable, the key is left
-        // NULL.  The caller of PutEntry() must fill in mKey when NULL.  This
-        // provides a mechanism for the caller of PutEntry() to determine
+        // nullptr.  The caller of PutEntry() must fill in mKey when nullptr.
+        // This provides a mechanism for the caller of PutEntry() to determine
         // whether the entry has been initialized.
         DepFcStrEntry(KeyTypePointer aName)
-            : mKey(NULL) { }
+            : mKey(nullptr) { }
 
         DepFcStrEntry(const DepFcStrEntry& toCopy)
             : mKey(toCopy.mKey) { }
 
         bool KeyEquals(KeyTypePointer aKey) const {
             return FcStrCmpIgnoreCase(aKey, mKey) == 0;
         }
 
@@ -248,17 +248,17 @@ protected:
     //
     // * The font does not always contain a single string for the fullname, so
     //   the key is sometimes a combination of family and style.
     //
     // * There is usually only one font.
     class FontsByFullnameEntry : public DepFcStrEntry {
     public:
         // When constructing a new entry in the hashtable, the key is left
-        // NULL.  The caller of PutEntry() is must fill in mKey when adding
+        // nullptr.  The caller of PutEntry() is must fill in mKey when adding
         // the first font if the key is not derived from the family and style.
         // If the key is derived from family and style, a font must be added.
         FontsByFullnameEntry(KeyTypePointer aName)
             : DepFcStrEntry(aName) { }
 
         FontsByFullnameEntry(const FontsByFullnameEntry& toCopy)
             : DepFcStrEntry(toCopy), mFonts(toCopy.mFonts) { }
 
--- a/gfx/thebes/gfxGDIFont.cpp
+++ b/gfx/thebes/gfxGDIFont.cpp
@@ -35,17 +35,17 @@ GetCairoAntialiasOption(gfxFont::Antiali
     }
 }
 
 gfxGDIFont::gfxGDIFont(GDIFontEntry *aFontEntry,
                        const gfxFontStyle *aFontStyle,
                        bool aNeedsBold,
                        AntialiasOption anAAOption)
     : gfxFont(aFontEntry, aFontStyle, anAAOption),
-      mFont(NULL),
+      mFont(nullptr),
       mFontFace(nullptr),
       mMetrics(nullptr),
       mSpaceGlyph(0),
       mNeedsBold(aNeedsBold)
 {
     if (FontCanSupportGraphite()) {
         mGraphiteShaper = new gfxGraphiteShaper(this);
     }
@@ -538,17 +538,17 @@ gfxGDIFont::GetGlyphWidth(gfxContext *aC
     if (mGlyphWidths.Get(aGID, &width)) {
         return width;
     }
 
     DCFromContext dc(aCtx);
     AutoSelectFont fs(dc, GetHFONT());
 
     int devWidth;
-    if (GetCharWidthI(dc, aGID, 1, NULL, &devWidth)) {
+    if (GetCharWidthI(dc, aGID, 1, nullptr, &devWidth)) {
         // ensure width is positive, 16.16 fixed-point value
         width = (devWidth & 0x7fff) << 16;
         mGlyphWidths.Put(aGID, width);
         return width;
     }
 
     return -1;
 }
--- a/gfx/thebes/gfxGDIFontList.cpp
+++ b/gfx/thebes/gfxGDIFontList.cpp
@@ -238,17 +238,18 @@ GDIFontEntry::CopyFontTable(uint32_t aTa
         return NS_ERROR_FAILURE;
     }
 
     AutoDC dc;
     AutoSelectFont font(dc.GetDC(), &mLogFont);
     if (font.IsValid()) {
         uint32_t tableSize =
             ::GetFontData(dc.GetDC(),
-                          NativeEndian::swapToBigEndian(aTableTag), 0, NULL, 0);
+                          NativeEndian::swapToBigEndian(aTableTag),
+                          0, nullptr, 0);
         if (tableSize != GDI_ERROR) {
             if (aBuffer.SetLength(tableSize)) {
                 ::GetFontData(dc.GetDC(),
                               NativeEndian::swapToBigEndian(aTableTag), 0,
                               aBuffer.Elements(), tableSize);
                 return NS_OK;
             }
             return NS_ERROR_OUT_OF_MEMORY;
@@ -338,24 +339,24 @@ GDIFontEntry::TestCharacterMap(uint32_t 
                 && glyph[0] != 0xFFFF
                 && (IsType1() || glyph[0] != MISSING_GLYPH))
             {
                 hasGlyph = true;
             }
         } else {
             // ScriptGetCMap works better than GetGlyphIndicesW 
             // for things like bitmap/vector fonts
-            SCRIPT_CACHE sc = NULL;
+            SCRIPT_CACHE sc = nullptr;
             HRESULT rv = ScriptGetCMap(dc, &sc, str, 1, 0, glyph);
             if (rv == S_OK)
                 hasGlyph = true;
         }
 
         SelectObject(dc, oldFont);
-        ReleaseDC(NULL, dc);
+        ReleaseDC(nullptr, dc);
 
         if (hasGlyph) {
             mCharacterMap->set(aCh);
             return true;
         }
     } else {
         // font had a cmap so simply check that
         return mCharacterMap->test(aCh);
@@ -594,17 +595,17 @@ gfxGDIFontList::GetFontSubstitutes()
         return NS_ERROR_FAILURE;
     }
 
     for (i = 0, rv = ERROR_SUCCESS; rv != ERROR_NO_MORE_ITEMS; i++) {
         aliasName[0] = 0;
         lenAlias = ArrayLength(aliasName);
         actualName[0] = 0;
         lenActual = sizeof(actualName);
-        rv = RegEnumValueW(hKey, i, aliasName, &lenAlias, NULL, &valueType, 
+        rv = RegEnumValueW(hKey, i, aliasName, &lenAlias, nullptr, &valueType,
                 (LPBYTE)actualName, &lenActual);
 
         if (rv != ERROR_SUCCESS || valueType != REG_SZ || lenAlias == 0) {
             continue;
         }
 
         if (aliasName[0] == WCHAR('@')) {
             continue;
--- a/gfx/thebes/gfxGDIFontList.h
+++ b/gfx/thebes/gfxGDIFontList.h
@@ -12,21 +12,21 @@
 #include "nsGkAtoms.h"
 
 #include <windows.h>
 
 class AutoDC // get the global device context, and auto-release it on destruction
 {
 public:
     AutoDC() {
-        mDC = ::GetDC(NULL);
+        mDC = ::GetDC(nullptr);
     }
 
     ~AutoDC() {
-        ::ReleaseDC(NULL, mDC);
+        ::ReleaseDC(nullptr, mDC);
     }
 
     HDC GetDC() {
         return mDC;
     }
 
 private:
     HDC mDC;
@@ -39,17 +39,17 @@ public:
         : mOwnsFont(false)
     {
         mFont = ::CreateFontIndirectW(aLogFont);
         if (mFont) {
             mOwnsFont = true;
             mDC = aDC;
             mOldFont = (HFONT)::SelectObject(aDC, mFont);
         } else {
-            mOldFont = NULL;
+            mOldFont = nullptr;
         }
     }
 
     AutoSelectFont(HDC aDC, HFONT aFont)
         : mOwnsFont(false)
     {
         mDC = aDC;
         mFont = aFont;
@@ -61,17 +61,17 @@ public:
             ::SelectObject(mDC, mOldFont);
             if (mOwnsFont) {
                 ::DeleteObject(mFont);
             }
         }
     }
 
     bool IsValid() const {
-        return mFont != NULL;
+        return mFont != nullptr;
     }
 
     HFONT GetFont() const {
         return mFont;
     }
 
 private:
     HDC    mDC;
--- a/gfx/thebes/gfxGDIShaper.cpp
+++ b/gfx/thebes/gfxGDIShaper.cpp
@@ -47,17 +47,17 @@ gfxGDIShaper::ShapeText(gfxContext      
     if (!partialWidthArray.SetLength(length)) {
         return false;
     }
 
     BOOL success = ::GetTextExtentExPointI(dc,
                                            glyphs,
                                            length,
                                            INT_MAX,
-                                           NULL,
+                                           nullptr,
                                            partialWidthArray.Elements(),
                                            &size);
     if (!success) {
         return false;
     }
 
     gfxTextRun::CompressedGlyph g;
     gfxTextRun::CompressedGlyph *charGlyphs =
--- a/gfx/thebes/gfxGdkNativeRenderer.cpp
+++ b/gfx/thebes/gfxGdkNativeRenderer.cpp
@@ -39,17 +39,17 @@ gfxGdkNativeRenderer::DrawWithXlib(gfxXl
         NS_ASSERTION(numClipRects == 1, "Too many clip rects");
         clipRect.x = clipRects[0].x;
         clipRect.y = clipRects[0].y;
         clipRect.width = clipRects[0].width;
         clipRect.height = clipRects[0].height;
     }
 
     return DrawWithGDK(drawable, offset.x, offset.y,
-                       numClipRects ? &clipRect : NULL, numClipRects);
+                       numClipRects ? &clipRect : nullptr, numClipRects);
 }
 
 void
 gfxGdkNativeRenderer::Draw(gfxContext* ctx, nsIntSize size,
                            uint32_t flags, GdkColormap* colormap)
 {
     mColormap = colormap;
 
--- a/gfx/thebes/gfxImageSurface.cpp
+++ b/gfx/thebes/gfxImageSurface.cpp
@@ -41,17 +41,17 @@ gfxImageSurface::gfxImageSurface(unsigne
 {
     InitWithData(aData, aSize, aStride, aFormat);
 }
 
 void
 gfxImageSurface::MakeInvalid()
 {
     mSize = gfxIntSize(-1, -1);
-    mData = NULL;
+    mData = nullptr;
     mStride = 0;
 }
 
 void
 gfxImageSurface::InitWithData(unsigned char *aData, const gfxIntSize& aSize,
                               long aStride, gfxImageFormat aFormat)
 {
     mSize = aSize;
--- a/gfx/thebes/gfxMacFont.cpp
+++ b/gfx/thebes/gfxMacFont.cpp
@@ -55,17 +55,17 @@ gfxMacFont::gfxMacFont(MacOSFontEntry *a
     }
 
     cairo_matrix_t sizeMatrix, ctm;
     cairo_matrix_init_identity(&ctm);
     cairo_matrix_init_scale(&sizeMatrix, mAdjustedSize, mAdjustedSize);
 
     // synthetic oblique by skewing via the font matrix
     bool needsOblique =
-        (mFontEntry != NULL) &&
+        (mFontEntry != nullptr) &&
         (!mFontEntry->IsItalic() &&
          (mStyle.style & (NS_FONT_STYLE_ITALIC | NS_FONT_STYLE_OBLIQUE)));
 
     if (needsOblique) {
         double skewfactor = (needsOblique ? Fix2X(kATSItalicQDSkew) : 0);
 
         cairo_matrix_t style;
         cairo_matrix_init(&style,
@@ -364,17 +364,17 @@ gfxMacFont::GetCharWidth(CFDataRef aCmap
 // We ONLY call this for local (platform) fonts that are not sfnt format;
 // for sfnts, including ALL downloadable fonts, we prefer to use
 // InitMetricsFromSfntTables and avoid platform APIs.
 void
 gfxMacFont::InitMetricsFromPlatform()
 {
     CTFontRef ctFont = ::CTFontCreateWithGraphicsFont(mCGFont,
                                                       mAdjustedSize,
-                                                      NULL, NULL);
+                                                      nullptr, nullptr);
     if (!ctFont) {
         return;
     }
 
     mMetrics.underlineOffset = ::CTFontGetUnderlinePosition(ctFont);
     mMetrics.underlineSize = ::CTFontGetUnderlineThickness(ctFont);
 
     mMetrics.externalLeading = ::CTFontGetLeading(ctFont);
--- a/gfx/thebes/gfxOS2Fonts.cpp
+++ b/gfx/thebes/gfxOS2Fonts.cpp
@@ -351,31 +351,31 @@ cairo_font_face_t *gfxOS2Font::CairoFont
         FcPatternAddInteger(fcPattern, FC_SLANT, fcProperty);
 
         // add the size we want
         FcPatternAddDouble(fcPattern, FC_PIXEL_SIZE,
                            mAdjustedSize ? mAdjustedSize : GetStyle()->size);
 
         // finally find a matching font
         FcResult fcRes;
-        FcPattern *fcMatch = FcFontMatch(NULL, fcPattern, &fcRes);
+        FcPattern *fcMatch = FcFontMatch(nullptr, fcPattern, &fcRes);
 
         // Most code that depends on FcFontMatch() assumes it won't fail,
         // then crashes when it does.  For now, at least, substitute the
         // default serif font when it fails to avoid those crashes.
         if (!fcMatch) {
 //#ifdef DEBUG
             printf("Could not match font for:\n"
                    "  family=%s, weight=%d, slant=%d, size=%f\n",
                    NS_LossyConvertUTF16toASCII(GetName()).get(),
                    GetStyle()->weight, GetStyle()->style, GetStyle()->size);
 //#endif
             // FcPatternAddString() will free the existing FC_FAMILY string
             FcPatternAddString(fcPattern, FC_FAMILY, (FcChar8*)"SERIF");
-            fcMatch = FcFontMatch(NULL, fcPattern, &fcRes);
+            fcMatch = FcFontMatch(nullptr, fcPattern, &fcRes);
 //#ifdef DEBUG
             printf("Attempt to substitute default SERIF font %s\n",
                    fcMatch ? "succeeded" : "failed");
 //#endif
         }
         FcPatternDestroy(fcPattern);
 
         if (fcMatch) {
@@ -444,17 +444,17 @@ cairo_scaled_font_t *gfxOS2Font::CairoSc
 bool gfxOS2Font::SetupCairoFont(gfxContext *aContext)
 {
 #ifdef DEBUG_thebes_2
     printf("gfxOS2Font[%#x]::SetupCairoFont(%#x)\n",
            (unsigned)this, (unsigned) aContext);
 #endif
     // gfxPangoFont checks the CTM but Windows doesn't so leave away here, too
 
-    // this implicitely ensures that mScaledFont is created if NULL
+    // this implicitely ensures that mScaledFont is created if nullptr
     cairo_scaled_font_t *scaledFont = CairoScaledFont();
     if (!scaledFont || cairo_scaled_font_status(scaledFont) != CAIRO_STATUS_SUCCESS) {
         // Don't cairo_set_scaled_font as that would propagate the error to
         // the cairo_t, precluding any further drawing.
         return false;
     }
     cairo_set_scaled_font(aContext->GetCairo(), scaledFont);
     return true;
--- a/gfx/thebes/gfxOS2Surface.cpp
+++ b/gfx/thebes/gfxOS2Surface.cpp
@@ -144,17 +144,17 @@ gfxOS2Surface::~gfxOS2Surface()
     // other hand were created on device contexts with the GPI functions, so
     // use those to clean up stuff.
     if (mWnd) {
         if (mPS) {
             WinReleasePS(mPS);
         }
     } else {
         if (mBitmap) {
-            GpiSetBitmap(mPS, NULL);
+            GpiSetBitmap(mPS, nullptr);
             GpiDeleteBitmap(mBitmap);
         }
         if (mPS) {
             GpiDestroyPS(mPS);
         }
         if (mDC) {
             DevCloseDC(mDC);
         }
--- a/gfx/thebes/gfxPangoFonts.cpp
+++ b/gfx/thebes/gfxPangoFonts.cpp
@@ -74,17 +74,17 @@ FindFunctionSymbol(const char *name)
         PR_UnloadLibrary(lib);
     }
 
     return result;
 }
 
 static bool HasChar(FcPattern *aFont, FcChar32 wc)
 {
-    FcCharSet *charset = NULL;
+    FcCharSet *charset = nullptr;
     FcPatternGetCharSet(aFont, FC_CHARSET, 0, &charset);
 
     return charset && FcCharSetHasChar(charset, wc);
 }
 
 /**
  * gfxFcFontEntry:
  *
@@ -182,32 +182,35 @@ public:
     // not a fully resolved pattern.
     gfxSystemFcFontEntry(cairo_font_face_t *aFontFace,
                          FcPattern *aFontPattern,
                          const nsAString& aName)
         : gfxFcFontEntry(aName), mFontFace(aFontFace),
           mFTFace(nullptr), mFTFaceInitialized(false)
     {
         cairo_font_face_reference(mFontFace);
-        cairo_font_face_set_user_data(mFontFace, &sFontEntryKey, this, NULL);
+        cairo_font_face_set_user_data(mFontFace, &sFontEntryKey, this, nullptr);
         mPatterns.AppendElement();
         // mPatterns is an nsAutoTArray with 1 space always available, so the
         // AppendElement always succeeds.
         mPatterns[0] = aFontPattern;
 
         FcChar8 *name;
         if (FcPatternGetString(aFontPattern,
                                FC_FAMILY, 0, &name) == FcResultMatch) {
             mFamilyName = NS_ConvertUTF8toUTF16((const char*)name);
         }
     }
 
     ~gfxSystemFcFontEntry()
     {
-        cairo_font_face_set_user_data(mFontFace, &sFontEntryKey, NULL, NULL);
+        cairo_font_face_set_user_data(mFontFace,
+                                      &sFontEntryKey,
+                                      nullptr,
+                                      nullptr);
         cairo_font_face_destroy(mFontFace);
     }
 
     virtual void ForgetHBFace();
     virtual void ReleaseGrFace(gr_face* aFace);
 
 protected:
     virtual nsresult
@@ -443,17 +446,17 @@ public:
 
 class gfxDownloadedFcFontEntry : public gfxUserFcFontEntry {
 public:
     // This takes ownership of the face and its underlying data
     gfxDownloadedFcFontEntry(const gfxProxyFontEntry &aProxyEntry,
                              const uint8_t *aData, FT_Face aFace)
         : gfxUserFcFontEntry(aProxyEntry), mFontData(aData), mFace(aFace)
     {
-        NS_PRECONDITION(aFace != NULL, "aFace is NULL!");
+        NS_PRECONDITION(aFace != nullptr, "aFace is NULL!");
         InitPattern();
     }
 
     virtual ~gfxDownloadedFcFontEntry();
 
     // Returns true on success
     bool SetCairoFace(cairo_font_face_t *aFace);
 
@@ -531,42 +534,46 @@ gfxDownloadedFcFontEntry::InitPattern()
     // FcFreeTypeQueryFace is the same function used to construct patterns for
     // system fonts and so is the preferred function to use for this purpose.
     // This will set up the langset property, which helps with sorting, and
     // the foundry, fullname, and fontversion properties, which properly
     // identify the font to fontconfig rules.  However, FcFreeTypeQueryFace is
     // available only from fontconfig-2.4.2 (December 2006).  (CentOS 5.0 has
     // fontconfig-2.4.1.)
     if (sQueryFacePtr) {
-        // The "file" argument cannot be NULL (in fontconfig-2.6.0 at least).
-        // The dummy file passed here is removed below.
+        // The "file" argument cannot be nullptr (in fontconfig-2.6.0 at
+        // least). The dummy file passed here is removed below.
         //
-        // When fontconfig scans the system fonts, FcConfigGetBlanks(NULL) is
-        // passed as the "blanks" argument, which provides that unexpectedly
-        // blank glyphs are elided.  Here, however, we pass NULL for "blanks",
-        // effectively assuming that, if the font has a blank glyph, then the
-        // author intends any associated character to be rendered blank.
+        // When fontconfig scans the system fonts, FcConfigGetBlanks(nullptr)
+        // is passed as the "blanks" argument, which provides that unexpectedly
+        // blank glyphs are elided.  Here, however, we pass nullptr for
+        // "blanks", effectively assuming that, if the font has a blank glyph,
+        // then the author intends any associated character to be rendered
+        // blank.
         pattern =
-            (*sQueryFacePtr)(mFace, gfxFontconfigUtils::ToFcChar8(""), 0, NULL);
+            (*sQueryFacePtr)(mFace,
+                             gfxFontconfigUtils::ToFcChar8(""),
+                             0,
+                             nullptr);
         if (!pattern)
             // Either OOM, or fontconfig chose to skip this font because it
             // has "no encoded characters", which I think means "BDF and PCF
             // fonts which are not in Unicode (or the effectively equivalent
             // ISO Latin-1) encoding".
             return;
 
         // These properties don't make sense for this face without a file.
         FcPatternDel(pattern, FC_FILE);
         FcPatternDel(pattern, FC_INDEX);
 
     } else {
         // Do the minimum necessary to construct a pattern for sorting.
 
         // FC_CHARSET is vital to determine which characters are supported.
-        nsAutoRef<FcCharSet> charset(FcFreeTypeCharSet(mFace, NULL));
+        nsAutoRef<FcCharSet> charset(FcFreeTypeCharSet(mFace, nullptr));
         // If there are no characters then assume we don't know how to read
         // this font.
         if (!charset || FcCharSetCount(charset) == 0)
             return;
 
         pattern = FcPatternCreate();
         FcPatternAddCharSet(pattern, FC_CHARSET, charset);
 
@@ -703,17 +710,17 @@ public:
     // A reference is held by the FontSet.
     // The caller may add a ref to keep the font alive longer than the FontSet.
     gfxFcFont *GetFontAt(uint32_t i, const gfxFontStyle *aFontStyle)
     {
         if (i >= mFonts.Length() || !mFonts[i].mFont) { 
             // GetFontPatternAt sets up mFonts
             FcPattern *fontPattern = GetFontPatternAt(i);
             if (!fontPattern)
-                return NULL;
+                return nullptr;
 
             mFonts[i].mFont =
                 gfxFcFont::GetOrMakeFont(mSortPattern, fontPattern,
                                          aFontStyle);
         }
         return mFonts[i].mFont;
     }
 
@@ -764,17 +771,17 @@ private:
     // fallback fonts.
     nsAutoRef<FcFontSet> mFcFontSet;
     // The set of characters supported by the fonts in mFonts.
     nsAutoRef<FcCharSet> mCharSet;
     // The index of the next font in mFcFontSet that has not yet been
     // considered for mFonts.
     int mFcFontsTrimmed;
     // True iff fallback fonts are either stored in mFcFontSet or have been
-    // trimmed and added to mFonts (so that mFcFontSet is NULL).
+    // trimmed and added to mFonts (so that mFcFontSet is nullptr).
     bool mHaveFallbackFonts;
     // True iff there was a user font set with pending downloads,
     // so the set may be updated when downloads complete
     bool mWaitingForUserFont;
 };
 
 // Find the FcPattern for an @font-face font suitable for CSS family |aFamily|
 // and style |aStyle| properties.
@@ -1051,17 +1058,17 @@ gfxFcFontSet::SortPreferredFonts(bool &a
                 // override the family name
                 if (!isUserFont) {
                     FcPatternReference(font);
                 }
             }
         }
     }
 
-    FcPattern *truncateMarker = NULL;
+    FcPattern *truncateMarker = nullptr;
     for (uint32_t r = 0; r < requiredLangs.Length(); ++r) {
         const nsTArray< nsCountedRef<FcPattern> >& langFonts =
             utils->GetFontsForLang(requiredLangs[r].mLang);
 
         bool haveLangFont = false;
         for (uint32_t f = 0; f < langFonts.Length(); ++f) {
             FcPattern *font = langFonts[f];
             if (!SlantIsAcceptable(font, requestedSlant))
@@ -1098,26 +1105,26 @@ gfxFcFontSet::SortPreferredFonts(bool &a
             }
             break;
         }
     }
 
     FcFontSet *sets[1] = { fontSet };
     FcResult result;
 #ifdef SOLARIS
-    // Get around a crash of FcFontSetSort when FcConfig is NULL
+    // Get around a crash of FcFontSetSort when FcConfig is nullptr
     // Solaris's FcFontSetSort needs an FcConfig (bug 474758)
     fontSet.own(FcFontSetSort(FcConfigGetCurrent(), sets, 1, mSortPattern,
-                              FcFalse, NULL, &result));
+                              FcFalse, nullptr, &result));
 #else
-    fontSet.own(FcFontSetSort(NULL, sets, 1, mSortPattern,
-                              FcFalse, NULL, &result));
+    fontSet.own(FcFontSetSort(nullptr, sets, 1, mSortPattern,
+                              FcFalse, nullptr, &result));
 #endif
 
-    if (truncateMarker != NULL && fontSet) {
+    if (truncateMarker != nullptr && fontSet) {
         nsAutoRef<FcFontSet> truncatedSet(FcFontSetCreate());
 
         for (int f = 0; f < fontSet->nfont; ++f) {
             FcPattern *font = fontSet->fonts[f];
             if (font == truncateMarker)
                 break;
 
             if (FcFontSetAdd(truncatedSet, font)) {
@@ -1138,33 +1145,33 @@ gfxFcFontSet::SortFallbackFonts()
     // but would take much longer due to comparing all the character sets.
     //
     // The references to fonts in this FcFontSet are almost free
     // as they are pointers into mmaped cache files.
     //
     // GetFontPatternAt() will trim lazily if and as needed, which will also
     // remove duplicates of preferred fonts.
     FcResult result;
-    return nsReturnRef<FcFontSet>(FcFontSort(NULL, mSortPattern,
-                                             FcFalse, NULL, &result));
+    return nsReturnRef<FcFontSet>(FcFontSort(nullptr, mSortPattern,
+                                             FcFalse, nullptr, &result));
 }
 
 // GetFontAt relies on this setting up all patterns up to |i|.
 FcPattern *
 gfxFcFontSet::GetFontPatternAt(uint32_t i)
 {
     while (i >= mFonts.Length()) {
         while (!mFcFontSet) {
             if (mHaveFallbackFonts)
                 return nullptr;
 
             mFcFontSet = SortFallbackFonts();
             mHaveFallbackFonts = true;
             mFcFontsTrimmed = 0;
-            // Loop to test that mFcFontSet is non-NULL.
+            // Loop to test that mFcFontSet is non-nullptr.
         }
 
         while (mFcFontsTrimmed < mFcFontSet->nfont) {
             FcPattern *font = mFcFontSet->fonts[mFcFontsTrimmed];
             ++mFcFontsTrimmed;
 
             if (mFonts.Length() != 0) {
                 // See if the next font provides support for any extra
@@ -1173,17 +1180,17 @@ gfxFcFontSet::GetFontPatternAt(uint32_t 
                 // allocating a new CharSet with Union.
                 FcCharSet *supportedChars = mCharSet;
                 if (!supportedChars) {
                     FcPatternGetCharSet(mFonts[mFonts.Length() - 1].mPattern,
                                         FC_CHARSET, 0, &supportedChars);
                 }
 
                 if (supportedChars) {
-                    FcCharSet *newChars = NULL;
+                    FcCharSet *newChars = nullptr;
                     FcPatternGetCharSet(font, FC_CHARSET, 0, &newChars);
                     if (newChars) {
                         if (FcCharSetIsSubset(newChars, supportedChars))
                             continue;
 
                         mCharSet.own(FcCharSetUnion(supportedChars, newChars));
                     } else if (!mCharSet) {
                         mCharSet.own(FcCharSetCopy(supportedChars));
@@ -1209,17 +1216,17 @@ gfxFcFontSet::GetFontPatternAt(uint32_t 
 static void ApplyGdkScreenFontOptions(FcPattern *aPattern);
 #endif
 
 // Apply user settings and defaults to pattern in preparation for matching.
 static void
 PrepareSortPattern(FcPattern *aPattern, double aFallbackSize,
                    double aSizeAdjustFactor, bool aIsPrinterFont)
 {
-    FcConfigSubstitute(NULL, aPattern, FcMatchPattern);
+    FcConfigSubstitute(nullptr, aPattern, FcMatchPattern);
 
     // This gets cairo_font_options_t for the Screen.  We should have
     // different font options for printing (no hinting) but we are not told
     // what we are measuring for.
     //
     // If cairo adds support for lcd_filter, gdk will not provide the default
     // setting for that option.  We could get the default setting by creating
     // an xlib surface once, recording its font_options, and then merging the
@@ -1548,17 +1555,17 @@ gfxPangoFontGroup::FindFontForChar(uint3
     //
     //   2. For system fonts, use the default Pango behavior to give
     //      consistency with other apps.  This is relevant when un-localized
     //      builds are run in non-Latin locales.  This special-case probably
     //      wouldn't be necessary but for bug 91190.
 
     gfxFcFontSet *fontSet = GetBaseFontSet();
     uint32_t nextFont = 0;
-    FcPattern *basePattern = NULL;
+    FcPattern *basePattern = nullptr;
     if (!mStyle.systemFont && mPangoLanguage) {
         basePattern = fontSet->GetFontPatternAt(0);
         if (HasChar(basePattern, aCh)) {
             *aMatchType = gfxTextRange::kFontGroup;
             return nsRefPtr<gfxFont>(GetBaseFont()).forget();
         }
 
         nextFont = 1;
@@ -1612,22 +1619,25 @@ CHECK_SCRIPT_CODE(NKO);
 
 cairo_user_data_key_t gfxFcFont::sGfxFontKey;
 
 gfxFcFont::gfxFcFont(cairo_scaled_font_t *aCairoFont,
                      gfxFcFontEntry *aFontEntry,
                      const gfxFontStyle *aFontStyle)
     : gfxFT2FontBase(aCairoFont, aFontEntry, aFontStyle)
 {
-    cairo_scaled_font_set_user_data(mScaledFont, &sGfxFontKey, this, NULL);
+    cairo_scaled_font_set_user_data(mScaledFont, &sGfxFontKey, this, nullptr);
 }
 
 gfxFcFont::~gfxFcFont()
 {
-    cairo_scaled_font_set_user_data(mScaledFont, &sGfxFontKey, NULL, NULL);
+    cairo_scaled_font_set_user_data(mScaledFont,
+                                    &sGfxFontKey,
+                                    nullptr,
+                                    nullptr);
 }
 
 bool
 gfxFcFont::ShapeText(gfxContext      *aContext,
                      const PRUnichar *aText,
                      uint32_t         aOffset,
                      uint32_t         aLength,
                      int32_t          aScript,
@@ -1664,17 +1674,17 @@ gfxFcFont::ShapeText(gfxContext      *aC
     return ok;
 }
 
 /* static */ void
 gfxPangoFontGroup::Shutdown()
 {
     // Resetting gFTLibrary in case this is wanted again after a
     // cairo_debug_reset_static_data.
-    gFTLibrary = NULL;
+    gFTLibrary = nullptr;
 }
 
 /* static */ gfxFontEntry *
 gfxPangoFontGroup::NewFontEntry(const gfxProxyFontEntry &aProxyEntry,
                                 const nsAString& aFullname)
 {
     gfxFontconfigUtils *utils = gfxFontconfigUtils::GetFontconfigUtils();
     if (!utils)
@@ -1699,17 +1709,17 @@ gfxPangoFontGroup::NewFontEntry(const gf
 
     nsAutoRef<FcPattern> pattern(FcPatternCreate());
     if (!pattern)
         return nullptr;
 
     NS_ConvertUTF16toUTF8 fullname(aFullname);
     FcPatternAddString(pattern, FC_FULLNAME,
                        gfxFontconfigUtils::ToFcChar8(fullname));
-    FcConfigSubstitute(NULL, pattern, FcMatchPattern);
+    FcConfigSubstitute(nullptr, pattern, FcMatchPattern);
 
     FcChar8 *name;
     for (int v = 0;
          FcPatternGetString(pattern, FC_FULLNAME, v, &name) == FcResultMatch;
          ++v) {
         const nsTArray< nsCountedRef<FcPattern> >& fonts =
             utils->GetFontsForFullname(name);
 
@@ -1734,37 +1744,37 @@ gfxPangoFontGroup::GetFTLibrary()
         // likely to be also used elsewhere.
         gfxFontStyle style;
         nsRefPtr<gfxPangoFontGroup> fontGroup =
             new gfxPangoFontGroup(NS_LITERAL_STRING("sans-serif"),
                                   &style, nullptr);
 
         gfxFcFont *font = fontGroup->GetBaseFont();
         if (!font)
-            return NULL;
+            return nullptr;
 
         gfxFT2LockedFace face(font);
         if (!face.get())
-            return NULL;
+            return nullptr;
 
         gFTLibrary = face.get()->glyph->library;
     }
 
     return gFTLibrary;
 }
 
 /* static */ gfxFontEntry *
 gfxPangoFontGroup::NewFontEntry(const gfxProxyFontEntry &aProxyEntry,
                                 const uint8_t *aFontData, uint32_t aLength)
 {
     // Ownership of aFontData is passed in here, and transferred to the
     // new fontEntry, which will release it when no longer needed.
 
     // Using face_index = 0 for the first face in the font, as we have no
-    // other information.  FT_New_Memory_Face checks for a NULL FT_Library.
+    // other information.  FT_New_Memory_Face checks for a nullptr FT_Library.
     FT_Face face;
     FT_Error error =
         FT_New_Memory_Face(GetFTLibrary(), aFontData, aLength, 0, &face);
     if (error != 0) {
         NS_Free((void*)aFontData);
         return nullptr;
     }
 
@@ -1798,17 +1808,17 @@ GetPixelSize(FcPattern *aPattern)
  */
 
 /* static */
 already_AddRefed<gfxFcFont>
 gfxFcFont::GetOrMakeFont(FcPattern *aRequestedPattern, FcPattern *aFontPattern,
                          const gfxFontStyle *aFontStyle)
 {
     nsAutoRef<FcPattern> renderPattern
-        (FcFontRenderPrepare(NULL, aRequestedPattern, aFontPattern));
+        (FcFontRenderPrepare(nullptr, aRequestedPattern, aFontPattern));
     cairo_font_face_t *face =
         cairo_ft_font_face_create_for_pattern(renderPattern);
 
     // Reuse an existing font entry if available.
     nsRefPtr<gfxFcFontEntry> fe = gfxFcFontEntry::LookupFontEntry(face);
     if (!fe) {
         gfxDownloadedFcFontEntry *downloadedFontEntry =
             GetDownloadedFontEntry(aFontPattern);
@@ -2120,24 +2130,24 @@ CreateScaledFont(FcPattern *aPattern, ca
     return scaledFont;
 }
 
 /* static */
 PangoLanguage *
 GuessPangoLanguage(nsIAtom *aLanguage)
 {
     if (!aLanguage)
-        return NULL;
+        return nullptr;
 
     // Pango and fontconfig won't understand mozilla's internal langGroups, so
     // find a real language.
     nsAutoCString lang;
     gfxFontconfigUtils::GetSampleLangForGroup(aLanguage, &lang);
     if (lang.IsEmpty())
-        return NULL;
+        return nullptr;
 
     return pango_language_from_string(lang.get());
 }
 
 #ifdef MOZ_WIDGET_GTK
 /***************************************************************************
  *
  * This function must be last in the file because it uses the system cairo
--- a/gfx/thebes/gfxPangoFonts.h
+++ b/gfx/thebes/gfxPangoFonts.h
@@ -47,19 +47,20 @@ public:
                                       const nsAString &aFullname);
     // Used for @font-face { src: url(); }
     static gfxFontEntry *NewFontEntry(const gfxProxyFontEntry &aProxyEntry,
                                       const uint8_t *aFontData,
                                       uint32_t aLength);
 
 private:
     // @param aLang [in] language to use for pref fonts and system default font
-    //        selection, or NULL for the language guessed from the gfxFontStyle.
+    //        selection, or nullptr for the language guessed from the
+    //        gfxFontStyle.
     // The FontGroup holds a reference to this set.
-    gfxFcFontSet *GetFontSet(PangoLanguage *aLang = NULL);
+    gfxFcFontSet *GetFontSet(PangoLanguage *aLang = nullptr);
 
     class FontSetByLangEntry {
     public:
         FontSetByLangEntry(PangoLanguage *aLang, gfxFcFontSet *aFontSet);
         PangoLanguage *mLang;
         nsRefPtr<gfxFcFontSet> mFontSet;
     };
     // There is only one of entry in this array unless characters from scripts
@@ -68,21 +69,21 @@ private:
 
     gfxFloat mSizeAdjustFactor;
     PangoLanguage *mPangoLanguage;
 
     void GetFcFamilies(nsTArray<nsString> *aFcFamilyList,
                        nsIAtom *aLanguage);
 
     // @param aLang [in] language to use for pref fonts and system font
-    //        resolution, or NULL to guess a language from the gfxFontStyle.
-    // @param aMatchPattern [out] if non-NULL, will return the pattern used.
+    //        resolution, or nullptr to guess a language from the gfxFontStyle.
+    // @param aMatchPattern [out] if non-nullptr, will return the pattern used.
     already_AddRefed<gfxFcFontSet>
     MakeFontSet(PangoLanguage *aLang, gfxFloat aSizeAdjustFactor,
-                nsAutoRef<FcPattern> *aMatchPattern = NULL);
+                nsAutoRef<FcPattern> *aMatchPattern = nullptr);
 
     gfxFcFontSet *GetBaseFontSet();
     gfxFcFont *GetBaseFont();
 
     gfxFloat GetSizeAdjustFactor()
     {
         if (mFontSets.Length() == 0)
             GetBaseFontSet();
--- a/gfx/thebes/gfxPattern.cpp
+++ b/gfx/thebes/gfxPattern.cpp
@@ -10,54 +10,54 @@
 
 #include "cairo.h"
 
 #include <vector>
 
 using namespace mozilla::gfx;
 
 gfxPattern::gfxPattern(cairo_pattern_t *aPattern)
-  : mGfxPattern(NULL)
+  : mGfxPattern(nullptr)
 {
     mPattern = cairo_pattern_reference(aPattern);
 }
 
 gfxPattern::gfxPattern(const gfxRGBA& aColor)
-  : mGfxPattern(NULL)
+  : mGfxPattern(nullptr)
 {
     mPattern = cairo_pattern_create_rgba(aColor.r, aColor.g, aColor.b, aColor.a);
 }
 
 // from another surface
 gfxPattern::gfxPattern(gfxASurface *surface)
-  : mGfxPattern(NULL)
+  : mGfxPattern(nullptr)
 {
     mPattern = cairo_pattern_create_for_surface(surface->CairoSurface());
 }
 
 // linear
 gfxPattern::gfxPattern(gfxFloat x0, gfxFloat y0, gfxFloat x1, gfxFloat y1)
-  : mGfxPattern(NULL)
+  : mGfxPattern(nullptr)
 {
     mPattern = cairo_pattern_create_linear(x0, y0, x1, y1);
 }
 
 // radial
 gfxPattern::gfxPattern(gfxFloat cx0, gfxFloat cy0, gfxFloat radius0,
                        gfxFloat cx1, gfxFloat cy1, gfxFloat radius1)
-  : mGfxPattern(NULL)
+  : mGfxPattern(nullptr)
 {
     mPattern = cairo_pattern_create_radial(cx0, cy0, radius0,
                                            cx1, cy1, radius1);
 }
 
 // Azure
 gfxPattern::gfxPattern(SourceSurface *aSurface, const Matrix &aTransform)
-  : mPattern(NULL)
-  , mGfxPattern(NULL)
+  : mPattern(nullptr)
+  , mGfxPattern(nullptr)
   , mSourceSurface(aSurface)
   , mTransform(aTransform)
   , mExtend(EXTEND_NONE)
 {
 }
 
 gfxPattern::~gfxPattern()
 {
@@ -73,17 +73,17 @@ gfxPattern::CairoPattern()
 {
     return mPattern;
 }
 
 void
 gfxPattern::AddColorStop(gfxFloat offset, const gfxRGBA& c)
 {
   if (mPattern) {
-    mStops = NULL;
+    mStops = nullptr;
     if (gfxPlatform::GetCMSMode() == eCMSMode_All) {
         gfxRGBA cms;
         qcms_transform *transform = gfxPlatform::GetCMSRGBTransform();
         if (transform)
           gfxPlatform::TransformPixel(c, cms, transform);
 
         // Use the original alpha to avoid unnecessary float->byte->float
         // conversion errors
@@ -172,17 +172,17 @@ gfxPattern::GetPattern(DrawTarget *aTarg
     }
   case CAIRO_PATTERN_TYPE_SURFACE:
     {
       GraphicsFilter filter = (GraphicsFilter)cairo_pattern_get_filter(mPattern);
       cairo_matrix_t mat;
       cairo_pattern_get_matrix(mPattern, &mat);
       gfxMatrix matrix(*reinterpret_cast<gfxMatrix*>(&mat));
 
-      cairo_surface_t *surf = NULL;
+      cairo_surface_t *surf = nullptr;
       cairo_pattern_get_surface(mPattern, &surf);
 
       if (!mSourceSurface) {
         nsRefPtr<gfxASurface> gfxSurf = gfxASurface::Wrap(surf);
         // The underlying surface here will be kept around by the gfxPattern.
         // This function is intended to be used right away.
         mSourceSurface =
           gfxPlatform::GetPlatform()->GetSourceSurfaceForSurface(aTarget, gfxSurf);
@@ -288,20 +288,20 @@ gfxPattern::GetPattern(DrawTarget *aTarg
   new (mColorPattern.addr()) ColorPattern(Color(0, 0, 0, 0));
   return mColorPattern.addr();
 }
 
 void
 gfxPattern::SetExtend(GraphicsExtend extend)
 {
   if (mPattern) {
-    mStops = NULL;
+    mStops = nullptr;
     if (extend == EXTEND_PAD_EDGE) {
         if (cairo_pattern_get_type(mPattern) == CAIRO_PATTERN_TYPE_SURFACE) {
-            cairo_surface_t *surf = NULL;
+            cairo_surface_t *surf = nullptr;
 
             cairo_pattern_get_surface (mPattern, &surf);
             if (surf) {
                 switch (cairo_surface_get_type(surf)) {
                     case CAIRO_SURFACE_TYPE_WIN32_PRINTING:
                     case CAIRO_SURFACE_TYPE_QUARTZ:
                         extend = EXTEND_NONE;
                         break;
@@ -330,17 +330,17 @@ gfxPattern::SetExtend(GraphicsExtend ext
 
 bool
 gfxPattern::IsOpaque()
 {
   if (mPattern) {
     switch (cairo_pattern_get_type(mPattern)) {
     case CAIRO_PATTERN_TYPE_SURFACE:
       {
-        cairo_surface_t *surf = NULL;
+        cairo_surface_t *surf = nullptr;
         cairo_pattern_get_surface(mPattern, &surf);
 
         if (cairo_surface_get_content(surf) == CAIRO_CONTENT_COLOR) {
           return true;
         }
       }
     default:
       return false;
--- a/gfx/thebes/gfxPattern.h
+++ b/gfx/thebes/gfxPattern.h
@@ -40,17 +40,17 @@ public:
     void SetColorStops(mozilla::RefPtr<mozilla::gfx::GradientStops> aStops);
 
     void SetMatrix(const gfxMatrix& matrix);
     gfxMatrix GetMatrix() const;
     gfxMatrix GetInverseMatrix() const;
 
     /* Get an Azure Pattern for the current Cairo pattern. aPattern transform
      * specifies the transform that was set on the DrawTarget when the pattern
-     * was set. When this is NULL it is assumed the transform is identical
+     * was set. When this is nullptr it is assumed the transform is identical
      * to the current transform.
      */
     mozilla::gfx::Pattern *GetPattern(mozilla::gfx::DrawTarget *aTarget,
                                       mozilla::gfx::Matrix *aPatternTransform = nullptr);
     bool IsOpaque();
 
     enum GraphicsExtend {
         EXTEND_NONE,
--- a/gfx/thebes/gfxPlatform.cpp
+++ b/gfx/thebes/gfxPlatform.cpp
@@ -551,17 +551,17 @@ gfxPlatform::OptimizeImage(gfxImageSurfa
 }
 
 cairo_user_data_key_t kDrawTarget;
 
 RefPtr<DrawTarget>
 gfxPlatform::CreateDrawTargetForSurface(gfxASurface *aSurface, const IntSize& aSize)
 {
   RefPtr<DrawTarget> drawTarget = Factory::CreateDrawTargetForCairoSurface(aSurface->CairoSurface(), aSize);
-  aSurface->SetData(&kDrawTarget, drawTarget, NULL);
+  aSurface->SetData(&kDrawTarget, drawTarget, nullptr);
   return drawTarget;
 }
 
 // This is a temporary function used by ContentClient to build a DrawTarget
 // around the gfxASurface. This should eventually be replaced by plumbing
 // the DrawTarget through directly
 RefPtr<DrawTarget>
 gfxPlatform::CreateDrawTargetForUpdateSurface(gfxASurface *aSurface, const IntSize& aSize)
@@ -599,23 +599,23 @@ void SourceBufferDestroy(void *srcSurfUD
 }
 
 #if MOZ_TREE_CAIRO
 void SourceSnapshotDetached(cairo_surface_t *nullSurf)
 {
   gfxImageSurface* origSurf =
     static_cast<gfxImageSurface*>(cairo_surface_get_user_data(nullSurf, &kSourceSurface));
 
-  origSurf->SetData(&kSourceSurface, NULL, NULL);
+  origSurf->SetData(&kSourceSurface, nullptr, nullptr);
 }
 #else
 void SourceSnapshotDetached(void *nullSurf)
 {
   gfxImageSurface* origSurf = static_cast<gfxImageSurface*>(nullSurf);
-  origSurf->SetData(&kSourceSurface, NULL, NULL);
+  origSurf->SetData(&kSourceSurface, nullptr, nullptr);
 }
 #endif
 
 void
 gfxPlatform::ClearSourceSurfaceForSurface(gfxASurface *aSurface)
 {
   aSurface->SetData(&kSourceSurface, nullptr, nullptr);
 }
@@ -733,17 +733,17 @@ gfxPlatform::GetSourceSurfaceForSurface(
     }
 
 #if MOZ_TREE_CAIRO
     cairo_surface_t *nullSurf =
 	cairo_null_surface_create(CAIRO_CONTENT_COLOR_ALPHA);
     cairo_surface_set_user_data(nullSurf,
                                 &kSourceSurface,
                                 imgSurface,
-                                NULL);
+                                nullptr);
     cairo_surface_attach_snapshot(imgSurface->CairoSurface(), nullSurf, SourceSnapshotDetached);
     cairo_surface_destroy(nullSurf);
 #else
     cairo_surface_set_mime_data(imgSurface->CairoSurface(), "mozilla/magic", (const unsigned char*) "data", 4, SourceSnapshotDetached, imgSurface.get());
 #endif
   }
 
   SourceSurfaceUserData *srcSurfUD = new SourceSurfaceUserData;
@@ -844,17 +844,17 @@ gfxPlatform::CreateDrawTargetForBackend(
   // mozilla::gfx::Factory can get away without having all this knowledge for
   // now, but this might need to change in the future (using
   // CreateOffscreenSurface() and CreateDrawTargetForSurface() for all
   // backends).
   if (aBackend == BACKEND_CAIRO) {
     nsRefPtr<gfxASurface> surf = CreateOffscreenSurface(ThebesIntSize(aSize),
                                                         ContentForFormat(aFormat));
     if (!surf || surf->CairoStatus()) {
-      return NULL;
+      return nullptr;
     }
 
     return CreateDrawTargetForSurface(surf, aSize);
   } else {
     return Factory::CreateDrawTarget(aBackend, aSize, aFormat);
   }
 }
 
--- a/gfx/thebes/gfxPlatform.h
+++ b/gfx/thebes/gfxPlatform.h
@@ -488,17 +488,17 @@ public:
      *
      * See bug 444014 for details.
      */
     static int GetRenderingIntent();
 
     /**
      * Convert a pixel using a cms transform in an endian-aware manner.
      *
-     * Sets 'out' to 'in' if transform is NULL.
+     * Sets 'out' to 'in' if transform is nullptr.
      */
     static void TransformPixel(const gfxRGBA& in, gfxRGBA& out, qcms_transform *transform);
 
     /**
      * Return the output device ICC profile.
      */
     static qcms_profile* GetCMSOutputProfile();
 
--- a/gfx/thebes/gfxPlatformGtk.cpp
+++ b/gfx/thebes/gfxPlatformGtk.cpp
@@ -54,21 +54,21 @@ using namespace mozilla;
 using namespace mozilla::gfx;
 using namespace mozilla::unicode;
 
 gfxFontconfigUtils *gfxPlatformGtk::sFontconfigUtils = nullptr;
 
 #ifndef MOZ_PANGO
 typedef nsDataHashtable<nsStringHashKey, nsRefPtr<FontFamily> > FontTable;
 typedef nsDataHashtable<nsCStringHashKey, nsTArray<nsRefPtr<gfxFontEntry> > > PrefFontTable;
-static FontTable *gPlatformFonts = NULL;
-static FontTable *gPlatformFontAliases = NULL;
-static PrefFontTable *gPrefFonts = NULL;
-static gfxSparseBitSet *gCodepointsWithNoFonts = NULL;
-static FT_Library gPlatformFTLibrary = NULL;
+static FontTable *gPlatformFonts = nullptr;
+static FontTable *gPlatformFontAliases = nullptr;
+static PrefFontTable *gPrefFonts = nullptr;
+static gfxSparseBitSet *gCodepointsWithNoFonts = nullptr;
+static FT_Library gPlatformFTLibrary = nullptr;
 #endif
 
 static cairo_user_data_key_t cairo_gdk_drawable_key;
 
 #ifdef MOZ_X11
     bool gfxPlatformGtk::sUseXRender = true;
 #endif
 
@@ -100,32 +100,32 @@ gfxPlatformGtk::~gfxPlatformGtk()
 {
     gfxFontconfigUtils::Shutdown();
     sFontconfigUtils = nullptr;
 
 #ifdef MOZ_PANGO
     gfxPangoFontGroup::Shutdown();
 #else
     delete gPlatformFonts;
-    gPlatformFonts = NULL;
+    gPlatformFonts = nullptr;
     delete gPlatformFontAliases;
-    gPlatformFontAliases = NULL;
+    gPlatformFontAliases = nullptr;
     delete gPrefFonts;
-    gPrefFonts = NULL;
+    gPrefFonts = nullptr;
     delete gCodepointsWithNoFonts;
-    gCodepointsWithNoFonts = NULL;
+    gCodepointsWithNoFonts = nullptr;
 
 #ifdef NS_FREE_PERMANENT_DATA
     // do cairo cleanup *before* closing down the FTLibrary,
     // otherwise we'll crash when the gfxPlatform destructor
     // calls it (bug 605009)
     cairo_debug_reset_static_data();
 
     FT_Done_FreeType(gPlatformFTLibrary);
-    gPlatformFTLibrary = NULL;
+    gPlatformFTLibrary = nullptr;
 #endif
 #endif
 
 #if 0
     // It would be nice to do this (although it might need to be after
     // the cairo shutdown that happens in ~gfxPlatform).  It even looks
     // idempotent.  But it has fatal assertions that fire if stuff is
     // leaked, and we hit them.
@@ -278,25 +278,25 @@ gfxPlatformGtk::GetFontList(nsIAtom *aLa
 {
     return sFontconfigUtils->GetFontList(aLangGroup, aGenericFamily,
                                          aListOfFonts);
 }
 
 nsresult
 gfxPlatformGtk::UpdateFontList()
 {
-    FcPattern *pat = NULL;
-    FcObjectSet *os = NULL;
-    FcFontSet *fs = NULL;
+    FcPattern *pat = nullptr;
+    FcObjectSet *os = nullptr;
+    FcFontSet *fs = nullptr;
     int32_t result = -1;
 
     pat = FcPatternCreate();
-    os = FcObjectSetBuild(FC_FAMILY, FC_FILE, FC_INDEX, FC_WEIGHT, FC_SLANT, FC_WIDTH, NULL);
+    os = FcObjectSetBuild(FC_FAMILY, FC_FILE, FC_INDEX, FC_WEIGHT, FC_SLANT, FC_WIDTH, nullptr);
 
-    fs = FcFontList(NULL, pat, os);
+    fs = FcFontList(nullptr, pat, os);
 
 
     for (int i = 0; i < fs->nfont; i++) {
         char *str;
 
         if (FcPatternGetString(fs->fonts[i], FC_FAMILY, 0, (FcChar8 **) &str) != FcResultMatch)
             continue;
 
@@ -371,18 +371,18 @@ gfxPlatformGtk::ResolveFontName(const ns
         aAborted = !(*aCallback)(ff->Name(), aClosure);
         return NS_OK;
     }
 
     nsAutoCString utf8Name = NS_ConvertUTF16toUTF8(aFontName);
 
     FcPattern *npat = FcPatternCreate();
     FcPatternAddString(npat, FC_FAMILY, (FcChar8*)utf8Name.get());
-    FcObjectSet *nos = FcObjectSetBuild(FC_FAMILY, NULL);
-    FcFontSet *nfs = FcFontList(NULL, npat, nos);
+    FcObjectSet *nos = FcObjectSetBuild(FC_FAMILY, nullptr);
+    FcFontSet *nfs = FcFontList(nullptr, npat, nos);
 
     for (int k = 0; k < nfs->nfont; k++) {
         FcChar8 *str;
         if (FcPatternGetString(nfs->fonts[k], FC_FAMILY, 0, (FcChar8 **) &str) != FcResultMatch)
             continue;
         nsAutoString altName = NS_ConvertUTF8toUTF16(nsDependentCString(reinterpret_cast<char*>(str)));
         ToLowerCase(altName);
         if (gPlatformFonts->Get(altName, &ff)) {
@@ -396,25 +396,25 @@ gfxPlatformGtk::ResolveFontName(const ns
     FcPatternDestroy(npat);
     FcObjectSetDestroy(nos);
     FcFontSetDestroy(nfs);
 
     {
     npat = FcPatternCreate();
     FcPatternAddString(npat, FC_FAMILY, (FcChar8*)utf8Name.get());
     FcPatternDel(npat, FC_LANG);
-    FcConfigSubstitute(NULL, npat, FcMatchPattern);
+    FcConfigSubstitute(nullptr, npat, FcMatchPattern);
     FcDefaultSubstitute(npat);
 
-    nos = FcObjectSetBuild(FC_FAMILY, NULL);
-    nfs = FcFontList(NULL, npat, nos);
+    nos = FcObjectSetBuild(FC_FAMILY, nullptr);
+    nfs = FcFontList(nullptr, npat, nos);
 
     FcResult fresult;
 
-    FcPattern *match = FcFontMatch(NULL, npat, &fresult);
+    FcPattern *match = FcFontMatch(nullptr, npat, &fresult);
     if (match)
         FcFontSetAdd(nfs, match);
 
     for (int k = 0; k < nfs->nfont; k++) {
         FcChar8 *str;
         if (FcPatternGetString(nfs->fonts[k], FC_FAMILY, 0, (FcChar8 **) &str) != FcResultMatch)
             continue;
         nsAutoString altName = NS_ConvertUTF8toUTF16(nsDependentCString(reinterpret_cast<char*>(str)));
@@ -516,19 +516,19 @@ gfxPlatformGtk::GetPlatformCMSOutputProf
 #ifdef MOZ_X11
     const char EDID1_ATOM_NAME[] = "XFree86_DDC_EDID1_RAWDATA";
     const char ICC_PROFILE_ATOM_NAME[] = "_ICC_PROFILE";
 
     Atom edidAtom, iccAtom;
     Display *dpy = GDK_DISPLAY_XDISPLAY(gdk_display_get_default());
     // In xpcshell tests, we never initialize X and hence don't have a Display.
     // In this case, there's no output colour management to be done, so we just
-    // return NULL.
+    // return nullptr.
     if (!dpy) {
-        return NULL;
+        return nullptr;
     }
 
     Window root = gdk_x11_get_default_root_xwindow();
 
     Atom retAtom;
     int retFormat;
     unsigned long retLength, retAfter;
     unsigned char *retProperty ;
@@ -536,17 +536,17 @@ gfxPlatformGtk::GetPlatformCMSOutputProf
     iccAtom = XInternAtom(dpy, ICC_PROFILE_ATOM_NAME, TRUE);
     if (iccAtom) {
         // read once to get size, once for the data
         if (Success == XGetWindowProperty(dpy, root, iccAtom,
                                           0, INT_MAX /* length */,
                                           False, AnyPropertyType,
                                           &retAtom, &retFormat, &retLength,
                                           &retAfter, &retProperty)) {
-            qcms_profile* profile = NULL;
+            qcms_profile* profile = nullptr;
 
             if (retLength > 0)
                 profile = qcms_profile_from_memory(retProperty, retLength);
 
             XFree(retProperty);
 
             if (profile) {
 #ifdef DEBUG_tor
@@ -734,49 +734,49 @@ gfxPlatformGtk::SetGdkDrawable(gfxASurfa
                                  drawable,
                                  g_object_unref);
 }
 
 GdkDrawable *
 gfxPlatformGtk::GetGdkDrawable(gfxASurface *target)
 {
     if (target->CairoStatus())
-        return NULL;
+        return nullptr;
 
     GdkDrawable *result;
 
     result = (GdkDrawable*) cairo_surface_get_user_data (target->CairoSurface(),
                                                          &cairo_gdk_drawable_key);
     if (result)
         return result;
 
 #ifdef MOZ_X11
     if (target->GetType() != gfxASurface::SurfaceTypeXlib)
-        return NULL;
+        return nullptr;
 
     gfxXlibSurface *xs = static_cast<gfxXlibSurface*>(target);
 
     // try looking it up in gdk's table
     result = (GdkDrawable*) gdk_xid_table_lookup(xs->XDrawable());
     if (result) {
         SetGdkDrawable(target, result);
         return result;
     }
 #endif
 
-    return NULL;
+    return nullptr;
 }
 #endif
 
 TemporaryRef<ScaledFont>
 gfxPlatformGtk::GetScaledFontForFont(DrawTarget* aTarget, gfxFont *aFont)
 {
     NativeFont nativeFont;
 
     if (aTarget->GetType() == BACKEND_CAIRO || aTarget->GetType() == BACKEND_SKIA) {
         nativeFont.mType = NATIVE_FONT_CAIRO_FONT_FACE;
         nativeFont.mFont = aFont->GetCairoScaledFont();
         return Factory::CreateScaledFontForNativeFont(nativeFont, aFont->GetAdjustedSize());
     }
 
-    return NULL;
+    return nullptr;
 
 }
--- a/gfx/thebes/gfxPlatformMac.cpp
+++ b/gfx/thebes/gfxPlatformMac.cpp
@@ -37,17 +37,17 @@ typedef uint32_t AutoActivationSetting;
 
 // bug 567552 - disable auto-activation of fonts
 
 static void 
 DisableFontActivation()
 {
     // get the main bundle identifier
     CFBundleRef mainBundle = ::CFBundleGetMainBundle();
-    CFStringRef mainBundleID = NULL;
+    CFStringRef mainBundleID = nullptr;
 
     if (mainBundle) {
         mainBundleID = ::CFBundleGetIdentifier(mainBundle);
     }
 
     // if possible, fetch CTFontManagerSetAutoActivationSetting
     void (*CTFontManagerSetAutoActivationSettingPtr)
             (CFStringRef, AutoActivationSetting);
@@ -465,17 +465,17 @@ gfxPlatformMac::GetPlatformCMSOutputProf
        corresponds directly to a CGSDisplayID */
     CGDirectDisplayID displayID = CGMainDisplayID();
 
     CMError err = CMGetProfileByAVID(static_cast<CMDisplayIDType>(displayID), &cmProfile);
     if (err != noErr)
         return nullptr;
 
     // get the size of location
-    err = NCMGetProfileLocation(cmProfile, NULL, &locationSize);
+    err = NCMGetProfileLocation(cmProfile, nullptr, &locationSize);
     if (err != noErr)
         return nullptr;
 
     // allocate enough room for location
     location = static_cast<CMProfileLocation*>(malloc(locationSize));
     if (!location)
         goto fail_close;
 
--- a/gfx/thebes/gfxQtNativeRenderer.cpp
+++ b/gfx/thebes/gfxQtNativeRenderer.cpp
@@ -33,17 +33,17 @@ gfxQtNativeRenderer::Draw(gfxContext* ct
                                gfxIntSize(size.width, size.height));
 
     if (!isOpaque) {
         nsRefPtr<gfxContext> tempCtx = new gfxContext(xsurf);
         tempCtx->SetOperator(gfxContext::OPERATOR_CLEAR);
         tempCtx->Paint();
     }
 
-    nsresult rv = DrawWithXlib(xsurf.get(), nsIntPoint(0, 0), NULL, 0);
+    nsresult rv = DrawWithXlib(xsurf.get(), nsIntPoint(0, 0), nullptr, 0);
 
     if (NS_FAILED(rv))
         return rv;
 
     ctx->SetSource(xsurf);
     ctx->Paint();
 
     return rv;
--- a/gfx/thebes/gfxQtPlatform.cpp
+++ b/gfx/thebes/gfxQtPlatform.cpp
@@ -73,21 +73,21 @@ static void do_qt_pixmap_unref (void *da
     delete pmap;
 }
 
 static gfxImageFormat sOffscreenFormat = gfxASurface::ImageFormatRGB24;
 
 #ifndef MOZ_PANGO
 typedef nsDataHashtable<nsStringHashKey, nsRefPtr<FontFamily> > FontTable;
 typedef nsDataHashtable<nsCStringHashKey, nsTArray<nsRefPtr<FontEntry> > > PrefFontTable;
-static FontTable *gPlatformFonts = NULL;
-static FontTable *gPlatformFontAliases = NULL;
-static PrefFontTable *gPrefFonts = NULL;
-static gfxSparseBitSet *gCodepointsWithNoFonts = NULL;
-static FT_Library gPlatformFTLibrary = NULL;
+static FontTable *gPlatformFonts = nullptr;
+static FontTable *gPlatformFontAliases = nullptr;
+static PrefFontTable *gPrefFonts = nullptr;
+static gfxSparseBitSet *gCodepointsWithNoFonts = nullptr;
+static FT_Library gPlatformFTLibrary = nullptr;
 #endif
 
 gfxQtPlatform::gfxQtPlatform()
 {
     mPrefFonts.Init(50);
 
     if (!sFontconfigUtils)
         sFontconfigUtils = gfxFontconfigUtils::GetFontconfigUtils();
@@ -147,28 +147,28 @@ gfxQtPlatform::~gfxQtPlatform()
 {
     gfxFontconfigUtils::Shutdown();
     sFontconfigUtils = nullptr;
 
 #ifdef MOZ_PANGO
     gfxPangoFontGroup::Shutdown();
 #else
     delete gPlatformFonts;
-    gPlatformFonts = NULL;
+    gPlatformFonts = nullptr;
     delete gPlatformFontAliases;
-    gPlatformFontAliases = NULL;
+    gPlatformFontAliases = nullptr;
     delete gPrefFonts;
-    gPrefFonts = NULL;
+    gPrefFonts = nullptr;
     delete gCodepointsWithNoFonts;
-    gCodepointsWithNoFonts = NULL;
+    gCodepointsWithNoFonts = nullptr;
 
     cairo_debug_reset_static_data();
 
     FT_Done_FreeType(gPlatformFTLibrary);
-    gPlatformFTLibrary = NULL;
+    gPlatformFTLibrary = nullptr;
 #endif
 
 #if 0
     // It would be nice to do this (although it might need to be after
     // the cairo shutdown that happens in ~gfxPlatform).  It even looks
     // idempotent.  But it has fatal assertions that fire if stuff is
     // leaked, and we hit them.
     FcFini();
@@ -255,24 +255,24 @@ gfxQtPlatform::GetFontList(nsIAtom *aLan
     return sFontconfigUtils->GetFontList(aLangGroup, aGenericFamily,
                                          aListOfFonts);
 }
 
 nsresult
 gfxQtPlatform::UpdateFontList()
 {
 #ifndef MOZ_PANGO
-    FcPattern *pat = NULL;
-    FcObjectSet *os = NULL;
-    FcFontSet *fs = NULL;
+    FcPattern *pat = nullptr;
+    FcObjectSet *os = nullptr;
+    FcFontSet *fs = nullptr;
 
     pat = FcPatternCreate();
-    os = FcObjectSetBuild(FC_FAMILY, FC_FILE, FC_INDEX, FC_WEIGHT, FC_SLANT, FC_WIDTH, NULL);
+    os = FcObjectSetBuild(FC_FAMILY, FC_FILE, FC_INDEX, FC_WEIGHT, FC_SLANT, FC_WIDTH, nullptr);
 
-    fs = FcFontList(NULL, pat, os);
+    fs = FcFontList(nullptr, pat, os);
 
 
     for (int i = 0; i < fs->nfont; i++) {
         char *str;
 
         if (FcPatternGetString(fs->fonts[i], FC_FAMILY, 0, (FcChar8 **) &str) != FcResultMatch)
             continue;
 
@@ -378,18 +378,18 @@ gfxQtPlatform::ResolveFontName(const nsA
         aAborted = !(*aCallback)(ff->Name(), aClosure);
         return NS_OK;
     }
 
     nsAutoCString utf8Name = NS_ConvertUTF16toUTF8(aFontName);
 
     FcPattern *npat = FcPatternCreate();
     FcPatternAddString(npat, FC_FAMILY, (FcChar8*)utf8Name.get());
-    FcObjectSet *nos = FcObjectSetBuild(FC_FAMILY, NULL);
-    FcFontSet *nfs = FcFontList(NULL, npat, nos);
+    FcObjectSet *nos = FcObjectSetBuild(FC_FAMILY, nullptr);
+    FcFontSet *nfs = FcFontList(nullptr, npat, nos);
 
     for (int k = 0; k < nfs->nfont; k++) {
         FcChar8 *str;
         if (FcPatternGetString(nfs->fonts[k], FC_FAMILY, 0, (FcChar8 **) &str) != FcResultMatch)
             continue;
         nsAutoString altName = NS_ConvertUTF8toUTF16(nsDependentCString(reinterpret_cast<char*>(str)));
         ToLowerCase(altName);
         if (gPlatformFonts->Get(altName, &ff)) {
@@ -402,25 +402,25 @@ gfxQtPlatform::ResolveFontName(const nsA
     FcPatternDestroy(npat);
     FcObjectSetDestroy(nos);
     FcFontSetDestroy(nfs);
 
     {
     npat = FcPatternCreate();
     FcPatternAddString(npat, FC_FAMILY, (FcChar8*)utf8Name.get());
     FcPatternDel(npat, FC_LANG);
-    FcConfigSubstitute(NULL, npat, FcMatchPattern);
+    FcConfigSubstitute(nullptr, npat, FcMatchPattern);
     FcDefaultSubstitute(npat);
 
-    nos = FcObjectSetBuild(FC_FAMILY, NULL);
-    nfs = FcFontList(NULL, npat, nos);
+    nos = FcObjectSetBuild(FC_FAMILY, nullptr);
+    nfs = FcFontList(nullptr, npat, nos);
 
     FcResult fresult;
 
-    FcPattern *match = FcFontMatch(NULL, npat, &fresult);
+    FcPattern *match = FcFontMatch(nullptr, npat, &fresult);
     if (match)
         FcFontSetAdd(nfs, match);
 
     for (int k = 0; k < nfs->nfont; k++) {
         FcChar8 *str;
         if (FcPatternGetString(nfs->fonts[k], FC_FAMILY, 0, (FcChar8 **) &str) != FcResultMatch)
             continue;
         nsAutoString altName = NS_ConvertUTF8toUTF16(nsDependentCString(reinterpret_cast<char*>(str)));
--- a/gfx/thebes/gfxQuartzImageSurface.cpp
+++ b/gfx/thebes/gfxQuartzImageSurface.cpp
@@ -5,17 +5,17 @@
 
 #include "gfxQuartzImageSurface.h"
 
 #include "cairo-quartz.h"
 #include "cairo-quartz-image.h"
 
 gfxQuartzImageSurface::gfxQuartzImageSurface(gfxImageSurface *imageSurface)
 {
-    if (imageSurface->CairoSurface() == NULL)
+    if (imageSurface->CairoSurface() == nullptr)
         return;
 
     cairo_surface_t *surf = cairo_quartz_image_surface_create (imageSurface->CairoSurface());
     Init (surf);
     mSize = ComputeSize();
 }
 
 gfxQuartzImageSurface::gfxQuartzImageSurface(cairo_surface_t *csurf)
--- a/gfx/thebes/gfxQuartzSurface.cpp
+++ b/gfx/thebes/gfxQuartzSurface.cpp
@@ -11,17 +11,17 @@
 void
 gfxQuartzSurface::MakeInvalid()
 {
     mSize = gfxIntSize(-1, -1);    
 }
 
 gfxQuartzSurface::gfxQuartzSurface(const gfxSize& desiredSize, gfxImageFormat format,
                                    bool aForPrinting)
-    : mCGContext(NULL), mSize(desiredSize), mForPrinting(aForPrinting)
+    : mCGContext(nullptr), mSize(desiredSize), mForPrinting(aForPrinting)
 {
     gfxIntSize size((unsigned int) floor(desiredSize.width),
                     (unsigned int) floor(desiredSize.height));
     if (!CheckSurfaceSize(size))
         MakeInvalid();
 
     unsigned int width = static_cast<unsigned int>(mSize.width);
     unsigned int height = static_cast<unsigned int>(mSize.height);
--- a/gfx/thebes/gfxUniscribeShaper.cpp
+++ b/gfx/thebes/gfxUniscribeShaper.cpp
@@ -179,17 +179,17 @@ public:
         }
 
         SCRIPT_ANALYSIS sa = mScriptItem->a;
 
         while (true) {
             rv = ScriptPlace(placeDC, mShaper->ScriptCache(),
                              mGlyphs.Elements(), mNumGlyphs,
                              mAttr.Elements(), &sa,
-                             mAdvances.Elements(), mOffsets.Elements(), NULL);
+                             mAdvances.Elements(), mOffsets.Elements(), nullptr);
 
             if (rv == E_PENDING) {
                 SelectFont();
                 placeDC = mDC;
                 continue;
             }
 
             if (rv == USP_E_SCRIPT_NOT_IN_FONT) {
@@ -203,17 +203,17 @@ public:
         return rv;
     }
 
     void ScriptFontProperties(SCRIPT_FONTPROPERTIES *sfp) {
         HRESULT rv;
 
         memset(sfp, 0, sizeof(SCRIPT_FONTPROPERTIES));
         sfp->cBytes = sizeof(SCRIPT_FONTPROPERTIES);
-        rv = ScriptGetFontProperties(NULL, mShaper->ScriptCache(),
+        rv = ScriptGetFontProperties(nullptr, mShaper->ScriptCache(),
                                      sfp);
         if (rv == E_PENDING) {
             SelectFont();
             rv = ScriptGetFontProperties(mDC, mShaper->ScriptCache(),
                                          sfp);
         }
     }
 
--- a/gfx/thebes/gfxUniscribeShaper.h
+++ b/gfx/thebes/gfxUniscribeShaper.h
@@ -14,17 +14,17 @@
 #include <cairo-win32.h>
 
 
 class gfxUniscribeShaper : public gfxFontShaper
 {
 public:
     gfxUniscribeShaper(gfxGDIFont *aFont)
         : gfxFontShaper(aFont)
-        , mScriptCache(NULL)
+        , mScriptCache(nullptr)
     {
         MOZ_COUNT_CTOR(gfxUniscribeShaper);
     }
 
     virtual ~gfxUniscribeShaper()
     {
         MOZ_COUNT_DTOR(gfxUniscribeShaper);
     }
--- a/gfx/thebes/gfxUserFontSet.cpp
+++ b/gfx/thebes/gfxUserFontSet.cpp
@@ -292,17 +292,17 @@ gfxUserFontSet::OTSMessage(void *aUserDa
     OTSCallbackUserData *d = static_cast<OTSCallbackUserData*>(aUserData);
     d->mFontSet->LogMessage(d->mFamily, d->mProxy, buf);
 
     return false;
 }
 #endif
 
 // Call the OTS library to sanitize an sfnt before attempting to use it.
-// Returns a newly-allocated block, or NULL in case of fatal errors.
+// Returns a newly-allocated block, or nullptr in case of fatal errors.
 const uint8_t*
 gfxUserFontSet::SanitizeOpenTypeData(gfxMixedFontFamily *aFamily,
                                      gfxProxyFontEntry *aProxy,
                                      const uint8_t* aData, uint32_t aLength,
                                      uint32_t& aSaneLength, bool aIsCompressed)
 {
     // limit output/expansion to 256MB
     ExpandingMemoryStream output(aIsCompressed ? aLength * 2 : aLength,
--- a/gfx/thebes/gfxUtils.cpp
+++ b/gfx/thebes/gfxUtils.cpp
@@ -857,10 +857,10 @@ gfxUtils::CopyAsDataURL(DrawTarget* aDT)
   } else {
     NS_WARNING("Failed to get Thebes surface!");
   }
 }
 
 bool gfxUtils::sDumpPaintList = getenv("MOZ_DUMP_PAINT_LIST") != 0;
 bool gfxUtils::sDumpPainting = getenv("MOZ_DUMP_PAINT") != 0;
 bool gfxUtils::sDumpPaintingToFile = getenv("MOZ_DUMP_PAINT_TO_FILE") != 0;
-FILE *gfxUtils::sDumpPaintFile = NULL;
+FILE *gfxUtils::sDumpPaintFile = nullptr;
 #endif
--- a/gfx/thebes/gfxWindowsNativeDrawing.cpp
+++ b/gfx/thebes/gfxWindowsNativeDrawing.cpp
@@ -141,17 +141,17 @@ gfxWindowsNativeDrawing::BeginNativeDraw
             SetGraphicsMode(mDC, GM_ADVANCED);
             GetWorldTransform(mDC, &mOldWorldTransform);
             SetWorldTransform(mDC, &mWorldTransform);
         }
         GetViewportOrgEx(mDC, &mOrigViewportOrigin);
         SetViewportOrgEx(mDC,
                          mOrigViewportOrigin.x + (int)mDeviceOffset.x,
                          mOrigViewportOrigin.y + (int)mDeviceOffset.y,
-                         NULL);
+                         nullptr);
 
         return mDC;
     } else if (mRenderState == RENDER_STATE_ALPHA_RECOVERY_BLACK ||
                mRenderState == RENDER_STATE_ALPHA_RECOVERY_WHITE)
     {
         // we're going to use mWinSurface to create our temporary surface here
 
         // get us a RGB24 DIB; DIB is important, because
@@ -222,17 +222,17 @@ gfxWindowsNativeDrawing::ShouldRenderAga
     return false;
 }
 
 void
 gfxWindowsNativeDrawing::EndNativeDrawing()
 {
     if (mRenderState == RENDER_STATE_NATIVE_DRAWING) {
         // we drew directly to the HDC in the context; undo our changes
-        SetViewportOrgEx(mDC, mOrigViewportOrigin.x, mOrigViewportOrigin.y, NULL);
+        SetViewportOrgEx(mDC, mOrigViewportOrigin.x, mOrigViewportOrigin.y, nullptr);
 
         if (mTransformType != TRANSLATION_ONLY)
             SetWorldTransform(mDC, &mOldWorldTransform);
 
         mWinSurface->MarkDirty();
 
         mRenderState = RENDER_STATE_NATIVE_DRAWING_DONE;
     } else if (mRenderState == RENDER_STATE_ALPHA_RECOVERY_BLACK) {
--- a/gfx/thebes/gfxWindowsPlatform.cpp
+++ b/gfx/thebes/gfxWindowsPlatform.cpp
@@ -357,19 +357,19 @@ gfxWindowsPlatform::gfxWindowsPlatform()
     mUseClearTypeForDownloadableFonts = UNINITIALIZED_VALUE;
     mUseClearTypeAlways = UNINITIALIZED_VALUE;
 
     mUsingGDIFonts = false;
 
     /* 
      * Initialize COM 
      */ 
-    CoInitialize(NULL); 
+    CoInitialize(nullptr); 
 
-    mScreenDC = GetDC(NULL);
+    mScreenDC = GetDC(nullptr);
 
 #ifdef CAIRO_HAS_D2D_SURFACE
     NS_RegisterMemoryReporter(new NS_MEMORY_REPORTER_NAME(D2DCache));
     NS_RegisterMemoryReporter(new NS_MEMORY_REPORTER_NAME(D2DVram));
     mD2DDevice = nullptr;
 #endif
     NS_RegisterMemoryReporter(new NS_MEMORY_REPORTER_NAME(D2DVRAMDT));
     NS_RegisterMemoryReporter(new NS_MEMORY_REPORTER_NAME(D2DVRAMSS));
@@ -379,17 +379,17 @@ gfxWindowsPlatform::gfxWindowsPlatform()
     mGPUAdapterMultiReporter = new GPUAdapterMultiReporter();
     NS_RegisterMemoryMultiReporter(mGPUAdapterMultiReporter);
 }
 
 gfxWindowsPlatform::~gfxWindowsPlatform()
 {
     NS_UnregisterMemoryMultiReporter(mGPUAdapterMultiReporter);
     
-    ::ReleaseDC(NULL, mScreenDC);
+    ::ReleaseDC(nullptr, mScreenDC);
     // not calling FT_Done_FreeType because cairo may still hold references to
     // these FT_Faces.  See bug 458169.
 #ifdef CAIRO_HAS_D2D_SURFACE
     if (mD2DDevice) {
         cairo_release_device(mD2DDevice);
     }
 #endif
 
@@ -516,17 +516,17 @@ gfxWindowsPlatform::CreateDevice(nsRefPt
     return E_FAIL;
   D3D10CreateDevice1Func createD3DDevice =
     (D3D10CreateDevice1Func)GetProcAddress(d3d10module, "D3D10CreateDevice1");
   if (!createD3DDevice)
     return E_FAIL;
 
   nsRefPtr<ID3D10Device1> device;
   HRESULT hr =
-    createD3DDevice(adapter1, D3D10_DRIVER_TYPE_HARDWARE, NULL,
+    createD3DDevice(adapter1, D3D10_DRIVER_TYPE_HARDWARE, nullptr,
                     D3D10_CREATE_DEVICE_BGRA_SUPPORT |
                     D3D10_CREATE_DEVICE_PREVENT_INTERNAL_THREADING_OPTIMIZATIONS,
                     static_cast<D3D10_FEATURE_LEVEL1>(kSupportedFeatureLevels[featureLevelIndex]),
                     D3D10_1_SDK_VERSION, getter_AddRefs(device));
 
   // If we fail here, the DirectX version or video card probably
   // changed.  We previously could use 10.1 but now we can't
   // anymore.  Revert back to doing a 10.0 check first before
@@ -747,33 +747,33 @@ gfxWindowsPlatform::GetScaledFontForFont
 
 already_AddRefed<gfxASurface>
 gfxWindowsPlatform::GetThebesSurfaceForDrawTarget(DrawTarget *aTarget)
 {
 #ifdef XP_WIN
   if (aTarget->GetType() == BACKEND_DIRECT2D) {
     if (!GetD2DDevice()) {
       // We no longer have a D2D device, can't do this.
-      return NULL;
+      return nullptr;
     }
 
     RefPtr<ID3D10Texture2D> texture =
       static_cast<ID3D10Texture2D*>(aTarget->GetNativeSurface(NATIVE_SURFACE_D3D10_TEXTURE));
 
     if (!texture) {
       return gfxPlatform::GetThebesSurfaceForDrawTarget(aTarget);
     }
 
     aTarget->Flush();
 
     nsRefPtr<gfxASurface> surf =
       new gfxD2DSurface(texture, ContentForFormat(aTarget->GetFormat()));
 
     // shouldn't this hold a reference?
-    surf->SetData(&kDrawTarget, aTarget, NULL);
+    surf->SetData(&kDrawTarget, aTarget, nullptr);
     return surf.forget();
   }
 #endif
 
   return gfxPlatform::GetThebesSurfaceForDrawTarget(aTarget);
 }
 
 nsresult
@@ -1167,17 +1167,17 @@ gfxWindowsPlatform::WindowsOSVersion(int
 }
 
 void 
 gfxWindowsPlatform::GetDLLVersion(const PRUnichar *aDLLPath, nsAString& aVersion)
 {
     DWORD versInfoSize, vers[4] = {0};
     // version info not available case
     aVersion.Assign(NS_LITERAL_STRING("0.0.0.0"));
-    versInfoSize = GetFileVersionInfoSizeW(aDLLPath, NULL);
+    versInfoSize = GetFileVersionInfoSizeW(aDLLPath, nullptr);
     nsAutoTArray<BYTE,512> versionInfo;
     
     if (versInfoSize == 0 ||
         !versionInfo.AppendElements(uint32_t(versInfoSize)))
     {
         return;
     }
 
@@ -1226,17 +1226,18 @@ gfxWindowsPlatform::GetCleartypeParams(n
 
     if (rv != ERROR_SUCCESS) {
         return;
     }
 
     // enumerate over subkeys
     for (i = 0, rv = ERROR_SUCCESS; rv != ERROR_NO_MORE_ITEMS; i++) {
         size = ArrayLength(displayName);
-        rv = RegEnumKeyExW(hKey, i, displayName, &size, NULL, NULL, NULL, NULL);
+        rv = RegEnumKeyExW(hKey, i, displayName, &size,
+                           nullptr, nullptr, nullptr, nullptr);
         if (rv != ERROR_SUCCESS) {
             continue;
         }
 
         ClearTypeParameterInfo ctinfo;
         ctinfo.displayName.Assign(displayName);
 
         DWORD subrv, value;
@@ -1246,50 +1247,50 @@ gfxWindowsPlatform::GetCleartypeParams(n
                    L"Software\\Microsoft\\Avalon.Graphics\\%s", displayName);
 
         // subkey for gamma, pixel structure
         subrv = RegOpenKeyExW(HKEY_LOCAL_MACHINE,
                               subkeyName, 0, KEY_QUERY_VALUE, &subKey);
 
         if (subrv == ERROR_SUCCESS) {
             size = sizeof(value);
-            subrv = RegQueryValueExW(subKey, L"GammaLevel", NULL, &type,
+            subrv = RegQueryValueExW(subKey, L"GammaLevel", nullptr, &type,
                                      (LPBYTE)&value, &size);
             if (subrv == ERROR_SUCCESS && type == REG_DWORD) {
                 foundData = true;
                 ctinfo.gamma = value;
             }
 
             size = sizeof(value);
-            subrv = RegQueryValueExW(subKey, L"PixelStructure", NULL, &type,
+            subrv = RegQueryValueExW(subKey, L"PixelStructure", nullptr, &type,
                                      (LPBYTE)&value, &size);
             if (subrv == ERROR_SUCCESS && type == REG_DWORD) {
                 foundData = true;
                 ctinfo.pixelStructure = value;
             }
 
             RegCloseKey(subKey);
         }
 
         // subkey for cleartype level, enhanced contrast
         subrv = RegOpenKeyExW(HKEY_CURRENT_USER,
                               subkeyName, 0, KEY_QUERY_VALUE, &subKey);
 
         if (subrv == ERROR_SUCCESS) {
             size = sizeof(value);
-            subrv = RegQueryValueExW(subKey, L"ClearTypeLevel", NULL, &type,
+            subrv = RegQueryValueExW(subKey, L"ClearTypeLevel", nullptr, &type,
                                      (LPBYTE)&value, &size);
             if (subrv == ERROR_SUCCESS && type == REG_DWORD) {
                 foundData = true;
                 ctinfo.clearTypeLevel = value;
             }
       
             size = sizeof(value);
             subrv = RegQueryValueExW(subKey, L"EnhancedContrastLevel",
-                                     NULL, &type, (LPBYTE)&value, &size);
+                                     nullptr, &type, (LPBYTE)&value, &size);
             if (subrv == ERROR_SUCCESS && type == REG_DWORD) {
                 foundData = true;
                 ctinfo.enhancedContrast = value;
             }
 
             RegCloseKey(subKey);
         }
 
@@ -1473,17 +1474,17 @@ gfxWindowsPlatform::GetD3D11Device()
   featureLevels.AppendElement(D3D_FEATURE_LEVEL_9_3);
 
   RefPtr<IDXGIAdapter1> adapter = GetDXGIAdapter();
 
   if (!adapter) {
     return nullptr;
   }
 
-  HRESULT hr = d3d11CreateDevice(adapter, D3D_DRIVER_TYPE_UNKNOWN, NULL,
+  HRESULT hr = d3d11CreateDevice(adapter, D3D_DRIVER_TYPE_UNKNOWN, nullptr,
                                  D3D11_CREATE_DEVICE_BGRA_SUPPORT,
                                  featureLevels.Elements(), featureLevels.Length(),
                                  D3D11_SDK_VERSION, byRef(mD3D11Device), nullptr, nullptr);
 
   // We leak these everywhere and we need them our entire runtime anyway, let's
   // leak it here as well.
   d3d11Module.disown();
 
--- a/gfx/thebes/gfxWindowsPlatform.h
+++ b/gfx/thebes/gfxWindowsPlatform.h
@@ -47,40 +47,40 @@ class ID3D11Device;
 class IDXGIAdapter1;
 
 class nsIMemoryMultiReporter;
 
 // Utility to get a Windows HDC from a thebes context,
 // used by both GDI and Uniscribe font shapers
 struct DCFromContext {
     DCFromContext(gfxContext *aContext) {
-        dc = NULL;
+        dc = nullptr;
         nsRefPtr<gfxASurface> aSurface = aContext->CurrentSurface();
         NS_ASSERTION(aSurface, "DCFromContext: null surface");
         if (aSurface &&
             (aSurface->GetType() == gfxASurface::SurfaceTypeWin32 ||
              aSurface->GetType() == gfxASurface::SurfaceTypeWin32Printing))
         {
             dc = static_cast<gfxWindowsSurface*>(aSurface.get())->GetDC();
             needsRelease = false;
             SaveDC(dc);
             cairo_scaled_font_t* scaled =
                 cairo_get_scaled_font(aContext->GetCairo());
             cairo_win32_scaled_font_select_font(scaled, dc);
         }
         if (!dc) {
-            dc = GetDC(NULL);
+            dc = GetDC(nullptr);
             SetGraphicsMode(dc, GM_ADVANCED);
             needsRelease = true;
         }
     }
 
     ~DCFromContext() {
         if (needsRelease) {
-            ReleaseDC(NULL, dc);
+            ReleaseDC(nullptr, dc);
         } else {
             RestoreDC(dc, -1);
         }
     }
 
     operator HDC () {
         return dc;
     }
--- a/gfx/thebes/gfxWindowsSurface.cpp
+++ b/gfx/thebes/gfxWindowsSurface.cpp
@@ -219,17 +219,17 @@ gfxWindowsSurface::BeginPrinting(const n
         titleStr.SetLength(DOC_TITLE_LENGTH-3);
         titleStr.AppendLiteral("...");
     }
 
     nsString docName(aPrintToFileName);
     docinfo.cbSize = sizeof(docinfo);
     docinfo.lpszDocName = titleStr.Length() > 0 ? titleStr.get() : L"Mozilla Document";
     docinfo.lpszOutput = docName.Length() > 0 ? docName.get() : nullptr;
-    docinfo.lpszDatatype = NULL;
+    docinfo.lpszDatatype = nullptr;
     docinfo.fwType = 0;
 
     ::StartDocW(mDC, &docinfo);
 
     return NS_OK;
 #else
     return NS_ERROR_FAILURE;
 #endif
--- a/gfx/thebes/gfxWindowsSurface.h
+++ b/gfx/thebes/gfxWindowsSurface.h
@@ -26,17 +26,17 @@ public:
 
     gfxWindowsSurface(HWND wnd, uint32_t flags = 0);
     gfxWindowsSurface(HDC dc, uint32_t flags = 0);
 
     // Create a DIB surface
     gfxWindowsSurface(const gfxIntSize& size,
                       gfxImageFormat imageFormat = ImageFormatRGB24);
 
-    // Create a DDB surface; dc may be NULL to use the screen DC
+    // Create a DDB surface; dc may be nullptr to use the screen DC
     gfxWindowsSurface(HDC dc,
                       const gfxIntSize& size,
                       gfxImageFormat imageFormat = ImageFormatRGB24);
 
     gfxWindowsSurface(cairo_surface_t *csurf);
 
     virtual already_AddRefed<gfxASurface> CreateSimilarSurface(gfxContentType aType,
                                                                const gfxIntSize& aSize);
--- a/gfx/thebes/gfxXlibNativeRenderer.cpp
+++ b/gfx/thebes/gfxXlibNativeRenderer.cpp
@@ -315,18 +315,18 @@ CreateTempXlibSurface (gfxASurface *dest
         // (If !drawIsOpaque, we'll need doCopyBackground or an alpha channel.)
         visual = DefaultVisualOfScreen(target_screen);
         screen = target_screen;
 
     } else if (doCopyBackground || (supportsAlternateVisual && drawIsOpaque)) {
         // Analyse the pixel formats either to check whether we can
         // doCopyBackground or to see if we can find a better visual for
         // opaque drawing.
-        Visual *target_visual = NULL;
-        XRenderPictFormat *target_format = NULL;
+        Visual *target_visual = nullptr;
+        XRenderPictFormat *target_format = nullptr;
         switch (target_type) {
         case CAIRO_SURFACE_TYPE_XLIB:
             target_visual = cairo_xlib_surface_get_visual (target);
             target_format = cairo_xlib_surface_get_xrender_format (target);
             break;
         case CAIRO_SURFACE_TYPE_IMAGE: {
             gfxASurface::gfxImageFormat imageFormat =
                 static_cast<gfxImageSurface*>(destination)->Format();
@@ -414,17 +414,17 @@ CreateTempXlibSurface (gfxASurface *dest
 
 bool
 gfxXlibNativeRenderer::DrawOntoTempSurface(gfxXlibSurface *tempXlibSurface,
                                            nsIntPoint offset)
 {
     tempXlibSurface->Flush();
     /* no clipping is needed because the callback can't draw outside the native
        surface anyway */
-    nsresult rv = DrawWithXlib(tempXlibSurface, offset, NULL, 0);
+    nsresult rv = DrawWithXlib(tempXlibSurface, offset, nullptr, 0);
     tempXlibSurface->MarkDirty();
     return NS_SUCCEEDED(rv);
 }
 
 static already_AddRefed<gfxImageSurface>
 CopyXlibSurfaceToImage(gfxXlibSurface *tempXlibSurface,
                        gfxASurface::gfxImageFormat format)
 {
@@ -440,17 +440,17 @@ CopyXlibSurfaceToImage(gfxXlibSurface *t
 }
 
 void
 gfxXlibNativeRenderer::Draw(gfxContext* ctx, nsIntSize size,
                             uint32_t flags, Screen *screen, Visual *visual,
                             DrawOutput* result)
 {
     if (result) {
-        result->mSurface = NULL;
+        result->mSurface = nullptr;
         result->mUniformAlpha = false;
         result->mUniformColor = false;
     }
 
     bool drawIsOpaque = (flags & DRAW_IS_OPAQUE) != 0;
     gfxMatrix matrix = ctx->CurrentMatrix();
 
     // We can only draw direct or onto a copied background if pixels align and
@@ -515,17 +515,17 @@ gfxXlibNativeRenderer::Draw(gfxContext* 
                               canDrawOverBackground, flags, screen, visual,
                               &method);
     if (!tempXlibSurface)
         return;
   
     if (drawingRect.Size() != size || method == eCopyBackground) {
         // Only drawing a portion, or copying background,
         // so won't return a result.
-        result = NULL;
+        result = nullptr;
     }
 
     nsRefPtr<gfxContext> tmpCtx;
     if (!drawIsOpaque) {
         tmpCtx = new gfxContext(tempXlibSurface);
         if (method == eCopyBackground) {
             tmpCtx->SetOperator(gfxContext::OPERATOR_SOURCE);
             tmpCtx->SetSource(target, -(offset + matrix.GetTranslation()));
--- a/gfx/thebes/gfxXlibSurface.cpp
+++ b/gfx/thebes/gfxXlibSurface.cpp
@@ -453,17 +453,17 @@ gfxXlibSurface::FindVisual(Screen *scree
             depth = 16;
             red_mask = 0xf800;
             green_mask = 0x7e0;
             blue_mask = 0x1f;
             break;
         case ImageFormatA8:
         case ImageFormatA1:
         default:
-            return NULL;
+            return nullptr;
     }
 
     for (int d = 0; d < screen->ndepths; d++) {
         const Depth& d_info = screen->depths[d];
         if (d_info.depth != depth)
             continue;
 
         for (int v = 0; v < d_info.nvisuals; v++) {
@@ -472,17 +472,17 @@ gfxXlibSurface::FindVisual(Screen *scree
             if (visual->c_class == TrueColor &&
                 visual->red_mask == red_mask &&
                 visual->green_mask == green_mask &&
                 visual->blue_mask == blue_mask)
                 return visual;
         }
     }
 
-    return NULL;
+    return nullptr;
 }
 
 /* static */
 XRenderPictFormat*
 gfxXlibSurface::FindRenderFormat(Display *dpy, gfxImageFormat format)
 {
     switch (format) {
         case ImageFormatARGB32:
@@ -490,28 +490,28 @@ gfxXlibSurface::FindRenderFormat(Display
         case ImageFormatRGB24:
             return XRenderFindStandardFormat (dpy, PictStandardRGB24);
         case ImageFormatRGB16_565: {
             // PictStandardRGB16_565 is not standard Xrender format
             // we should try to find related visual
             // and find xrender format by visual
             Visual *visual = FindVisual(DefaultScreenOfDisplay(dpy), format);
             if (!visual)
-                return NULL;
+                return nullptr;
             return XRenderFindVisualFormat(dpy, visual);
         }
         case ImageFormatA8:
             return XRenderFindStandardFormat (dpy, PictStandardA8);
         case ImageFormatA1:
             return XRenderFindStandardFormat (dpy, PictStandardA1);
         default:
             break;
     }
 
-    return (XRenderPictFormat*)NULL;
+    return nullptr;
 }
 
 Screen*
 gfxXlibSurface::XScreen()
 {
     return cairo_xlib_surface_get_screen(CairoSurface());
 }
 
--- a/gfx/thebes/nsSurfaceTexture.cpp
+++ b/gfx/thebes/nsSurfaceTexture.cpp
@@ -47,21 +47,21 @@ public:
 
     mInitialized = true;
     return true;
   }
 
   jobject CreateSurfaceTexture(GLuint aTexture)
   {
     if (!EnsureInitialized())
-      return NULL;
+      return nullptr;
 
     JNIEnv* env = GetJNIForThread();
     if (!env)
-      return NULL;
+      return nullptr;
 
     AutoLocalJNIFrame jniFrame(env);
 
     return env->NewGlobalRef(env->NewObject(jSurfaceTextureClass, jSurfaceTexture_Ctor, (int) aTexture));
   }
 
   void ReleaseSurfaceTexture(jobject aSurfaceTexture)
   {
@@ -88,17 +88,17 @@ public:
     if (!env)
       return false;
 
     AutoLocalJNIFrame jniFrame(env);
 
     jfloatArray jarray = env->NewFloatArray(16);
     env->CallVoidMethod(aSurfaceTexture, jSurfaceTexture_getTransformMatrix, jarray);
 
-    jfloat* array = env->GetFloatArrayElements(jarray, NULL);
+    jfloat* array = env->GetFloatArrayElements(jarray, nullptr);
 
     aMatrix._11 = array[0];
     aMatrix._12 = array[1];
     aMatrix._13 = array[2];
     aMatrix._14 = array[3];
 
     aMatrix._21 = array[4];
     aMatrix._22 = array[5];
@@ -131,36 +131,36 @@ private:
 } sJNIFunctions;
 
 nsSurfaceTexture*
 nsSurfaceTexture::Create(GLuint aTexture)
 {
   // Right now we only support creating this on the main thread because
   // of the JNIEnv assumptions in JNIHelper and elsewhere
   if (!NS_IsMainThread())
-    return NULL;
+    return nullptr;
 
   nsSurfaceTexture* st = new nsSurfaceTexture();
   if (!st->Init(aTexture)) {
     LOG("Failed to initialize nsSurfaceTexture");
     delete st;
-    st = NULL;
+    st = nullptr;
   }
 
   return st;
 }
 
 nsSurfaceTexture*
 nsSurfaceTexture::Find(int id)
 {
   std::map<int, nsSurfaceTexture*>::iterator it;
 
   it = sInstances.find(id);
   if (it == sInstances.end())
-    return NULL;
+    return nullptr;
 
   return it->second;
 }
 
 bool
 nsSurfaceTexture::Check()
 {
   return sJNIFunctions.EnsureInitialized();
@@ -184,40 +184,40 @@ nsSurfaceTexture::Init(GLuint aTexture)
 
   mID = ++sNextID;
   sInstances.insert(std::pair<int, nsSurfaceTexture*>(mID, this));
 
   return true;
 }
 
 nsSurfaceTexture::nsSurfaceTexture()
-  : mSurfaceTexture(NULL), mNativeWindow(NULL)
+  : mSurfaceTexture(nullptr), mNativeWindow(nullptr)
 {
 }
 
 nsSurfaceTexture::~nsSurfaceTexture()
 {
   sInstances.erase(mID);
 
-  mFrameAvailableCallback = NULL;
+  mFrameAvailableCallback = nullptr;
 
   if (mNativeWindow) {
     AndroidBridge::Bridge()->ReleaseNativeWindowForSurfaceTexture(mSurfaceTexture);
-    mNativeWindow = NULL;
+    mNativeWindow = nullptr;
   }
 
   JNIEnv* env = GetJNIForThread();
   if (!env)
     return;
 
   if (mSurfaceTexture && env) {
     AndroidBridge::Bridge()->UnregisterSurfaceTextureFrameListener(mSurfaceTexture);
 
     env->DeleteGlobalRef(mSurfaceTexture);
-    mSurfaceTexture = NULL;
+    mSurfaceTexture = nullptr;
   }
 }
 
 void*
 nsSurfaceTexture::GetNativeWindow()
 {
   return mNativeWindow;
 }
--- a/js/jsd/jsd_val.cpp
+++ b/js/jsd/jsd_val.cpp
@@ -576,17 +576,17 @@ jsd_GetValuePrototype(JSDContext* jsdc, 
     {
         JS::RootedObject obj(cx);
         JS::RootedObject proto(cx);
         JS_ASSERT(!jsdval->proto);
         SET_BIT_FLAG(jsdval->flags, GOT_PROTO);
         if(JSVAL_IS_PRIMITIVE(jsdval->val))
             return NULL;
         obj = JSVAL_TO_OBJECT(jsdval->val);
-        if(!JS_GetPrototype(cx, obj, proto.address()))
+        if(!JS_GetPrototype(cx, obj, &proto))
             return NULL;
         if(!proto)
             return NULL;
         jsdval->proto = jsd_NewValue(jsdc, OBJECT_TO_JSVAL(proto));
     }
     if(jsdval->proto)
         jsdval->proto->nref++;
     return jsdval->proto;
@@ -627,17 +627,17 @@ jsd_GetValueConstructor(JSDContext* jsdc
         JS::RootedObject obj(cx);
         JS::RootedObject proto(cx);
         JS::RootedObject ctor(cx);
         JS_ASSERT(!jsdval->ctor);
         SET_BIT_FLAG(jsdval->flags, GOT_CTOR);
         if(JSVAL_IS_PRIMITIVE(jsdval->val))
             return NULL;
         obj = JSVAL_TO_OBJECT(jsdval->val);
-        if(!JS_GetPrototype(cx, obj, proto.address()))
+        if(!JS_GetPrototype(cx, obj, &proto))
             return NULL;
         if(!proto)
             return NULL;
         {
             JSAutoCompartment ac(cx, obj);
             ctor = JS_GetConstructor(cx, proto);
         }
         if(!ctor)
--- a/js/src/builtin/BinaryData.cpp
+++ b/js/src/builtin/BinaryData.cpp
@@ -471,18 +471,18 @@ SetupAndGetPrototypeObjectForComplexType
                                complexTypePrototypeObj,
                                cx->names().classPrototype,
                                &complexTypePrototypePrototypeVal))
         return NULL;
 
     RootedObject prototypeObj(cx,
         NewObjectWithGivenProto(cx, &JSObject::class_, NULL, global));
 
-    if (!JS_SetPrototype(cx, prototypeObj,
-                         complexTypePrototypePrototypeVal.toObjectOrNull()))
+    RootedObject proto(cx, complexTypePrototypePrototypeVal.toObjectOrNull());
+    if (!JS_SetPrototype(cx, prototypeObj, proto))
         return NULL;
 
     return prototypeObj;
 }
 
 Class ArrayType::class_ = {
     "ArrayType",
     JSCLASS_HAS_RESERVED_SLOTS(TYPE_RESERVED_SLOTS) |
--- a/js/src/builtin/MapObject.cpp
+++ b/js/src/builtin/MapObject.cpp
@@ -783,17 +783,17 @@ class OrderedHashSet
 };
 
 }  // namespace js
 
 
 /*** HashableValue *******************************************************************************/
 
 bool
-HashableValue::setValue(JSContext *cx, const Value &v)
+HashableValue::setValue(JSContext *cx, HandleValue v)
 {
     if (v.isString()) {
         // Atomize so that hash() and operator==() are fast and infallible.
         JSString *str = AtomizeString<CanGC>(cx, v.toString(), DoNotInternAtom);
         if (!str)
             return false;
         value = StringValue(str);
     } else if (v.isDouble()) {
--- a/js/src/builtin/MapObject.h
+++ b/js/src/builtin/MapObject.h
@@ -31,34 +31,34 @@ class HashableValue {
         static HashNumber hash(const Lookup &v) { return v.hash(); }
         static bool match(const HashableValue &k, const Lookup &l) { return k == l; }
         static bool isEmpty(const HashableValue &v) { return v.value.isMagic(JS_HASH_KEY_EMPTY); }
         static void makeEmpty(HashableValue *vp) { vp->value = MagicValue(JS_HASH_KEY_EMPTY); }
     };
 
     HashableValue() : value(UndefinedValue()) {}
 
-    bool setValue(JSContext *cx, const Value &v);
+    bool setValue(JSContext *cx, HandleValue v);
     HashNumber hash() const;
     bool operator==(const HashableValue &other) const;
     HashableValue mark(JSTracer *trc) const;
     Value get() const { return value.get(); }
 };
 
 class AutoHashableValueRooter : private AutoGCRooter
 {
   public:
     explicit AutoHashableValueRooter(JSContext *cx
                                      MOZ_GUARD_OBJECT_NOTIFIER_PARAM)
         : AutoGCRooter(cx, HASHABLEVALUE)
         {
             MOZ_GUARD_OBJECT_NOTIFIER_INIT;
         }
 
-    bool setValue(JSContext *cx, const Value &v) {
+    bool setValue(JSContext *cx, HandleValue v) {
         return value.setValue(cx, v);
     }
 
     operator const HashableValue & () {
         return value;
     }
 
     friend void AutoGCRooter::trace(JSTracer *trc);
--- a/js/src/ctypes/CTypes.cpp
+++ b/js/src/ctypes/CTypes.cpp
@@ -827,17 +827,17 @@ InitCTypeClass(JSContext* cx, HandleObje
 {
   JSFunction *fun = JS_DefineFunction(cx, parent, "CType", ConstructAbstract, 0,
                                       CTYPESCTOR_FLAGS);
   if (!fun)
     return NULL;
 
   RootedObject ctor(cx, JS_GetFunctionObject(fun));
   RootedObject fnproto(cx);
-  if (!JS_GetPrototype(cx, ctor, fnproto.address()))
+  if (!JS_GetPrototype(cx, ctor, &fnproto))
     return NULL;
   JS_ASSERT(ctor);
   JS_ASSERT(fnproto);
 
   // Set up ctypes.CType.prototype.
   RootedObject prototype(cx, JS_NewObject(cx, &sCTypeProtoClass, fnproto, parent));
   if (!prototype)
     return NULL;
@@ -3568,23 +3568,24 @@ CType::GetProtoFromCtor(JSObject* obj, C
   JS_ASSERT(CType::IsCTypeProto(proto));
 
   // Get the desired prototype.
   jsval result = JS_GetReservedSlot(proto, slot);
   return &result.toObject();
 }
 
 JSObject*
-CType::GetProtoFromType(JSContext* cx, JSObject* obj, CTypeProtoSlot slot)
-{
-  JS_ASSERT(IsCType(obj));
+CType::GetProtoFromType(JSContext* cx, JSObject* objArg, CTypeProtoSlot slot)
+{
+  JS_ASSERT(IsCType(objArg));
+  RootedObject obj(cx, objArg);
 
   // Get the prototype of the type object.
   RootedObject proto(cx);
-  if (!JS_GetPrototype(cx, obj, proto.address()))
+  if (!JS_GetPrototype(cx, obj, &proto))
     return NULL;
   JS_ASSERT(proto);
   JS_ASSERT(CType::IsCTypeProto(proto));
 
   // Get the requested ctypes.{Pointer,Array,Struct,Function}Type.prototype.
   jsval result = JS_GetReservedSlot(proto, slot);
   JS_ASSERT(!JSVAL_IS_PRIMITIVE(result));
   return JSVAL_TO_OBJECT(result);
@@ -3755,35 +3756,36 @@ CType::HasInstance(JSContext* cx, Handle
   JS_ASSERT(CData::IsCDataProto(prototype));
 
   *bp = JS_FALSE;
   if (JSVAL_IS_PRIMITIVE(v))
     return JS_TRUE;
 
   RootedObject proto(cx, &v.toObject());
   for (;;) {
-    if (!JS_GetPrototype(cx, proto, proto.address()))
+    if (!JS_GetPrototype(cx, proto, &proto))
       return JS_FALSE;
     if (!proto)
       break;
     if (proto == prototype) {
       *bp = JS_TRUE;
       break;
     }
   }
   return JS_TRUE;
 }
 
 static JSObject*
-CType::GetGlobalCTypes(JSContext* cx, JSObject* obj)
-{
-  JS_ASSERT(CType::IsCType(obj));
-
+CType::GetGlobalCTypes(JSContext* cx, JSObject* objArg)
+{
+  JS_ASSERT(CType::IsCType(objArg));
+
+  RootedObject obj(cx, objArg);
   RootedObject objTypeProto(cx);
-  if (!JS_GetPrototype(cx, obj, objTypeProto.address()))
+  if (!JS_GetPrototype(cx, obj, &objTypeProto))
     return NULL;
   JS_ASSERT(objTypeProto);
   JS_ASSERT(CType::IsCTypeProto(objTypeProto));
 
   jsval valCTypes = JS_GetReservedSlot(objTypeProto, SLOT_CTYPES);
   JS_ASSERT(!JSVAL_IS_PRIMITIVE(valCTypes));
 
   JS_ASSERT(!JSVAL_IS_PRIMITIVE(valCTypes));
@@ -5992,17 +5994,17 @@ CClosure::Create(JSContext* cx,
   if (!cinfo) {
     JS_ReportOutOfMemory(cx);
     return NULL;
   }
 
   // Get the prototype of the FunctionType object, of class CTypeProto,
   // which stores our JSContext for use with the closure.
   RootedObject proto(cx);
-  if (!JS_GetPrototype(cx, typeObj, proto.address()))
+  if (!JS_GetPrototype(cx, typeObj, &proto))
     return NULL;
   JS_ASSERT(proto);
   JS_ASSERT(CType::IsCTypeProto(proto));
 
   // Get a JSContext for use with the closure.
   jsval slot = JS_GetReservedSlot(proto, SLOT_CLOSURECX);
   if (!JSVAL_IS_VOID(slot)) {
     // Use the existing JSContext.
--- a/js/src/jsapi-tests/testResolveRecursion.cpp
+++ b/js/src/jsapi-tests/testResolveRecursion.cpp
@@ -22,16 +22,20 @@ BEGIN_TEST(testResolveRecursion)
         JS_DeletePropertyStub, // delete
         JS_PropertyStub,       // get
         JS_StrictPropertyStub, // set
         JS_EnumerateStub,
         (JSResolveOp) my_resolve,
         JS_ConvertStub
     };
 
+    obj1 = obj2 = NULL;
+    JS_AddObjectRoot(cx, &obj1);
+    JS_AddObjectRoot(cx, &obj2);
+
     obj1 = JS_NewObject(cx, &my_resolve_class, NULL, NULL);
     CHECK(obj1);
     obj2 = JS_NewObject(cx, &my_resolve_class, NULL, NULL);
     CHECK(obj2);
     JS_SetPrivate(obj1, this);
     JS_SetPrivate(obj2, this);
 
     CHECK(JS_DefineProperty(cx, global, "obj1", OBJECT_TO_JSVAL(obj1), NULL, NULL, 0));
@@ -41,16 +45,19 @@ BEGIN_TEST(testResolveRecursion)
     resolveExitCount = 0;
 
     /* Start the essence of the test via invoking the first resolve hook. */
     JS::RootedValue v(cx);
     EVAL("obj1.x", v.address());
     CHECK_SAME(v, JSVAL_FALSE);
     CHECK_EQUAL(resolveEntryCount, 4);
     CHECK_EQUAL(resolveExitCount, 4);
+
+    JS_RemoveObjectRoot(cx, &obj1);
+    JS_RemoveObjectRoot(cx, &obj2);
     return true;
 }
 
 JSObject *obj1;
 JSObject *obj2;
 unsigned resolveEntryCount;
 unsigned resolveExitCount;
 
--- a/js/src/jsapi-tests/testTypedArrays.cpp
+++ b/js/src/jsapi-tests/testTypedArrays.cpp
@@ -26,17 +26,17 @@ BEGIN_TEST(testTypedArrays)
         TestPlainTypedArray<JS_NewFloat32Array, float, JS_GetFloat32ArrayData>(cx) &&
         TestPlainTypedArray<JS_NewFloat64Array, double, JS_GetFloat64ArrayData>(cx);
 
     size_t nbytes = sizeof(double) * 8;
     RootedObject buffer(cx, JS_NewArrayBuffer(cx, nbytes));
     CHECK(JS_IsArrayBufferObject(buffer));
 
     RootedObject proto(cx);
-    JS_GetPrototype(cx, buffer, proto.address());
+    JS_GetPrototype(cx, buffer, &proto);
     CHECK(!JS_IsArrayBufferObject(proto));
     RootedObject dummy(cx, JS_GetParent(proto));
     CHECK(!JS_IsArrayBufferObject(dummy));
 
     CHECK_EQUAL(JS_GetArrayBufferByteLength(buffer), nbytes);
     memset(JS_GetArrayBufferData(buffer), 1, nbytes);
 
     ok = ok &&
@@ -62,17 +62,17 @@ TestPlainTypedArray(JSContext *cx)
     {
         RootedObject notArray(cx, Create(cx, UINT32_MAX));
         CHECK(!notArray);
     }
 
     RootedObject array(cx, Create(cx, 7));
     CHECK(JS_IsTypedArrayObject(array));
     RootedObject proto(cx);
-    JS_GetPrototype(cx, array, proto.address());
+    JS_GetPrototype(cx, array, &proto);
     CHECK(!JS_IsTypedArrayObject(proto));
     RootedObject dummy(cx, JS_GetParent(proto));
     CHECK(!JS_IsTypedArrayObject(dummy));
 
     CHECK_EQUAL(JS_GetTypedArrayLength(array), 7);
     CHECK_EQUAL(JS_GetTypedArrayByteOffset(array), 0);
     CHECK_EQUAL(JS_GetTypedArrayByteLength(array), sizeof(Element) * 7);
 
--- a/js/src/jsapi.cpp
+++ b/js/src/jsapi.cpp
@@ -2812,30 +2812,24 @@ JS_GetInstancePrivate(JSContext *cx, JSO
 {
     RootedObject obj(cx, objArg);
     if (!JS_InstanceOf(cx, obj, clasp, argv))
         return NULL;
     return obj->getPrivate();
 }
 
 JS_PUBLIC_API(JSBool)
-JS_GetPrototype(JSContext *cx, JSObject *objArg, JSObject **protop)
-{
-    RootedObject obj(cx, objArg);
-    RootedObject proto(cx);
-    bool rv = JSObject::getProto(cx, obj, &proto);
<