Merge m-c to inbound.
authorRyan VanderMeulen <ryanvm@gmail.com>
Wed, 15 Aug 2012 21:00:42 -0400
changeset 102492 2d89567b206bc026c5190ddbfc4bb93d28dcfdc3
parent 102491 ac8287aea1fbc951caecd3a6e9103d3c31265b44 (diff)
parent 102406 996a68d8420ee36b459933a3e27853d4810e6b39 (current diff)
child 102493 e79bf6f458f74c4352babb58bb8b9408a48aa8a6
push id23288
push useremorley@mozilla.com
push dateThu, 16 Aug 2012 13:14:48 +0000
treeherdermozilla-central@3940df6f9356 [default view] [failures only]
perfherder[talos] [build metrics] [platform microbench] (compared to previous push)
milestone17.0a1
first release with
nightly linux32
nightly linux64
nightly mac
nightly win32
nightly win64
last release without
nightly linux32
nightly linux64
nightly mac
nightly win32
nightly win64
Merge m-c to inbound.
--- a/accessible/src/jsat/AccessFu.jsm
+++ b/accessible/src/jsat/AccessFu.jsm
@@ -39,17 +39,17 @@ var AccessFu = {
     this.chromeWin = aWindow;
     this.presenters = [];
 
     this.prefsBranch = Cc['@mozilla.org/preferences-service;1']
       .getService(Ci.nsIPrefService).getBranch('accessibility.accessfu.');
     this.prefsBranch.addObserver('activate', this, false);
     this.prefsBranch.addObserver('explorebytouch', this, false);
 
-    if (Utils.OS == 'Android')
+    if (Utils.MozBuildApp == 'mobile/android')
       Services.obs.addObserver(this, 'Accessibility:Settings', false);
 
     this._processPreferences();
   },
 
   /**
    * Start AccessFu mode, this primarily means controlling the virtual cursor
    * with arrow keys.
@@ -111,17 +111,17 @@ var AccessFu = {
 
     let ebtPref = ACCESSFU_DISABLE;
     try {
       ebtPref = (aTouchEnabled == undefined) ?
         this.prefsBranch.getIntPref('explorebytouch') : aTouchEnabled;
     } catch (x) {
     }
 
-    if (Utils.OS == 'Android') {
+    if (Utils.MozBuildApp == 'mobile/android') {
       if (accessPref == ACCESSFU_AUTO) {
         Cc['@mozilla.org/android/bridge;1'].
           getService(Ci.nsIAndroidBridge).handleGeckoMessage(
             JSON.stringify({ gecko: { type: 'Accessibility:Ready' } }));
         return;
       }
     }
 
--- a/accessible/src/jsat/UtteranceGenerator.jsm
+++ b/accessible/src/jsat/UtteranceGenerator.jsm
@@ -147,17 +147,17 @@ var UtteranceGenerator = {
     'toolbar': INCLUDE_DESC,
     'table': INCLUDE_DESC | INCLUDE_NAME,
     'link': INCLUDE_DESC,
     'listitem': INCLUDE_DESC,
     'outline': INCLUDE_DESC,
     'outlineitem': INCLUDE_DESC,
     'pagetab': INCLUDE_DESC,
     'graphic': INCLUDE_DESC,
-    'pushbutton': INCLUDE_DESC,
+    'pushbutton': INCLUDE_DESC | INCLUDE_NAME,
     'checkbutton': INCLUDE_DESC,
     'radiobutton': INCLUDE_DESC,
     'combobox': INCLUDE_DESC,
     'droplist': INCLUDE_DESC,
     'progressbar': INCLUDE_DESC,
     'slider': INCLUDE_DESC,
     'spinbutton': INCLUDE_DESC,
     'diagram': INCLUDE_DESC,
--- a/accessible/src/jsat/VirtualCursorController.jsm
+++ b/accessible/src/jsat/VirtualCursorController.jsm
@@ -255,38 +255,16 @@ var VirtualCursorController = {
         let methodName = '', rule = {};
         try {
           [methodName, rule] = this.keyMap[key];
         } catch (x) {
           return;
         }
         this[methodName](document, false, rule);
         break;
-      case aEvent.DOM_VK_END:
-        if (this.editableState) {
-          if (target.selectionEnd != target.textLength)
-            // Don't move forward if caret is not at end of entry.
-            // XXX: Fix for rtl
-            return;
-          else
-            target.blur();
-        }
-        this.moveForward(document, true);
-        break;
-      case aEvent.DOM_VK_HOME:
-        if (this.editableState) {
-          if (target.selectionEnd != 0)
-            // Don't move backward if caret is not at start of entry.
-            // XXX: Fix for rtl
-            return;
-          else
-            target.blur();
-        }
-        this.moveBackward(document, true);
-        break;
       case aEvent.DOM_VK_RIGHT:
         if (this.editableState) {
           if (target.selectionEnd != target.textLength)
             // Don't move forward if caret is not at end of entry.
             // XXX: Fix for rtl
             return;
           else
             target.blur();
@@ -308,17 +286,17 @@ var VirtualCursorController = {
         if (this.editableState & Ci.nsIAccessibleStates.EXT_STATE_MULTI_LINE) {
           if (target.selectionEnd != 0)
             // Don't blur content if caret is not at start of text area.
             return;
           else
             target.blur();
         }
 
-        if (Utils.OS == 'Android')
+        if (Utils.MozBuildApp == 'mobile/android')
           // Return focus to native Android browser chrome.
           Cc['@mozilla.org/android/bridge;1'].
             getService(Ci.nsIAndroidBridge).handleGeckoMessage(
               JSON.stringify({ gecko: { type: 'ToggleChrome:Focus' } }));
         break;
       case aEvent.DOM_VK_RETURN:
       case aEvent.DOM_VK_ENTER:
         if (this.editableState)
--- a/b2g/chrome/content/shell.js
+++ b/b2g/chrome/content/shell.js
@@ -39,16 +39,21 @@ XPCOMUtils.defineLazyServiceGetter(Servi
                                    '@mozilla.org/focus-manager;1',
                                    'nsIFocusManager');
 
 XPCOMUtils.defineLazyGetter(this, 'DebuggerServer', function() {
   Cu.import('resource://gre/modules/devtools/dbg-server.jsm');
   return DebuggerServer;
 });
 
+XPCOMUtils.defineLazyGetter(this, "ppmm", function() {
+  return Cc["@mozilla.org/parentprocessmessagemanager;1"]
+         .getService(Ci.nsIFrameMessageManager);
+});
+
 function getContentWindow() {
   return shell.contentBrowser.contentWindow;
 }
 
 var shell = {
 
   get CrashSubmit() {
     delete this.CrashSubmit;
@@ -144,26 +149,29 @@ var shell = {
     SettingsListener.observe("debug.fps.enabled", false, function(value) {
       Services.prefs.setBoolPref("layers.acceleration.draw-fps", value);
     });
     SettingsListener.observe("debug.paint-flashing.enabled", false, function(value) {
       Services.prefs.setBoolPref("nglayout.debug.paint_flashing", value);
     });
 
     this.contentBrowser.src = homeURL;
+
+    ppmm.addMessageListener("content-handler", this);
   },
 
   stop: function shell_stop() {
     window.removeEventListener('keydown', this, true);
     window.removeEventListener('keypress', this, true);
     window.removeEventListener('keyup', this, true);
     window.removeEventListener('MozApplicationManifest', this);
     window.removeEventListener('mozfullscreenchange', this);
     window.removeEventListener('sizemodechange', this);
     this.contentBrowser.removeEventListener('mozbrowserloadstart', this, true);
+    ppmm.removeMessageListener("content-handler", this);
 
 #ifndef MOZ_WIDGET_GONK
     delete Services.audioManager;
 #endif
   },
 
   // If this key event actually represents a hardware button, filter it here
   // and send a mozChromeEvent with detail.type set to xxx-button-press or
@@ -293,23 +301,39 @@ var shell = {
                               .getService(Ci.nsIOfflineCacheUpdateService);
           updateService.scheduleUpdate(manifestURI, documentURI, window);
         } catch (e) {
           dump('Error while creating offline cache: ' + e + '\n');
         }
         break;
     }
   },
+
   sendEvent: function shell_sendEvent(content, type, details) {
     let event = content.document.createEvent('CustomEvent');
     event.initCustomEvent(type, true, true, details ? details : {});
     content.dispatchEvent(event);
   },
+
   sendChromeEvent: function shell_sendChromeEvent(details) {
     this.sendEvent(getContentWindow(), "mozChromeEvent", details);
+  },
+
+  receiveMessage: function shell_receiveMessage(message) {
+    if (message.name != 'content-handler') {
+      return;
+    }
+    let handler = message.json;
+    new MozActivity({
+      name: 'view',
+      data: {
+        type: handler.type,
+        url: handler.url
+      }
+    });
   }
 };
 
 function nsBrowserAccess() {
 }
 
 nsBrowserAccess.prototype = {
   QueryInterface: XPCOMUtils.generateQI([Ci.nsIBrowserDOMWindow]),
@@ -342,17 +366,18 @@ nsBrowserAccess.prototype = {
 // Listen for system messages and relay them to Gaia.
 Services.obs.addObserver(function onSystemMessage(subject, topic, data) {
   let msg = JSON.parse(data);
   let origin = Services.io.newURI(msg.manifest, null, null).prePath;
   shell.sendChromeEvent({
     type: 'open-app',
     url: msg.uri,
     origin: origin,
-    manifest: msg.manifest
+    manifest: msg.manifest,
+    target: msg.target
   });
 }, 'system-messages-open-app', false);
 
 Services.obs.addObserver(function(aSubject, aTopic, aData) {
   shell.sendEvent(shell.contentBrowser.contentWindow,
                   "mozChromeEvent", { type: "fullscreenoriginchange",
                                       fullscreenorigin: aData } );
 }, "fullscreen-origin-change", false);
@@ -596,27 +621,16 @@ window.addEventListener('ContentStart', 
       shell.sendChromeEvent({
         type: 'take-screenshot-error',
         error: String(e)
       });
     }
   });
 });
 
-Services.obs.addObserver(function ContentHandler(subject, topic, data) {
-  let handler = JSON.parse(data);
-  new MozActivity({
-    name: 'view',
-    data: {
-      type: handler.type,
-      url: handler.url
-    }
-  });
-}, 'content-handler', false);
-
 (function geolocationStatusTracker() {
   let gGeolocationActiveCount = 0;
 
   Services.obs.addObserver(function(aSubject, aTopic, aData) {
     let oldCount = gGeolocationActiveCount;
     if (aData == "starting") {
       gGeolocationActiveCount += 1;
     } else if (aData == "shutdown") {
--- a/b2g/components/ContentHandler.js
+++ b/b2g/components/ContentHandler.js
@@ -8,16 +8,20 @@ const Ci = Components.interfaces;
 const Cr = Components.results;
 const Cu = Components.utils;
 
 const PDF_CONTENT_TYPE = "application/pdf";
 
 Cu.import("resource://gre/modules/XPCOMUtils.jsm");
 Cu.import("resource://gre/modules/Services.jsm");
 
+XPCOMUtils.defineLazyGetter(this, "cpmm", function() {
+  return Cc["@mozilla.org/childprocessmessagemanager;1"].getService(Ci.nsIFrameMessageManager);
+});
+
 function log(aMsg) {
   let msg = "ContentHandler.js: " + (aMsg.join ? aMsg.join("") : aMsg);
   Cc["@mozilla.org/consoleservice;1"].getService(Ci.nsIConsoleService)
                                      .logStringMessage(msg);
   dump(msg + "\n");
 }
 
 const NS_ERROR_WONT_HANDLE_CONTENT = 0x805d0001;
@@ -31,17 +35,17 @@ ContentHandler.prototype = {
 
     if (!(aRequest instanceof Ci.nsIChannel))
       throw NS_ERROR_WONT_HANDLE_CONTENT;
 
     let detail = {
       "type": aMimetype,
       "url": aRequest.URI.spec
     };
-    Services.obs.notifyObservers(this, "content-handler", JSON.stringify(detail)); 
+    cpmm.sendAsyncMessage("content-handler", detail);
 
     aRequest.cancel(Cr.NS_BINDING_ABORTED);
   },
 
   classID: Components.ID("{d18d0216-d50c-11e1-ba54-efb18d0ef0ac}"),
   QueryInterface: XPCOMUtils.generateQI([Ci.nsIContentHandler])
 };
 
--- a/b2g/config/mozconfigs/win32_gecko/nightly
+++ b/b2g/config/mozconfigs/win32_gecko/nightly
@@ -17,19 +17,13 @@ export MOZ_TELEMETRY_REPORTING=1
 mk_add_options MOZ_MAKE_FLAGS=-j1
 
 if test "$PROCESSOR_ARCHITECTURE" = "AMD64" -o "$PROCESSOR_ARCHITEW6432" = "AMD64"; then
   . $topsrcdir/build/win32/mozconfig.vs2010-win64
 else
   . $topsrcdir/build/win32/mozconfig.vs2010
 fi
 
-# For known full-clobber builds on Windows (like nightlies/try), 
-# this speeds things up. IS_NIGHTLY is set by the build automation.
-if test "$IS_NIGHTLY" != ""; then 
-  ac_add_options --disable-auto-deps
-fi
-
 # B2G Options
 ac_add_options --enable-application=b2g
 ac_add_options --enable-marionette
 
 export CXXFLAGS=-DMOZ_ENABLE_JS_DUMP
--- a/browser/base/content/browser-fullZoom.js
+++ b/browser/base/content/browser-fullZoom.js
@@ -83,33 +83,36 @@ var FullZoom = {
       case "DOMMouseScroll":
         this._handleMouseScrolled(event);
         break;
     }
   },
 
   _handleMouseScrolled: function FullZoom__handleMouseScrolled(event) {
     // Construct the "mousewheel action" pref key corresponding to this event.
-    // Based on nsEventStateManager::GetBasePrefKeyForMouseWheel.
-    var pref = "mousewheel";
-    if (event.axis == event.HORIZONTAL_AXIS)
-      pref += ".horizscroll";
+    // Based on nsEventStateManager::WheelPrefs::GetBasePrefName().
+    var pref = "mousewheel.";
 
-    if (event.shiftKey)
-      pref += ".withshiftkey";
-    else if (event.ctrlKey)
-      pref += ".withcontrolkey";
-    else if (event.altKey)
-      pref += ".withaltkey";
-    else if (event.metaKey)
-      pref += ".withmetakey";
-    else
-      pref += ".withnokey";
+    var pressedModifierCount = event.shiftKey + event.ctrlKey + event.altKey +
+                                 event.metaKey + event.getModifierState("OS");
+    if (pressedModifierCount != 1) {
+      pref += "default.";
+    } else if (event.shiftKey) {
+      pref += "with_shift.";
+    } else if (event.ctrlKey) {
+      pref += "with_control.";
+    } else if (event.altKey) {
+      pref += "with_alt.";
+    } else if (event.metaKey) {
+      pref += "with_meta.";
+    } else {
+      pref += "with_win.";
+    }
 
-    pref += ".action";
+    pref += "action";
 
     // Don't do anything if this isn't a "zoom" scroll event.
     var isZoomEvent = false;
     try {
       isZoomEvent = (gPrefService.getIntPref(pref) == MOUSE_SCROLL_ZOOM);
     } catch (e) {}
     if (!isZoomEvent)
       return;
--- a/browser/config/mozconfigs/win32/nightly
+++ b/browser/config/mozconfigs/win32/nightly
@@ -20,14 +20,8 @@ mk_add_options MOZ_MAKE_FLAGS=-j1
 if test "$PROCESSOR_ARCHITECTURE" = "AMD64" -o "$PROCESSOR_ARCHITEW6432" = "AMD64"; then
   . $topsrcdir/build/win32/mozconfig.vs2010-win64
 else
   . $topsrcdir/build/win32/mozconfig.vs2010
 fi
 
 # Package js shell.
 export MOZ_PACKAGE_JSSHELL=1
-
-# For known full-clobber builds on Windows (like nightlies/try), 
-# this speeds things up. IS_NIGHTLY is set by the build automation.
-if test "$IS_NIGHTLY" != ""; then 
-  ac_add_options --disable-auto-deps
-fi
--- a/browser/config/mozconfigs/win64/nightly
+++ b/browser/config/mozconfigs/win64/nightly
@@ -18,15 +18,9 @@ export MOZILLA_OFFICIAL=1
 
 export MOZ_TELEMETRY_REPORTING=1
 
 mk_add_options MOZ_MAKE_FLAGS=-j1
 
 # Package js shell.
 export MOZ_PACKAGE_JSSHELL=1
 
-# For known full-clobber builds on Windows (like nightlies/try), 
-# this speeds things up. IS_NIGHTLY is set by the build automation.
-if test "$IS_NIGHTLY" != ""; then 
-  ac_add_options --disable-auto-deps
-fi
-
 . $topsrcdir/build/win64/mozconfig.vs2010
--- a/build/autoconf/mozconfig2client-mk
+++ b/build/autoconf/mozconfig2client-mk
@@ -5,21 +5,20 @@
 # file, You can obtain one at http://mozilla.org/MPL/2.0/.
 
 # mozconfig2client-mk - Translates .mozconfig into options for client.mk.
 #    Prints defines to stdout.
 #
 # See mozconfig2configure for more details
 
 print_header() {
-  _mozconfig=${MOZCONFIG:-$HOME/.mozconfig}
   cat <<EOF
 # gmake
 # This file is automatically generated for client.mk.
-# Do not edit. Edit $_mozconfig instead.
+# Do not edit. Edit $FOUND_MOZCONFIG instead.
 
 EOF
 }
 
 ac_add_options() {
   echo "# $* is used by configure (not client.mk)"
 }
 
@@ -48,18 +47,16 @@ mk_echo_options() {
 
 # Main
 #--------------------------------------------------
 
 scriptdir=`dirname $0`
 topsrcdir=$1
 opts=""
 
-print_header
-
 # If the path changes, configure should be rerun
 echo "# PATH=$PATH"
 
 # If FOUND_MOZCONFIG isn't set, look for it and make sure the script doesn't error out
 isfoundset=${FOUND_MOZCONFIG+yes}
 if [ -z $isfoundset ]; then
   FOUND_MOZCONFIG=`$scriptdir/mozconfig-find $topsrcdir`
   if [ $? -ne 0 ]; then
@@ -67,16 +64,17 @@ if [ -z $isfoundset ]; then
   else
     isfoundset=yes
   fi
 fi
 
 if [ -n $isfoundset ]; then
   if [ "$FOUND_MOZCONFIG" ]
   then
+    print_header
     . "$FOUND_MOZCONFIG"
   fi
   echo "export FOUND_MOZCONFIG := $FOUND_MOZCONFIG"
 
   if [ "$opts" ]; then
     mk_echo_options
   fi
 fi
--- a/build/mobile/b2gautomation.py
+++ b/build/mobile/b2gautomation.py
@@ -38,16 +38,18 @@ class B2GRemoteAutomation(Automation):
                  marionette=None, context_chrome=True):
         self._devicemanager = deviceManager
         self._appName = appName
         self._remoteProfile = None
         self._remoteLog = remoteLog
         self.marionette = marionette
         self.context_chrome = context_chrome
         self._is_emulator = False
+        self.test_script = None
+        self.test_script_args = None
 
         # Default our product to b2g
         self._product = "b2g"
         # Default log finish to mochitest standard
         self.logFinish = 'INFO SimpleTest FINISHED' 
         Automation.__init__(self)
 
     def setEmulator(self, is_emulator):
@@ -249,24 +251,24 @@ class B2GRemoteAutomation(Automation):
 
         # start the tests
         if hasattr(self, 'testURL'):
             # Start the tests by navigating to the mochitest url, by setting it
             # as the 'src' attribute to the homescreen mozbrowser element
             # provided by B2G's shell.js.
             self.marionette.execute_script("document.getElementById('homescreen').src='%s';" % self.testURL)
         # run the script that starts the tests
-        elif hasattr(self, 'testScript'):
-            if os.path.isfile(self.testScript):
-                script = open(self.testScript, 'r')
-                self.marionette.execute_script(script.read())
+        elif self.test_script:
+            if os.path.isfile(self.test_script):
+                script = open(self.test_script, 'r')
+                self.marionette.execute_script(script.read(), script_args=self.test_script_args)
                 script.close()
             else:
-                # assume testScript is a string
-                self.marionette.execute_script(self.testScript)
+                # assume test_script is a string
+                self.marionette.execute_script(self.test_script, script_args=self.test_script_args)
         else:
             # assumes the tests are started on startup automatically
             pass
 
         return instance
 
     # be careful here as this inner class doesn't have access to outer class members
     class B2GInstance(object):
--- a/build/mobile/devicemanager.py
+++ b/build/mobile/devicemanager.py
@@ -33,19 +33,22 @@ def abstractmethod(method):
     raise NotImplementedError('Abstract method %s at File "%s", line %s '
                               'should be implemented by a concrete class' %
                               (repr(method), filename,line))
   return not_implemented
 
 class DeviceManager:
 
   @abstractmethod
-  def shell(self, cmd, outputfile, env=None, cwd=None):
+  def shell(self, cmd, outputfile, env=None, cwd=None, timeout=None):
     """
     executes shell command on device
+
+    timeout is specified in seconds, and if no timeout is given, 
+    we will run until the script returns
     returns:
     success: Return code from command
     failure: None
     """
 
   @abstractmethod
   def pushFile(self, localname, destname):
     """
--- a/build/mobile/devicemanagerADB.py
+++ b/build/mobile/devicemanagerADB.py
@@ -85,21 +85,23 @@ class DeviceManagerADB(DeviceManager):
       self.verifyZip()
     except DMError:
       pass
 
   def __del__(self):
     if self.host:
       self.disconnectRemoteADB()
 
-  # external function: executes shell command on device
+  # external function: executes shell command on device.
+  # timeout is specified in seconds, and if no timeout is given, 
+  # we will run until the script returns
   # returns:
   # success: <return code>
   # failure: None
-  def shell(self, cmd, outputfile, env=None, cwd=None):
+  def shell(self, cmd, outputfile, env=None, cwd=None, timeout=None):
     # FIXME: this function buffers all output of the command into memory,
     # always. :(
 
     # Getting the return code is more complex than you'd think because adb
     # doesn't actually return the return code from a process, so we have to
     # capture the output to get it
     cmdline = "%s; echo $?" % self._escapedCommandLine(cmd)
 
@@ -112,16 +114,26 @@ class DeviceManagerADB(DeviceManager):
 
     # all output should be in stdout
     args=[self.adbPath]
     if self.deviceSerial:
         args.extend(['-s', self.deviceSerial])
     args.extend(["shell", cmdline])
     proc = subprocess.Popen(args,
                             stdout=subprocess.PIPE, stderr=subprocess.PIPE)
+    if timeout:
+        timeout = int(timeout)
+        start_time = time.time()
+        ret_code = proc.poll()
+        while ((time.time() - start_time) <= timeout) and ret_code == None:
+            time.sleep(1)
+            ret_code = proc.poll()
+        if ret_code == None:
+            proc.kill()
+            raise DMError("Timeout exceeded for shell call")
     (stdout, stderr) = proc.communicate()
     outputfile.write(stdout.rstrip('\n'))
 
     lastline = _pop_last_line(outputfile)
     if lastline:
       m = re.search('([0-9]+)', lastline)
       if m:
         return_code = m.group(1)
@@ -707,33 +719,47 @@ class DeviceManagerADB(DeviceManager):
     return subprocess.Popen(finalArgs, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
 
   def runCmdAs(self, args):
     if self.useRunAs:
       args.insert(1, "run-as")
       args.insert(2, self.packageName)
     return self.runCmd(args)
 
-  def checkCmd(self, args):
+  # timeout is specified in seconds, and if no timeout is given, 
+  # we will run until the script returns
+  def checkCmd(self, args, timeout=None):
     # If we are not root but have run-as, and we're trying to execute
     # a shell command then using run-as is the best we can do
     finalArgs = [self.adbPath]
     if self.deviceSerial:
       finalArgs.extend(['-s', self.deviceSerial])
     if (not self.haveRoot and self.useRunAs and args[0] == "shell" and args[1] != "run-as"):
       args.insert(1, "run-as")
       args.insert(2, self.packageName)
     finalArgs.extend(args)
+    if timeout:
+        timeout = int(timeout)
+        proc = subprocess.Popen(finalArgs)
+        start_time = time.time()
+        ret_code = proc.poll()
+        while ((time.time() - start_time) <= timeout) and ret_code == None:
+            time.sleep(1)
+            ret_code = proc.poll()
+        if ret_code == None:
+            proc.kill()
+            raise DMError("Timeout exceeded for checkCmd call")
+        return ret_code
     return subprocess.check_call(finalArgs)
 
-  def checkCmdAs(self, args):
+  def checkCmdAs(self, args, timeout=None):
     if (self.useRunAs):
       args.insert(1, "run-as")
       args.insert(2, self.packageName)
-    return self.checkCmd(args)
+    return self.checkCmd(args, timeout)
 
   # external function
   # returns:
   #  success: True
   #  failure: False
   def chmodDir(self, remoteDir):
     if (self.isDir(remoteDir)):
       files = self.listFiles(remoteDir.strip())
--- a/build/mobile/devicemanagerSUT.py
+++ b/build/mobile/devicemanagerSUT.py
@@ -118,16 +118,18 @@ class DeviceManagerSUT(DeviceManager):
     '''
     a wrapper for _doCmds that loops up to self.retrylimit iterations.
     this allows us to move the retry logic outside of the _doCmds() to make it
     easier for debugging in the future.
     note that since cmdlist is a list of commands, they will all be retried if
     one fails.  this is necessary in particular for pushFile(), where we don't want
     to accidentally send extra data if a failure occurs during data transmission.
     '''
+    if timeout:
+      raise NotImplementedError("'timeout' parameter is not yet supported")
     while self.retries < self.retrylimit:
       try:
         self._doCmds(cmdlist, outputfile, timeout)
         return
       except AgentError, err:
         # re-raise error if it's fatal (i.e. the device got the command but
         # couldn't execute it). retry otherwise
         if err.fatal:
@@ -256,26 +258,26 @@ class DeviceManagerSUT(DeviceManager):
       except:
         self._sock = None
         raise AgentError("Error closing socket")
 
   # external function: executes shell command on device
   # returns:
   # success: <return code>
   # failure: None
-  def shell(self, cmd, outputfile, env=None, cwd=None):
+  def shell(self, cmd, outputfile, env=None, cwd=None, timeout=None):
     cmdline = self._escapedCommandLine(cmd)
     if env:
       cmdline = '%s %s' % (self.formatEnvString(env), cmdline)
 
     try:
       if cwd:
-        self.sendCmds([{ 'cmd': 'execcwd %s %s' % (cwd, cmdline) }], outputfile)
+        self.sendCmds([{ 'cmd': 'execcwd %s %s' % (cwd, cmdline) }], outputfile, timeout)
       else:
-        self.sendCmds([{ 'cmd': 'exec su -c "%s"' % cmdline }], outputfile)
+        self.sendCmds([{ 'cmd': 'exec su -c "%s"' % cmdline }], outputfile, timeout)
     except AgentError:
       return None
 
     # dig through the output to get the return code
     lastline = _pop_last_line(outputfile)
     if lastline:
       m = re.search('return code \[([0-9]+)\]', lastline)
       if m:
--- a/caps/tests/mochitest/test_principal_extendedorigin_appid_appstatus.html
+++ b/caps/tests/mochitest/test_principal_extendedorigin_appid_appstatus.html
@@ -359,16 +359,17 @@ function checkIFrame(aFrame, data) {
             "childPrincipal and parent principal should have different appId");
     }
   }
 
   eoList.push(principal.extendedOrigin);
 
   checkedCount++;
   if (checkedCount == checksTodo) {
+    SpecialPowers.removePermission("browser", "http://example.org");
     SimpleTest.finish();
   } else {
     gTestRunner.next();
   }
 }
 
 is('appStatus' in document.nodePrincipal, true,
    'appStatus should be present in nsIPrincipal');
@@ -423,16 +424,16 @@ function runTest() {
     content.appendChild(iframe);
 
     yield;
   }
 }
 
 var gTestRunner = runTest();
 
-SpecialPowers.pushPrefEnv({'set': [["dom.mozBrowserFramesEnabled", true],
-                                   ["dom.mozBrowserFramesWhitelist", "http://example.org"]]},
+SpecialPowers.addPermission("browser", true, "http://example.org");
+SpecialPowers.pushPrefEnv({'set':[["dom.mozBrowserFramesEnabled", true]]},
                            function() { gTestRunner.next(); });
 
 </script>
 </pre>
 </body>
 </html>
--- a/client.mk
+++ b/client.mk
@@ -65,17 +65,17 @@ AUTOCONF=$(error Could not find autoconf
 endif
 
 SH := /bin/sh
 PERL ?= perl
 PYTHON ?= python
 
 CONFIG_GUESS_SCRIPT := $(wildcard $(TOPSRCDIR)/build/autoconf/config.guess)
 ifdef CONFIG_GUESS_SCRIPT
-  CONFIG_GUESS = $(shell $(CONFIG_GUESS_SCRIPT))
+  CONFIG_GUESS := $(shell $(CONFIG_GUESS_SCRIPT))
 endif
 
 
 ####################################
 # Sanity checks
 
 ifneq (,$(findstring mingw,$(CONFIG_GUESS)))
 # check for CRLF line endings
@@ -87,18 +87,16 @@ endif
 endif
 
 ####################################
 # Load mozconfig Options
 
 # See build pages, http://www.mozilla.org/build/ for how to set up mozconfig.
 
 MOZCONFIG_LOADER := build/autoconf/mozconfig2client-mk
-MOZCONFIG_FINDER := build/autoconf/mozconfig-find 
-MOZCONFIG_MODULES := build/unix/uniq.pl
 
 define CR
 
 
 endef
 
 # As $(shell) doesn't preserve newlines, use sed to replace them with an
 # unlikely sequence (||), which is then replaced back to newlines by make
--- a/configure.in
+++ b/configure.in
@@ -8636,20 +8636,18 @@ if test "$MOZ_GL_DEFAULT_PROVIDER" = "GL
 fi # MOZ_GL_DEFAULT_PROVIDER=GLX
 fi # COMPILE_ENVIRONMENT
 
 dnl Set various defines and substitutions
 dnl ========================================================
 
 if test "$OS_ARCH" = "Darwin"; then
   AC_DEFINE(XP_UNIX)
-  AC_DEFINE(UNIX_ASYNC_DNS)
 elif test "$OS_ARCH" != "WINNT" -a "$OS_ARCH" != "OS2"; then
   AC_DEFINE(XP_UNIX)
-  AC_DEFINE(UNIX_ASYNC_DNS)
 fi
 
 if test "$MOZ_DEBUG"; then
     AC_DEFINE(MOZ_REFLOW_PERF)
     AC_DEFINE(MOZ_REFLOW_PERF_DSP)
 fi
 
 if test "$ACCESSIBILITY" -a "$MOZ_ENABLE_GTK2" ; then
--- a/content/base/src/nsAttrValue.cpp
+++ b/content/base/src/nsAttrValue.cpp
@@ -1305,17 +1305,17 @@ nsAttrValue::ParseEnumValue(const nsAStr
   return false;
 }
 
 bool
 nsAttrValue::ParseSpecialIntValue(const nsAString& aString)
 {
   ResetIfSet();
 
-  PRInt32 ec;
+  nsresult ec;
   bool strict;
   bool isPercent = false;
   nsAutoString tmp(aString);
   PRInt32 originalVal = StringToInteger(aString, &strict, &ec, true, &isPercent);
 
   if (NS_FAILED(ec)) {
     return false;
   }
@@ -1338,17 +1338,17 @@ nsAttrValue::ParseSpecialIntValue(const 
 bool
 nsAttrValue::ParseIntWithBounds(const nsAString& aString,
                                 PRInt32 aMin, PRInt32 aMax)
 {
   NS_PRECONDITION(aMin < aMax, "bad boundaries");
 
   ResetIfSet();
 
-  PRInt32 ec;
+  nsresult ec;
   bool strict;
   PRInt32 originalVal = StringToInteger(aString, &strict, &ec);
   if (NS_FAILED(ec)) {
     return false;
   }
 
   PRInt32 val = NS_MAX(originalVal, aMin);
   val = NS_MIN(val, aMax);
@@ -1358,34 +1358,34 @@ nsAttrValue::ParseIntWithBounds(const ns
   return true;
 }
 
 bool
 nsAttrValue::ParseNonNegativeIntValue(const nsAString& aString)
 {
   ResetIfSet();
 
-  PRInt32 ec;
+  nsresult ec;
   bool strict;
   PRInt32 originalVal = StringToInteger(aString, &strict, &ec);
   if (NS_FAILED(ec) || originalVal < 0) {
     return false;
   }
 
   SetIntValueAndType(originalVal, eInteger, strict ? nullptr : &aString);
 
   return true;
 }
 
 bool
 nsAttrValue::ParsePositiveIntValue(const nsAString& aString)
 {
   ResetIfSet();
 
-  PRInt32 ec;
+  nsresult ec;
   bool strict;
   PRInt32 originalVal = StringToInteger(aString, &strict, &ec);
   if (NS_FAILED(ec) || originalVal <= 0) {
     return false;
   }
 
   SetIntValueAndType(originalVal, eInteger, strict ? nullptr : &aString);
 
@@ -1656,17 +1656,17 @@ nsAttrValue::GetStringBuffer(const nsASt
   PRUnichar *data = static_cast<PRUnichar*>(buf->Data());
   CopyUnicodeTo(aValue, 0, data, len);
   data[len] = PRUnichar(0);
   return buf;
 }
 
 PRInt32
 nsAttrValue::StringToInteger(const nsAString& aValue, bool* aStrict,
-                             PRInt32* aErrorCode,
+                             nsresult* aErrorCode,
                              bool aCanBePercent,
                              bool* aIsPercent) const
 {
   *aStrict = true;
   *aErrorCode = NS_ERROR_ILLEGAL_VALUE;
   if (aCanBePercent) {
     *aIsPercent = false;
   }
--- a/content/base/src/nsAttrValue.h
+++ b/content/base/src/nsAttrValue.h
@@ -413,17 +413,17 @@ private:
 
   bool EnsureEmptyMiscContainer();
   bool EnsureEmptyAtomArray();
   nsStringBuffer* GetStringBuffer(const nsAString& aValue) const;
   // aStrict is set true if stringifying the return value equals with
   // aValue.
   PRInt32 StringToInteger(const nsAString& aValue,
                           bool* aStrict,
-                          PRInt32* aErrorCode,
+                          nsresult* aErrorCode,
                           bool aCanBePercent = false,
                           bool* aIsPercent = nullptr) const;
   // Given an enum table and a particular entry in that table, return
   // the actual integer value we should store.
   PRInt32 EnumTableEntryToValue(const EnumTable* aEnumTable,
                                 const EnumTable* aTableEntry);  
 
   static nsTArray<const EnumTable*, nsTArrayDefaultAllocator>* sEnumTableArray;
--- a/content/base/src/nsDocumentEncoder.cpp
+++ b/content/base/src/nsDocumentEncoder.cpp
@@ -1415,17 +1415,17 @@ nsHTMLCopyEncoder::SetSelection(nsISelec
   nsCOMPtr<nsIEnumerator> enumerator;
   rv = privSelection->GetEnumerator(getter_AddRefs(enumerator));
   NS_ENSURE_SUCCESS(rv, rv);
   NS_ENSURE_TRUE(enumerator, NS_ERROR_FAILURE);
 
   // loop thru the ranges in the selection
   enumerator->First(); 
   nsCOMPtr<nsISupports> currentItem;
-  while ((NS_ENUMERATOR_FALSE == enumerator->IsDone()))
+  while (static_cast<nsresult>(NS_ENUMERATOR_FALSE) == enumerator->IsDone())
   {
     rv = enumerator->CurrentItem(getter_AddRefs(currentItem));
     NS_ENSURE_SUCCESS(rv, rv);
     NS_ENSURE_TRUE(currentItem, NS_ERROR_FAILURE);
     
     range = do_QueryInterface(currentItem);
     NS_ENSURE_TRUE(range, NS_ERROR_FAILURE);
     nsCOMPtr<nsIDOMRange> myRange;
--- a/content/base/src/nsObjectLoadingContent.cpp
+++ b/content/base/src/nsObjectLoadingContent.cpp
@@ -1514,17 +1514,19 @@ nsObjectLoadingContent::LoadObject(bool 
   }
 
   // Save these for NotifyStateChanged();
   nsEventStates oldState = ObjectState();
   ObjectType oldType = mType;
 
   ParameterUpdateFlags stateChange = UpdateObjectParameters();
 
-  if (!stateChange && !aForceLoad) {
+  // If nothing changed and we are not force-loading, or we're in state loading
+  // but continuing to wait on a channel, we're done
+  if ((!stateChange && !aForceLoad) || (mType == eType_Loading && mChannel)) {
     return NS_OK;
   }
 
   ///
   /// State has changed, unload existing content and attempt to load new type
   ///
   LOG(("OBJLC [%p]: LoadObject - plugin state changed (%u)",
        this, stateChange));
@@ -1712,31 +1714,25 @@ nsObjectLoadingContent::LoadObject(bool 
     {
       if (!mChannel) {
         // We could mFrameLoader->LoadURI(mURI), but UpdateObjectParameters
         // requires documents have a channel, so this is not a valid state.
         NS_NOTREACHED("Attempting to load a document without a channel");
         mType = eType_Null;
         break;
       }
+      
+      mFrameLoader = nsFrameLoader::Create(thisContent->AsElement(),
+                                           mNetworkCreated);
       if (!mFrameLoader) {
-        // Force a sync state change, we need the frame created
-        NotifyStateChanged(oldType, oldState, true, aNotify);
-        oldType = mType;
-        oldState = ObjectState();
-
-        mFrameLoader = nsFrameLoader::Create(thisContent->AsElement(),
-                                             mNetworkCreated);
-        if (!mFrameLoader) {
-          NS_NOTREACHED("nsFrameLoader::Create failed");
-          mType = eType_Null;
-          break;
-        }
+        NS_NOTREACHED("nsFrameLoader::Create failed");
+        mType = eType_Null;
+        break;
       }
-
+      
       rv = mFrameLoader->CheckForRecursiveLoad(mURI);
       if (NS_FAILED(rv)) {
         mType = eType_Null;
         break;
       }
 
       // We're loading a document, so we have to set LOAD_DOCUMENT_URI
       // (especially important for firing onload)
@@ -1807,20 +1803,21 @@ nsObjectLoadingContent::LoadObject(bool 
     // Don't notify or send events - we'll handle those ourselves
     // (so really this is just setting mFallbackType)
     LoadFallback(fallbackType, false);
   }
 
   // Notify of our final state if we haven't already
   NotifyStateChanged(oldType, oldState, false, aNotify);
 
-  if (mType == eType_Null && mFallbackType != eFallbackAlternate) {
-    // if we're not showing alternate content, fire a pluginerror to trigger
-    // (we stopped LoadFallback from doing so above, it doesn't know of our old
-    //  state)
+  if (mType == eType_Null && !mContentType.IsEmpty() &&
+      mFallbackType != eFallbackAlternate) {
+    // if we have a content type and are not showing alternate
+    // content, fire a pluginerror to trigger (we stopped LoadFallback
+    // from doing so above, it doesn't know of our old state)
     FirePluginError(mFallbackType);
   }
 
   return NS_OK;
 }
 
 nsresult
 nsObjectLoadingContent::CloseChannel()
--- a/content/base/test/test_ipc_messagemanager_blob.html
+++ b/content/base/test/test_ipc_messagemanager_blob.html
@@ -68,16 +68,17 @@
         let mm = SpecialPowers.getBrowserFrameMessageManager(iframe);
         mm.addMessageListener("test:ipcClonedMessage", function(message) {
           // We need to wrap to access message.json, and unwrap to do the
           // identity check.
           is(SpecialPowers.unwrap(SpecialPowers.wrap(message).json),
              messages[receivedMessageIndex++],
              "Got correct round-tripped response");
           if (receivedMessageIndex == messages.length) {
+            SpecialPowers.removePermission("browser", document);
             SimpleTest.finish();
           }
         });
         mm.loadFrameScript("data:,(" + childFrameScript.toString() + ")();",
                            false);
 
         for each (let message in messages) {
           mm.sendAsyncMessage("test:ipcClonedMessage", message);
@@ -85,30 +86,20 @@
       });
 
       document.body.appendChild(iframe);
     }
 
     addEventListener("load", function() {
       info("Got load event.");
 
-      let whitelist;
-      try {
-        whitelist =
-          SpecialPowers.getCharPref("dom.mozBrowserFramesWhitelist") + ", ";
-      } catch (e) {
-        whitelist = "";
-      }
-
-      whitelist += window.location.protocol + "//" + window.location.host;
-
+      SpecialPowers.addPermission("browser", true, document);
       SpecialPowers.pushPrefEnv({
         "set": [
           ["dom.ipc.browser_frames.oop_by_default", true],
           ["dom.mozBrowserFramesEnabled", true],
-          ["dom.mozBrowserFramesWhitelist", whitelist],
           ["browser.pageThumbs.enabled", false]
         ]
       }, runTests);
     });
   </script>
 </body>
 </html>
--- a/content/canvas/test/webgl/conformance/attribs/gl-enable-vertex-attrib.html
+++ b/content/canvas/test/webgl/conformance/attribs/gl-enable-vertex-attrib.html
@@ -45,13 +45,13 @@ gl.vertexAttribPointer(0, 3, gl.FLOAT, f
 gl.enableVertexAttribArray(3);
 glErrorShouldBe(gl, gl.NO_ERROR);
 
 gl.drawArrays(gl.TRIANGLES, 0, 3);
 glErrorShouldBe(gl, gl.INVALID_OPERATION);
 
 successfullyParsed = true;
 </script>
-<script src="../../resources/js-test-post.js"></script>
+<script>finishTest();</script>
 
 </body>
 </html>
 
--- a/content/canvas/test/webgl/conformance/attribs/gl-vertex-attrib-zero-issues.html
+++ b/content/canvas/test/webgl/conformance/attribs/gl-vertex-attrib-zero-issues.html
@@ -79,13 +79,13 @@ for (var ii = 0; ii < 5; ++ii) {
       gl, gl.NO_ERROR,
       "drawing using attrib 3 with 60000 verts");
 }
 
 wtu.checkCanvas(gl, [0, 0, 0, 0], "canvas should be 0, 0, 0, 0");
 
 successfullyParsed = true;
 </script>
-<script src="../../resources/js-test-post.js"></script>
+<script>finishTest();</script>
 
 </body>
 </html>
 
--- a/content/canvas/test/webgl/conformance/attribs/gl-vertex-attrib.html
+++ b/content/canvas/test/webgl/conformance/attribs/gl-vertex-attrib.html
@@ -83,12 +83,12 @@ if (!gl) {
   }
   glErrorShouldBe(gl, gl.NO_ERROR);
 }
 
 debug("");
 successfullyParsed = true;
 
 </script>
-<script src="../../resources/js-test-post.js"></script>
+<script>finishTest();</script>
 
 </body>
 </html>
--- a/content/canvas/test/webgl/conformance/attribs/gl-vertexattribpointer-offsets.html
+++ b/content/canvas/test/webgl/conformance/attribs/gl-vertexattribpointer-offsets.html
@@ -182,12 +182,12 @@ There is supposed to be an example drawi
                 }
               }
             }
        }
 
        init();
        successfullyParsed = true;
     </script>
-<script src="../../resources/js-test-post.js"></script>
+<script>finishTest();</script>
 
 </body>
 </html>
--- a/content/canvas/test/webgl/conformance/attribs/gl-vertexattribpointer.html
+++ b/content/canvas/test/webgl/conformance/attribs/gl-vertexattribpointer.html
@@ -122,12 +122,12 @@ if (!gl) {
     }
   }
 }
 
 debug("");
 successfullyParsed = true;
 
 </script>
-<script src="../../resources/js-test-post.js"></script>
+<script>finishTest();</script>
 
 </body>
 </html>
--- a/content/canvas/test/webgl/conformance/buffers/buffer-bind-test.html
+++ b/content/canvas/test/webgl/conformance/buffers/buffer-bind-test.html
@@ -51,13 +51,13 @@ if (!gl) {
   gl.bindBuffer(gl.ARRAY_BUFFER, buf);
   glErrorShouldBe(gl, gl.INVALID_OPERATION,
             "should get INVALID_OPERATION if attempting to bind buffer to different target");
 }
 
 debug("");
 successfullyParsed = true;
 </script>
-<script src="../../resources/js-test-post.js"></script>
+<script>finishTest();</script>
 
 </body>
 </html>
 
--- a/content/canvas/test/webgl/conformance/buffers/buffer-data-array-buffer.html
+++ b/content/canvas/test/webgl/conformance/buffers/buffer-data-array-buffer.html
@@ -57,11 +57,11 @@ gl.bufferSubData(gl.ARRAY_BUFFER, 10, ar
 glErrorShouldBe(gl, gl.NO_ERROR);
 
 gl.bufferSubData(gl.ARRAY_BUFFER, 10, null);
 glErrorShouldBe(gl, gl.NO_ERROR);
 
 successfullyParsed = true;
 </script>
 
-<script src="../../resources/js-test-post.js"></script>
+<script>finishTest();</script>
 </body>
 </html>
--- a/content/canvas/test/webgl/conformance/buffers/index-validation-copies-indices.html
+++ b/content/canvas/test/webgl/conformance/buffers/index-validation-copies-indices.html
@@ -66,11 +66,11 @@ indices[5] = 1;
 shouldGenerateGLError(context, context.NO_ERROR, "context.drawElements(context.TRIANGLE_STRIP, 4, context.UNSIGNED_SHORT, 2)");
 shouldGenerateGLError(context, context.INVALID_OPERATION, "context.drawElements(context.TRIANGLE_STRIP, 4, context.UNSIGNED_SHORT, 0)");
 shouldGenerateGLError(context, context.INVALID_OPERATION, "context.drawElements(context.TRIANGLE_STRIP, 4, context.UNSIGNED_SHORT, 4)");
 
 debug("")
 successfullyParsed = true;
 </script>
 
-<script src="../../resources/js-test-post.js"></script>
+<script>finishTest();</script>
 </body>
 </html>
--- a/content/canvas/test/webgl/conformance/buffers/index-validation-crash-with-buffer-sub-data.html
+++ b/content/canvas/test/webgl/conformance/buffers/index-validation-crash-with-buffer-sub-data.html
@@ -25,11 +25,11 @@ gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, e
 gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, 256, gl.STATIC_DRAW);
 var data = new Uint8Array(127);
 gl.bufferSubData(gl.ELEMENT_ARRAY_BUFFER, 63, data);
 testPassed("bufferSubData, when buffer object was initialized with null, did not crash");
 
 successfullyParsed = true;
 </script>
 
-<script src="../../resources/js-test-post.js"></script>
+<script>finishTest();</script>
 </body>
 </html>
--- a/content/canvas/test/webgl/conformance/buffers/index-validation-verifies-too-many-indices.html
+++ b/content/canvas/test/webgl/conformance/buffers/index-validation-verifies-too-many-indices.html
@@ -37,11 +37,11 @@ context.bufferData(context.ELEMENT_ARRAY
 shouldGenerateGLError(context, context.NO_ERROR, "context.drawElements(context.TRIANGLE_STRIP, 4, context.UNSIGNED_SHORT, 2)");
 shouldGenerateGLError(context, context.INVALID_OPERATION, "context.drawElements(context.TRIANGLE_STRIP, 4, context.UNSIGNED_SHORT, 0)");
 shouldGenerateGLError(context, context.INVALID_OPERATION, "context.drawElements(context.TRIANGLE_STRIP, 4, context.UNSIGNED_SHORT, 4)");
 
 debug("")
 successfullyParsed = true;
 </script>
 
-<script src="../../resources/js-test-post.js"></script>
+<script>finishTest();</script>
 </body>
 </html>
--- a/content/canvas/test/webgl/conformance/buffers/index-validation-with-resized-buffer.html
+++ b/content/canvas/test/webgl/conformance/buffers/index-validation-with-resized-buffer.html
@@ -94,11 +94,11 @@ gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, i
 glErrorShouldBe(gl, gl.NO_ERROR, "after setting up indices");
 gl.drawElements(gl.TRIANGLES, numQuads * 6, gl.UNSIGNED_BYTE, 0);
 glErrorShouldBe(gl, gl.NO_ERROR, "after drawing");
 
 debug("")
 successfullyParsed = true;
 </script>
 
-<script src="../../resources/js-test-post.js"></script>
+<script>finishTest();</script>
 </body>
 </html>
--- a/content/canvas/test/webgl/conformance/buffers/index-validation.html
+++ b/content/canvas/test/webgl/conformance/buffers/index-validation.html
@@ -131,11 +131,11 @@ shouldBeUndefined('gl.drawElements(gl.TR
 debug("Pass large negative index to vertexAttribPointer");
 gl.vertexAttribPointer(normalLoc, 3, gl.FLOAT, false, 7 * sizeInBytes(gl.FLOAT), -2000000000 * sizeInBytes(gl.FLOAT));
 glErrorShouldBe(gl, gl.INVALID_VALUE);
 shouldBeUndefined('gl.drawElements(gl.TRIANGLES, 3, gl.UNSIGNED_SHORT, 0)');
 
 successfullyParsed = true;
 </script>
 
-<script src="../../resources/js-test-post.js"></script>
+<script>finishTest();</script>
 </body>
 </html>
--- a/content/canvas/test/webgl/conformance/canvas/canvas-zero-size.html
+++ b/content/canvas/test/webgl/conformance/canvas/canvas-zero-size.html
@@ -31,12 +31,12 @@ gl.bindTexture(gl.TEXTURE_2D, tex);
 var pixel = new Uint8Array([0, 255, 0, 255]);
 gl.texImage2D(
   gl.TEXTURE_2D, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, pixel);
 wtu.drawQuad(gl);
 
 glErrorShouldBe(gl, gl.NO_ERROR, "Should be no errors from setup.");
 successfullyParsed = true;
 </script>
-<script src="../../resources/js-test-post.js"></script>
+<script>finishTest();</script>
 
 </body>
 </html>
--- a/content/canvas/test/webgl/conformance/canvas/drawingbuffer-static-canvas-test.html
+++ b/content/canvas/test/webgl/conformance/canvas/drawingbuffer-static-canvas-test.html
@@ -138,11 +138,11 @@ if (!gl) {
   shouldBeTrue('gl.drawingBufferHeight == 50');
   shouldBe('gl.getError()', 'gl.NO_ERROR');
   drawTriangleTest(gl);
   shouldBe('gl.getError()', 'gl.NO_ERROR');
 }
 debug("")
 successfullyParsed = true;
 </script>
-<script src="../../resources/js-test-post.js"></script>
+<script>finishTest();</script>
 </body>
 </html>
--- a/content/canvas/test/webgl/conformance/canvas/drawingbuffer-test.html
+++ b/content/canvas/test/webgl/conformance/canvas/drawingbuffer-test.html
@@ -137,11 +137,11 @@ if (!gl) {
   shouldBeTrue('gl.drawingBufferHeight == 50');
   shouldBe('gl.getError()', 'gl.NO_ERROR');
   drawTriangleTest(gl);
   shouldBe('gl.getError()', 'gl.NO_ERROR');
 }
 debug("")
 successfullyParsed = true;
 </script>
-<script src="../../resources/js-test-post.js"></script>
+<script>finishTest();</script>
 </body>
 </html>
--- a/content/canvas/test/webgl/conformance/canvas/viewport-unchanged-upon-resize.html
+++ b/content/canvas/test/webgl/conformance/canvas/viewport-unchanged-upon-resize.html
@@ -101,12 +101,12 @@ if (passed) {
     if (passed) {
       testPassed("Viewport correctly did not change size during canvas resize");
     }
   }
 }
 
 successfullyParsed = true;
 </script>
-<script src="../../resources/js-test-post.js"></script>
+<script>finishTest();</script>
 </body>
 </html>
 
--- a/content/canvas/test/webgl/conformance/context/constants.html
+++ b/content/canvas/test/webgl/conformance/context/constants.html
@@ -474,12 +474,12 @@ for (var i in gl) {
     }
     debug(i);
   }
 }
 
 debug("");
 successfullyParsed = true;
 </script>
-<script src="../../resources/js-test-post.js"></script>
+<script>finishTest();</script>
 
 </body>
 </html>
--- a/content/canvas/test/webgl/conformance/context/context-type-test.html
+++ b/content/canvas/test/webgl/conformance/context/context-type-test.html
@@ -38,12 +38,12 @@ if (!gl) {
 
   debug("Checking context type");
   assertMsg(gl instanceof WebGLRenderingContext,
             "context type should be WebGLRenderingContext");
 }
 debug("");
 successfullyParsed = true;
 </script>
-<script src="../../resources/js-test-post.js"></script>
+<script>finishTest();</script>
 
 </body>
 </html>
--- a/content/canvas/test/webgl/conformance/context/incorrect-context-object-behaviour.html
+++ b/content/canvas/test/webgl/conformance/context/incorrect-context-object-behaviour.html
@@ -73,11 +73,11 @@ shouldGenerateGLError(contextA, contextA
 shouldGenerateGLError(contextA, contextA.INVALID_OPERATION, "contextA.getShaderInfoLog(shaderB, 0)");
 shouldGenerateGLError(contextA, contextA.INVALID_OPERATION, "contextA.getShaderSource(shaderB)");
 shouldGenerateGLError(contextA, contextA.INVALID_OPERATION, "contextA.getUniform(programB, locationA)");
 shouldGenerateGLError(contextA, contextA.INVALID_OPERATION, "contextA.getUniformLocation(programB, 'u_modelViewProjMatrix')");
 
 successfullyParsed = true;
 </script>
 
-<script src="../../resources/js-test-post.js"></script>
+<script>finishTest();</script>
 </body>
 </html>
--- a/content/canvas/test/webgl/conformance/context/methods.html
+++ b/content/canvas/test/webgl/conformance/context/methods.html
@@ -189,12 +189,12 @@ for (var i in gl) {
     }
     debug(i);
   }
 }
 
 debug("");
 successfullyParsed = true;
 </script>
-<script src="../../resources/js-test-post.js"></script>
+<script>finishTest();</script>
 
 </body>
 </html>
--- a/content/canvas/test/webgl/conformance/context/resource-sharing-test.html
+++ b/content/canvas/test/webgl/conformance/context/resource-sharing-test.html
@@ -30,12 +30,12 @@ assertMsg(gl1 && gl2,
 var vertexObject = gl1.createBuffer();
 gl2.bindBuffer(gl2.ARRAY_BUFFER, vertexObject);
 assertMsg(
   gl2.getError() == gl2.INVALID_OPERATION,
   "attempt to use a resource from the wrong context should fail with INVALID_OPERATION");
 
 successfullyParsed = true;
 </script>
-<script src="../../resources/js-test-post.js"></script>
+<script>finishTest();</script>
 </body>
 </html>
 
--- a/content/canvas/test/webgl/conformance/extensions/ext-texture-filter-anisotropic.html
+++ b/content/canvas/test/webgl/conformance/extensions/ext-texture-filter-anisotropic.html
@@ -166,12 +166,12 @@ function runHintTestEnabled() {
     }
 
     gl.deleteTexture(texture);
 }
 
 debug("");
 successfullyParsed = true;
 </script>
-<script src="../../resources/js-test-post.js"></script>
+<script>finishTest();</script>
 
 </body>
 </html>
--- a/content/canvas/test/webgl/conformance/extensions/oes-standard-derivatives.html
+++ b/content/canvas/test/webgl/conformance/extensions/oes-standard-derivatives.html
@@ -363,12 +363,12 @@ function runReferenceCycleTest()
 
     // create a self-cycle on the extension object
     ext.ext = ext;
 }
 
 debug("");
 successfullyParsed = true;
 </script>
-<script src="../../resources/js-test-post.js"></script>
+<script>finishTest();</script>
 
 </body>
 </html>
--- a/content/canvas/test/webgl/conformance/extensions/oes-texture-float.html
+++ b/content/canvas/test/webgl/conformance/extensions/oes-texture-float.html
@@ -204,12 +204,12 @@ function runReferenceCycleTest()
 
     // create a self-cycle on the extension object
     ext.ext = ext;
 }
 
 debug("");
 successfullyParsed = true;
 </script>
-<script src="../../resources/js-test-post.js"></script>
+<script>finishTest();</script>
 
 </body>
 </html>
--- a/content/canvas/test/webgl/conformance/extensions/oes-vertex-array-object.html
+++ b/content/canvas/test/webgl/conformance/extensions/oes-vertex-array-object.html
@@ -399,12 +399,12 @@ function runDrawTests() {
     ext.bindVertexArrayOES(null);
     ext.deleteVertexArrayOES(vao0);
     ext.deleteVertexArrayOES(vao1);
 }
 
 debug("");
 successfullyParsed = true;
 </script>
-<script src="../../resources/js-test-post.js"></script>
+<script>finishTest();</script>
 
 </body>
 </html>
--- a/content/canvas/test/webgl/conformance/extensions/webgl-compressed-texture-s3tc.html
+++ b/content/canvas/test/webgl/conformance/extensions/webgl-compressed-texture-s3tc.html
@@ -603,12 +603,12 @@ function compareRect(
 
 function testPVRTCTextures() {
     testFailed("PVRTC test not yet implemented");
 }
 
 debug("");
 successfullyParsed = true;
 </script>
-<script src="../../resources/js-test-post.js"></script>
+<script>finishTest();</script>
 
 </body>
 </html>
--- a/content/canvas/test/webgl/conformance/extensions/webgl-debug-renderer-info.html
+++ b/content/canvas/test/webgl/conformance/extensions/webgl-debug-renderer-info.html
@@ -93,12 +93,12 @@ function runTestEnabled() {
     shouldBe("ext.UNMASKED_RENDERER_WEBGL", "0x9246");
     gl.getParameter(ext.UNMASKED_RENDERER_WEBGL);
     glErrorShouldBe(gl, gl.NO_ERROR, "UNMASKED_RENDERER_WEBGL query should succeed if extension is enable");
 }
 
 debug("");
 successfullyParsed = true;
 </script>
-<script src="../../resources/js-test-post.js"></script>
+<script>finishTest();</script>
 
 </body>
 </html>
--- a/content/canvas/test/webgl/conformance/extensions/webgl-debug-shaders.html
+++ b/content/canvas/test/webgl/conformance/extensions/webgl-debug-shaders.html
@@ -86,12 +86,12 @@ function runTestEnabled() {
         testPassed("Successfully called getTranslatedShaderSource()");
     else
         testFailed("Calling getTranslatedShaderSource() failed");
 }
 
 debug("");
 successfullyParsed = true;
 </script>
-<script src="../../resources/js-test-post.js"></script>
+<script>finishTest();</script>
 
 </body>
 </html>
--- a/content/canvas/test/webgl/conformance/glsl/misc/attrib-location-length-limits.html
+++ b/content/canvas/test/webgl/conformance/glsl/misc/attrib-location-length-limits.html
@@ -72,11 +72,11 @@ wtu.glErrorShouldBe(gl, gl.INVALID_VALUE
 
 debug("Attempt to fetch too-long attrib location should produce error");
 program = wtu.loadStandardProgram(gl);
 shouldBe('gl.getAttribLocation(program, "vPosition01234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567")', '-1');
 wtu.glErrorShouldBe(gl, gl.INVALID_VALUE);
 
 successfullyParsed = true;
 </script>
-<script src="../../../resources/js-test-post.js"></script>
+<script>finishTest();</script>
 </body>
 </html>
--- a/content/canvas/test/webgl/conformance/glsl/misc/glsl-2types-of-textures-on-same-unit.html
+++ b/content/canvas/test/webgl/conformance/glsl/misc/glsl-2types-of-textures-on-same-unit.html
@@ -125,13 +125,13 @@ function init()
     glErrorShouldBe(gl, gl.INVALID_OPERATION,
               "drawing with 2 different targets on the same texture unit should generate INVALID_VALUE");
   }
 }
 
 init();
 successfullyParsed = true;
 </script>
-<script src="../../../resources/js-test-post.js"></script>
+<script>finishTest();</script>
 
 </body>
 </html>
 
--- a/content/canvas/test/webgl/conformance/glsl/misc/glsl-function-nodes.html
+++ b/content/canvas/test/webgl/conformance/glsl/misc/glsl-function-nodes.html
@@ -128,12 +128,12 @@ function init()
         else
             testPassed("Rendering results are the same");
     }
 }
 
 init();
 successfullyParsed = true;
 </script>
-<script src="../../../resources/js-test-post.js"></script>
+<script>finishTest();</script>
 </body>
 </html>
 
--- a/content/canvas/test/webgl/conformance/glsl/misc/glsl-long-variable-names.html
+++ b/content/canvas/test/webgl/conformance/glsl/misc/glsl-long-variable-names.html
@@ -239,11 +239,11 @@
                     return;
                 }
 
             pass();
         }
 
         successfullyParsed = true;
     </script>
-    <script src="../../../resources/js-test-post.js"></script>
+    <script>finishTest();</script>
 </body>
 </html>
--- a/content/canvas/test/webgl/conformance/glsl/misc/glsl-vertex-branch.html
+++ b/content/canvas/test/webgl/conformance/glsl/misc/glsl-vertex-branch.html
@@ -119,12 +119,12 @@ function init()
         else
             testPassed("Rendering results are the same");
     }
 }
 
 init();
 successfullyParsed = true;
 </script>
-<script src="../../../resources/js-test-post.js"></script>
+<script>finishTest();</script>
 </body>
 </html>
 
--- a/content/canvas/test/webgl/conformance/glsl/misc/re-compile-re-link.html
+++ b/content/canvas/test/webgl/conformance/glsl/misc/re-compile-re-link.html
@@ -138,14 +138,14 @@ for (var i = 0; i < 10; ++i) {
   gl.linkProgram(program);
   checkProgramStatus(program)
 }
 
 glErrorShouldBe(gl, gl.NO_ERROR, "Should be no errors");
 
 successfullyParsed = true;
 </script>
-<script src="../../../resources/js-test-post.js"></script>
+<script>finishTest();</script>
 
 </body>
 </html>
 
 
--- a/content/canvas/test/webgl/conformance/glsl/misc/uniform-location-length-limits.html
+++ b/content/canvas/test/webgl/conformance/glsl/misc/uniform-location-length-limits.html
@@ -75,11 +75,11 @@ program = wtu.loadProgramFromScript(gl, 
 wtu.glErrorShouldBe(gl, gl.NONE);
 shouldBe('gl.getProgramParameter(program, gl.LINK_STATUS)', 'true');
 var uniformLoc = gl.getUniformLocation(program, "identifier128CharactersLong_0123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789.identifier64CharactersLong_0123456789012345678901234567890123456.identifier63CharactersLong_012345678901234567890123456789012345");
 wtu.glErrorShouldBe(gl, gl.INVALID_VALUE);
 shouldBeNull('uniformLoc');
 
 successfullyParsed = true;
 </script>
-<script src="../../../resources/js-test-post.js"></script>
+<script>finishTest();</script>
 </body>
 </html>
--- a/content/canvas/test/webgl/conformance/glsl/samplers/glsl-function-texture2d-bias.html
+++ b/content/canvas/test/webgl/conformance/glsl/samplers/glsl-function-texture2d-bias.html
@@ -89,14 +89,14 @@ for (var ii = 0; ii < colors.length; ++i
       "256x256 texture drawn to 256x256 dest with bias = " + ii +
       " should be " + color.name);
 }
 glErrorShouldBe(gl, gl.NO_ERROR, "Should be no errors.");
 
 successfullyParsed = true;
 
 </script>
-<script src="../../../resources/js-test-post.js"></script>
+<script>finishTest();</script>
 
 </body>
 </html>
 
 
--- a/content/canvas/test/webgl/conformance/glsl/samplers/glsl-function-texture2dlod.html
+++ b/content/canvas/test/webgl/conformance/glsl/samplers/glsl-function-texture2dlod.html
@@ -89,14 +89,14 @@ for (var ii = 0; ii < colors.length; ++i
       "256x256 texture drawn to 256x256 dest with lod = " + ii +
       " should be " + color.name);
 }
 glErrorShouldBe(gl, gl.NO_ERROR, "Should be no errors.");
 
 successfullyParsed = true;
 
 </script>
-<script src="../../../resources/js-test-post.js"></script>
+<script>finishTest();</script>
 
 </body>
 </html>
 
 
--- a/content/canvas/test/webgl/conformance/glsl/samplers/glsl-function-texture2dproj.html
+++ b/content/canvas/test/webgl/conformance/glsl/samplers/glsl-function-texture2dproj.html
@@ -104,14 +104,14 @@ for (var ss = 0; ss < 2; ++ss) {
 	}
   }
 }
 glErrorShouldBe(gl, gl.NO_ERROR, "Should be no errors.");
 
 successfullyParsed = true;
 
 </script>
-<script src="../../../resources/js-test-post.js"></script>
+<script>finishTest();</script>
 
 </body>
 </html>
 
 
--- a/content/canvas/test/webgl/conformance/glsl/variables/gl-fragcoord.html
+++ b/content/canvas/test/webgl/conformance/glsl/variables/gl-fragcoord.html
@@ -76,12 +76,12 @@ found in the LICENSE file.
               gl, xx, yy, 1, 1, color, msg, 4);
         }
       }
     }
 
     init();
     successfullyParsed = true;
   </script>
-<script src="../../../resources/js-test-post.js"></script>
+<script>finishTest();</script>
 
 </body>
 </html>
--- a/content/canvas/test/webgl/conformance/glsl/variables/gl-frontfacing.html
+++ b/content/canvas/test/webgl/conformance/glsl/variables/gl-frontfacing.html
@@ -77,12 +77,12 @@ found in the LICENSE file.
           }
         }
       }
     }
 
     init();
     successfullyParsed = true;
   </script>
-<script src="../../../resources/js-test-post.js"></script>
+<script>finishTest();</script>
 
 </body>
 </html>
--- a/content/canvas/test/webgl/conformance/glsl/variables/gl-pointcoord.html
+++ b/content/canvas/test/webgl/conformance/glsl/variables/gl-pointcoord.html
@@ -130,12 +130,12 @@ found in the LICENSE file.
             wtu.checkCanvasRect(gl, xf, yf, 1, 1, color, msg, 4);
           }
         }
       }
     }
 
     successfullyParsed = true;
   </script>
-  <script src="../../../resources/js-test-post.js"></script>
+  <script>finishTest();</script>
 
 </body>
 </html>
--- a/content/canvas/test/webgl/conformance/limits/gl-max-texture-dimensions.html
+++ b/content/canvas/test/webgl/conformance/limits/gl-max-texture-dimensions.html
@@ -84,14 +84,14 @@ var program = wtu.setupProgram(
 glErrorShouldBe(gl, gl.NO_ERROR, "Should be no errors.");
 
 // NOTE: We can't easily test cube maps because they require width == height
 // and we might not have enough memory for maxSize by maxSize texture.
 
 successfullyParsed = true;
 
 </script>
-<script src="../../resources/js-test-post.js"></script>
+<script>finishTest();</script>
 
 </body>
 </html>
 
 
--- a/content/canvas/test/webgl/conformance/limits/gl-min-attribs.html
+++ b/content/canvas/test/webgl/conformance/limits/gl-min-attribs.html
@@ -72,14 +72,14 @@ for (var ii = 0; ii < 7; ++ii) {
 wtu.drawQuad(gl);
 glErrorShouldBe(gl, gl.NO_ERROR, "Should be no errors from setup.");
 wtu.checkCanvasRect(gl, 0, 0, gl.canvas.width, gl.canvas.height, [255, 127, 64, 32], "Should render 255,127,64,32 (+/-1)", 1);
 
 successfullyParsed = true;
 
 </script>
 </body>
-<script src="../../resources/js-test-post.js"></script>
+<script>finishTest();</script>
 
 </body>
 </html>
 
 
--- a/content/canvas/test/webgl/conformance/limits/gl-min-textures.html
+++ b/content/canvas/test/webgl/conformance/limits/gl-min-textures.html
@@ -59,14 +59,14 @@ for (var ii = 0; ii < 8; ++ii) {
 wtu.drawQuad(gl);
 glErrorShouldBe(gl, gl.NO_ERROR, "Should be no errors from setup.");
 wtu.checkCanvas(gl, [255, 128, 64, 252],
                 "Should render using all texture units", 1);
 
 successfullyParsed = true;
 
 </script>
-<script src="../../resources/js-test-post.js"></script>
+<script>finishTest();</script>
 
 </body>
 </html>
 
 
--- a/content/canvas/test/webgl/conformance/limits/gl-min-uniforms.html
+++ b/content/canvas/test/webgl/conformance/limits/gl-min-uniforms.html
@@ -91,14 +91,14 @@ for (var ii = 0; ii < 16; ++ii) {
 glErrorShouldBe(gl, gl.NO_ERROR, "Should be no errors from setup.");
 wtu.drawQuad(gl);
 glErrorShouldBe(gl, gl.NO_ERROR, "Should be no errors from setup.");
 wtu.checkCanvasRect(gl, 0, 0, gl.canvas.width, gl.canvas.height, [32, 64, 127, 255], "Should render 32,64,127,255 (+/-1)", 1);
 
 successfullyParsed = true;
 
 </script>
-<script src="../../resources/js-test-post.js"></script>
+<script>finishTest();</script>
 
 </body>
 </html>
 
 
--- a/content/canvas/test/webgl/conformance/misc/bad-arguments-test.html
+++ b/content/canvas/test/webgl/conformance/misc/bad-arguments-test.html
@@ -107,11 +107,11 @@ for (var i = 0; i < arguments.length; ++
   func3("context.getProgramInfoLog(argument)");
   func3("context.getShaderInfoLog(argument)");
   func3("context.getShaderSource(argument)");
 }
 
 successfullyParsed = true;
 </script>
 
-<script src="../../resources/js-test-post.js"></script>
+<script>finishTest();</script>
 </body>
 </html>
--- a/content/canvas/test/webgl/conformance/misc/error-reporting.html
+++ b/content/canvas/test/webgl/conformance/misc/error-reporting.html
@@ -90,11 +90,11 @@ shouldBeUndefined("context.framebufferTe
 // Synthetic OpenGL error
 glErrorShouldBe(context, context.INVALID_OPERATION);
 // Error state should be clear by this point
 glErrorShouldBe(context, context.NO_ERROR);
 
 successfullyParsed = true;
 </script>
 
-<script src="../../resources/js-test-post.js"></script>
+<script>finishTest();</script>
 </body>
 </html>
--- a/content/canvas/test/webgl/conformance/misc/functions-returning-strings.html
+++ b/content/canvas/test/webgl/conformance/misc/functions-returning-strings.html
@@ -92,12 +92,12 @@ if (!gl) {
   shouldReturnString("gl.getParameter(gl.VERSION)");
   shouldReturnString("gl.getParameter(gl.SHADING_LANGUAGE_VERSION)");
 }
 
 debug("");
 successfullyParsed = true;
 
 </script>
-<script src="../../resources/js-test-post.js"></script>
+<script>finishTest();</script>
 
 </body>
 </html>
--- a/content/canvas/test/webgl/conformance/misc/instanceof-test.html
+++ b/content/canvas/test/webgl/conformance/misc/instanceof-test.html
@@ -76,14 +76,14 @@ shouldThrowWithNew(window.WebGLProgram, 
 shouldThrowWithNew(window.WebGLRenderbuffer, 'WebGLRenderbuffer');
 shouldThrowWithNew(window.WebGLShader, 'WebGLShader');
 shouldThrowWithNew(window.WebGLTexture, 'WebGLTexture');
 shouldThrowWithNew(window.WebGLUniformLocation, 'WebGLUniformLocation');
 shouldThrowWithNew(window.WebGLShaderPrecisionFormat, 'WebGLShaderPrecisionFormat');
 
 successfullyParsed = true;
 </script>
-<script src="../../resources/js-test-post.js"></script>
+<script>finishTest();</script>
 
 </body>
 </html>
 
 
--- a/content/canvas/test/webgl/conformance/misc/invalid-passed-params.html
+++ b/content/canvas/test/webgl/conformance/misc/invalid-passed-params.html
@@ -183,11 +183,11 @@ for (var i = 0; i < invalidSet.length; +
   context.getUniformLocation(program, invalidName);
   shouldBe("context.getError()", "context.INVALID_VALUE");
 }
 
 debug("")
 successfullyParsed = true;
 </script>
 
-<script src="../../resources/js-test-post.js"></script>
+<script>finishTest();</script>
 </body>
 </html>
--- a/content/canvas/test/webgl/conformance/misc/is-object.html
+++ b/content/canvas/test/webgl/conformance/misc/is-object.html
@@ -63,11 +63,11 @@ debug("");
 shouldGenerateGLError(gl, gl.NO_ERROR, "shader = gl.createShader(gl.VERTEX_SHADER)");
 shouldBeTrue("gl.isShader(shader)");
 shouldGenerateGLError(gl, gl.NO_ERROR, "gl.deleteShader(shader)");
 shouldBeFalse("gl.isShader(shader)");
 debug("");
 
 successfullyParsed = true;
 </script>
-<script src="../../resources/js-test-post.js"></script>
+<script>finishTest();</script>
 </body>
 </html>
--- a/content/canvas/test/webgl/conformance/misc/null-object-behaviour.html
+++ b/content/canvas/test/webgl/conformance/misc/null-object-behaviour.html
@@ -97,11 +97,11 @@ shouldGenerateGLError(context, context.I
 shouldGenerateGLError(context, context.INVALID_OPERATION, "context.texImage2D(context.TEXTURE_2D, 0, context.RGBA, 1, 1, 0, context.RGBA, context.UNSIGNED_BYTE, new Uint8Array([0,0,0,0]))");
 shouldGenerateGLError(context, context.INVALID_OPERATION, "context.texParameteri(context.TEXTURE_2D, context.TEXTURE_MIN_FILTER, context.NEAREST)");
 shouldGenerateGLError(context, context.INVALID_OPERATION, "context.getTexParameter(context.TEXTURE_2D, context.TEXTURE_MIN_FILTER)");
 
 
 successfullyParsed = true;
 </script>
 
-<script src="../../resources/js-test-post.js"></script>
+<script>finishTest();</script>
 </body>
 </html>
--- a/content/canvas/test/webgl/conformance/misc/object-deletion-behaviour.html
+++ b/content/canvas/test/webgl/conformance/misc/object-deletion-behaviour.html
@@ -418,11 +418,11 @@ if (gl.checkFramebufferStatus(gl.FRAMEBU
   shouldGenerateGLError(gl, gl.NO_ERROR, "gl.bindFramebuffer(gl.FRAMEBUFFER, null)");
   // check again because many buggy implementations will have bound to the true backbuffer on deleteFramebuffer.
   shouldGenerateGLError(gl, gl.NO_ERROR, 'wtu.checkCanvasRect(gl, 0, 0, 300, 150, [0,255,0,255], "fbo should be green")');
 }
 
 successfullyParsed = true;
 </script>
 
-<script src="../../resources/js-test-post.js"></script>
+<script>finishTest();</script>
 </body>
 </html>
--- a/content/canvas/test/webgl/conformance/misc/type-conversion-test.html
+++ b/content/canvas/test/webgl/conformance/misc/type-conversion-test.html
@@ -159,12 +159,12 @@ for (var i = 0; i < args.length; ++i) {
   func1("context.uniform4f(loc, 0, argument, 0, 0)");
   func1("context.uniform4f(loc, 0, 0, argument, 0)");
   func1("context.uniform4f(loc, 0, 0, 0, argument)");
 }
 
 successfullyParsed = true;
 </script>
 
-<script src="../../resources/js-test-post.js"></script>
+<script>finishTest();</script>
 </body>
 </html>
 
--- a/content/canvas/test/webgl/conformance/misc/uninitialized-test.html
+++ b/content/canvas/test/webgl/conformance/misc/uninitialized-test.html
@@ -159,12 +159,12 @@ glErrorShouldBe(gl, gl.NO_ERROR);
 //TODO: uninitialized vertex elements buffer
 //TODO: uninitialized framebuffer? (implementations would need to do a GL clear at first binding?)
 //TODO: uninitialized renderbuffer? (implementations would need to do a GL clear at first binding?)
 //TODO: uninitialized uniform arrays?
 
 debug("");
 successfullyParsed = true;
 </script>
-<script src="../../resources/js-test-post.js"></script>
+<script>finishTest();</script>
 </body>
 </html>
 
--- a/content/canvas/test/webgl/conformance/misc/webgl-specific.html
+++ b/content/canvas/test/webgl/conformance/misc/webgl-specific.html
@@ -94,11 +94,11 @@ glErrorShouldBe(gl, gl.NO_ERROR, "set/ge
 
 debug("");
 debug("Verify that drawingBufferWidth and drawingBufferHeights are implemented");
 shouldBeTrue("gl.drawingBufferWidth >= 0 && gl.drawingBufferHeight >= 0");
 
 successfullyParsed = true;
 </script>
 
-<script src="../../resources/js-test-post.js"></script>
+<script>finishTest();</script>
 </body>
 </html>
--- a/content/canvas/test/webgl/conformance/programs/get-active-test.html
+++ b/content/canvas/test/webgl/conformance/programs/get-active-test.html
@@ -125,11 +125,11 @@ context.deleteProgram(program);
 shouldBeNull("context.getActiveUniform(program, 0)");
 glErrorShouldBe(context, context.INVALID_VALUE);
 shouldBeNull("context.getActiveAttrib(program, 0)");
 glErrorShouldBe(context, context.INVALID_VALUE);
 
 successfullyParsed = true;
 </script>
 
-<script src="../../resources/js-test-post.js"></script>
+<script>finishTest();</script>
 </body>
 </html>
--- a/content/canvas/test/webgl/conformance/programs/gl-bind-attrib-location-test.html
+++ b/content/canvas/test/webgl/conformance/programs/gl-bind-attrib-location-test.html
@@ -190,12 +190,12 @@ gl.vertexAttrib4f(0, 1, 0, 0, 1);
 checkDraw(0, 3, 255, 0, 0, 255);
 
 glErrorShouldBe(gl, gl.NO_ERROR);
 
 debug("");
 successfullyParsed = true;
 
 </script>
-<script src="../../resources/js-test-post.js"></script>
+<script>finishTest();</script>
 
 </body>
 </html>
--- a/content/canvas/test/webgl/conformance/programs/gl-get-active-attribute.html
+++ b/content/canvas/test/webgl/conformance/programs/gl-get-active-attribute.html
@@ -71,14 +71,14 @@ for (var tt = 0; tt < tests.length; ++tt
   }
   if (!found) {
     testFailed("attrib 'attr0' not found");
   }
 }
 
 successfullyParsed = true;
 </script>
-<script src="../../resources/js-test-post.js"></script>
+<script>finishTest();</script>
 
 </body>
 </html>
 
 
--- a/content/canvas/test/webgl/conformance/programs/gl-get-active-uniform.html
+++ b/content/canvas/test/webgl/conformance/programs/gl-get-active-uniform.html
@@ -130,14 +130,14 @@ gl.useProgram(p2);
 gl.uniform1f(l2, 1);
 glErrorShouldBe(gl, gl.NO_ERROR, "no errors setting uniform 0");
 gl.uniform1f(l1, 2);
 glErrorShouldBe(gl, gl.INVALID_OPERATION,
                 "setting a uniform using a location from another program");
 
 successfullyParsed = true;
 </script>
-<script src="../../resources/js-test-post.js"></script>
+<script>finishTest();</script>
 
 </body>
 </html>
 
 
--- a/content/canvas/test/webgl/conformance/programs/gl-getshadersource.html
+++ b/content/canvas/test/webgl/conformance/programs/gl-getshadersource.html
@@ -25,14 +25,14 @@ var gl = wtu.create3DContext("example");
 var original = document.getElementById("vshader").text;
 var shader = gl.createShader(gl.VERTEX_SHADER);
 gl.shaderSource(shader, original);
 var source = gl.getShaderSource(shader);
 shouldBe("source", "original");
 glErrorShouldBe(gl, gl.NO_ERROR, "Should be no errors.");
 successfullyParsed = true;
 </script>
-<script src="../../resources/js-test-post.js"></script>
+<script>finishTest();</script>
 
 </body>
 </html>
 
 
--- a/content/canvas/test/webgl/conformance/programs/gl-shader-test.html
+++ b/content/canvas/test/webgl/conformance/programs/gl-shader-test.html
@@ -37,12 +37,12 @@ if (!gl) {
   assertMsg(shader == null,
             "should not be able to create GEOMETRY shader");
 }
 
 debug("");
 successfullyParsed = true;
 
 </script>
-<script src="../../resources/js-test-post.js"></script>
+<script>finishTest();</script>
 
 </body>
 </html>
--- a/content/canvas/test/webgl/conformance/programs/invalid-UTF-16.html
+++ b/content/canvas/test/webgl/conformance/programs/invalid-UTF-16.html
@@ -40,11 +40,11 @@ var string = array.join('');
 
 var gl = create3DContext();
 var program = gl.createProgram();
 gl.bindAttribLocation(program, 0, string);
 testPassed("bindAttribLocation with invalid UTF-16 did not crash");
 
 successfullyParsed = true;
 </script>
-<script src="../../resources/js-test-post.js"></script>
+<script>finishTest();</script>
 </body>
 </html>
--- a/content/canvas/test/webgl/conformance/programs/program-test.html
+++ b/content/canvas/test/webgl/conformance/programs/program-test.html
@@ -316,12 +316,12 @@ function go() {
     glErrorShouldBe(gl, gl.INVALID_VALUE, "a delete-marked shader should be deleted once all its attachments are removed");
 }
 
 debug("");
 go();
 
 successfullyParsed = true;
 </script>
-<script src="../../resources/js-test-post.js"></script>
+<script>finishTest();</script>
 
 </body>
 </html>
--- a/content/canvas/test/webgl/conformance/reading/read-pixels-pack-alignment.html
+++ b/content/canvas/test/webgl/conformance/reading/read-pixels-pack-alignment.html
@@ -230,11 +230,11 @@ for (var i = 0; i < formats.length; ++i)
     runTestIteration(format, gl.UNSIGNED_BYTE, 1, -1, 1);
     runTestIteration(format, gl.UNSIGNED_BYTE, 2, 1, -1);
     runTestIteration(format, gl.UNSIGNED_BYTE, 4, 0, -1);
     runTestIteration(format, gl.UNSIGNED_BYTE, 8, -1, -1);
 }
     
 successfullyParsed = true;
 </script>
-<script src="../../resources/js-test-post.js"></script>
+<script>finishTest();</script>
 </body>
 </html>
--- a/content/canvas/test/webgl/conformance/renderbuffers/framebuffer-object-attachment.html
+++ b/content/canvas/test/webgl/conformance/renderbuffers/framebuffer-object-attachment.html
@@ -413,11 +413,11 @@ function testFramebufferIncompleteDimens
     checkFramebuffer(gl.FRAMEBUFFER_COMPLETE);
 
     glErrorShouldBe(gl, gl.NO_ERROR);
 }
 
 successfullyParsed = true;
 </script>
 
-<script src="../../resources/js-test-post.js"></script>
+<script>finishTest();</script>
 </body>
 </html>
--- a/content/canvas/test/webgl/conformance/renderbuffers/framebuffer-test.html
+++ b/content/canvas/test/webgl/conformance/renderbuffers/framebuffer-test.html
@@ -162,12 +162,12 @@ if (!gl) {
   glErrorShouldBe(gl, gl.NO_ERROR,
             "binding default (null) framebuffer should succeed.");
 }
 
 debug("");
 successfullyParsed = true;
 
 </script>
-<script src="../../resources/js-test-post.js"></script>
+<script>finishTest();</script>
 
 </body>
 </html>
--- a/content/canvas/test/webgl/conformance/renderbuffers/renderbuffer-initialization.html
+++ b/content/canvas/test/webgl/conformance/renderbuffers/renderbuffer-initialization.html
@@ -88,11 +88,11 @@ function runTest(gl, width, height, orde
     gl.canvas.width += 1;
     gl.canvas.height += 1;
 
     debug('');
 }
 
 successfullyParsed = true;
 </script>
-<script src="../../resources/js-test-post.js"></script>
+<script>finishTest();</script>
 </body>
 </html>
--- a/content/canvas/test/webgl/conformance/rendering/draw-arrays-out-of-bounds.html
+++ b/content/canvas/test/webgl/conformance/rendering/draw-arrays-out-of-bounds.html
@@ -123,11 +123,11 @@ shouldGenerateGLError(context, context.I
 shouldGenerateGLError(context, context.INVALID_OPERATION, "context.drawArrays(context.TRIANGLES, 0, 0x7fffffff)");
 shouldGenerateGLError(context, context.INVALID_OPERATION, "context.drawArrays(context.TRIANGLES, 0x7fffffff, 1)");
 shouldGenerateGLError(context, context.INVALID_OPERATION, "context.drawArrays(context.TRIANGLES, 0x7fffffff, 0x7fffffff)");
 
 debug("")
 successfullyParsed = true;
 </script>
 
-<script src="../../resources/js-test-post.js"></script>
+<script>finishTest();</script>
 </body>
 </html>
--- a/content/canvas/test/webgl/conformance/rendering/draw-elements-out-of-bounds.html
+++ b/content/canvas/test/webgl/conformance/rendering/draw-elements-out-of-bounds.html
@@ -167,11 +167,11 @@ context.vertexAttribPointer(0, 3, contex
 context.disableVertexAttribArray(0);
 shouldGenerateGLError(context, context.NO_ERROR, "context.drawElements(context.TRIANGLES, 6, context.UNSIGNED_SHORT, 2)");
 context.bindBuffer(context.ELEMENT_ARRAY_BUFFER, null);
 shouldGenerateGLError(context, context.INVALID_OPERATION, "context.drawElements(context.TRIANGLES, 6, context.UNSIGNED_SHORT, 2)");
 debug("")
 successfullyParsed = true;
 </script>
 
-<script src="../../resources/js-test-post.js"></script>
+<script>finishTest();</script>
 </body>
 </html>
--- a/content/canvas/test/webgl/conformance/rendering/gl-clear.html
+++ b/content/canvas/test/webgl/conformance/rendering/gl-clear.html
@@ -55,12 +55,12 @@ gl.clearColor(1,1,1,1);
 gl.clear(gl.COLOR_BUFFER_BIT);
 wtu.checkCanvas(gl, [128,128,128,255], "should be 128,128,128,255");
 
 // TODO: Test depth and stencil clearing.
 
 debug("");
 successfullyParsed = true;
 </script>
-<script src="../../resources/js-test-post.js"></script>
+<script>finishTest();</script>
 </body>
 </html>
 
--- a/content/canvas/test/webgl/conformance/rendering/gl-drawelements.html
+++ b/content/canvas/test/webgl/conformance/rendering/gl-drawelements.html
@@ -87,12 +87,12 @@ found in the LICENSE file.
                 gl.TRIANGLES, 3, gl.UNSIGNED_INT,
                 gl.INVALID_ENUM, "gl.DrawElements should return INVALID_ENUM with UNSIGNED_INT");
 
        }
 
        init();
        successfullyParsed = true;
     </script>
-<script src="../../resources/js-test-post.js"></script>
+<script>finishTest();</script>
 
 </body>
 </html>
--- a/content/canvas/test/webgl/conformance/rendering/gl-scissor-test.html
+++ b/content/canvas/test/webgl/conformance/rendering/gl-scissor-test.html
@@ -62,12 +62,12 @@ if (!gl) {
   checkPixel(b, 0, 1, [0, 0, 0, 0]);
   checkPixel(b, 1, 1, [0, 0, 0, 0]);
 }
 
 debug("");
 successfullyParsed = true;
 
 </script>
-<script src="../../resources/js-test-post.js"></script>
+<script>finishTest();</script>
 
 </body>
 </html>
--- a/content/canvas/test/webgl/conformance/rendering/line-loop-tri-fan.html
+++ b/content/canvas/test/webgl/conformance/rendering/line-loop-tri-fan.html
@@ -232,11 +232,11 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE
         <canvas id="testbed" width="10px" height="10px" style="width:50px; height:50px"></canvas>
         <div id="description"></div>
         <div id="console"></div>
         <script>
             description('Verify that LINE_LOOP and TRIANGLE_FAN works correctly.');
             runTest();
             successfullyParsed = true;
         </script>
-        <script src="../../resources/js-test-post.js"></script>
+        <script>finishTest();</script>
     </body>
 </html>
--- a/content/canvas/test/webgl/conformance/rendering/more-than-65536-indices.html
+++ b/content/canvas/test/webgl/conformance/rendering/more-than-65536-indices.html
@@ -81,14 +81,14 @@ gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, i
 wtu.glErrorShouldBe(gl, gl.NO_ERROR, "after setting up indices");
 gl.drawElements(gl.TRIANGLES, numQuads * 6, gl.UNSIGNED_BYTE, 0);
 wtu.glErrorShouldBe(gl, gl.NO_ERROR, "after drawing");
 wtu.checkCanvas(gl, [0, 255, 0, 255], "Should be green.");
 
 successfullyParsed = true;
 </script>
 
-<script src="../../resources/js-test-post.js"></script>
+<script>finishTest();</script>
 
 </body>
 </html>
 
 
--- a/content/canvas/test/webgl/conformance/rendering/point-size.html
+++ b/content/canvas/test/webgl/conformance/rendering/point-size.html
@@ -114,12 +114,12 @@ found in the LICENSE file.
                 index += 4;
             }
         }
     }
 
     successfullyParsed = true;
 </script>
 
-<script src="../../resources/js-test-post.js"></script>
+<script>finishTest();</script>
 
 </body>
 </html>
--- a/content/canvas/test/webgl/conformance/rendering/triangle.html
+++ b/content/canvas/test/webgl/conformance/rendering/triangle.html
@@ -112,12 +112,12 @@ There is supposed to be an example drawi
                 }
 
             pass();
        }
 
        init();
        successfullyParsed = true;
     </script>
-<script src="../../resources/js-test-post.js"></script>
+<script>finishTest();</script>
 
 </body>
 </html>
--- a/content/canvas/test/webgl/conformance/state/gl-enable-enum-test.html
+++ b/content/canvas/test/webgl/conformance/state/gl-enable-enum-test.html
@@ -122,12 +122,12 @@ if (!gl) {
   }
 
 }
 
 debug("");
 successfullyParsed = true;
 
 </script>
-<script src="../../resources/js-test-post.js"></script>
+<script>finishTest();</script>
 
 </body>
 </html>
--- a/content/canvas/test/webgl/conformance/state/gl-enum-tests.html
+++ b/content/canvas/test/webgl/conformance/state/gl-enum-tests.html
@@ -75,13 +75,13 @@ if (!gl) {
               tests[ii] + " should return INVALID_ENUM.");
   }
 }
 
 debug("");
 successfullyParsed = true;
 
 </script>
-<script src="../../resources/js-test-post.js"></script>
+<script>finishTest();</script>
 
 </body>
 </html>
 
--- a/content/canvas/test/webgl/conformance/state/gl-get-calls.html
+++ b/content/canvas/test/webgl/conformance/state/gl-get-calls.html
@@ -145,12 +145,12 @@ else {
     shouldBeTrue('context.getParameter(context.MAX_VIEWPORT_DIMS)[0] >= window.screen.width');
     shouldBeTrue('context.getParameter(context.MAX_VIEWPORT_DIMS)[1] >= window.screen.height');
 }
 
 debug("");
 successfullyParsed = true;
 
 </script>
-<script src="../../resources/js-test-post.js"></script>
+<script>finishTest();</script>
 
 </body>
 </html>
--- a/content/canvas/test/webgl/conformance/state/gl-geterror.html
+++ b/content/canvas/test/webgl/conformance/state/gl-geterror.html
@@ -65,12 +65,12 @@ if (err2 == gl.NO_ERROR) {
                'err5 == gl.INVALID_VALUE || ' +
                'err6 == gl.INVALID_VALUE');
   shouldBeTrue('gl.getError() == gl.NO_ERROR');
 }
 
 debug("");
 successfullyParsed = true;
 </script>
-<script src="../../resources/js-test-post.js"></script>
+<script>finishTest();</script>
 </body>
 </html>
 
--- a/content/canvas/test/webgl/conformance/state/gl-getstring.html
+++ b/content/canvas/test/webgl/conformance/state/gl-getstring.html
@@ -47,12 +47,12 @@ function checkPrefix(expected, enum_val)
     testFailed("getParameter(gl." + enum_val + ") did not start with " + expected);
   }
 }
 
 debug("");
 successfullyParsed = true;
 
 </script>
-<script src="../../resources/js-test-post.js"></script>
+<script>finishTest();</script>
 
 </body>
 </html>
--- a/content/canvas/test/webgl/conformance/state/gl-object-get-calls.html
+++ b/content/canvas/test/webgl/conformance/state/gl-object-get-calls.html
@@ -266,11 +266,11 @@ gl.deleteRenderbuffer(renderbuffer);
 shouldBe('gl.getFramebufferAttachmentParameter(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE)', 'gl.NONE');
 gl.deleteBuffer(buffer);
 shouldBeNull('gl.getVertexAttrib(1, gl.VERTEX_ATTRIB_ARRAY_BUFFER_BINDING)');
 glErrorShouldBe(gl, gl.NO_ERROR);
 
 successfullyParsed = true;
 </script>
 
-<script src="../../resources/js-test-post.js"></script>
+<script>finishTest();</script>
 </body>
 </html>
--- a/content/canvas/test/webgl/conformance/textures/compressed-tex-image.html
+++ b/content/canvas/test/webgl/conformance/textures/compressed-tex-image.html
@@ -50,11 +50,11 @@ if (!gl) {
 
   shouldGenerateGLError(gl, gl.NO_ERROR, "formats = gl.getParameter(gl.COMPRESSED_TEXTURE_FORMATS)");
   shouldBeNonNull("formats");
   shouldBe("formats.length", "0");
 }
 
 successfullyParsed = true;
 </script>
-<script src="../../resources/js-test-post.js"></script>
+<script>finishTest();</script>
 </body>
 </html>
--- a/content/canvas/test/webgl/conformance/textures/gl-pixelstorei.html
+++ b/content/canvas/test/webgl/conformance/textures/gl-pixelstorei.html
@@ -113,12 +113,12 @@ function init() {
     assertMsg(gl.getParameter(gl.PACK_ALIGNMENT) == table[ii],
         "PACK_ALIGNMENT is " + table[ii]);
   }
 }
 
 init();
 successfullyParsed = true;
 </script>
-<script src="../../resources/js-test-post.js"></script>
+<script>finishTest();</script>
 
 </body>
 </html>
--- a/content/canvas/test/webgl/conformance/textures/tex-image-and-sub-image-2d-with-array-buffer-view.html
+++ b/content/canvas/test/webgl/conformance/textures/tex-image-and-sub-image-2d-with-array-buffer-view.html
@@ -183,11 +183,11 @@ gl.clearColor(0,0,0,1);
 gl.clearDepth(1);
 
 textureLoc = gl.getUniformLocation(program, "tex");
 
 runTest();
 glErrorShouldBe(gl, gl.NO_ERROR, "should be no errors");
 successfullyParsed = true;
 </script>
-<script src="../../resources/js-test-post.js"></script>
+<script>finishTest();</script>
 </body>
 </html>
--- a/content/canvas/test/webgl/conformance/textures/tex-image-and-uniform-binding-bugs.html
+++ b/content/canvas/test/webgl/conformance/textures/tex-image-and-uniform-binding-bugs.html
@@ -55,12 +55,12 @@ tmpcanvas.width = 2;
 tmpcanvas.height = 2;
 var texture = gl.createTexture();
 shouldBeUndefined("gl.bindTexture(gl.TEXTURE_2D, texture)");
 shouldBeUndefined("gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, tmpcanvas)");
 
 successfullyParsed = true;
 
 </script>
-<script src="../../resources/js-test-post.js"></script>
+<script>finishTest();</script>
 
 </body>
 </html>
--- a/content/canvas/test/webgl/conformance/textures/tex-image-with-invalid-data.html
+++ b/content/canvas/test/webgl/conformance/textures/tex-image-with-invalid-data.html
@@ -89,13 +89,13 @@ test("Passing texSubImage2D parameter da
      function () {
       gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, 64, 64, gl.RGBA, gl.UNSIGNED_BYTE, "not a buffer");
      },
      "exception");
 
 debug("");
 successfullyParsed = true;
 </script>
-<script src="../../resources/js-test-post.js"></script>
+<script>finishTest();</script>
 
 </body>
 </html>
 
--- a/content/canvas/test/webgl/conformance/textures/tex-input-validation.html
+++ b/content/canvas/test/webgl/conformance/textures/tex-input-validation.html
@@ -351,11 +351,11 @@ testCases =
      expectedError: gl.INVALID_OPERATION} ];
 
 for (var ii = 0; ii < testCases.length; ++ii)
     testCopyFromInternalFBO(testCases[ii]);
 
 successfullyParsed = true;
 </script>
 
-<script src="../../resources/js-test-post.js"></script>
+<script>finishTest();</script>
 </body>
 </html>
--- a/content/canvas/test/webgl/conformance/textures/tex-sub-image-2d-bad-args.html
+++ b/content/canvas/test/webgl/conformance/textures/tex-sub-image-2d-bad-args.html
@@ -56,11 +56,11 @@ gl.texSubImage2D(gl.TEXTURE_2D, 0, 0,0, 
 glErrorShouldBe(gl, gl.NO_ERROR, "format same as original RGBA 4_4_4_4");
 gl.texSubImage2D(gl.TEXTURE_2D, 0, 0,0, gl.RGB, gl.UNSIGNED_BYTE, c);
 glErrorShouldBe(gl, gl.INVALID_OPERATION, "format not same as original RGBA 4_4_4_4");
 gl.texSubImage2D(gl.TEXTURE_2D, 0, 0,0, gl.RGBA, gl.UNSIGNED_BYTE, c);
 glErrorShouldBe(gl, gl.INVALID_OPERATION, "type not same as original RGBA 4_4_4_4");
 
 successfullyParsed = true;
 </script>
-<script src="../../resources/js-test-post.js"></script>
+<script>finishTest();</script>
 </body>
 </html>
--- a/content/canvas/test/webgl/conformance/textures/tex-sub-image-2d.html
+++ b/content/canvas/test/webgl/conformance/textures/tex-sub-image-2d.html
@@ -90,11 +90,11 @@ for (var i = 0; i < textureWidth; i++) {
     }
 }
 
 if (passed)
     testPassed("");
 
 successfullyParsed = true;
 </script>
-<script src="../../resources/js-test-post.js"></script>
+<script>finishTest();</script>
 </body>
 </html>
--- a/content/canvas/test/webgl/conformance/textures/texparameter-test.html
+++ b/content/canvas/test/webgl/conformance/textures/texparameter-test.html
@@ -176,13 +176,13 @@ function init()
   if (passed) {
     testPassed("rendered as expected");
    }
 }
 
 init();
 successfullyParsed = true;
 </script>
-<script src="../../resources/js-test-post.js"></script>
+<script>finishTest();</script>
 
 </body>
 </html>
 
--- a/content/canvas/test/webgl/conformance/textures/texture-active-bind-2.html
+++ b/content/canvas/test/webgl/conformance/textures/texture-active-bind-2.html
@@ -177,13 +177,13 @@ function init()
 
     testPassed(msg);
   }
 }
 
 init();
 successfullyParsed = true;
 </script>
-<script src="../../resources/js-test-post.js"></script>
+<script>finishTest();</script>
 
 </body>
 </html>
 
--- a/content/canvas/test/webgl/conformance/textures/texture-active-bind.html
+++ b/content/canvas/test/webgl/conformance/textures/texture-active-bind.html
@@ -126,13 +126,13 @@ function init()
       testPassed(msg);
   }
 }
 
 init();
 successfullyParsed = true;
 </script>
 
-<script src="../../resources/js-test-post.js"></script>
+<script>finishTest();</script>
 
 </body>
 </html>
 
--- a/content/canvas/test/webgl/conformance/textures/texture-clear.html
+++ b/content/canvas/test/webgl/conformance/textures/texture-clear.html
@@ -30,13 +30,13 @@ gl.bindTexture(gl.TEXTURE_2D, tex);
 gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
 gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, new Uint8Array([0,255,0,255]));
 wtu.drawQuad(gl);
 wtu.checkCanvas(
     gl, [0, 255, 0, 255], "should be green");
 glErrorShouldBe(gl, gl.NO_ERROR, "Should be no errors from setup.");
 successfullyParsed = true;
 </script>
-<script src="../../resources/js-test-post.js"></script>
+<script>finishTest();</script>
 
 </body>
 </html>
 
--- a/content/canvas/test/webgl/conformance/textures/texture-complete.html
+++ b/content/canvas/test/webgl/conformance/textures/texture-complete.html
@@ -55,13 +55,13 @@ function init()
       "texture that is not -texture-complete- when " +
       "TEXTURE_MIN_FILTER not NEAREST or LINEAR should draw with 0,0,0,255");
 }
 
 init();
 successfullyParsed = true;
 </script>
 
-<script src="../../resources/js-test-post.js"></script>
+<script>finishTest();</script>
 
 </body>
 </html>
 
--- a/content/canvas/test/webgl/conformance/textures/texture-formats-test.html
+++ b/content/canvas/test/webgl/conformance/textures/texture-formats-test.html
@@ -240,12 +240,12 @@ if (!gl) {
   }
   checkTypes();
 }
 
 debug("");
 successfullyParsed = true;
 
 </script>
-<script src="../../resources/js-test-post.js"></script>
+<script>finishTest();</script>
 
 </body>
 </html>
--- a/content/canvas/test/webgl/conformance/textures/texture-mips.html
+++ b/content/canvas/test/webgl/conformance/textures/texture-mips.html
@@ -245,12 +245,12 @@ function init()
     return 'rgb(' + c[0] + ',' + c[1] + ',' + c[2] +')';
   }
 }
 
 init();
 successfullyParsed = true;
 </script>
 
-<script src="../../resources/js-test-post.js"></script>
+<script>finishTest();</script>
 </body>
 </html>
 
--- a/content/canvas/test/webgl/conformance/textures/texture-npot.html
+++ b/content/canvas/test/webgl/conformance/textures/texture-npot.html
@@ -213,13 +213,13 @@ function fillCubeTexture(gl, tex, width,
     gl.TEXTURE_CUBE_MAP_NEGATIVE_Z];
   for (var tt = 0; tt < targets.length; ++tt) {
     gl.texImage2D(
         targets[tt], opt_level, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, canvas);
   }
 };
 
 </script>
-<script src="../../resources/js-test-post.js"></script>
+<script>finishTest();</script>
 
 </body>
 </html>
 
--- a/content/canvas/test/webgl/conformance/typedarrays/array-buffer-crash.html
+++ b/content/canvas/test/webgl/conformance/typedarrays/array-buffer-crash.html
@@ -28,11 +28,11 @@ try {
   new ArrayBuffer().byteLength;
 } catch (e) {
 }
 
 testPassed("new ArrayBuffer().byteLength did not crash");
 successfullyParsed = true;
 
 </script>
-<script src="../../resources/js-test-post.js"></script>
+<script>finishTest();</script>
 </body>
 </html>
--- a/content/canvas/test/webgl/conformance/typedarrays/array-buffer-view-crash.html
+++ b/content/canvas/test/webgl/conformance/typedarrays/array-buffer-view-crash.html
@@ -54,12 +54,12 @@ try {
   new Uint32Array().length;
 } catch (e) {
 }
 
 testPassed("new Uint32Array().length did not crash");
 successfullyParsed = true;
 
 </script>
-<script src="../../resources/js-test-post.js"></script>
+<script>finishTest();</script>
 
 </body>
 </html>
--- a/content/canvas/test/webgl/conformance/typedarrays/array-unit-tests.html
+++ b/content/canvas/test/webgl/conformance/typedarrays/array-unit-tests.html
@@ -1061,12 +1061,12 @@ function runTests() {
 
   printSummary();
 }
 
 runTests();
 successfullyParsed = true;
 
 </script>
-<script src="../../resources/js-test-post.js"></script>
+<script>finishTest();</script>
 
 </body>
 </html>
--- a/content/canvas/test/webgl/conformance/uniforms/gl-uniform-arrays.html
+++ b/content/canvas/test/webgl/conformance/uniforms/gl-uniform-arrays.html
@@ -291,12 +291,12 @@ for (var tt = 0; tt < typeInfos.length; 
   gl.useProgram(null);
   glErrorShouldBe(gl, gl.NO_ERROR,
                   "can call gl.useProgram(null)");
 }
 debug("");
 successfullyParsed = true;
 
 </script>
-<script src="../../resources/js-test-post.js"></script>
+<script>finishTest();</script>
 
 </body>
 </html>
--- a/content/canvas/test/webgl/conformance/uniforms/gl-uniform-bool.html
+++ b/content/canvas/test/webgl/conformance/uniforms/gl-uniform-bool.html
@@ -45,12 +45,12 @@ var loc = gl.getUniformLocation(gl.progr
 gl.uniform1f(loc, 1);
 glErrorShouldBe(gl, gl.NO_ERROR,
                 "should be able to set bool with gl.uniform1f");
 
 debug("");
 successfullyParsed = true;
 
 </script>
-<script src="../../resources/js-test-post.js"></script>
+<script>finishTest();</script>
 
 </body>
 </html>
--- a/content/canvas/test/webgl/conformance/uniforms/gl-uniformmatrix4fv.html
+++ b/content/canvas/test/webgl/conformance/uniforms/gl-uniformmatrix4fv.html
@@ -68,12 +68,12 @@ for (var ii = 2; ii <= 4; ++ii) {
   gl[name](loc, true, mat);
   glErrorShouldBe(gl, gl.INVALID_VALUE, name + " should return INVALID_VALUE with transpose = true");
 }
 
 debug("");
 successfullyParsed = true;
 
 </script>
-<script src="../../resources/js-test-post.js"></script>
+<script>finishTest();</script>
 
 </body>
 </html>
--- a/content/canvas/test/webgl/conformance/uniforms/gl-unknown-uniform.html
+++ b/content/canvas/test/webgl/conformance/uniforms/gl-unknown-uniform.html
@@ -54,12 +54,12 @@ if (!gl) {
   glErrorShouldBe(gl, gl.NO_ERROR,
             "there should be no error from trying to set an unknown uniform");
 }
 
 debug("");
 successfullyParsed = true;
 
 </script>
-<script src="../../resources/js-test-post.js"></script>
+<script>finishTest();</script>
 
 </body>
 </html>
--- a/content/canvas/test/webgl/conformance/uniforms/null-uniform-location.html
+++ b/content/canvas/test/webgl/conformance/uniforms/null-uniform-location.html
@@ -66,11 +66,11 @@ for (var i = 0; i < funcs.length; i++) {
   callString = "callUniformFunction('" + funcs[i] + "')";
   shouldBeUndefined(callString);
   glErrorShouldBe(gl, gl.NO_ERROR);
 }
 
 successfullyParsed = true;
 </script>
 
-<script src="../../resources/js-test-post.js"></script>
+<script>finishTest();</script>
 </body>
 </html>
--- a/content/canvas/test/webgl/conformance/uniforms/uniform-location.html
+++ b/content/canvas/test/webgl/conformance/uniforms/uniform-location.html
@@ -102,11 +102,11 @@ locationSx2 = contextA.getUniformLocatio
 shouldBeFalse("locationSx === locationSx2");
 locationSx.foo  = {};
 locationSx2.foo = {};
 shouldBeFalse("locationSx.foo === locationSx2.foo");
 
 successfullyParsed = true;
 </script>
 
-<script src="../../resources/js-test-post.js"></script>
+<script>finishTest();</script>
 </body>
 </html>
--- a/content/canvas/test/webgl/conformance/uniforms/uniform-samplers-test.html
+++ b/content/canvas/test/webgl/conformance/uniforms/uniform-samplers-test.html
@@ -49,12 +49,12 @@ function init()
   gl.uniform1fv(textureLoc, [1]);
   glErrorShouldBe(gl, gl.INVALID_OPERATION,
             "uniform1fv returns INVALID_OPERATION if attempting to set a sampler uniform");
 }
 
 init();
 successfullyParsed = true;
 </script>
-<script src="../../resources/js-test-post.js"></script>
+<script>finishTest();</script>
 </body>
 </html>
 
--- a/content/canvas/test/webgl/ext-texture-filter-anisotropic.patch
+++ b/content/canvas/test/webgl/ext-texture-filter-anisotropic.patch
@@ -186,12 +186,12 @@ new file mode 100644
 +    }
 +
 +    gl.deleteTexture(texture);
 +}
 +
 +debug("");
 +successfullyParsed = true;
 +</script>
-+<script src="../../resources/js-test-post.js"></script>
++<script>finishTest();</script>
 +
 +</body>
 +</html>
--- a/content/canvas/test/webgl/extra/canvas-compositing-test.html
+++ b/content/canvas/test/webgl/extra/canvas-compositing-test.html
@@ -111,15 +111,15 @@ img tag<br/>
             gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
             gl.drawArrays(gl.TRIANGLES, 0, 3);
        }
 
        init();
        successfullyParsed = true;
     </script>
 </body>
-<script src="../resources/js-test-post.js"></script>
+<script>finishTest();</script>
 
 <script>
 </script>
 
 </body>
 </html>
--- a/content/canvas/test/webgl/extra/out-of-memory.html
+++ b/content/canvas/test/webgl/extra/out-of-memory.html
@@ -78,15 +78,15 @@ if (!gl) {
 }
 
 function finish() {
   debug("");
   successfullyParsed = true;
 }
 
 </script>
-<!-- <script src="../resources/js-test-post.js"></script> -->
+<!-- <script>finishTest();</script> -->
 
 <script>
 </script>
 
 </body>
 </html>
--- a/content/canvas/test/webgl/failing_tests_android.txt
+++ b/content/canvas/test/webgl/failing_tests_android.txt
@@ -21,15 +21,14 @@ conformance/glsl/functions/glsl-function
 conformance/glsl/functions/glsl-function-mod-gentype.html
 conformance/glsl/functions/glsl-function-normalize.html
 conformance/glsl/functions/glsl-function-reflect.html
 conformance/glsl/functions/glsl-function-sign.html
 conformance/glsl/functions/glsl-function-smoothstep-float.html
 conformance/glsl/functions/glsl-function-smoothstep-gentype.html
 conformance/glsl/functions/glsl-function-step-float.html
 conformance/glsl/functions/glsl-function-step-gentype.html
-conformance/glsl/misc/glsl-function-nodes.html
 conformance/glsl/misc/shared.html
 conformance/misc/null-object-behaviour.html
 conformance/renderbuffers/framebuffer-object-attachment.html
 conformance/textures/texture-mips.html
 conformance/textures/texture-npot.html
 conformance/textures/texture-npot-video.html
--- a/content/canvas/test/webgl/reference-cycle-test.patch
+++ b/content/canvas/test/webgl/reference-cycle-test.patch
@@ -44,17 +44,17 @@ diff --git a/content/canvas/test/webgl/c
 +
 +    // create a self-cycle on the extension object
 +    ext.ext = ext;
 +}
  
  debug("");
  successfullyParsed = true;
  </script>
- <script src="../../resources/js-test-post.js"></script>
+ <script>finishTest();</script>
  
  </body>
  </html>
 diff --git a/content/canvas/test/webgl/conformance/extensions/oes-texture-float.html b/content/canvas/test/webgl/conformance/extensions/oes-texture-float.html
 --- a/content/canvas/test/webgl/conformance/extensions/oes-texture-float.html
 +++ b/content/canvas/test/webgl/conformance/extensions/oes-texture-float.html
 @@ -81,16 +81,17 @@ if (!gl) {
  
@@ -96,12 +96,12 @@ diff --git a/content/canvas/test/webgl/c
 +
 +    // create a self-cycle on the extension object
 +    ext.ext = ext;
 +}
  
  debug("");
  successfullyParsed = true;
  </script>
- <script src="../../resources/js-test-post.js"></script>
+ <script>finishTest();</script>
  
  </body>
  </html>
deleted file mode 100644
--- a/content/canvas/test/webgl/resources/js-test-post.js
+++ /dev/null
@@ -1,3 +0,0 @@
-shouldBeTrue("successfullyParsed");
-debug('<br /><span class="pass">TEST COMPLETE</span>');
-notifyFinishedToHarness()
--- a/content/canvas/test/webgl/resources/js-test-pre.js
+++ b/content/canvas/test/webgl/resources/js-test-pre.js
@@ -464,35 +464,12 @@ function gc() {
         temp += "foo";
         gcRec(n-1);
     }
     for (var i = 0; i < 1000; i++)
         gcRec(10);
 }
 
 function finishTest() {
-  testPassed("beginning of finishTest: " + (new Date().getTime()));
-
-  successfullyParsed = true;
-  var epilogue = document.createElement("script");
-  epilogue.onload = function() {
-    testPassed("finishTest epilogue onload: " + (new Date().getTime()));
-    if (window.nonKhronosFrameworkNotifyDone) {
-      window.nonKhronosFrameworkNotifyDone();
-    }
-  };
-
-  var basePath = "";
-  var expectedBase = "js-test-pre.js";
-  var scripts = document.getElementsByTagName('script');
-  for (var script, i = 0; script = scripts[i]; i++) {
-    var src = script.src;
-    var l = src.length;
-    if (src.substr(l - expectedBase.length) == expectedBase) {
-      basePath = src.substr(0, l - expectedBase.length);
-      break;
-    }
-  }
-  epilogue.src = basePath + "js-test-post.js";
-  document.body.appendChild(epilogue);
-  testPassed("end of finishTest: " + (new Date().getTime()));
+    debug('<br /><span class="pass">TEST COMPLETE</span>');
+    notifyFinishedToHarness();
 }
 
--- a/content/events/public/nsEventNameList.h
+++ b/content/events/public/nsEventNameList.h
@@ -312,16 +312,20 @@ EVENT(timeupdate,
 EVENT(volumechange,
       NS_VOLUMECHANGE,
       EventNameType_HTML,
       NS_EVENT_NULL)
 EVENT(waiting,
       NS_WAITING,
       EventNameType_HTML,
       NS_EVENT_NULL)
+EVENT(wheel,
+      NS_WHEEL_WHEEL,
+      EventNameType_All,
+      NS_WHEEL_EVENT)
 // Gecko-specific extensions that apply to elements
 EVENT(copy,
       NS_COPY,
       EventNameType_HTMLXUL,
       NS_EVENT)
 EVENT(cut,
       NS_CUT,
       EventNameType_HTMLXUL,
@@ -595,20 +599,16 @@ NON_IDL_EVENT(draggesture,
 NON_IDL_EVENT(overflow,
               NS_SCROLLPORT_OVERFLOW,
               EventNameType_XUL,
               NS_EVENT_NULL)
 NON_IDL_EVENT(underflow,
               NS_SCROLLPORT_UNDERFLOW,
               EventNameType_XUL,
               NS_EVENT_NULL)
-NON_IDL_EVENT(wheel,
-              NS_WHEEL_WHEEL,
-              EventNameType_XUL,
-              NS_WHEEL_EVENT)
 
 // Various SVG events
 NON_IDL_EVENT(SVGLoad,
               NS_SVG_LOAD,
               EventNameType_None,
               NS_SVG_EVENT)
 NON_IDL_EVENT(SVGUnload,
               NS_SVG_UNLOAD,
--- a/content/events/src/nsDOMEvent.cpp
+++ b/content/events/src/nsDOMEvent.cpp
@@ -137,18 +137,16 @@ nsDOMEvent::nsDOMEvent(nsPresContext* aP
           ...
         }
      */
     mEvent = new nsEvent(false, 0);
     mEvent->time = PR_Now();
   }
 
   InitPresContextData(aPresContext);
-
-  NS_ASSERTION(mEvent->message != NS_PAINT, "Trying to create a DOM paint event!");
 }
 
 void
 nsDOMEvent::InitPresContextData(nsPresContext* aPresContext)
 {
   mPresContext = aPresContext;
   // Get the explicit original target (if it's anonymous make it null)
   {
@@ -596,44 +594,16 @@ nsDOMEvent::DuplicatePrivateData()
       break;
     }
     case NS_GUI_EVENT:
     {
       // Not copying widget, it is a weak reference.
       newEvent = new nsGUIEvent(false, msg, nullptr);
       break;
     }
-    case NS_SIZE_EVENT:
-    {
-      nsSizeEvent* sizeEvent = new nsSizeEvent(false, msg, nullptr);
-      NS_ENSURE_TRUE(sizeEvent, NS_ERROR_OUT_OF_MEMORY);
-      sizeEvent->mWinWidth = static_cast<nsSizeEvent*>(mEvent)->mWinWidth;
-      sizeEvent->mWinHeight = static_cast<nsSizeEvent*>(mEvent)->mWinHeight;
-      newEvent = sizeEvent;
-      break;
-    }
-    case NS_SIZEMODE_EVENT:
-    {
-      newEvent = new nsSizeModeEvent(false, msg, nullptr);
-      NS_ENSURE_TRUE(newEvent, NS_ERROR_OUT_OF_MEMORY);
-      static_cast<nsSizeModeEvent*>(newEvent)->mSizeMode =
-        static_cast<nsSizeModeEvent*>(mEvent)->mSizeMode;
-      break;
-    }
-    case NS_ZLEVEL_EVENT:
-    {
-      nsZLevelEvent* zLevelEvent = new nsZLevelEvent(false, msg, nullptr);
-      NS_ENSURE_TRUE(zLevelEvent, NS_ERROR_OUT_OF_MEMORY);
-      nsZLevelEvent* oldZLevelEvent = static_cast<nsZLevelEvent*>(mEvent);
-      zLevelEvent->mPlacement = oldZLevelEvent->mPlacement;
-      zLevelEvent->mImmediate = oldZLevelEvent->mImmediate;
-      zLevelEvent->mAdjusted = oldZLevelEvent->mAdjusted;
-      newEvent = zLevelEvent;
-      break;
-    }
     case NS_SCROLLBAR_EVENT:
     {
       newEvent = new nsScrollbarEvent(false, msg, nullptr);
       NS_ENSURE_TRUE(newEvent, NS_ERROR_OUT_OF_MEMORY);
       static_cast<nsScrollbarEvent*>(newEvent)->position =
         static_cast<nsScrollbarEvent*>(mEvent)->position;
       break;
     }
@@ -787,24 +757,16 @@ nsDOMEvent::DuplicatePrivateData()
       mutationEvent->mRelatedNode = oldMutationEvent->mRelatedNode;
       mutationEvent->mAttrName = oldMutationEvent->mAttrName;
       mutationEvent->mPrevAttrValue = oldMutationEvent->mPrevAttrValue;
       mutationEvent->mNewAttrValue = oldMutationEvent->mNewAttrValue;
       mutationEvent->mAttrChange = oldMutationEvent->mAttrChange;
       newEvent = mutationEvent;
       break;
     }
-#ifdef ACCESSIBILITY
-    case NS_ACCESSIBLE_EVENT:
-    {
-      newEvent = new nsAccessibleEvent(false, msg, nullptr);
-      isInputEvent = true;
-      break;
-    }
-#endif
     case NS_FORM_EVENT:
     {
       newEvent = new nsFormEvent(false, msg);
       break;
     }
     case NS_FOCUS_EVENT:
     {
       nsFocusEvent* newFocusEvent = new nsFocusEvent(false, msg);
--- a/content/events/test/test_bug422132.html
+++ b/content/events/test/test_bug422132.html
@@ -34,16 +34,17 @@ function hitEventLoop(aFunc, aTimes)
   } else {
     setTimeout(aFunc, 20);
   }
 }
 
 function runTests()
 {
   SpecialPowers.setIntPref("mousewheel.min_line_scroll_amount", 1);
+  SpecialPowers.setIntPref("mousewheel.transaction.timeout", 100000);
 
   var target = document.getElementById("target");
 
   var scrollLeft = target.scrollLeft;
   var scrollTop = target.scrollTop;
   synthesizeWheel(target, 10, 10,
     { deltaMode: WheelEvent.DOM_DELTA_PIXEL,
       deltaX: 0.5, deltaY: 0.5, lineOrPageDeltaX: 0, lineOrPageDeltaY: 0 });
@@ -74,16 +75,17 @@ function runTests()
           { deltaMode: WheelEvent.DOM_DELTA_LINE,
             deltaX: 0.5, deltaY: 0.5, lineOrPageDeltaX: 1, lineOrPageDeltaY: 1 });
         hitEventLoop(function () {
           ok(target.scrollLeft > scrollLeft,
              "not scrolled to right by 0.5 line delta value with pending 0.5 line delta");
           ok(target.scrollTop > scrollTop,
              "not scrolled to bottom by 0.5 line delta value with pending 0.5 line delta");
           SpecialPowers.clearUserPref("mousewheel.min_line_scroll_amount");
+          SpecialPowers.clearUserPref("mousewheel.transaction.timeout");
           SimpleTest.finish();
         }, 20);
       }, 20);
     }, 20);
   }, 20);
 }
 
 </script>
--- a/content/events/test/test_dom_wheel_event.html
+++ b/content/events/test/test_dom_wheel_event.html
@@ -647,16 +647,52 @@ function testEventOrder()
   window.removeEventListener("DOMMouseScroll", handler, true);
   window.removeEventListener("MozMousePixelScroll", handler, true);
 
   SpecialPowers.removeSystemEventListener(window, "wheel", systemHandler, true);
   SpecialPowers.removeSystemEventListener(window, "DOMMouseScroll", systemHandler, true);
   SpecialPowers.removeSystemEventListener(window, "MozMousePixelScroll", systemHandler, true);
 }
 
+var gOnWheelAttrHandled = new Array;
+
+function testOnWheelAttr()
+{
+  document.documentElement.setAttribute("onwheel", "gOnWheelAttrHandled['html'] = true;");
+  document.body.setAttribute("onwheel", "gOnWheelAttrHandled['body'] = true;");
+  gScrollableElement.setAttribute("onwheel", "gOnWheelAttrHandled['div'] = true;");
+  var target = document.getElementById("onwheel");
+  synthesizeWheel(gScrollableElement, 10, 10,
+                  { deltaMode: WheelEvent.DOM_DELTA_LINE,
+                    deltaX: 1.0, deltaY: 2.0 });
+  ok(gOnWheelAttrHandled['html'], "html element's onwheel attribute isn't performed");
+  ok(gOnWheelAttrHandled['body'], "body element's onwheel attribute isn't performed");
+  ok(gOnWheelAttrHandled['div'], "div element's onwheel attribute isn't performed");
+}
+
+var gOnWheelPropHandled = new Array;
+
+function testOnWheelProperty()
+{
+  window.onwheel = function (e) { gOnWheelPropHandled["window"] = true; }
+  document.onwheel = function (e) { gOnWheelPropHandled["document"] = true; }
+  document.documentElement.onwheel = function (e) { gOnWheelPropHandled["html"] = true; };
+  document.body.onwheel = function (e) { gOnWheelPropHandled["body"] = true; };
+  gScrollableElement.onwheel = function (e) { gOnWheelPropHandled["div"] = true; };
+  var target = document.getElementById("onwheel");
+  synthesizeWheel(gScrollableElement, 10, 10,
+                  { deltaMode: WheelEvent.DOM_DELTA_LINE,
+                    deltaX: 1.0, deltaY: 2.0 });
+  ok(gOnWheelPropHandled['window'], "window's onwheel property isn't performed");
+  ok(gOnWheelPropHandled['document'], "document's onwheel property isn't performed");
+  ok(gOnWheelPropHandled['html'], "html element's onwheel property isn't performed");
+  ok(gOnWheelPropHandled['body'], "body element's onwheel property isn't performed");
+  ok(gOnWheelPropHandled['div'], "div element's onwheel property isn't performed");
+}
+
 function runTests()
 {
   SpecialPowers.setIntPref("mousewheel.default.delta_multiplier_x", 100);
   SpecialPowers.setIntPref("mousewheel.default.delta_multiplier_y", 100);
   SpecialPowers.setIntPref("mousewheel.default.delta_multiplier_z", 100);
   SpecialPowers.setIntPref("mousewheel.with_alt.delta_multiplier_x", 100);
   SpecialPowers.setIntPref("mousewheel.with_alt.delta_multiplier_y", 100);
   SpecialPowers.setIntPref("mousewheel.with_alt.delta_multiplier_z", 100);
@@ -673,16 +709,18 @@ function runTests()
   SpecialPowers.setIntPref("mousewheel.with_win.delta_multiplier_y", 100);
   SpecialPowers.setIntPref("mousewheel.with_win.delta_multiplier_z", 100);
 
   prepareScrollUnits();
   testMakingUntrustedEvent();
   testDeltaMultiplierPrefs();
   testDispatchingUntrustEvent();
   testEventOrder();
+  testOnWheelAttr();
+  testOnWheelProperty();
 
   SpecialPowers.clearUserPref("mousewheel.default.delta_multiplier_x");
   SpecialPowers.clearUserPref("mousewheel.default.delta_multiplier_y");
   SpecialPowers.clearUserPref("mousewheel.default.delta_multiplier_z");
   SpecialPowers.clearUserPref("mousewheel.with_alt.delta_multiplier_x");
   SpecialPowers.clearUserPref("mousewheel.with_alt.delta_multiplier_y");
   SpecialPowers.clearUserPref("mousewheel.with_alt.delta_multiplier_z");
   SpecialPowers.clearUserPref("mousewheel.with_control.delta_multiplier_x");
--- a/content/events/test/window_bug659071.html
+++ b/content/events/test/window_bug659071.html
@@ -29,30 +29,30 @@ function hitEventLoop(aFunc, aTimes)
   } else {
     setTimeout(aFunc, 20);
   }
 }
 
 function runTests()
 {
   SpecialPowers.setIntPref("mousewheel.with_control.action", 3);
-  SpecialPowers.setFullZoom(window, 1.0);
+  synthesizeKey("0", { accelKey: true });
 
   var video = document.getElementById("v");
   hitEventLoop(function () {
     is(SpecialPowers.getFullZoom(window), 1.0,
        "failed to reset zoom");
     synthesizeWheel(video, 10, 10,
       { deltaMode: WheelEvent.DOM_DELTA_LINE, ctrlKey: true,
         deltaX: 0, deltaY: 1.0, lineOrPageDeltaX: 0, lineOrPageDeltaY: 1 });
     hitEventLoop(function () {
       isnot(SpecialPowers.getFullZoom(window), 1.0,
              "failed to zoom by ctrl+wheel");
 
-      SpecialPowers.setFullZoom(window, 1.0);
+      synthesizeKey("0", { accelKey: true });
       SpecialPowers.clearUserPref("mousewheel.with_control.action");
 
       hitEventLoop(window.opener.finish, 20);
     }, 20);
   }, 20);
 }
 
 </script>
--- a/content/events/test/window_wheel_default_action.html
+++ b/content/events/test/window_wheel_default_action.html
@@ -777,29 +777,29 @@ function doTestZoom(aSettings, aCallback
           ok(SpecialPowers.getFullZoom(window) > 1.0,
              description + "not zoomed in, got " + SpecialPowers.getFullZoom(window));
         } else {
           ok(SpecialPowers.getFullZoom(window) < 1.0,
              description + "not zoomed out, got " + SpecialPowers.getFullZoom(window));
         }
       }
 
-      SpecialPowers.setFullZoom(window, 1.0);
+      synthesizeKey("0", { accelKey: true });
       hitEventLoop(doNextTest, 20);
     }, 20);
   }
   doNextTest();
 }
 
 function doTestZoomedScroll()
 {
   function testZoomedPixelScroll()
   {
     // Reset zoom and store the scroll amount into the data.
-    SpecialPowers.setFullZoom(window, 1.0);
+    synthesizeKey("0", { accelKey: true });
     gScrollableElement.scrollTop = 1000;
     gScrollableElement.scrollLeft = 1000;
     // Ensure not to be in reflow.
     hitEventLoop(function () {
       function handler(aEvent)
       {
         if (aEvent.axis == MouseScrollEvent.HORIZONTAL_AXIS) {
           is(aEvent.detail, 16,
@@ -838,28 +838,28 @@ function doTestZoomedScroll()
             ok(Math.abs(gScrollableElement.scrollLeft - (1000 + (scrolledX - 1000) / 2)) <= 1,
                "doTestZoomedScroll: zoomed horizontal scroll amount by pixel wheel event is different from normal, scrollLeft=" +
                  gScrollableElement.scrollLeft + ", scrolledX=" + scrolledX);
             ok(Math.abs(gScrollableElement.scrollTop - (1000 + (scrolledY - 1000) / 2)) <= 1,
                "doTestZoomedScroll: zoomed vertical scroll amount by pixel wheel event is different from normal, scrollTop=" +
                  gScrollableElement.scrollTop + ", scrolledY=" + scrolledY);
             window.removeEventListener("MozMousePixelScroll", handler, true);
 
-            SpecialPowers.setFullZoom(window, 1.0);
+            synthesizeKey("0", { accelKey: true });
             testZoomedLineScroll();
           }, 20);
         }, 20);
       }, 20);
     }, 20);
   }
 
   function testZoomedLineScroll()
   {
     // Reset zoom and store the scroll amount into the data.
-    SpecialPowers.setFullZoom(window, 1.0);
+    synthesizeKey("0", { accelKey: true });
     gScrollableElement.scrollTop = 1000;
     gScrollableElement.scrollLeft = 1000;
     // Ensure not to be in reflow.
     hitEventLoop(function () {
       var lineHeightX, lineHeightY;
       function handler(aEvent)
       {
         if (aEvent.axis == MouseScrollEvent.HORIZONTAL_AXIS) {
@@ -910,17 +910,17 @@ function doTestZoomedScroll()
                "doTestZoomedScroll: zoomed horizontal scroll amount by line wheel event is different from normal, scrollLeft=" +
                  gScrollableElement.scrollLeft + ", scrolledX=" + scrolledX);
             ok(Math.abs(gScrollableElement.scrollTop - scrolledY) <= 1,
                "doTestZoomedScroll: zoomed vertical scroll amount by line wheel event is different from normal, scrollTop=" +
                  gScrollableElement.scrollTop + ", scrolledY=" + scrolledY);
 
             window.removeEventListener("MozMousePixelScroll", handler, true);
 
-            SpecialPowers.setFullZoom(window, 1.0);
+            synthesizeKey("0", { accelKey: true });
           }, 20);
         }, 20);
       }, 20);
     }, 20);
   }
 
   // XXX It's too difficult to test page scroll because the page scroll amount
   //     is computed by complex logic.
--- a/content/html/content/src/nsGenericHTMLFrameElement.cpp
+++ b/content/html/content/src/nsGenericHTMLFrameElement.cpp
@@ -7,16 +7,17 @@
 
 #include "nsGenericHTMLFrameElement.h"
 #include "nsIInterfaceRequestorUtils.h"
 #include "nsContentUtils.h"
 #include "mozilla/Preferences.h"
 #include "nsIAppsService.h"
 #include "nsServiceManagerUtils.h"
 #include "nsIDOMApplicationRegistry.h"
+#include "nsIPermissionManager.h"
 
 using namespace mozilla;
 using namespace mozilla::dom;
 
 NS_IMPL_CYCLE_COLLECTION_CLASS(nsGenericHTMLFrameElement)
 NS_IMPL_CYCLE_COLLECTION_TRAVERSE_BEGIN_INHERITED(nsGenericHTMLFrameElement,
                                                   nsGenericHTMLElement)
   NS_IMPL_CYCLE_COLLECTION_TRAVERSE_NSCOMPTR_AMBIGUOUS(mFrameLoader, nsIFrameLoader)
@@ -285,28 +286,25 @@ nsGenericHTMLFrameElement::GetReallyIsBr
   // Fail if this frame doesn't have the mozbrowser attribute.
   bool isBrowser = false;
   GetMozbrowser(&isBrowser);
   if (!isBrowser) {
     return NS_OK;
   }
 
   // Fail if the node principal isn't trusted.
-  // TODO: check properly for mozApps rights when mozApps will be less hacky.
   nsIPrincipal *principal = NodePrincipal();
-  nsCOMPtr<nsIURI> principalURI;
-  principal->GetURI(getter_AddRefs(principalURI));
-  if (!nsContentUtils::IsSystemPrincipal(principal) &&
-      !nsContentUtils::URIIsChromeOrInPref(principalURI,
-                                           "dom.mozBrowserFramesWhitelist")) {
-    return NS_OK;
-  }
+  nsCOMPtr<nsIPermissionManager> permMgr =
+    do_GetService(NS_PERMISSIONMANAGER_CONTRACTID);
+  NS_ENSURE_STATE(permMgr);
 
-  // Otherwise, succeed.
-  *aOut = true;
+  PRUint32 permission = nsIPermissionManager::DENY_ACTION;
+  nsresult rv = permMgr->TestPermissionFromPrincipal(principal, "browser", &permission);
+  NS_ENSURE_SUCCESS(rv, NS_OK);
+  *aOut = permission == nsIPermissionManager::ALLOW_ACTION;
   return NS_OK;
 }
 
 NS_IMETHODIMP
 nsGenericHTMLFrameElement::GetReallyIsApp(bool *aOut)
 {
   nsAutoString manifestURL;
   GetAppManifestURL(manifestURL);
--- a/content/svg/content/src/SVGFragmentIdentifier.cpp
+++ b/content/svg/content/src/SVGFragmentIdentifier.cpp
@@ -27,67 +27,67 @@ GetViewElement(nsIDocument *aDocument, c
   dom::Element* element = aDocument->GetElementById(aId);
   return (element && element->IsSVG(nsGkAtoms::view)) ?
             static_cast<nsSVGViewElement*>(element) : nullptr;
 }
 
 void 
 SVGFragmentIdentifier::SaveOldPreserveAspectRatio(nsSVGSVGElement *root)
 {
-  const SVGPreserveAspectRatio *oldPARPtr = root->GetPreserveAspectRatioProperty();
-  if (!oldPARPtr) {
+  if (root->mPreserveAspectRatio.IsExplicitlySet()) {
     root->SetPreserveAspectRatioProperty(root->mPreserveAspectRatio.GetBaseValue());
   }
 }
 
 void 
 SVGFragmentIdentifier::RestoreOldPreserveAspectRatio(nsSVGSVGElement *root)
 {
   const SVGPreserveAspectRatio *oldPARPtr = root->GetPreserveAspectRatioProperty();
   if (oldPARPtr) {
     root->mPreserveAspectRatio.SetBaseValue(*oldPARPtr, root);
-    root->ClearPreserveAspectRatioProperty();
+  } else if (root->mPreserveAspectRatio.IsExplicitlySet()) {
+    root->RemoveAttribute(NS_LITERAL_STRING("preserveAspectRatio"));
   }
 }
 
 void 
 SVGFragmentIdentifier::SaveOldViewBox(nsSVGSVGElement *root)
 {
-  const nsSVGViewBoxRect *oldViewBoxPtr = root->GetViewBoxProperty();
-  if (!oldViewBoxPtr) {
+  if (root->mViewBox.IsExplicitlySet()) {
     root->SetViewBoxProperty(root->mViewBox.GetBaseValue());
   }
 }
 
 void 
 SVGFragmentIdentifier::RestoreOldViewBox(nsSVGSVGElement *root)
 {
   const nsSVGViewBoxRect *oldViewBoxPtr = root->GetViewBoxProperty();
   if (oldViewBoxPtr) {
     root->mViewBox.SetBaseValue(*oldViewBoxPtr, root);
-    root->ClearViewBoxProperty();
+  } else if (root->mViewBox.IsExplicitlySet()) {
+    root->RemoveAttribute(NS_LITERAL_STRING("viewBox"));
   }
 }
 
 void 
 SVGFragmentIdentifier::SaveOldZoomAndPan(nsSVGSVGElement *root)
 {
-  PRUint16 oldZoomAndPan = root->GetZoomAndPanProperty();
-  if (oldZoomAndPan == nsIDOMSVGZoomAndPan::SVG_ZOOMANDPAN_UNKNOWN) {
+  if (root->mEnumAttributes[nsSVGSVGElement::ZOOMANDPAN].IsExplicitlySet()) {
     root->SetZoomAndPanProperty(root->mEnumAttributes[nsSVGSVGElement::ZOOMANDPAN].GetBaseValue());
   }
 }
 
 void 
 SVGFragmentIdentifier::RestoreOldZoomAndPan(nsSVGSVGElement *root)
 {
   PRUint16 oldZoomAndPan = root->GetZoomAndPanProperty();
   if (oldZoomAndPan != nsIDOMSVGZoomAndPan::SVG_ZOOMANDPAN_UNKNOWN) {
     root->mEnumAttributes[nsSVGSVGElement::ZOOMANDPAN].SetBaseValue(oldZoomAndPan, root);
-    root->ClearZoomAndPanProperty();
+  } else if (root->mEnumAttributes[nsSVGSVGElement::ZOOMANDPAN].IsExplicitlySet()) {
+    root->RemoveAttribute(NS_LITERAL_STRING("zoomAndPan"));
   }
 }
 
 bool
 SVGFragmentIdentifier::ProcessSVGViewSpec(const nsAString &aViewSpec,
                                           nsSVGSVGElement *root)
 {
   if (!IsMatchingParameter(aViewSpec, NS_LITERAL_STRING("svgView"))) {
@@ -141,31 +141,28 @@ SVGFragmentIdentifier::ProcessSVGViewSpe
       zoomAndPanParams = &params;
     } else {
       // We don't support transform or viewTarget currently
       return false;
     }
   } while (tokenizer.hasMoreTokens());
 
   if (viewBoxParams) {
-    SaveOldViewBox(root);
     root->mViewBox.SetBaseValueString(*viewBoxParams, root);
   } else {
     RestoreOldViewBox(root);
   }
 
   if (preserveAspectRatioParams) {
-    SaveOldPreserveAspectRatio(root);
     root->mPreserveAspectRatio.SetBaseValueString(*preserveAspectRatioParams, root);
   } else {
     RestoreOldPreserveAspectRatio(root);
   }
 
   if (zoomAndPanParams) {
-    SaveOldZoomAndPan(root);
     nsCOMPtr<nsIAtom> valAtom = do_GetAtom(*zoomAndPanParams);
     const nsSVGEnumMapping *mapping = root->sZoomAndPanMap;
     while (mapping->mKey) {
       if (valAtom == *(mapping->mKey)) {
         root->mEnumAttributes[nsSVGSVGElement::ZOOMANDPAN].SetBaseValue(mapping->mVal, root);
         break;
       }
       mapping++;
@@ -182,45 +179,51 @@ SVGFragmentIdentifier::ProcessFragmentId
                                                  const nsAString &aAnchorName)
 {
   NS_ABORT_IF_FALSE(aDocument->GetRootElement()->IsSVG(nsGkAtoms::svg),
                     "expecting an SVG root element");
 
   nsSVGSVGElement *rootElement =
     static_cast<nsSVGSVGElement*>(aDocument->GetRootElement());
 
+  if (!rootElement->mUseCurrentView) {
+    SaveOldViewBox(rootElement);
+    SaveOldPreserveAspectRatio(rootElement);
+    SaveOldZoomAndPan(rootElement);
+  }
+
   const nsSVGViewElement *viewElement = GetViewElement(aDocument, aAnchorName);
 
   if (viewElement) {
     if (viewElement->mViewBox.IsExplicitlySet()) {
-      SaveOldViewBox(rootElement);
       rootElement->mViewBox.SetBaseValue(
         viewElement->mViewBox.GetBaseValue(), rootElement);
     } else {
       RestoreOldViewBox(rootElement);
     }
     if (viewElement->mPreserveAspectRatio.IsExplicitlySet()) {
-      SaveOldPreserveAspectRatio(rootElement);
       rootElement->mPreserveAspectRatio.SetBaseValue(
         viewElement->mPreserveAspectRatio.GetBaseValue(), rootElement);
     } else {
       RestoreOldPreserveAspectRatio(rootElement);
     }
     if (viewElement->mEnumAttributes[nsSVGViewElement::ZOOMANDPAN].IsExplicitlySet()) {
-      SaveOldZoomAndPan(rootElement);
       rootElement->mEnumAttributes[nsSVGSVGElement::ZOOMANDPAN].SetBaseValue(
         viewElement->mEnumAttributes[nsSVGViewElement::ZOOMANDPAN].GetBaseValue(), rootElement);
     } else {
       RestoreOldZoomAndPan(rootElement);
     }
     rootElement->mUseCurrentView = true;
     return true;
   }
 
   rootElement->mUseCurrentView = ProcessSVGViewSpec(aAnchorName, rootElement);
   if (rootElement->mUseCurrentView) {
     return true;
   }
   RestoreOldViewBox(rootElement);
+  rootElement->ClearViewBoxProperty();
   RestoreOldPreserveAspectRatio(rootElement);
+  rootElement->ClearPreserveAspectRatioProperty();
   RestoreOldZoomAndPan(rootElement);
+  rootElement->ClearZoomAndPanProperty();
   return false;
 }
--- a/content/xbl/src/nsXBLWindowKeyHandler.cpp
+++ b/content/xbl/src/nsXBLWindowKeyHandler.cpp
@@ -454,17 +454,17 @@ nsXBLWindowKeyHandler::WalkHandlersAndEx
   nsresult rv;
 
   // Try all of the handlers until we find one that matches the event.
   for (nsXBLPrototypeHandler *currHandler = aHandler; currHandler;
        currHandler = currHandler->GetNextHandler()) {
     bool stopped = aKeyEvent->IsDispatchStopped();
     if (stopped) {
       // The event is finished, don't execute any more handlers
-      return NS_OK;
+      return false;
     }
 
     if (!EventMatched(currHandler, aEventType, aKeyEvent,
                       aCharCode, aIgnoreShiftKey))
       continue;  // try the next one
 
     // Before executing this handler, check that it's not disabled,
     // and that it has something to do (oncommand of the <key> or its
--- a/dom/activities/src/ActivitiesService.jsm
+++ b/dom/activities/src/ActivitiesService.jsm
@@ -218,19 +218,22 @@ let Activities = {
         if (!sysmm) {
           // System message is not present, what should we do?
           return;
         }
 
         debug("Sending system message...");
         let result = aResults.options[aChoice];
         sysmm.sendMessage("activity", {
-          "id": aMsg.id,
-          "payload": aMsg.options
-        }, Services.io.newURI(result.manifest, null, null));
+            "id": aMsg.id,
+            "payload": aMsg.options,
+            "target": result.description
+          },
+          Services.io.newURI(result.description.href, null, null),
+          Services.io.newURI(result.manifest, null, null));
 
         if (!result.description.returnValue) {
           ppmm.sendAsyncMessage("Activity:FireSuccess", {
             "id": aMsg.id,
             "result": null
           });
         }
       };
@@ -243,17 +246,21 @@ let Activities = {
     let errorCb = function errorCb(aError) {
       // Something unexpected happened. Should we send an error back?
       debug("Error in startActivity: " + aError + "\n");
     };
 
     let matchFunc = function matchFunc(aResult) {
       // Bug 773383: arrays of strings / regexp.
       for (let prop in aResult.description.filters) {
-        if (aMsg.options.data[prop] !== aResult.description.filters[prop]) {
+        if (Array.isArray(aResult.description.filters[prop])) {
+          if (aResult.description.filters[prop].indexOf(aMsg.options.data[prop]) == -1) {
+            return false;
+          }
+        } else if (aResult.description.filters[prop] !== aMsg.options.data[prop] ) {
           return false;
         }
       }
       return true;
     };
 
     this.db.find(aMsg, successCb, errorCb, matchFunc);
   },
--- a/dom/alarm/AlarmDB.jsm
+++ b/dom/alarm/AlarmDB.jsm
@@ -41,16 +41,17 @@ AlarmDB.prototype = {
     debug("upgradeSchema()");
 
     let objectStore = aDb.createObjectStore(ALARMSTORE_NAME, { keyPath: "id", autoIncrement: true });
 
     objectStore.createIndex("date",           "date",           { unique: false });
     objectStore.createIndex("ignoreTimezone", "ignoreTimezone", { unique: false });
     objectStore.createIndex("timezoneOffset", "timezoneOffset", { unique: false });
     objectStore.createIndex("data",           "data",           { unique: false });
+    objectStore.createIndex("pageURL",        "pageURL",        { unique: false });
     objectStore.createIndex("manifestURL",    "manifestURL",    { unique: false });
 
     debug("Created object stores and indexes");
   },
 
   /**
    * @param aAlarm
    *        The record to be added.
--- a/dom/alarm/AlarmService.jsm
+++ b/dom/alarm/AlarmService.jsm
@@ -93,16 +93,17 @@ let AlarmService = {
 
       case "AlarmsManager:Add":
         // prepare a record for the new alarm to be added
         let newAlarm = {
           date: json.date, 
           ignoreTimezone: json.ignoreTimezone, 
           timezoneOffset: this._currentTimezoneOffset, 
           data: json.data,
+          pageURL: json.pageURL,
           manifestURL: json.manifestURL
         };
 
         let newAlarmTime = this._getAlarmTime(newAlarm);
         if (newAlarmTime <= Date.now()) {
           debug("Adding a alarm that has past time. Return DOMError.");
           this._debugCurrentAlarm();
           this._sendAsyncMessage(mm, "Add", false, json.requestId, "InvalidStateError");
@@ -248,17 +249,18 @@ let AlarmService = {
         throw Components.results.NS_ERROR_NOT_IMPLEMENTED;
       }
     );
   },
 
   _fireSystemMessage: function _fireSystemMessage(aAlarm) {
     debug("Fire system message: " + JSON.stringify(aAlarm));
     let manifestURI = Services.io.newURI(aAlarm.manifestURL, null, null);
-    messenger.sendMessage("alarm", aAlarm, manifestURI);
+    let pageURI = Services.io.newURI(aAlarm.pageURL, null, null);
+    messenger.sendMessage("alarm", aAlarm, pageURI, manifestURI);
   },
 
   _onAlarmFired: function _onAlarmFired() {
     debug("_onAlarmFired()");
 
     if (this._currentAlarm) {
       this._fireSystemMessage(this._currentAlarm);
       this._removeAlarmFromDb(this._currentAlarm.id, null);
--- a/dom/alarm/AlarmsManager.js
+++ b/dom/alarm/AlarmsManager.js
@@ -63,17 +63,22 @@ AlarmsManager.prototype = {
       default:
         throw Components.results.NS_ERROR_NOT_IMPLEMENTED;
         break;
     }
 
     let request = this.createRequest();
     this._cpmm.sendAsyncMessage(
       "AlarmsManager:Add", 
-      { requestId: this.getRequestId(request), date: aDate, ignoreTimezone: isIgnoreTimezone, data: aData, manifestURL: this._manifestURL }
+      { requestId: this.getRequestId(request),
+        date: aDate,
+        ignoreTimezone: isIgnoreTimezone,
+        data: aData,
+        pageURL: this._pageURL,
+        manifestURL: this._manifestURL }
     );
     return request;
   },
 
   remove: function remove(aId) {
     debug("remove()");
 
     return this._cpmm.sendSyncMessage(
@@ -151,16 +156,17 @@ AlarmsManager.prototype = {
 
     // Add the valid messages to be listened.
     this.initHelper(aWindow, ["AlarmsManager:Add:Return:OK", "AlarmsManager:Add:Return:KO", 
                               "AlarmsManager:GetAll:Return:OK", "AlarmsManager:GetAll:Return:KO"]);
 
     // Get the manifest URL if this is an installed app
     let appsService = Cc["@mozilla.org/AppsService;1"]
                         .getService(Ci.nsIAppsService);
+    this._pageURL = principal.URI.spec;
     this._manifestURL = appsService.getManifestURLByLocalId(principal.appId);
   },
 
   // Called from DOMRequestIpcHelper.
   uninit: function uninit() {
     debug("uninit()");
   },
 }
--- a/dom/apps/src/Webapps.jsm
+++ b/dom/apps/src/Webapps.jsm
@@ -34,16 +34,18 @@ XPCOMUtils.defineLazyServiceGetter(this,
 
 XPCOMUtils.defineLazyGetter(this, "msgmgr", function() {
   return Cc["@mozilla.org/system-message-internal;1"]
          .getService(Ci.nsISystemMessagesInternal);
 });
 
 #ifdef MOZ_WIDGET_GONK
   const DIRECTORY_NAME = "webappsDir";
+#elifdef ANDROID
+  const DIRECTORY_NAME = "webappsDir";
 #else
   // If we're executing in the context of the webapp runtime, the data files
   // are in a different directory (currently the Firefox profile that installed
   // the webapp); otherwise, they're in the current profile.
   const DIRECTORY_NAME = WEBAPP_RUNTIME ? "WebappRegD" : "ProfD";
 #endif
 
 let DOMApplicationRegistry = {
@@ -53,17 +55,17 @@ let DOMApplicationRegistry = {
 
   init: function() {
     this.messages = ["Webapps:Install", "Webapps:Uninstall",
                     "Webapps:GetSelf",
                     "Webapps:GetInstalled", "Webapps:GetNotInstalled",
                     "Webapps:Launch", "Webapps:GetAll",
                     "Webapps:InstallPackage", "Webapps:GetBasePath",
                     "WebApps:GetAppByManifestURL", "WebApps:GetAppLocalIdByManifestURL",
-                    "WebApps:GetAppByLocalId", "Webapps:GetManifestURLByLocalId"];
+                    "WebApps:GetAppByLocalId", "WebApps:GetManifestURLByLocalId"];
 
     this.messages.forEach((function(msgName) {
       ppmm.addMessageListener(msgName, this);
     }).bind(this));
 
     Services.obs.addObserver(this, "xpcom-shutdown", false);
 
     this.appsFile = FileUtils.getFile(DIRECTORY_NAME,
@@ -109,16 +111,20 @@ let DOMApplicationRegistry = {
   _registerActivities: function(aManifest, aApp) {
     if (!aManifest.activities) {
       return;
     }
 
     let manifest = new DOMApplicationManifest(aManifest, aApp.origin);
     for (let activity in aManifest.activities) {
       let description = aManifest.activities[activity];
+      if (!description.href) {
+        description.href = manifest.launch_path;
+      }
+      description.href = manifest.resolveFromOrigin(description.href);
       let json = {
         "manifest": aApp.manifestURL,
         "name": activity,
         "title": manifest.name,
         "icon": manifest.iconURLForSize(128),
         "description": description
       }
       cpmm.sendAsyncMessage("Activities:Register", json);
--- a/dom/base/nsGlobalWindow.cpp
+++ b/dom/base/nsGlobalWindow.cpp
@@ -65,16 +65,17 @@
 #include "mozilla/dom/workers/Workers.h"
 #include "nsJSPrincipals.h"
 #include "mozilla/Attributes.h"
 
 // Interfaces Needed
 #include "nsIFrame.h"
 #include "nsCanvasFrame.h"
 #include "nsIWidget.h"
+#include "nsIWidgetListener.h"
 #include "nsIBaseWindow.h"
 #include "nsDeviceSensors.h"
 #include "nsIContent.h"
 #include "nsIContentViewerEdit.h"
 #include "nsIDocShell.h"
 #include "nsIDocShellLoadInfo.h"
 #include "nsIDocShellTreeItem.h"
 #include "nsIDocShellTreeNode.h"
@@ -7703,20 +7704,21 @@ nsGlobalWindow::ActivateOrDeactivate(boo
   nsCOMPtr<nsIDOMWindow> topLevelWindow;
   if (topLevelWidget == mainWidget) {
     topLevelWindow = static_cast<nsIDOMWindow*>(this);
   } else {
     // This is a workaround for the following problem:
     // When a window with an open sheet loses focus, only the sheet window
     // receives the NS_DEACTIVATE event. However, it's not the sheet that
     // should lose the active styling, but the containing top level window.
-    void* clientData;
-    topLevelWidget->GetClientData(clientData); // clientData is nsXULWindow
-    nsISupports* data = static_cast<nsISupports*>(clientData);
-    nsCOMPtr<nsIInterfaceRequestor> req(do_QueryInterface(data));
+
+    // widgetListener should be a nsXULWindow
+    nsIWidgetListener* listener = topLevelWidget->GetWidgetListener();
+    nsCOMPtr<nsIXULWindow> window = listener->GetXULWindow();
+    nsCOMPtr<nsIInterfaceRequestor> req(do_QueryInterface(window));
     topLevelWindow = do_GetInterface(req);
   }
   if (topLevelWindow) {
     nsCOMPtr<nsPIDOMWindow> piWin(do_QueryInterface(topLevelWindow));
     piWin->SetActive(aActivate);
   }
 }
 
--- a/dom/base/nsScriptNameSpaceManager.cpp
+++ b/dom/base/nsScriptNameSpaceManager.cpp
@@ -216,17 +216,19 @@ nsScriptNameSpaceManager::FillHashWithDO
     return NS_OK;
   }
 
   bool found_old;
   nsCOMPtr<nsIInterfaceInfo> if_info;
   const char *if_name = nullptr;
   const nsIID *iid;
 
-  for ( ; domInterfaces->IsDone() == NS_ENUMERATOR_FALSE; domInterfaces->Next()) {
+  for ( ;
+       domInterfaces->IsDone() == static_cast<nsresult>(NS_ENUMERATOR_FALSE);
+       domInterfaces->Next()) {
     rv = domInterfaces->CurrentItem(getter_AddRefs(entry));
     NS_ENSURE_SUCCESS(rv, rv);
 
     nsCOMPtr<nsIInterfaceInfo> if_info(do_QueryInterface(entry));
     if_info->GetNameShared(&if_name);
     if_info->GetIIDShared(&iid);
     rv = RegisterInterface(if_name + sizeof(NS_DOM_INTERFACE_PREFIX) - 1,
                            iid, &found_old);
--- a/dom/browser-element/mochitest/browserElementTestHelpers.js
+++ b/dom/browser-element/mochitest/browserElementTestHelpers.js
@@ -44,24 +44,16 @@ const browserElementTestHelpers = {
   getEnabledPref: function() {
     return this._getBoolPref('dom.mozBrowserFramesEnabled');
   },
 
   setEnabledPref: function(value) {
     this._setBoolPref('dom.mozBrowserFramesEnabled', value);
   },
 
-  getWhitelistPref: function() {
-    return this._getCharPref('dom.mozBrowserFramesWhitelist');
-  },
-
-  setWhitelistPref: function(whitelist) {
-    this._setCharPref('dom.mozBrowserFramesWhitelist', whitelist);
-  },
-
   getOOPDisabledPref: function() {
     return this._getBoolPref('dom.ipc.tabs.disabled');
   },
 
   setOOPDisabledPref: function(value) {
     this._setBoolPref('dom.ipc.tabs.disabled', value);
   },
 
@@ -76,35 +68,45 @@ const browserElementTestHelpers = {
   getPageThumbsEnabledPref: function() {
     return this._getBoolPref('browser.pageThumbs.enabled');
   },
 
   setPageThumbsEnabledPref: function(value) {
     this._setBoolPref('browser.pageThumbs.enabled', value);
   },
 
-  addToWhitelist: function() {
-    var whitelist = this.getWhitelistPref();
-    whitelist += ',  http://' + window.location.host + ',  ';
-    this.setWhitelistPref(whitelist);
+  addPermission: function() {
+    SpecialPowers.addPermission("browser", true, document);
+    this.tempPermissions.push(location.href)
+  },
+
+  removeAllTempPermissions: function() {
+    for(var i = 0; i < this.tempPermissions.length; i++) {
+      SpecialPowers.removePermission("browser", this.tempPermissions[i]);
+    }
+  },
+
+  addPermissionForUrl: function(url) {
+    SpecialPowers.addPermission("browser", true, url);
+    this.tempPermissions.push(url);
   },
 
   restoreOriginalPrefs: function() {
     this.setEnabledPref(this.origEnabledPref);
-    this.setWhitelistPref(this.origWhitelistPref);
     this.setOOPDisabledPref(this.origOOPDisabledPref);
     this.setOOPByDefaultPref(this.origOOPByDefaultPref);
     this.setPageThumbsEnabledPref(this.origPageThumbsEnabledPref);
+    this.removeAllTempPermissions();
   },
 
   'origEnabledPref': null,
-  'origWhitelistPref': null,
   'origOOPDisabledPref': null,
   'origOOPByDefaultPref': null,
   'origPageThumbsEnabledPref': null,
+  'tempPermissions': [],
 
   // Some basically-empty pages from different domains you can load.
   'emptyPage1': 'http://example.com' +
                 window.location.pathname.substring(0, window.location.pathname.lastIndexOf('/')) +
                 '/file_empty.html',
   'emptyPage2': 'http://example.org' +
                 window.location.pathname.substring(0, window.location.pathname.lastIndexOf('/')) +
                 '/file_empty.html',
@@ -112,17 +114,16 @@ const browserElementTestHelpers = {
                 window.location.pathname.substring(0, window.location.pathname.lastIndexOf('/')) +
                 '/file_empty.html',
   'focusPage': 'http://example.org' +
                 window.location.pathname.substring(0, window.location.pathname.lastIndexOf('/')) +
                 '/file_focus.html',
 };
 
 browserElementTestHelpers.origEnabledPref = browserElementTestHelpers.getEnabledPref();
-browserElementTestHelpers.origWhitelistPref = browserElementTestHelpers.getWhitelistPref();
 browserElementTestHelpers.origOOPDisabledPref = browserElementTestHelpers.getOOPDisabledPref();
 browserElementTestHelpers.origOOPByDefaultPref = browserElementTestHelpers.getOOPByDefaultPref();
 browserElementTestHelpers.origPageThumbsEnabledPref = browserElementTestHelpers.getPageThumbsEnabledPref();
 
 // Disable tab view; it seriously messes us up.
 browserElementTestHelpers.setPageThumbsEnabledPref(false);
 
 // Enable or disable OOP-by-default depending on the test's filename.  You can
--- a/dom/browser-element/mochitest/browserElement_Alert.js
+++ b/dom/browser-element/mochitest/browserElement_Alert.js
@@ -7,17 +7,17 @@
 SimpleTest.waitForExplicitFinish();
 
 var numPendingChildTests = 0;
 var iframe;
 var mm;
 
 function runTest() {
   browserElementTestHelpers.setEnabledPref(true);
-  browserElementTestHelpers.addToWhitelist();
+  browserElementTestHelpers.addPermission();
 
   iframe = document.createElement('iframe');
   iframe.mozbrowser = true;
   document.body.appendChild(iframe);
 
   mm = SpecialPowers.getBrowserFrameMessageManager(iframe);
   mm.addMessageListener('test-success', function(msg) {
     numPendingChildTests--;
--- a/dom/browser-element/mochitest/browserElement_AlertInFrame.js
+++ b/dom/browser-element/mochitest/browserElement_AlertInFrame.js
@@ -3,17 +3,17 @@
 
 // Test that alert works from inside an <iframe> inside an <iframe mozbrowser>.
 "use strict";
 
 SimpleTest.waitForExplicitFinish();
 
 function runTest() {
   browserElementTestHelpers.setEnabledPref(true);
-  browserElementTestHelpers.addToWhitelist();
+  browserElementTestHelpers.addPermission();
 
   var iframe = document.createElement('iframe');
   iframe.mozbrowser = true;
 
   iframe.addEventListener('mozbrowsershowmodalprompt', function(e) {
     is(e.detail.message, 'Hello');
     SimpleTest.finish();
   });
--- a/dom/browser-element/mochitest/browserElement_AppWindowNamespace.js
+++ b/dom/browser-element/mochitest/browserElement_AppWindowNamespace.js
@@ -3,17 +3,17 @@
 
 // Bug 780351 - Test that mozapp divides the window name namespace.
 "use strict";
 
 SimpleTest.waitForExplicitFinish();
 
 function runTest() {
   browserElementTestHelpers.setEnabledPref(true);
-  browserElementTestHelpers.addToWhitelist();
+  browserElementTestHelpers.addPermission();
 
   var iframe1 = document.createElement('iframe');
   iframe1.mozbrowser = true;
   iframe1.setAttribute('mozapp', 'http://example.org/manifest.webapp');
 
   // Two mozapp frames for different apps with the same code both do the same
   // window.open("foo", "bar") call.  We should get two mozbrowseropenwindow
   // events.
--- a/dom/browser-element/mochitest/browserElement_BackForward.js
+++ b/dom/browser-element/mochitest/browserElement_BackForward.js
@@ -14,17 +14,17 @@ function addOneShotIframeEventListener(e
     fn(e);
   };
 
   iframe.addEventListener(event, wrapper);
 }
 
 function runTest() {
   browserElementTestHelpers.setEnabledPref(true);
-  browserElementTestHelpers.addToWhitelist();
+  browserElementTestHelpers.addPermission();
 
   iframe = document.createElement('iframe');
   iframe.mozbrowser = true;
 
   addOneShotIframeEventListener('mozbrowserloadend', function() {
     SimpleTest.executeSoon(test2);
   });
 
--- a/dom/browser-element/mochitest/browserElement_BrowserWindowNamespace.js
+++ b/dom/browser-element/mochitest/browserElement_BrowserWindowNamespace.js
@@ -6,17 +6,17 @@
 // they share a window name namespace.
 
 "use strict";
 
 SimpleTest.waitForExplicitFinish();
 
 function runTest() {
   browserElementTestHelpers.setEnabledPref(true);
-  browserElementTestHelpers.addToWhitelist();
+  browserElementTestHelpers.addPermission();
 
   var iframe1 = document.createElement('iframe');
   iframe1.mozbrowser = true;
 
   // Two mozbrowser frames with the same code both do the same
   // window.open("foo", "bar") call.  We should only get one
   // mozbrowseropenwindow event.
 
--- a/dom/browser-element/mochitest/browserElement_Close.js
+++ b/dom/browser-element/mochitest/browserElement_Close.js
@@ -3,17 +3,17 @@
 
 // Test that window.close() works.
 "use strict";
 
 SimpleTest.waitForExplicitFinish();
 
 function runTest() {
   browserElementTestHelpers.setEnabledPref(true);
-  browserElementTestHelpers.addToWhitelist();
+  browserElementTestHelpers.addPermission();
 
   var iframe = document.createElement('iframe');
   iframe.mozbrowser = true;
   document.body.appendChild(iframe);
 
   iframe.addEventListener("mozbrowserclose", function(e) {
     ok(true, "got mozbrowserclose event.");
     SimpleTest.finish();
--- a/dom/browser-element/mochitest/browserElement_CloseFromOpener.js
+++ b/dom/browser-element/mochitest/browserElement_CloseFromOpener.js
@@ -3,17 +3,17 @@
 
 // Bug 764718 - Test that window.close() works from the opener window.
 "use strict";
 
 SimpleTest.waitForExplicitFinish();
 
 function runTest() {
   browserElementTestHelpers.setEnabledPref(true);
-  browserElementTestHelpers.addToWhitelist();
+  browserElementTestHelpers.addPermission();
 
   var iframe = document.createElement('iframe');
   iframe.mozbrowser = true;
 
   iframe.addEventListener('mozbrowseropenwindow', function(e) {
     ok(true, "got openwindow event.");
     document.body.appendChild(e.detail.frameElement);
 
--- a/dom/browser-element/mochitest/browserElement_ContextmenuEvents.js
+++ b/dom/browser-element/mochitest/browserElement_ContextmenuEvents.js
@@ -26,17 +26,17 @@ var iframeScript = function() {
 
 var trigger1 = function() {
   content.fireContextMenu(content.document.getElementById('menu1-trigger'));
 };
 
 function runTest() {
 
   browserElementTestHelpers.setEnabledPref(true);
-  browserElementTestHelpers.addToWhitelist();
+  browserElementTestHelpers.addPermission();
 
   var iframe1 = document.createElement('iframe');
   iframe1.mozbrowser = true;
   document.body.appendChild(iframe1);
   iframe1.src = 'data:text/html,<html>' +
     '<body>' +
     '<menu type="context" id="menu1" label="firstmenu">' +
       '<menuitem label="foo" onclick="window.ctxCallbackFired(\'foo\')"></menuitem>' +
--- a/dom/browser-element/mochitest/browserElement_DataURI.js
+++ b/dom/browser-element/mochitest/browserElement_DataURI.js
@@ -3,17 +3,17 @@
 
 // Test that data: URIs work with mozbrowserlocationchange events.
 
 "use strict";
 SimpleTest.waitForExplicitFinish();
 
 function runTest() {
   browserElementTestHelpers.setEnabledPref(true);
-  browserElementTestHelpers.addToWhitelist();
+  browserElementTestHelpers.addPermission();
 
   var iframe1 = document.createElement('iframe');
   iframe1.mozbrowser = true;
   iframe1.id = 'iframe1';
   iframe1.addEventListener('mozbrowserloadend', function if1_loadend() {
     iframe1.removeEventListener('mozbrowserloadend', if1_loadend);
     ok(true, 'Got first loadend event.');
     SimpleTest.executeSoon(runTest2);
--- a/dom/browser-element/mochitest/browserElement_ErrorSecurity.js
+++ b/dom/browser-element/mochitest/browserElement_ErrorSecurity.js
@@ -4,17 +4,17 @@
 // Bug 764718 - Test that mozbrowsererror works for a security error.
 
 "use strict";
 
 SimpleTest.waitForExplicitFinish();
 
 function runTest() {
   browserElementTestHelpers.setEnabledPref(true);
-  browserElementTestHelpers.addToWhitelist();
+  browserElementTestHelpers.addPermission();
 
   var iframe = document.createElement('iframe');
   iframe.mozbrowser = true;
 
   iframe.addEventListener("mozbrowsererror", function(e) {
     ok(true, "Got mozbrowsererror event.");
     ok(e.detail.type, "Event's detail has a |type| param.");
     SimpleTest.finish();
--- a/dom/browser-element/mochitest/browserElement_ForwardName.js
+++ b/dom/browser-element/mochitest/browserElement_ForwardName.js
@@ -5,17 +5,17 @@
 // forwarded down to remote mozbrowsers.
 
 "use strict";
 
 SimpleTest.waitForExplicitFinish();
 
 function runTest() {
   browserElementTestHelpers.setEnabledPref(true);
-  browserElementTestHelpers.addToWhitelist();
+  browserElementTestHelpers.addPermission();
 
   var iframe = document.createElement('iframe');
   iframe.mozbrowser = true;
   iframe.setAttribute('name', 'foo');
 
   iframe.addEventListener("mozbrowseropenwindow", function(e) {
     ok(false, 'Got mozbrowseropenwindow, but should not have.');
   });
--- a/dom/browser-element/mochitest/browserElement_GetScreenshot.js
+++ b/dom/browser-element/mochitest/browserElement_GetScreenshot.js
@@ -4,17 +4,17 @@
 // Test the getScreenshot property for mozbrowser
 "use strict";
 
 SimpleTest.waitForExplicitFinish();
 
 function runTest() {
 
   browserElementTestHelpers.setEnabledPref(true);
-  browserElementTestHelpers.addToWhitelist();
+  browserElementTestHelpers.addPermission();
 
   var iframe1 = document.createElement('iframe');
   iframe1.mozbrowser = true;
   document.body.appendChild(iframe1);
   iframe1.src = 'data:text/html,<html>' +
     '<body style="background:green">hello</body></html>';
 
   var screenshots = [];
--- a/dom/browser-element/mochitest/browserElement_Iconchange.js
+++ b/dom/browser-element/mochitest/browserElement_Iconchange.js
@@ -11,17 +11,17 @@ function createHtml(link) {
 }
 
 function createLink(name) {
   return '<link rel="icon" type="image/png" href="http://example.com/' + name + '.png">';
 }
 
 function runTest() {
   browserElementTestHelpers.setEnabledPref(true);
-  browserElementTestHelpers.addToWhitelist();
+  browserElementTestHelpers.addPermission();
 
   var iframe1 = document.createElement('iframe');
   iframe1.mozbrowser = true;
   document.body.appendChild(iframe1);
 
   // iframe2 is a red herring; we modify its favicon but don't listen for
   // iconchanges; we want to make sure that its iconchange events aren't
   // picked up by the listener on iframe1.
--- a/dom/browser-element/mochitest/browserElement_KeyEvents.js
+++ b/dom/browser-element/mochitest/browserElement_KeyEvents.js
@@ -14,17 +14,17 @@ let whitelistedEvents = [
   Ci.nsIDOMKeyEvent.DOM_VK_F5,       // Search button.
   Ci.nsIDOMKeyEvent.DOM_VK_PAGE_UP,  // Volume up.
   Ci.nsIDOMKeyEvent.DOM_VK_PAGE_DOWN // Volume down.
 ];
 
 SimpleTest.waitForExplicitFinish();
 
 browserElementTestHelpers.setEnabledPref(true);
-browserElementTestHelpers.addToWhitelist();
+browserElementTestHelpers.addPermission();
 browserElementTestHelpers.setOOPDisabledPref(true); // this is breaking the autofocus.
 
 var iframe = document.createElement('iframe');
 iframe.mozbrowser = true;
 iframe.src = browserElementTestHelpers.focusPage;
 document.body.appendChild(iframe);
 
 // Number of expected events at which point we will consider the test as done.
--- a/dom/browser-element/mochitest/browserElement_LoadEvents.js
+++ b/dom/browser-element/mochitest/browserElement_LoadEvents.js
@@ -4,17 +4,17 @@
 // Test that an iframe with the |mozbrowser| attribute emits mozbrowserloadX
 // events when this page is in the whitelist.
 
 "use strict";
 SimpleTest.waitForExplicitFinish();
 
 function runTest() {
   browserElementTestHelpers.setEnabledPref(true);
-  browserElementTestHelpers.addToWhitelist();
+  browserElementTestHelpers.addPermission();
 
   // Load emptypage1 into the iframe, wait for that to finish loading, then
   // call runTest2.
   //
   // This should trigger loadstart, locationchange, and loadend events.
 
   var seenLoadEnd = false;
   var seenLoadStart = false;
--- a/dom/browser-element/mochitest/browserElement_OpenNamed.js
+++ b/dom/browser-element/mochitest/browserElement_OpenNamed.js
@@ -6,17 +6,17 @@
 
 "use strict";
 SimpleTest.waitForExplicitFinish();
 
 var iframe;
 var popupFrame;
 function runTest() {
   browserElementTestHelpers.setEnabledPref(true);
-  browserElementTestHelpers.addToWhitelist();
+  browserElementTestHelpers.addPermission();
 
   iframe = document.createElement('iframe');
   iframe.mozbrowser = true;
 
   var gotPopup = false;
   iframe.addEventListener('mozbrowseropenwindow', function(e) {
     is(gotPopup, false, 'Should get just one popup.');
     gotPopup = true;
--- a/dom/browser-element/mochitest/browserElement_OpenWindow.js
+++ b/dom/browser-element/mochitest/browserElement_OpenWindow.js
@@ -3,17 +3,17 @@
 
 // Bug 742944 - Test that window.open works with <iframe mozbrowser>.
 
 "use strict";
 SimpleTest.waitForExplicitFinish();
 
 function runTest() {
   browserElementTestHelpers.setEnabledPref(true);
-  browserElementTestHelpers.addToWhitelist();
+  browserElementTestHelpers.addPermission();
 
   var iframe = document.createElement('iframe');
   iframe.mozbrowser = true;
 
   var gotPopup = false;
   iframe.addEventListener('mozbrowseropenwindow', function(e) {
     is(gotPopup, false, 'Should get just one popup.');
     gotPopup = true;
--- a/dom/browser-element/mochitest/browserElement_OpenWindowDifferentOrigin.js
+++ b/dom/browser-element/mochitest/browserElement_OpenWindowDifferentOrigin.js
@@ -3,17 +3,17 @@
 
 // Bug 769182 - window.open to a different origin should load the page.
 
 "use strict";
 SimpleTest.waitForExplicitFinish();
 
 function runTest() {
   browserElementTestHelpers.setEnabledPref(true);
-  browserElementTestHelpers.addToWhitelist();
+  browserElementTestHelpers.addPermission();
 
   var iframe = document.createElement('iframe');
   iframe.mozbrowser = true;
 
   iframe.addEventListener('mozbrowseropenwindow', function(e) {
     ok(true, 'Got first window.open call');
 
     e.detail.frameElement.addEventListener('mozbrowseropenwindow', function(e) {
--- a/dom/browser-element/mochitest/browserElement_OpenWindowInFrame.js
+++ b/dom/browser-element/mochitest/browserElement_OpenWindowInFrame.js
@@ -9,17 +9,17 @@
 // mozbrowser.  OpenWindowInFrame loads file_browserElement_Open1.html inside
 // an iframe.
 
 "use strict";
 SimpleTest.waitForExplicitFinish();
 
 function runTest() {
   browserElementTestHelpers.setEnabledPref(true);
-  browserElementTestHelpers.addToWhitelist();
+  browserElementTestHelpers.addPermission();
 
   var iframe = document.createElement('iframe');
   iframe.mozbrowser = true;
 
   var gotPopup = false;
   iframe.addEventListener('mozbrowseropenwindow', function(e) {
     is(gotPopup, false, 'Should get just one popup.');
     gotPopup = true;
--- a/dom/browser-element/mochitest/browserElement_OpenWindowRejected.js
+++ b/dom/browser-element/mochitest/browserElement_OpenWindowRejected.js
@@ -4,17 +4,17 @@
 // Bug 742944 - Do window.open from inside <iframe mozbrowser>.  But then
 // reject the call.  This shouldn't cause problems (crashes, leaks).
 
 "use strict";
 SimpleTest.waitForExplicitFinish();
 
 function runTest() {
   browserElementTestHelpers.setEnabledPref(true);
-  browserElementTestHelpers.addToWhitelist();
+  browserElementTestHelpers.addPermission();
 
   var iframe = document.createElement('iframe');
   iframe.mozbrowser = true;
 
   iframe.addEventListener('mozbrowseropenwindow', function(e) {
     ok(e.detail.url.indexOf('does_not_exist.html') != -1,
        'Opened URL; got ' + e.detail.url);
     is(e.detail.name, '');
--- a/dom/browser-element/mochitest/browserElement_OpenWindowRejected2.js
+++ b/dom/browser-element/mochitest/browserElement_OpenWindowRejected2.js
@@ -8,17 +8,17 @@
 // adding the iframe element to our DOM, instead of by not calling
 // preventDefault() on the event.
 
 "use strict";
 SimpleTest.waitForExplicitFinish();
 
 function runTest() {
   browserElementTestHelpers.setEnabledPref(true);
-  browserElementTestHelpers.addToWhitelist();
+  browserElementTestHelpers.addPermission();
 
   var iframe = document.createElement('iframe');
   iframe.mozbrowser = true;
 
   iframe.addEventListener('mozbrowseropenwindow', function(e) {
     ok(e.detail.url.indexOf('does_not_exist.html') != -1,
        'Opened URL; got ' + e.detail.url);
     is(e.detail.name, '');
--- a/dom/browser-element/mochitest/browserElement_PromptCheck.js
+++ b/dom/browser-element/mochitest/browserElement_PromptCheck.js
@@ -7,17 +7,17 @@
 //
 // At the moment, we treat alertCheck/promptCheck/confirmCheck just like a
 // normal alert.  But it's different to nsIPrompt!
 "use strict";
 
 SimpleTest.waitForExplicitFinish();
 
 browserElementTestHelpers.setEnabledPref(true);
-browserElementTestHelpers.addToWhitelist();
+browserElementTestHelpers.addPermission();
 
 // Test harness sets dom.successive_dialog_time_limit to 0 for some bizarre
 // reason.  That's not normal usage, and it keeps us from testing alertCheck!
 const dialogTimeLimitPrefName = 'dom.successive_dialog_time_limit';
 var oldDialogTimeLimitPref;
 try {
   oldDialogTimeLimitPref = SpecialPowers.getIntPref(dialogTimeLimitPrefName);
 }
--- a/dom/browser-element/mochitest/browserElement_PromptConfirm.js
+++ b/dom/browser-element/mochitest/browserElement_PromptConfirm.js
@@ -7,17 +7,17 @@
 // We use alert() to communicate the return values of prompt/confirm back to
 // ourselves.
 "use strict";
 
 SimpleTest.waitForExplicitFinish();
 
 function runTest() {
   browserElementTestHelpers.setEnabledPref(true);
-  browserElementTestHelpers.addToWhitelist();
+  browserElementTestHelpers.addPermission();
 
   var iframe = document.createElement('iframe');
   iframe.mozbrowser = true;
   document.body.appendChild(iframe);
 
   var prompts = [
     {msg: 1, type: 'alert', rv: 42, expected: 'undefined'},
     {msg: 2, type: 'confirm', rv: true, expected: 'true'},
--- a/dom/browser-element/mochitest/browserElement_Reload.js
+++ b/dom/browser-element/mochitest/browserElement_Reload.js
@@ -14,17 +14,17 @@ var iframeScript = function() {
 
 var mm;
 var iframe;
 var loadedEvents = 0;
 var countAcc;
 
 function runTest() {
   browserElementTestHelpers.setEnabledPref(true);
-  browserElementTestHelpers.addToWhitelist();
+  browserElementTestHelpers.addPermission();
 
   iframe = document.createElement('iframe');
   iframe.mozbrowser = true;
 
   iframe.addEventListener('mozbrowserloadend', mozbrowserLoaded);
 
   iframe.src = 'file_bug741717.sjs';
   document.body.appendChild(iframe);
--- a/dom/browser-element/mochitest/browserElement_ScrollEvent.js
+++ b/dom/browser-element/mochitest/browserElement_ScrollEvent.js
@@ -3,17 +3,17 @@
 
 // Test that scroll event bubbles up.
 "use strict";
 
 SimpleTest.waitForExplicitFinish();
 
 function runTest() {
   browserElementTestHelpers.setEnabledPref(true);
-  browserElementTestHelpers.addToWhitelist();
+  browserElementTestHelpers.addPermission();
 
   var iframe = document.createElement('iframe');
   iframe.mozbrowser = true;
   document.body.appendChild(iframe);
 
   iframe.addEventListener("mozbrowserscroll", function(e) {
     ok(true, "got mozbrowserscroll event.");
     ok(e.detail, "event.detail is not null.");
--- a/dom/browser-element/mochitest/browserElement_SecurityChange.js
+++ b/dom/browser-element/mochitest/browserElement_SecurityChange.js
@@ -4,17 +4,17 @@
 // Bug 763694 - Test that <iframe mozbrowser> delivers proper
 // mozbrowsersecuritychange events.
 
 "use strict";
 SimpleTest.waitForExplicitFinish();
 
 function runTest() {
   browserElementTestHelpers.setEnabledPref(true);
-  browserElementTestHelpers.addToWhitelist();
+  browserElementTestHelpers.addPermission();
 
   var iframe = document.createElement('iframe');
   iframe.mozbrowser = true;
 
   var lastSecurityState;
   iframe.addEventListener('mozbrowsersecuritychange', function(e) {
     lastSecurityState = e.detail;
   });
--- a/dom/browser-element/mochitest/browserElement_SendEvent.js
+++ b/dom/browser-element/mochitest/browserElement_SendEvent.js
@@ -3,17 +3,17 @@
 
 // Test that sendMouseEvent dispatch events.
 "use strict";
 
 SimpleTest.waitForExplicitFinish();
 
 function runTest() {
   browserElementTestHelpers.setEnabledPref(true);
-  browserElementTestHelpers.addToWhitelist();
+  browserElementTestHelpers.addPermission();
 
   var iframe = document.createElement("iframe");
   iframe.mozbrowser = true;
   document.body.appendChild(iframe);
 
   iframe.addEventListener("mozbrowserloadend", function onloadend(e) {
     iframe.sendMouseEvent("mousedown", 10, 10, 0, 1, 0);
   });
--- a/dom/browser-element/mochitest/browserElement_SetVisible.js
+++ b/dom/browser-element/mochitest/browserElement_SetVisible.js
@@ -12,17 +12,17 @@ var iframeScript = function() {
       hidden: content.document.mozHidden
     });
   }, false);
 }
 
 function runTest() {
 
   browserElementTestHelpers.setEnabledPref(true);
-  browserElementTestHelpers.addToWhitelist();
+  browserElementTestHelpers.addPermission();
 
   var mm;
   var numEvents = 0;
   var iframe1 = document.createElement('iframe');
   iframe1.mozbrowser = true;
   iframe1.src = 'data:text/html,1';
 
   document.body.appendChild(iframe1);
--- a/dom/browser-element/mochitest/browserElement_SetVisibleFrames.js
+++ b/dom/browser-element/mochitest/browserElement_SetVisibleFrames.js
@@ -11,17 +11,17 @@
 "use strict";
 
 SimpleTest.waitForExplicitFinish();
 
 var iframe;
 
 function runTest() {
   browserElementTestHelpers.setEnabledPref(true);
-  browserElementTestHelpers.addToWhitelist();
+  browserElementTestHelpers.addPermission();
 
   iframe = document.createElement('iframe');
   iframe.mozbrowser = true;
 
   // Our test involves three <iframe mozbrowser>'s, parent, child1, and child2.
   // child1 and child2 are contained inside parent.  child1 is visibile, and
   // child2 is not.
   //
--- a/dom/browser-element/mochitest/browserElement_SetVisibleFrames2.js
+++ b/dom/browser-element/mochitest/browserElement_SetVisibleFrames2.js
@@ -5,17 +5,17 @@
 // inside an invisible <iframe mozbrowser> doesn't trigger any events.
 
 "use strict";
 
 SimpleTest.waitForExplicitFinish();
 
 function runTest() {
   browserElementTestHelpers.setEnabledPref(true);
-  browserElementTestHelpers.addToWhitelist();
+  browserElementTestHelpers.addPermission();
 
   var iframe = document.createElement('iframe');
   iframe.mozbrowser = true;
 
   // We need remote = false here until bug 761935 is fixed; see
   // SetVisibleFrames.js for an explanation.
   iframe.remote = false;
 
--- a/dom/browser-element/mochitest/browserElement_Stop.js
+++ b/dom/browser-element/mochitest/browserElement_Stop.js
@@ -12,17 +12,17 @@
 SimpleTest.waitForExplicitFinish();
 
 var iframe;
 var stopped = false;
 var imgSrc = 'http://test/tests/dom/browser-element/mochitest/file_bug709759.sjs';
 
 function runTest() {
   browserElementTestHelpers.setEnabledPref(true);
-  browserElementTestHelpers.addToWhitelist();
+  browserElementTestHelpers.addPermission();
 
   iframe = document.createElement('iframe');
   iframe.mozbrowser = true;
 
   iframe.addEventListener('mozbrowserloadend', loadend);
   iframe.src = 'data:text/html,<html>' +
     '<body><img src="' + imgSrc + '" /></body></html>';
 
--- a/dom/browser-element/mochitest/browserElement_TargetBlank.js
+++ b/dom/browser-element/mochitest/browserElement_TargetBlank.js
@@ -4,17 +4,17 @@
 // Bug 764718 - Test that clicking a link with _target=blank works.
 
 "use strict";
 
 SimpleTest.waitForExplicitFinish();
 
 function runTest() {
   browserElementTestHelpers.setEnabledPref(true);
-  browserElementTestHelpers.addToWhitelist();
+  browserElementTestHelpers.addPermission();
 
   var iframe = document.createElement('iframe');
   iframe.mozbrowser = true;
 
   iframe.addEventListener('mozbrowseropenwindow', function(e) {
     is(e.detail.url, 'http://example.com/');
     SimpleTest.finish();
   });
--- a/dom/browser-element/mochitest/browserElement_TargetTop.js
+++ b/dom/browser-element/mochitest/browserElement_TargetTop.js
@@ -4,17 +4,17 @@
 // Bug 771273 - Check that window.open(url, '_top') works properly with <iframe
 // mozbrowser>.
 "use strict";
 
 SimpleTest.waitForExplicitFinish();
 
 function runTest() {
   browserElementTestHelpers.setEnabledPref(true);
-  browserElementTestHelpers.addToWhitelist();
+  browserElementTestHelpers.addPermission();
 
   var iframe = document.createElement('iframe');
   iframe.mozbrowser = true;
 
   iframe.addEventListener('mozbrowseropenwindow', function(e) {
     ok(false, 'Not expecting an openwindow event.');
   });
 
--- a/dom/browser-element/mochitest/browserElement_Titlechange.js
+++ b/dom/browser-element/mochitest/browserElement_Titlechange.js
@@ -3,17 +3,17 @@
 
 // Test that the onmozbrowsertitlechange event works.
 "use strict";
 
 SimpleTest.waitForExplicitFinish();
 
 function runTest() {
   browserElementTestHelpers.setEnabledPref(true);
-  browserElementTestHelpers.addToWhitelist();
+  browserElementTestHelpers.addPermission();
 
   var iframe1 = document.createElement('iframe');
   iframe1.mozbrowser = true;
   document.body.appendChild(iframe1);
 
   // iframe2 is a red herring; we modify its title but don't listen for
   // titlechanges; we want to make sure that its titlechange events aren't
   // picked up by the listener on iframe1.
--- a/dom/browser-element/mochitest/browserElement_TopBarrier.js
+++ b/dom/browser-element/mochitest/browserElement_TopBarrier.js
@@ -1,16 +1,16 @@
 /* Any copyright is dedicated to the public domain.
    http://creativecommons.org/publicdomain/zero/1.0/ */
 
 // Test that an <iframe mozbrowser> is a window.{top,parent,frameElement} barrier.
 "use strict";
 
 browserElementTestHelpers.setEnabledPref(true);
-browserElementTestHelpers.addToWhitelist();
+browserElementTestHelpers.addPermission();
 
 var iframe;
 function runTest() {
   iframe = document.createElement('iframe');
   iframe.addEventListener('mozbrowserloadend', function() {
     try {
       outerIframeLoaded();
     } catch(e) {
--- a/dom/browser-element/mochitest/browserElement_XFrameOptions.js
+++ b/dom/browser-element/mochitest/browserElement_XFrameOptions.js
@@ -4,17 +4,17 @@
 // Bug 770239 - Test that we can load pages with X-Frame-Options: Deny inside
 // <iframe mozbrowser>.
 "use strict";
 
 SimpleTest.waitForExplicitFinish();
 
 function runTest() {
   browserElementTestHelpers.setEnabledPref(true);
-  browserElementTestHelpers.addToWhitelist();
+  browserElementTestHelpers.addPermission();
 
   var iframe = document.createElement('iframe');
   iframe.mozbrowser = true;
 
   // The page we load will fire an alert when it successfully loads.
   iframe.addEventListener('mozbrowsershowmodalprompt', function(e) {
     ok(true, "Got alert");
     SimpleTest.finish();
--- a/dom/browser-element/mochitest/browserElement_XFrameOptionsDeny.js
+++ b/dom/browser-element/mochitest/browserElement_XFrameOptionsDeny.js
@@ -6,17 +6,17 @@
 "use strict";
 
 SimpleTest.waitForExplicitFinish();
 
 var initialScreenshot;
 
 function runTest() {
   browserElementTestHelpers.setEnabledPref(true);
-  browserElementTestHelpers.addToWhitelist();
+  browserElementTestHelpers.addPermission();
 
   var iframe = document.createElement('iframe');
   iframe.mozbrowser = true;
 
   // Our child will create two iframes, so make sure this iframe is big enough
   // to show both of them without scrolling, so taking a screenshot gets both
   // frames.
   iframe.height = '1000px';
--- a/dom/browser-element/mochitest/browserElement_XFrameOptionsSameOrigin.js
+++ b/dom/browser-element/mochitest/browserElement_XFrameOptionsSameOrigin.js
@@ -6,17 +6,17 @@
 // this page will be of a different origin.  The load should succeed.
 
 "use strict";
 
 SimpleTest.waitForExplicitFinish();
 
 function runTest() {
   browserElementTestHelpers.setEnabledPref(true);
-  browserElementTestHelpers.addToWhitelist();
+  browserElementTestHelpers.addPermission();
 
   var iframe = document.createElement('iframe');
   iframe.mozbrowser = true;
 
   // The innermost page we load will fire an alert when it successfully loads.
   iframe.addEventListener('mozbrowsershowmodalprompt', function(e) {
     ok(true, "Got alert");
     SimpleTest.finish();
--- a/dom/browser-element/mochitest/createNewTest.py
+++ b/dom/browser-element/mochitest/createNewTest.py
@@ -33,17 +33,17 @@ js_template = textwrap.dedent("""\
 
     // Bug {bug} - FILL IN TEST DESCRIPTION
     "use strict";
 
     SimpleTest.waitForExplicitFinish();
 
     function runTest() {{
       browserElementTestHelpers.setEnabledPref(true);
-      browserElementTestHelpers.addToWhitelist();
+      browserElementTestHelpers.addPermission();
 
       var iframe = document.createElement('iframe');
       iframe.mozbrowser = true;
 
       // FILL IN TEST
 
       document.body.appendChild(iframe);
     }}
--- a/dom/browser-element/mochitest/test_browserElement_NoWhitelist.html
+++ b/dom/browser-element/mochitest/test_browserElement_NoWhitelist.html
@@ -19,17 +19,17 @@ https://bugzilla.mozilla.org/show_bug.cg
 
 <script type="application/javascript;version=1.7">
 "use strict";
 
 SimpleTest.waitForExplicitFinish();
 
 function runTest() {
   browserElementTestHelpers.setEnabledPref(true);
-  browserElementTestHelpers.setWhitelistPref(' http://foobar.com');
+  browserElementTestHelpers.addPermissionForUrl('http://foobar.com');
 
   var iframe = document.createElement('iframe');
   iframe.mozbrowser = true;
   document.body.appendChild(iframe);
 
   iframe.addEventListener('mozbrowserloadstart', function() {
     ok(false, 'Should not send mozbrowserloadstart event.');
   });
--- a/dom/contacts/ContactManager.js
+++ b/dom/contacts/ContactManager.js
@@ -74,60 +74,61 @@ ContactAddress.prototype = {
                                      contractID: CONTACTADDRESS_CONTRACTID,
                                      classDescription: "ContactAddress",
                                      interfaces: [nsIDOMContactAddress],
                                      flags: nsIClassInfo.DOM_OBJECT}),
 
   QueryInterface : XPCOMUtils.generateQI([nsIDOMContactAddress])
 }
 
-//ContactEmail
+//ContactField
 
-const CONTACTEMAIL_CONTRACTID = "@mozilla.org/contactEmail;1";
-const CONTACTEMAIL_CID        = Components.ID("{94811520-c11f-11e1-afa7-0800200c9a66}");
-const nsIDOMContactEmail      = Components.interfaces.nsIDOMContactEmail;
+const CONTACTFIELD_CONTRACTID = "@mozilla.org/contactField;1";
+const CONTACTFIELD_CID        = Components.ID("{e2cb19c0-e4aa-11e1-9b23-0800200c9a66}");
+const nsIDOMContactField      = Components.interfaces.nsIDOMContactField;
 
-function ContactEmail(aType, aAddress) {
+function ContactField(aType, aValue) {
   this.type = aType || null;
-  this.address = aAddress || null;
+  this.value = aValue || null;
 };
 
-ContactEmail.prototype = {
+ContactField.prototype = {
 
-  classID : CONTACTEMAIL_CID,
-  classInfo : XPCOMUtils.generateCI({classID: CONTACTEMAIL_CID,
-                                     contractID: CONTACTEMAIL_CONTRACTID,
-                                     classDescription: "ContactEmail",
-                                     interfaces: [nsIDOMContactEmail],
+  classID : CONTACTFIELD_CID,
+  classInfo : XPCOMUtils.generateCI({classID: CONTACTFIELD_CID,
+                                     contractID: CONTACTFIELD_CONTRACTID,
+                                     classDescription: "ContactField",
+                                     interfaces: [nsIDOMContactField],
                                      flags: nsIClassInfo.DOM_OBJECT}),
 
-  QueryInterface : XPCOMUtils.generateQI([nsIDOMContactEmail])
+  QueryInterface : XPCOMUtils.generateQI([nsIDOMContactField])
 }
 
-//ContactTelephone
+//ContactTelField
 
-const CONTACTTELEPHONE_CONTRACTID = "@mozilla.org/contactTelephone;1";
-const CONTACTTELEPHONE_CID        = Components.ID("{82601b20-89e8-11e1-b0c4-0800200c9a66}");
-const nsIDOMContactTelephone      = Components.interfaces.nsIDOMContactTelephone;
+const CONTACTTELFIELD_CONTRACTID = "@mozilla.org/contactTelField;1";
+const CONTACTTELFIELD_CID        = Components.ID("{ed0ab260-e4aa-11e1-9b23-0800200c9a66}");
+const nsIDOMContactTelField      = Components.interfaces.nsIDOMContactTelField;
 
-function ContactTelephone(aType, aNumber) {
+function ContactTelField(aType, aValue, aCarrier) {
   this.type = aType || null;
-  this.number = aNumber || null;
+  this.value = aValue || null;
+  this.carrier = aCarrier || null;
 };
 
-ContactTelephone.prototype = {
+ContactTelField.prototype = {
 
-  classID : CONTACTTELEPHONE_CID,
-  classInfo : XPCOMUtils.generateCI({classID: CONTACTTELEPHONE_CID,
-                                     contractID: CONTACTTELEPHONE_CONTRACTID,
-                                     classDescription: "ContactTelephone",
-                                     interfaces: [nsIDOMContactTelephone],
+  classID : CONTACTTELFIELD_CID,
+  classInfo : XPCOMUtils.generateCI({classID: CONTACTTELFIELD_CID,
+                                     contractID: CONTACTTELFIELD_CONTRACTID,
+                                     classDescription: "ContactTelField",
+                                     interfaces: [nsIDOMContactTelField],
                                      flags: nsIClassInfo.DOM_OBJECT}),
 
-  QueryInterface : XPCOMUtils.generateQI([nsIDOMContactTelephone])
+  QueryInterface : XPCOMUtils.generateQI([nsIDOMContactTelField])
 }
 
 //ContactFindOptions
 
 const CONTACTFINDOPTIONS_CONTRACTID = "@mozilla.org/contactFindOptions;1";
 const CONTACTFINDOPTIONS_CID        = Components.ID("{e31daea0-0cb6-11e1-be50-0800200c9a66}");
 const nsIDOMContactFindOptions      = Components.interfaces.nsIDOMContactFindOptions;
 
@@ -191,23 +192,22 @@ Contact.prototype = {
     this.familyName =      _create(aProp.familyName) || null;
     this.honorificSuffix = _create(aProp.honorificSuffix) || null;
     this.nickname =        _create(aProp.nickname) || null;
 
     if (aProp.email) {
       aProp.email = Array.isArray(aProp.email) ? aProp.email : [aProp.email];
       this.email = new Array();
       for (let i = 0; i < aProp.email.length; i++)
-        this.email.push(new ContactEmail(aProp.email[i].type, aProp.email[i].address));
+        this.email.push(new ContactField(aProp.email[i].type, aProp.email[i].value));
     } else {
       this.email = null;
     }
 
     this.photo =           _checkBlobArray(aProp.photo) || null;
-    this.url =             _create(aProp.url) || null;
     this.category =        _create(aProp.category) || null;
 
     if (aProp.adr) {
       // Make sure adr argument is an array. Instanceof doesn't work.
       aProp.adr = Array.isArray(aProp.adr) ? aProp.adr : [aProp.adr];
 
       this.adr = new Array();
       for (let i = 0; i < aProp.adr.length; i++)
@@ -216,26 +216,44 @@ Contact.prototype = {
     } else {
       this.adr = null;
     }
 
     if (aProp.tel) {
       aProp.tel = Array.isArray(aProp.tel) ? aProp.tel : [aProp.tel];
       this.tel = new Array();
       for (let i = 0; i < aProp.tel.length; i++)
-        this.tel.push(new ContactTelephone(aProp.tel[i].type, aProp.tel[i].number));
+        this.tel.push(new ContactTelField(aProp.tel[i].type, aProp.tel[i].value, aProp.tel[i].carrier));
     } else {
       this.tel = null;
     }
 
     this.org =             _create(aProp.org) || null;
     this.jobTitle =        _create(aProp.jobTitle) || null;
     this.bday =            (aProp.bday == "undefined" || aProp.bday == null) ? null : new Date(aProp.bday);
     this.note =            _create(aProp.note) || null;
-    this.impp =            _create(aProp.impp) || null;
+
+    if (aProp.impp) {
+      aProp.impp = Array.isArray(aProp.impp) ? aProp.impp : [aProp.impp];
+      this.impp = new Array();
+      for (let i = 0; i < aProp.impp.length; i++)
+        this.impp.push(new ContactField(aProp.impp[i].type, aProp.impp[i].value));
+    } else {
+      this.impp = null;
+    }
+
+    if (aProp.url) {
+      aProp.url = Array.isArray(aProp.url) ? aProp.url : [aProp.url];
+      this.url = new Array();
+      for (let i = 0; i < aProp.url.length; i++)
+        this.url.push(new ContactField(aProp.url[i].type, aProp.url[i].value));
+    } else {
+      this.url = null;
+    }
+
     this.anniversary =     (aProp.anniversary == "undefined" || aProp.anniversary == null) ? null : new Date(aProp.anniversary);
     this.sex =             (aProp.sex != "undefined") ? aProp.sex : null;
     this.genderIdentity =  (aProp.genderIdentity != "undefined") ? aProp.genderIdentity : null;
   },
 
   get published () {
     return this._published;
   },
@@ -534,9 +552,9 @@ ContactManager.prototype = {
   classInfo : XPCOMUtils.generateCI({classID: CONTACTMANAGER_CID,
                                      contractID: CONTACTMANAGER_CONTRACTID,
                                      classDescription: "ContactManager",
                                      interfaces: [nsIDOMContactManager],
                                      flags: nsIClassInfo.DOM_OBJECT})
 }
 
 const NSGetFactory = XPCOMUtils.generateNSGetFactory(
-                       [Contact, ContactManager, ContactProperties, ContactAddress, ContactTelephone, ContactFindOptions, ContactEmail])
+                       [Contact, ContactManager, ContactProperties, ContactAddress, ContactField, ContactTelField, ContactFindOptions])
--- a/dom/contacts/ContactManager.manifest
+++ b/dom/contacts/ContactManager.manifest
@@ -1,19 +1,19 @@
 component {f5181640-89e8-11e1-b0c4-0800200c9a66} ContactManager.js
 contract @mozilla.org/contactProperties;1 {f5181640-89e8-11e1-b0c4-0800200c9a66}
 
 component {eba48030-89e8-11e1-b0c4-0800200c9a66} ContactManager.js
 contract @mozilla.org/contactAddress;1 {eba48030-89e8-11e1-b0c4-0800200c9a66}
 
-component {82601b20-89e8-11e1-b0c4-0800200c9a66} ContactManager.js
-contract @mozilla.org/contactTelephone;1 {82601b20-89e8-11e1-b0c4-0800200c9a66}
+component {e2cb19c0-e4aa-11e1-9b23-0800200c9a66} ContactManager.js
+contract @mozilla.org/contactField;1 {e2cb19c0-e4aa-11e1-9b23-0800200c9a66}
 
-component {94811520-c11f-11e1-afa7-0800200c9a66} ContactManager.js
-contract @mozilla.org/contactEmail;1 {94811520-c11f-11e1-afa7-0800200c9a66}
+component {ed0ab260-e4aa-11e1-9b23-0800200c9a66} ContactManager.js
+contract @mozilla.org/contactTelField;1 {ed0ab260-e4aa-11e1-9b23-0800200c9a66}
 
 component {e31daea0-0cb6-11e1-be50-0800200c9a66} ContactManager.js
 contract @mozilla.org/contactFindOptions;1 {e31daea0-0cb6-11e1-be50-0800200c9a66}
 
 component {da0f7040-388b-11e1-b86c-0800200c9a66} ContactManager.js
 contract @mozilla.org/contact;1 {da0f7040-388b-11e1-b86c-0800200c9a66}
 category JavaScript-global-constructor mozContact @mozilla.org/contact;1
 
--- a/dom/contacts/fallback/ContactDB.jsm
+++ b/dom/contacts/fallback/ContactDB.jsm
@@ -17,17 +17,17 @@ if (DEBUG) {
 const Cu = Components.utils;
 const Cc = Components.classes;
 const Ci = Components.interfaces;
 
 Cu.import("resource://gre/modules/Services.jsm");
 Cu.import("resource://gre/modules/IndexedDBHelper.jsm");
 
 const DB_NAME = "contacts";
-const DB_VERSION = 3;
+const DB_VERSION = 4;
 const STORE_NAME = "contacts";
 
 function ContactDB(aGlobal) {
   debug("Constructor");
   this._global = aGlobal;
 }
 
 ContactDB.prototype = {
@@ -121,16 +121,47 @@ ContactDB.prototype = {
             cursor.update(cursor.value);
             debug("upgrade email2: " + JSON.stringify(cursor.value));
             cursor.continue();
           }
         };
 
         // Create new searchable indexes.
         objectStore.createIndex("email", "search.email", { unique: false, multiEntry: true });
+      } else if (currVersion == 3) {
+        debug("upgrade 3");
+
+        if (!objectStore) {
+          objectStore = aTransaction.objectStore(STORE_NAME);
+        }
+
+        // Upgrade existing impp field in the DB.
+        objectStore.openCursor().onsuccess = function(event) {
+          let cursor = event.target.result;
+          if (cursor) {
+            debug("upgrade impp1: " + JSON.stringify(cursor.value));
+            cursor.value.properties.impp =
+              cursor.value.properties.impp.map(function(value) { return { value: value }; });
+            cursor.update(cursor.value);
+            debug("upgrade impp2: " + JSON.stringify(cursor.value));
+            cursor.continue();
+          }
+        };
+        // Upgrade existing url field in the DB.
+        objectStore.openCursor().onsuccess = function(event) {
+          let cursor = event.target.result;
+          if (cursor) {
+            debug("upgrade url1: " + JSON.stringify(cursor.value));
+            cursor.value.properties.url =
+              cursor.value.properties.url.map(function(value) { return { value: value }; });
+            cursor.update(cursor.value);
+            debug("upgrade impp2: " + JSON.stringify(cursor.value));
+            cursor.continue();
+          }
+        };
       }
     }
   },
 
   makeImport: function makeImport(aContact) {
     let contact = {};
     contact.properties = {
       name:            [],
@@ -179,34 +210,41 @@ ContactDB.prototype = {
       if (aContact.properties[field] && contact.search[field]) {
         for (let i = 0; i <= aContact.properties[field].length; i++) {
           if (aContact.properties[field][i]) {
             if (field == "tel") {
               // Special case telephone number.
               // "+1-234-567" should also be found with 1234, 234-56, 23456
 
               // Chop off the first characters
-              let number = aContact.properties[field][i].number;
-              for(let i = 0; i < number.length; i++) {
-                contact.search[field].push(number.substring(i, number.length));
+              let number = aContact.properties[field][i].value;
+              if (number) {
+                for (let i = 0; i < number.length; i++) {
+                  contact.search[field].push(number.substring(i, number.length));
+                }
+                // Store +1-234-567 as ["1234567", "234567"...]
+                let digits = number.match(/\d/g);
+                if (digits && number.length != digits.length) {
+                  digits = digits.join('');
+                  for(let i = 0; i < digits.length; i++) {
+                    contact.search[field].push(digits.substring(i, digits.length));
+                  }
+                }
+              debug("lookup: " + JSON.stringify(contact.search[field]));
               }
-              // Store +1-234-567 as ["1234567", "234567"...]
-              let digits = number.match(/\d/g);
-              if (digits && number.length != digits.length) {
-                digits = digits.join('');
-                for(let i = 0; i < digits.length; i++) {
-                  contact.search[field].push(digits.substring(i, digits.length));
-                }
-              }
-              debug("lookup: " + JSON.stringify(contact.search[field]));
             } else if (field == "email") {
-              let address = aContact.properties[field][i].address;
+              let address = aContact.properties[field][i].value;
               if (address && typeof address == "string") {
                 contact.search[field].push(address.toLowerCase());
               }
+            } else if (field == "impp") {
+              let value = aContact.properties[field][i].value;
+              if (value && typeof value == "string") {
+                contact.search[field].push(value.toLowerCase());
+              }
             } else {
               let val = aContact.properties[field][i];
               if (typeof val == "string") {
                 contact.search[field].push(val.toLowerCase());
               }
             }
           }
         }
--- a/dom/contacts/tests/test_contacts_basics.html
+++ b/dom/contacts/tests/test_contacts_basics.html
@@ -73,39 +73,39 @@ var adr2 = {
   countryName: "country2"
 };
 
 var properties1 = {
   name: "Testname1",
   familyName: ["TestFamilyName","Wagner"],
   givenName: ["Test1","Test2"],
   nickname: "nicktest",
-  tel: [{type: "work", number: "123456"} , {type: "home", number: "+9-876-5432"}],
+  tel: [{type: ["work"], value: "123456", carrier: "testCarrier"} , {type: ["home", "fax"], value: "+9-876-5432"}],
   adr: adr1,
-  email: [{type: "work", address: "x@y.com"}]
+  email: [{type: ["work"], value: "x@y.com"}]
 };
 
 var properties2 = {
   name: ["dummyName", "dummyName2"],
   familyName: "dummyFamilyName",
   givenName: "dummyGivenName",
   honorificPrefix: ["dummyHonorificPrefix","dummyHonorificPrefix2"],
   honorificSuffix: "dummyHonorificSuffix",
   additionalName: "dummyadditionalName",
   nickname: "dummyNickname",
-  tel: [{type: "test", number: "123456789"},{type: "home", number: "234567890"}],
-  email: [{type: "test", address: "a@b.c"}, {address: "b@c.d"}],
+  tel: [{type: ["test"], value: "123456789"},{type: ["home", "custom"], value: "234567890"}],
+  email: [{type: ["test"], value: "a@b.c"}, {value: "b@c.d"}],
   adr: [adr1, adr2],
-  impp: ["im1", "im2"],
+  impp: [{type: ["aim"], value:"im1"}, {value: "im2"}],
   org: ["org1", "org2"],
   jobTitle: ["boss", "superboss"],
   bday: new Date("1980, 12, 01"),
   note: "test note",
   category: ["cat1", "cat2"],
-  url: ["www.1.com", "www.2.com"],
+  url: [{type: ["work", "work2"], value: "www.1.com"}, {value:"www2.com"}],
   anniversary: new Date("2000, 12, 01"),
   sex: "male",
   genderIdentity: "test"
 };
 
 var sample_id1;
 var sample_id2;
 
@@ -143,49 +143,87 @@ function checkAddress(adr1, adr2) {
   checkStr(adr1.locality, adr2.locality, "Same locality");
   checkStr(adr1.region, adr2.region, "Same region");
   checkStr(adr1.postalCode, adr2.postalCode, "Same postalCode");
   checkStr(adr1.countryName, adr2.countryName, "Same countryName");
 }
 
 function checkTel(tel1, tel2) {
   checkStr(tel1.type, tel2.type, "Same type");
-  checkStr(tel1.number, tel2.number, "Same number");
+  checkStr(tel1.value, tel2.value, "Same value");
+  checkStr(tel1.carrier, tel2.carrier, "Same carrier");
 }
 
-function checkEmail(email1, email2) {
-  checkStr(email1.type, email2.type, "Same type");
-  checkStr(email1.address, email2.address, "Same address");
+function checkField(field1, field2) {
+  checkStr(field1.type, field1.type, "Same type");
+  checkStr(field1.value, field1.value, "Same value");
 }
 
 function checkContacts(contact1, contact2) {
   checkStr(contact1.name, contact2.name, "Same name");
   checkStr(contact1.honorificPrefix, contact2.honorificPrefix, "Same honorificPrefix");
   checkStr(contact1.givenName, contact2.givenName, "Same givenName");
   checkStr(contact1.additionalName, contact2.additionalName, "Same additionalName");
   checkStr(contact1.familyName, contact2.familyName, "Same familyName");
   checkStr(contact1.honorificSuffix, contact2.honorificSuffix, "Same honorificSuffix");
   checkStr(contact1.nickname, contact2.nickname, "Same nickname");
-  checkStr(contact1.url, contact2.url, "Same url");
   checkStr(contact1.category, contact2.category, "Same category");
   checkStr(contact1.org, contact2.org, "Same org");
   checkStr(contact1.jobTitle, contact2.jobTitle, "Same jobTitle");
   is(contact1.bday ? contact1.bday.valueOf() : null, contact2.bday ? contact2.bday.valueOf() : null, "Same birthday");
   checkStr(contact1.note, contact2.note, "Same note");
-  checkStr(contact1.impp, contact2.impp, "Same impp");
   is(contact1.anniversary ? contact1.anniversary.valueOf() : null , contact2.anniversary ? contact2.anniversary.valueOf() : null, "Same anniversary");
   is(contact1.sex, contact2.sex, "Same sex");
   is(contact1.genderIdentity, contact2.genderIdentity, "Same genderIdentity");
 
-  for (var i in contact1.email)
-    checkEmail(contact1.email[i], contact2.email[i]);
-  for (var i in contact1.adr)
+  for (var i in contact1.email) {
+    if (contact1.email) {
+      ok(contact2.email != null, "conatct2.email exists");
+    }
+    if (contact2.email) {
+      ok(contact1.email != null, "conatct1.email exists");
+    }
+    checkField(contact1.email[i], contact2.email[i]);
+  }
+  for (var i in contact1.adr) {
+    if (contact1.adr) {
+      ok(contact2.adr != null, "conatct2.adr exists");
+    }
+    if (contact2.adr) {
+      ok(contact1.adr != null, "conatct1.adr exists");
+    }
     checkAddress(contact1.adr[i], contact2.adr[i]);
-  for (var i in contact1.tel)
+  }
+  for (var i in contact1.tel) {
+    if (contact1.tel) {
+      ok(contact2.tel != null, "conatct2.tel exists");
+    }
+    if (contact2.tel) {
+      ok(contact1.tel != null, "conatct1.tel exists");
+    }
     checkTel(contact1.tel[i], contact2.tel[i]);
+  }
+  for (var i in contact1.url) {
+    if (contact1.url) {
+      ok(contact2.url != null, "conatct2.url exists");
+    }
+    if (contact2.url) {
+      ok(contact1.url != null, "conatct1.url exists");
+    }
+    checkField(contact1.url[i], contact2.url[i]);
+  }
+  for (var i in contact1.impp) {
+    if (contact1.impp) {
+      ok(contact2.impp != null, "conatct2.impp exists");
+    }
+    if (contact2.impp) {
+      ok(contact1.impp != null, "conatct1.impp exists");
+    }
+    checkField(contact1.impp[i], contact2.impp[i]);
+  }
 }
 
 var req;
 var index = 0;
 
 var mozContacts = window.navigator.mozContacts
 
 var steps = [
@@ -276,17 +314,17 @@ var steps = [
       next();
     };
     req.onerror = onFailure;
   },
   function () {
     ok(true, "Searching for exact email");
     var options = {filterBy: ["email"],
                    filterOp: "equals",
-                   filterValue: properties1.email[0].address};
+                   filterValue: properties1.email[0].value};
     req = mozContacts.find(options);
     req.onsuccess = function () {
       ok(req.result.length == 1, "Found exactly 1 contact.");
       findResult1 = req.result[0];
       ok(findResult1.id == sample_id1, "Same ID");
       checkContacts(findResult1, createResult1);
       next();
     };
@@ -415,17 +453,17 @@ var steps = [
       next();
     };
     req.onerror = onFailure;
   },
   function () {
     ok(true, "Retrieving by substring tel1");
     var options = {filterBy: ["tel"],
                    filterOp: "contains",
-                   filterValue: properties1.tel[1].number.substring(1,5)};
+                   filterValue: properties1.tel[1].value.substring(1,5)};
     req = mozContacts.find(options);
     req.onsuccess = function () {
       ok(req.result.length == 1, "Found exactly 1 contact.");
       findResult1 = req.result[0];
       ok(findResult1.id == sample_id1, "Same ID");
       checkContacts(createResult1, properties1);
       next();
     };
@@ -517,17 +555,17 @@ var steps = [
       ok(findResult1.updated, "Has updated field");
       ok(findResult1.published, "Has published field");
       next();
     }
     req.onerror = onFailure;
   },
   function () {
     ok(true, "Modifying contact1");
-    findResult1.impp = properties1.impp = (["phil impp"]);
+    findResult1.impp = properties1.impp = [{value:"phil impp"}];
     req = navigator.mozContacts.save(findResult1);
     req.onsuccess = function () {
       var req2 = mozContacts.find({});
       req2.onsuccess = function() {
         ok(req2.result.length == 1, "Found exactly 1 contact.");
         findResult2 = req2.result[0];
         ok(findResult2.id == sample_id1, "Same ID");
         checkContacts(findResult2, properties1);
@@ -549,47 +587,47 @@ var steps = [
     var options = {filterBy: ["id"],
                    filterOp: "equals",
                    filterValue: sample_id1};
     req = mozContacts.find(options);
     req.onsuccess = function () {
       ok(req.result.length == 1, "Found exactly 1 contact.");
       findResult1 = req.result[0];
       ok(findResult1.id == sample_id1, "Same ID");
-      checkContacts(createResult1, properties1);
+      checkContacts(findResult1, properties1);
       next();
     };
     req.onerror = onFailure;
   },
   function () {
     ok(true, "Retrieving a specific contact by givenName");
     var options = {filterBy: ["givenName"],
                    filterOp: "equals",
                    filterValue: properties1.givenName[0]};
     req = mozContacts.find(options);
     req.onsuccess = function () {
       ok(req.result.length == 1, "Found exactly 1 contact.");
       findResult1 = req.result[0];
       ok(findResult1.id == sample_id1, "Same ID");
-      checkContacts(findResult1, createResult1);
+      checkContacts(findResult1, properties1);
       next();
     }
     req.onerror = onFailure;
   },
   function () {
     ok(true, "Modifying contact2");
-    findResult1.impp = properties1.impp = (["phil impp"]);
+    findResult1.impp = properties1.impp = [{value: "phil impp"}];
     req = mozContacts.save(findResult1);
     req.onsuccess = function () {
       var req2 = mozContacts.find({});
       req2.onsuccess = function () {
         ok(req2.result.length == 1, "Found exactly 1 contact.");
         findResult1 = req2.result[0];
         ok(findResult1.id == sample_id1, "Same ID");
-        checkContacts(findResult1, createResult1);
+        checkContacts(findResult1, properties1);
         ok(findResult1.impp.length == 1, "Found exactly 1 IMS info.");
         next();
       }
       req2.onerror = onFailure;
     };
     req.onerror = onFailure;
   },
   function () {
@@ -597,54 +635,54 @@ var steps = [
     var options = {filterBy: ["name", "email"],
                    filterOp: "contains",
                    filterValue: properties1.name[0].substring(0,4)};
     req = mozContacts.find(options);
     req.onsuccess = function () {
       ok(req.result.length == 1, "Found exactly 1 contact.");
       findResult1 = req.result[0];
       ok(findResult1.id == sample_id1, "Same ID");
-      checkContacts(findResult1, createResult1);
+      checkContacts(findResult1, properties1);
       next();
     };
     req.onerror = onFailure;
   },
   function () {
     ok(true, "Searching contacts by query");
     var options = {filterBy: ["nickname", "email"],
                    filterOp: "contains",
                    filterValue: properties1.nickname};
     req = mozContacts.find(options);
     req.onsuccess = function () {
       ok(req.result.length == 1, "Found exactly 1 contact.");
       findResult1 = req.result[0];
       ok(findResult1.id == sample_id1, "Same ID");
-      checkContacts(findResult1, createResult1);
+      checkContacts(findResult1, properties1);
       next();
     };
     req.onerror = onFailure;
   },
   function () {
     ok(true, "Searching contacts with multiple indices");
     var options = {filterBy: ["nickname", "email", "name"],
                    filterOp: "equals",
                    filterValue: properties1.nickname};
     req = mozContacts.find(options);
     req.onsuccess = function () {
       ok(req.result.length == 1, "Found exactly 1 contact.");
       findResult1 = req.result[0];
       ok(findResult1.id == sample_id1, "Same ID");
-      checkContacts(findResult1, createResult1);
+      checkContacts(findResult1, properties1);
       next();
     };
     req.onerror = onFailure;
   },
   function () {
     ok(true, "Modifying contact3");
-    findResult1.email = [{address: properties1.nickname}];
+    findResult1.email = [{value: properties1.nickname}];
     findResult1.nickname = "TEST";
     var newContact = new mozContact();
     newContact.init(findResult1);
     req = mozContacts.save(newContact);
     req.onsuccess = function () {
       var options = {filterBy: ["nickname", "email", "name"],
                      filterOp: "contains",
                      filterValue: properties1.nickname};
@@ -744,32 +782,32 @@ var steps = [
       next();
     }
     req.onerror = onFailure;
   },
   function () {
     ok(true, "Searching contacts by tel");
     var options = {filterBy: ["tel"],
                    filterOp: "contains",
-                   filterValue: properties2.tel[0].number.substring(0, 7)};
+                   filterValue: properties2.tel[0].value.substring(0, 7)};
     req = mozContacts.find(options);
     req.onsuccess = function () {
       ok(req.result.length == 1, "Found exactly 1 contact.");
       findResult1 = req.result[0];
       ok(findResult1.id == sample_id2, "Same ID");
       checkContacts(findResult1, createResult2);
       next();
     }
     req.onerror = onFailure;
   },
   function () {
     ok(true, "Searching contacts by email");
     var options = {filterBy: ["email"],
                    filterOp: "contains",
-                   filterValue: properties2.email[0].address.substring(0, 4)};
+                   filterValue: properties2.email[0].value.substring(0, 4)};
     req = mozContacts.find(options);
     req.onsuccess = function () {
       ok(req.result.length == 1, "Found exactly 1 contact.");
       findResult1 = req.result[0];
       ok(findResult1.id == sample_id2, "Same ID");
       checkContacts(findResult1, createResult2);
       next();
     }
@@ -883,22 +921,22 @@ var steps = [
       next();
     }
     req.onerror = onFailure;
   },
   function() {
     ok(true, "Testing clone contact2");
     var cloned = new mozContact(createResult1);
     ok(cloned.id != createResult1.id, "Cloned contact has new ID");
-    cloned.email = {address: "new email!"};
+    cloned.email = {value: "new email!"};
     cloned.givenName = "Tom";
     req = mozContacts.save(cloned);
     req.onsuccess = function () {
       ok(cloned.id, "The contact now has an ID.");
-      ok(cloned.email.address == "new email!", "Same Email");
+      ok(cloned.email.value == "new email!", "Same Email");
       ok(createResult1.email != cloned.email, "Clone has different email");
       ok(cloned.givenName == "Tom", "New Name");
       next();
     }
     req.onerror = onFailure;
   },
   function () {
     ok(true, "Retrieving all contacts");
@@ -910,17 +948,17 @@ var steps = [
       ok(req.result.length == 2, "2 Entries.");
       next();
     }
     req.onerror = onFailure;
   },
   function () {
     ok(true, "Search with redundant fields should only return 1 contact");
     createResult1 = new mozContact();
-    createResult1.init({name: "XXX", nickname: "XXX", email: [{address: "XXX"}], tel: {number: "XXX"}});
+    createResult1.init({name: "XXX", nickname: "XXX", email: [{value: "XXX"}], tel: {value: "XXX"}});
     req = mozContacts.save(createResult1);
     req.onsuccess = function() {
       var options = {filterBy: [],
                      filterOp: "equals",
                      filterValue: "XXX"};
       var req2 = mozContacts.find(options);
       req2.onsuccess = function() {
         ok(req2.result.length == 1, "1 Entry");
--- a/dom/devicestorage/ipc/test_ipc.html
+++ b/dom/devicestorage/ipc/test_ipc.html
@@ -125,36 +125,27 @@
       href = href.substring(0, href.lastIndexOf('/'));
       href = href.substring(0, href.lastIndexOf('/'));
       iframe.src = href + "/test?consoleLevel=INFO";
 
       document.body.appendChild(iframe);
     }
 
     addEventListener("load", function() {
-      let whitelist;
-      try {
-        whitelist =
-          SpecialPowers.getCharPref("dom.mozBrowserFramesWhitelist") + ", ";
-      } catch (e) {
-        whitelist = "";
-      }
 
-      whitelist += window.location.protocol + "//" + window.location.host;
-
+      SpecialPowers.addPermission("browser", true, document);
       SpecialPowers.pushPrefEnv({
         "set": [
 
           ["device.storage.enabled", true],
           ["device.storage.testing", true],
           ["device.storage.prompt.testing", true],
 
           ["dom.ipc.browser_frames.oop_by_default", true],
           ["dom.mozBrowserFramesEnabled", true],
-          ["browser.pageThumbs.enabled", false],
-          ["dom.mozBrowserFramesWhitelist", whitelist]
+          ["browser.pageThumbs.enabled", false]
         ]
       }, runTests);
     });
 
   </script>
 </body>
 </html>
--- a/dom/interfaces/contacts/nsIDOMContactProperties.idl
+++ b/dom/interfaces/contacts/nsIDOMContactProperties.idl
@@ -13,58 +13,57 @@ interface nsIDOMContactAddress : nsISupp
   attribute DOMString type;
   attribute DOMString streetAddress;
   attribute DOMString locality;
   attribute DOMString region;
   attribute DOMString postalCode;
   attribute DOMString countryName;
 };
 
-[scriptable, uuid(82601b20-89e8-11e1-b0c4-0800200c9a66)]
-interface nsIDOMContactTelephone : nsISupports
+[scriptable, uuid(e2cb19c0-e4aa-11e1-9b23-0800200c9a66)]
+interface nsIDOMContactField : nsISupports
 {
-  attribute DOMString type;
-  attribute DOMString number;
+  attribute jsval type; // DOMString[] for primary/favorite (use:"PREF"), "home", "work", etc.
+  attribute DOMString value;
 };
 
-[scriptable, uuid(94811520-c11f-11e1-afa7-0800200c9a66)]
-interface nsIDOMContactEmail : nsISupports
+[scriptable, uuid(ed0ab260-e4aa-11e1-9b23-0800200c9a66)]
+interface nsIDOMContactTelField : nsIDOMContactField
 {
-  attribute DOMString type;
-  attribute DOMString address;
+  attribute DOMString carrier;
 };
 
 [scriptable, uuid(e31daea0-0cb6-11e1-be50-0800200c9a66)]
 interface nsIDOMContactFindOptions : nsISupports
 {
   attribute DOMString filterValue;  // e.g. "Tom"
   attribute DOMString filterOp;     // e.g. "contains"
   attribute jsval filterBy;         // DOMString[], e.g. ["givenName", "nickname"]
   attribute DOMString sortBy;       // "givenName" or "familyName"
   attribute DOMString sortOrder;    // e.g. "descending"
   attribute unsigned long filterLimit;
 };
 
-[scriptable, uuid(f5181640-89e8-11e1-b0c4-0800200c9a66)]
+[scriptable, uuid(f0ddb360-e4aa-11e1-9b23-0800200c9a66)]
 interface nsIDOMContactProperties : nsISupports
 {
   attribute jsval         name;               // DOMString[]
   attribute jsval         honorificPrefix;    // DOMString[]
   attribute jsval         givenName;          // DOMString[]
   attribute jsval         additionalName;     // DOMString[]
   attribute jsval         familyName;         // DOMString[]
   attribute jsval         honorificSuffix;    // DOMString[]
   attribute jsval         nickname;           // DOMString[]
-  attribute jsval         email;              // ContactEmail[]
+  attribute jsval         email;              // ContactField[]
   attribute jsval         photo;              // nsIDOMBlob[]
-  attribute jsval         url;                // DOMString[]
+  attribute jsval         url;                // ContactField[]
   attribute jsval         category;           // DOMString[]
   attribute jsval         adr;                // ContactAddress[]
-  attribute jsval         tel;                // ContactTelephone[]
+  attribute jsval         tel;                // ContactTelField[]
   attribute jsval         org;                // DOMString[]
   attribute jsval         jobTitle;           // DOMString[]
   attribute jsval         bday;               // Date
   attribute jsval         note;               // DOMString[]
-  attribute jsval         impp;               // DOMString[]
+  attribute jsval         impp;               // ContactField[]
   attribute jsval         anniversary;        // Date
   attribute jsval         sex;                // DOMString
   attribute jsval         genderIdentity;     // DOMString
 };
--- a/dom/interfaces/core/nsIInlineEventHandlers.idl
+++ b/dom/interfaces/core/nsIInlineEventHandlers.idl
@@ -2,17 +2,17 @@
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 #include "domstubs.idl"
 
 %{ C++
 #include "jspubtd.h"
 %}
 
-[scriptable, uuid(5b3f9656-9d81-40e4-85ba-01f302177815)]
+[scriptable, uuid(22df6ed6-d094-4e45-97fc-a8eca11c390c)]
 interface nsIInlineEventHandlers : nsISupports
 {
   [implicit_jscontext] attribute jsval onabort;
   [implicit_jscontext] attribute jsval onblur;
   [implicit_jscontext] attribute jsval oncanplay;
   [implicit_jscontext] attribute jsval oncanplaythrough;
   [implicit_jscontext] attribute jsval onchange;
   [implicit_jscontext] attribute jsval onclick;
@@ -64,16 +64,17 @@ interface nsIInlineEventHandlers : nsISu
   [implicit_jscontext] attribute jsval onselect;
   [implicit_jscontext] attribute jsval onshow;
   [implicit_jscontext] attribute jsval onstalled;
   [implicit_jscontext] attribute jsval onsubmit;
   [implicit_jscontext] attribute jsval onsuspend;
   [implicit_jscontext] attribute jsval ontimeupdate;
   [implicit_jscontext] attribute jsval onvolumechange;
   [implicit_jscontext] attribute jsval onwaiting;
+  [implicit_jscontext] attribute jsval onwheel;
 
   /**
    * Non-HTML5 event attributes
    */
   [implicit_jscontext] attribute jsval oncopy;
   [implicit_jscontext] attribute jsval oncut;
   [implicit_jscontext] attribute jsval onpaste;
   [implicit_jscontext] attribute jsval onbeforescriptexecute;
--- a/dom/ipc/ContentParent.cpp
+++ b/dom/ipc/ContentParent.cpp
@@ -681,17 +681,19 @@ ContentParent::RecvReadPermissions(Infal
     // Ask for future changes
     mSendPermissionUpdates = true;
 #endif
 
     return true;
 }
 
 bool
-ContentParent::RecvSetClipboardText(const nsString& text, const PRInt32& whichClipboard)
+ContentParent::RecvSetClipboardText(const nsString& text,
+                                       const bool& isPrivateData,
+                                       const PRInt32& whichClipboard)
 {
     nsresult rv;
     nsCOMPtr<nsIClipboard> clipboard(do_GetService(kCClipboardCID, &rv));
     NS_ENSURE_SUCCESS(rv, true);
 
     nsCOMPtr<nsISupportsString> dataWrapper =
         do_CreateInstance(NS_SUPPORTS_STRING_CONTRACTID, &rv);
     NS_ENSURE_SUCCESS(rv, true);
@@ -700,16 +702,17 @@ ContentParent::RecvSetClipboardText(cons
     NS_ENSURE_SUCCESS(rv, true);
     
     nsCOMPtr<nsITransferable> trans = do_CreateInstance("@mozilla.org/widget/transferable;1", &rv);
     NS_ENSURE_SUCCESS(rv, true);
     trans->Init(nullptr);
     
     // If our data flavor has already been added, this will fail. But we don't care
     trans->AddDataFlavor(kUnicodeMime);
+    trans->SetIsPrivateData(isPrivateData);
     
     nsCOMPtr<nsISupports> nsisupportsDataWrapper =
         do_QueryInterface(dataWrapper);
     
     rv = trans->SetTransferData(kUnicodeMime, nsisupportsDataWrapper,
                                 text.Length() * sizeof(PRUnichar));
     NS_ENSURE_SUCCESS(rv, true);
     
--- a/dom/ipc/ContentParent.h
+++ b/dom/ipc/ContentParent.h
@@ -196,17 +196,17 @@ private:
     virtual PStorageParent* AllocPStorage(const StorageConstructData& aData);
     virtual bool DeallocPStorage(PStorageParent* aActor);
 
     virtual bool RecvReadPrefsArray(InfallibleTArray<PrefTuple> *retValue);
     virtual bool RecvReadFontList(InfallibleTArray<FontListEntry>* retValue);
 
     virtual bool RecvReadPermissions(InfallibleTArray<IPC::Permission>* aPermissions);
 
-    virtual bool RecvSetClipboardText(const nsString& text, const PRInt32& whichClipboard);
+    virtual bool RecvSetClipboardText(const nsString& text, const bool& isPrivateData, const PRInt32& whichClipboard);
     virtual bool RecvGetClipboardText(const PRInt32& whichClipboard, nsString* text);
     virtual bool RecvEmptyClipboard();
     virtual bool RecvClipboardHasText(bool* hasText);
 
     virtual bool RecvGetSystemColors(const PRUint32& colorsCount, InfallibleTArray<PRUint32>* colors);
     virtual bool RecvGetIconForExtension(const nsCString& aFileExt, const PRUint32& aIconSize, InfallibleTArray<PRUint8>* bits);
     virtual bool RecvGetShowPasswordSetting(bool* showPassword);
 
--- a/dom/ipc/PContent.ipdl
+++ b/dom/ipc/PContent.ipdl
@@ -274,17 +274,17 @@ parent:
                 PRUint32 lineNumber, PRUint32 colNumber, PRUint32 flags,
                 nsCString category); 
 
     // nsIPermissionManager messages
     sync ReadPermissions() returns (Permission[] permissions);
 
     // These clipboard methods are only really used on Android since
     // the clipboard is not available in the content process.
-    SetClipboardText(nsString text, PRInt32 whichClipboard);
+    SetClipboardText(nsString text, bool isPrivateData, PRInt32 whichClipboard);
     sync GetClipboardText(PRInt32 whichClipboard)
         returns (nsString text);
     EmptyClipboard();
     sync ClipboardHasText()
         returns (bool hasText);
 
     sync GetSystemColors(PRUint32 colorsCount)
         returns (PRUint32[] colors);
--- a/dom/messages/SystemMessageInternal.js
+++ b/dom/messages/SystemMessageInternal.js
@@ -21,49 +21,54 @@ let kMaxPendingMessages;
 try {
   kMaxPendingMessages = Services.prefs.getIntPref("dom.messages.maxPendingMessages");
 } catch(e) {
   // getIntPref throws when the pref is not set.
   kMaxPendingMessages = 5;
 }
 
 function debug(aMsg) { 
-  //dump("-- SystemMessageInternal " + Date.now() + " : " + aMsg + "\n"); 
+  //dump("-- SystemMessageInternal " + Date.now() + " : " + aMsg + "\n");
 }
 
 // Implementation of the component used by internal users.
 
 function SystemMessageInternal() {
   // The set of pages registered by installed apps. We keep the
   // list of pending messages for each page here also.
   this._pages = [];
   Services.obs.addObserver(this, "xpcom-shutdown", false);
   ppmm.addMessageListener("SystemMessageManager:GetPending", this);
 }
 
 SystemMessageInternal.prototype = {
-  sendMessage: function sendMessage(aType, aMessage, aManifestURI) {
+  sendMessage: function sendMessage(aType, aMessage, aPageURI, aManifestURI) {
     debug("Broadcasting " + aType + " " + JSON.stringify(aMessage));
     ppmm.sendAsyncMessage("SystemMessageManager:Message" , { type: aType,
                                                              msg: aMessage,
                                                              manifest: aManifestURI.spec });
 
     // Queue the message for pages that registered an handler for this type.
     this._pages.forEach(function sendMess_openPage(aPage) {
-      if (aPage.type != aType || aPage.manifest != aManifestURI.spec) {
+      if (aPage.type != aType ||
+          aPage.manifest != aManifestURI.spec ||
+          aPage.uri != aPageURI.spec) {
         return;
       }
 
       aPage.pending.push(aMessage);
       if (aPage.pending.length > kMaxPendingMessages) {
         aPage.pending.splice(0, 1);
       }
 
       // We don't need to send the full object to observers.
-      let page = { uri: aPage.uri, manifest: aPage.manifest };
+      let page = { uri: aPage.uri,
+                   manifest: aPage.manifest,
+                   type: aPage.type,
+                   target: aMessage.target };
       debug("Asking to open  " + JSON.stringify(page));
       Services.obs.notifyObservers(this, "system-messages-open-app", JSON.stringify(page));
     }.bind(this))
   },
 
   registerPage: function registerPage(aType, aPageURI, aManifestURI) {
     if (!aPageURI || !aManifestURI) {
       throw Cr.NS_ERROR_INVALID_ARG;
--- a/dom/messages/interfaces/nsISystemMessagesInternal.idl
+++ b/dom/messages/interfaces/nsISystemMessagesInternal.idl
@@ -3,26 +3,27 @@
  * You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #include "domstubs.idl"
 
 interface nsIURI;
 
 // Implemented by the contract id @mozilla.org/system-message-internal;1
 
-[scriptable, uuid(fdc1ba03-5d8f-4de9-894a-333c7a136c5f)]
+[scriptable, uuid(3a50fd6b-0263-45c1-b738-a002052ad31b)]
 interface nsISystemMessagesInternal : nsISupports
 {
   /*
    * Allow any internal user to broadcast a message of a given type.
    * @param type        The type of the message to be sent.
    * @param message     The message payload.
+   * @param pageURI     The URI of the page that will be opened.
    * @param manifestURI The webapp's manifest URI.
    */
-  void sendMessage(in DOMString type, in jsval message, in nsIURI manifestURI);
+  void sendMessage(in DOMString type, in jsval message, in nsIURI pageURI, in nsIURI manifestURI);
 
   /*
    * Registration of a page that wants to be notified of a message type.
    * @param type          The message type.
    * @param pageURI       The URI of the page that will be opened.
    * @param manifestURI   The webapp's manifest URI.
    */
   void registerPage(in DOMString type, in nsIURI pageURI, in nsIURI manifestURI);
--- a/dom/plugins/base/nsNPAPIPlugin.cpp
+++ b/dom/plugins/base/nsNPAPIPlugin.cpp
@@ -2525,17 +2525,17 @@ NPError NP_CALLBACK
 
   if (!streamlistener->mStreamListenerPeer)
     return NPERR_GENERIC_ERROR;
 
   nsresult rv = streamlistener->mStreamListenerPeer->RequestRead((NPByteRange *)rangeList);
   if (NS_FAILED(rv))
     return NPERR_GENERIC_ERROR;
 
-  return NS_OK;
+  return NPERR_NO_ERROR;
 }
 
 // Deprecated, only stubbed out
 void* NP_CALLBACK /* OJI type: JRIEnv* */
 _getJavaEnv()
 {
   NPN_PLUGIN_LOG(PLUGIN_LOG_NORMAL, ("NPN_GetJavaEnv\n"));
   return NULL;
--- a/dom/plugins/base/nsPluginInstanceOwner.cpp
+++ b/dom/plugins/base/nsPluginInstanceOwner.cpp
@@ -3352,17 +3352,17 @@ NS_IMETHODIMP nsPluginInstanceOwner::Cre
     }
 
     nsWidgetInitData initData;
     initData.mWindowType = eWindowType_plugin;
     initData.mUnicode = false;
     initData.clipChildren = true;
     initData.clipSiblings = true;
     rv = mWidget->Create(parentWidget.get(), nullptr, nsIntRect(0,0,0,0),
-                         nullptr, nullptr, &initData);
+                         nullptr, &initData);
     if (NS_FAILED(rv)) {
       mWidget->Destroy();
       mWidget = nullptr;
       return rv;
     }
 
     mWidget->EnableDragDrop(true);
     mWidget->Show(false);
--- a/dom/system/gonk/RILContentHelper.js
+++ b/dom/system/gonk/RILContentHelper.js
@@ -44,22 +44,17 @@ const RIL_IPC_MSG_NAMES = [
   "RIL:GetAvailableNetworks",
   "RIL:NetworkSelectionModeChanged",
   "RIL:SelectNetwork",
   "RIL:SelectNetworkAuto",
   "RIL:CallStateChanged",
   "RIL:VoicemailNotification",
   "RIL:VoicemailNumberChanged",
   "RIL:CallError",
-  "RIL:GetCardLock:Return:OK",
-  "RIL:GetCardLock:Return:KO",
-  "RIL:SetCardLock:Return:OK",
-  "RIL:SetCardLock:Return:KO",
-  "RIL:UnlockCardLock:Return:OK",
-  "RIL:UnlockCardLock:Return:KO",
+  "RIL:CardLockResult",
   "RIL:UssdReceived",
   "RIL:SendUssd:Return:OK",
   "RIL:SendUssd:Return:KO",
   "RIL:CancelUssd:Return:OK",
   "RIL:CancelUssd:Return:KO"
 ];
 
 const kVoiceChangedTopic     = "mobile-connection-voice-changed";
@@ -565,25 +560,22 @@ RILContentHelper.prototype = {
         break;
       case "RIL:VoicemailNotification":
         this.handleVoicemailNotification(msg.json);
         break;
       case "RIL:VoicemailNumberChanged":
         this.voicemailNumber = msg.json.number;
         this.voicemailDisplayName = msg.json.alphaId;
         break;
-      case "RIL:GetCardLock:Return:OK":
-      case "RIL:SetCardLock:Return:OK":
-      case "RIL:UnlockCardLock:Return:OK":
-        this.fireRequestSuccess(msg.json.requestId, msg.json);
-        break;
-      case "RIL:GetCardLock:Return:KO":
-      case "RIL:SetCardLock:Return:KO":
-      case "RIL:UnlockCardLock:Return:KO":
-        this.fireRequestError(msg.json.requestId, msg.json.errorMsg);
+      case "RIL:CardLockResult":
+        if (msg.json.success) {
+          this.fireRequestSuccess(msg.json.requestId, msg.json);
+        } else {
+          this.fireRequestError(msg.json.requestId, msg.json);
+        }
         break;
       case "RIL:UssdReceived":
         Services.obs.notifyObservers(null, kUssdReceivedTopic,
                                      msg.json.message);
         break;
       case "RIL:SendUssd:Return:OK":
       case "RIL:CancelUssd:Return:OK":
         request = this.takeRequest(msg.json.requestId);
--- a/dom/system/gonk/RadioInterfaceLayer.js
+++ b/dom/system/gonk/RadioInterfaceLayer.js
@@ -393,24 +393,20 @@ RadioInterfaceLayer.prototype = {
         debug("nitzTime networkTime=" + message.networkTimeInSeconds +
               " timezone=" + message.networkTimeZoneInMinutes +
               " dst=" + message.dstFlag +
               " timestamp=" + message.localTimeStampInMS);
         break;
       case "iccinfochange":
         this.rilContext.icc = message;
         break;
-      case "iccgetcardlock":
-        this.handleICCGetCardLock(message);
-        break;
-      case "iccsetcardlock":
-        this.handleICCSetCardLock(message);
-        break;
-      case "iccunlockcardlock":
-        this.handleICCUnlockCardLock(message);
+      case "iccGetCardLock":
+      case "iccSetCardLock":
+      case "iccUnlockCardLock":
+        this.handleICCCardLockResult(message);
         break;
       case "icccontacts":
         if (!this._contactsCallbacks) {
           return;
         }
         let callback = this._contactsCallbacks[message.requestId];
         if (callback) {
           delete this._contactsCallbacks[message.requestId];
@@ -941,26 +937,18 @@ RadioInterfaceLayer.prototype = {
   /**
    * Handle data call list.
    */
   handleDataCallList: function handleDataCallList(message) {
     this._deliverDataCallCallback("receiveDataCallList",
                                   [message.datacalls, message.datacalls.length]);
   },
 
-  handleICCGetCardLock: function handleICCGetCardLock(message) {
-    ppmm.sendAsyncMessage("RIL:GetCardLock:Return:OK", message);
-  },
-
-  handleICCSetCardLock: function handleICCSetCardLock(message) {
-    ppmm.sendAsyncMessage("RIL:SetCardLock:Return:OK", message);
-  },
-
-  handleICCUnlockCardLock: function handleICCUnlockCardLock(message) {
-    ppmm.sendAsyncMessage("RIL:UnlockCardLock:Return:OK", message);
+  handleICCCardLockResult: function handleICCCardLockResult(message) {
+    ppmm.sendAsyncMessage("RIL:CardLockResult", message);
   },
 
   handleUSSDReceived: function handleUSSDReceived(ussd) {
     debug("handleUSSDReceived " + JSON.stringify(ussd));
     ppmm.sendAsyncMessage("RIL:UssdReceived", ussd);
   },
 
   handleSendUSSD: function handleSendUSSD(message) {
@@ -1635,77 +1623,27 @@ RadioInterfaceLayer.prototype = {
                              reason: reason});
   },
 
   getDataCallList: function getDataCallList() {
     this.worker.postMessage({rilMessageType: "getDataCallList"});
   },
 
   getCardLock: function getCardLock(message) {
-    // Currently only support pin.
-    switch (message.lockType) {
-      case "pin" :
-        message.rilMessageType = "getICCPinLock";
-        break;
-      default:
-        ppmm.sendAsyncMessage("RIL:GetCardLock:Return:KO",
-                              {errorMsg: "Unsupported Card Lock.",
-                               requestId: message.requestId});
-        return;
-    }
+    message.rilMessageType = "iccGetCardLock";
     this.worker.postMessage(message);
   },
 
   unlockCardLock: function unlockCardLock(message) {
-    switch (message.lockType) {
-      case "pin":
-        message.rilMessageType = "enterICCPIN";
-        break;
-      case "pin2":
-        message.rilMessageType = "enterICCPIN2";
-        break;
-      case "puk":
-        message.rilMessageType = "enterICCPUK";
-        break;
-      case "puk2":
-        message.rilMessageType = "enterICCPUK2";
-        break;
-      default:
-        ppmm.sendAsyncMessage("RIL:UnlockCardLock:Return:KO",
-                              {errorMsg: "Unsupported Card Lock.",
-                               requestId: message.requestId});
-        return;
-    }
+    message.rilMessageType = "iccUnlockCardLock";
     this.worker.postMessage(message);
   },
 
   setCardLock: function setCardLock(message) {
-    // Change pin.
-    if (message.newPin !== undefined) {
-      switch (message.lockType) {
-        case "pin":
-          message.rilMessageType = "changeICCPIN";
-          break;
-        case "pin2":
-          message.rilMessageType = "changeICCPIN2";
-          break;
-        default:
-          ppmm.sendAsyncMessage("RIL:SetCardLock:Return:KO",
-                                {errorMsg: "Unsupported Card Lock.",
-                                 requestId: message.requestId});
-          return;
-      }
-    } else { // Enable/Disable pin lock.
-      if (message.lockType != "pin") {
-          ppmm.sendAsyncMessage("RIL:SetCardLock:Return:KO",
-                                {errorMsg: "Unsupported Card Lock.",
-                                 requestId: message.requestId});
-      }
-      message.rilMessageType = "setICCPinLock";
-    }
+    message.rilMessageType = "iccSetCardLock";
     this.worker.postMessage(message);
   },
 
   _contactsCallbacks: null,
   getICCContacts: function getICCContacts(type, callback) {
     if (!this._contactsCallbacks) {
       this._contactsCallbacks = {};
     } 
--- a/dom/system/gonk/ril_consts.js
+++ b/dom/system/gonk/ril_consts.js
@@ -226,23 +226,25 @@ const ERROR_SS_MODIFIED_TO_USSD = 24;
 const ERROR_SS_MODIFIED_TO_SS = 25;
 const ERROR_SUBSCRIPTION_NOT_SUPPORTED = 26;
 
 const GECKO_ERROR_SUCCESS = null;
 const GECKO_ERROR_RADIO_NOT_AVAILABLE = "RadioNotAvailable";
 const GECKO_ERROR_GENERIC_FAILURE = "GenericFailure";
 const GECKO_ERROR_REQUEST_NOT_SUPPORTED = "RequestNotSupported";
 const GECKO_ERROR_ILLEGAL_SIM_OR_ME = "IllegalSIMorME";
+const GECKO_ERROR_PASSWORD_INCORRECT = "IncorrectPassword";
 
 const RIL_ERROR_TO_GECKO_ERROR = {};
 RIL_ERROR_TO_GECKO_ERROR[ERROR_SUCCESS] = GECKO_ERROR_SUCCESS;
 RIL_ERROR_TO_GECKO_ERROR[ERROR_RADIO_NOT_AVAILABLE] = GECKO_ERROR_RADIO_NOT_AVAILABLE;
 RIL_ERROR_TO_GECKO_ERROR[ERROR_GENERIC_FAILURE] = GECKO_ERROR_GENERIC_FAILURE;
 RIL_ERROR_TO_GECKO_ERROR[ERROR_REQUEST_NOT_SUPPORTED] = GECKO_ERROR_REQUEST_NOT_SUPPORTED;
 RIL_ERROR_TO_GECKO_ERROR[ERROR_ILLEGAL_SIM_OR_ME] = GECKO_ERROR_ILLEGAL_SIM_OR_ME;
+RIL_ERROR_TO_GECKO_ERROR[ERROR_PASSWORD_INCORRECT] = GECKO_ERROR_PASSWORD_INCORRECT;
 
 // 3GPP 23.040 clause 9.2.3.6 TP-Message-Reference(TP-MR):
 // The number of times the MS automatically repeats the SMS-SUBMIT shall be in
 // the range 1 to 3 but the precise number is an implementation matter.
 const SMS_RETRY_MAX = 3;
 
 const RADIO_STATE_OFF = 0;
 const RADIO_STATE_UNAVAILABLE = 1;
--- a/dom/system/gonk/ril_worker.js
+++ b/dom/system/gonk/ril_worker.js
@@ -728,16 +728,40 @@ let RIL = {
 
   /**
    * Retrieve the ICC's status.
    */
   getICCStatus: function getICCStatus() {
     Buf.simpleRequest(REQUEST_GET_SIM_STATUS);
   },
 
+   /**
+   * Helper function for unlocking ICC locks.
+   */
+  iccUnlockCardLock: function iccUnlockCardLock(options) {
+    switch (options.lockType) {
+      case "pin":
+        this.enterICCPIN(options);
+        break;
+      case "pin2":
+        this.enterICCPIN2(options);
+        break;
+      case "puk":
+        this.enterICCPUK(options);
+        break;
+      case "puk2":
+        this.enterICCPUK2(options);
+        break;
+      default:
+        options.errorMsg = "Unsupported Card Lock.";
+        options.success = false;
+        this.sendDOMMessage(options);
+    }
+  },
+
   /**
    * Enter a PIN to unlock the ICC.
    *
    * @param pin
    *        String containing the PIN.
    * @param [optional] aid
    *        AID value.
    */
@@ -764,16 +788,44 @@ let RIL = {
     Buf.writeUint32(RILQUIRKS_V5_LEGACY ? 1 : 2);
     Buf.writeString(options.pin);
     if (!RILQUIRKS_V5_LEGACY) {
       Buf.writeString(options.aid ? options.aid : this.aid);
     }
     Buf.sendParcel();
   },
 
+   /**
+   * Helper function for changing ICC locks.
+   */
+  iccSetCardLock: function iccSetCardLock(options) {
+    if (options.newPin !== undefined) {
+      switch (options.lockType) {
+        case "pin":
+          this.changeICCPIN(options);
+          break;
+        case "pin2":
+          this.changeICCPIN2(options);
+          break;
+        default:
+          options.errorMsg = "Unsupported Card Lock.";
+          options.success = false;
+          this.sendDOMMessage(options);
+      }
+    } else { // Enable/Disable pin lock.
+      if (options.lockType != "pin") {
+        options.errorMsg = "Unsupported Card Lock.";
+        options.success = false;
+        this.sendDOMMessage(options);
+        return;
+      }
+      this.setICCPinLock(options);
+    }
+  },
+
   /**
    * Change the current ICC PIN number.
    *
    * @param pin
    *        String containing the old PIN value
    * @param newPin
    *        String containing the new PIN value
    * @param [optional] aid
@@ -848,27 +900,42 @@ let RIL = {
      Buf.writeString(options.newPin);
      if (!RILQUIRKS_V5_LEGACY) {
        Buf.writeString(options.aid ? options.aid : this.aid);
      }
      Buf.sendParcel();
    },
 
   /**
+   * Helper function for fetching the state of ICC locks.
+   */
+  iccGetCardLock: function iccGetCardLock(options) {
+    switch (options.lockType) {
+      case "pin":
+        this.getICCPinLock(options);
+        break;
+      default:
+        options.errorMsg = "Unsupported Card Lock.";
+        options.success = false;
+        this.sendDOMMessage(options);
+    }
+  },
+
+  /**
    * Get ICC Pin lock. A wrapper call to queryICCFacilityLock.
    *
    * @param requestId
    *        Request Id from RadioInterfaceLayer.
    */
   getICCPinLock: function getICCPinLock(options) {
     options.facility = ICC_CB_FACILITY_SIM;
     options.password = ""; // For query no need to provide pin.
     options.serviceClass = ICC_SERVICE_CLASS_VOICE |
                            ICC_SERVICE_CLASS_DATA  |
-                           ICC_SERVICE_CLASS_FAX,
+                           ICC_SERVICE_CLASS_FAX;
     this.queryICCFacilityLock(options);
   },
 
   /**
    * Query ICC facility lock.
    *
    * @param facility
    *        One of ICC_CB_FACILITY_*.
@@ -902,17 +969,17 @@ let RIL = {
    *        Request Id from RadioInterfaceLayer.
    */
   setICCPinLock: function setICCPinLock(options) {
     options.facility = ICC_CB_FACILITY_SIM;
     options.enabled = options.enabled;
     options.password = options.pin;
     options.serviceClass = ICC_SERVICE_CLASS_VOICE |
                            ICC_SERVICE_CLASS_DATA  |
-                           ICC_SERVICE_CLASS_FAX,
+                           ICC_SERVICE_CLASS_FAX;
     this.setICCFacilityLock(options);
   },
 
   /**
    * Set ICC facility lock.
    *
    * @param facility
    *        One of ICC_CB_FACILITY_*.
@@ -1966,16 +2033,28 @@ let RIL = {
     this.getSignalStrength();
     this.fetchICCRecords();
 
     this.cardState = newCardState;
     this.sendDOMMessage({rilMessageType: "cardstatechange",
                          cardState: this.cardState});
   },
 
+   /**
+   * Helper for processing responses of functions such as enterICC* and changeICC*.
+   */
+  _processEnterAndChangeICCResponses: function _processEnterAndChangeICCResponses(length, options) {
+    options.success = options.rilRequestError == 0;
+    if (!options.success) {
+      options.errorMsg = RIL_ERROR_TO_GECKO_ERROR[options.rilRequestError];
+    }
+    options.retryCount = length ? Buf.readUint32List()[0] : -1;
+    this.sendDOMMessage(options);
+  },
+
   /**
    * Process a ICC_COMMAND_GET_RESPONSE type command for REQUEST_SIM_IO.
    */
   _processICCIOGetResponse: function _processICCIOGetResponse(options) {
     let length = Buf.readUint32();
 
     // The format is from TS 51.011, clause 9.2.1
 
@@ -2832,56 +2911,32 @@ RIL[REQUEST_GET_SIM_STATUS] = function R
       Buf.readUint32();
     }
   }
 
   if (DEBUG) debug("iccStatus: " + JSON.stringify(iccStatus));
   this._processICCStatus(iccStatus);
 };
 RIL[REQUEST_ENTER_SIM_PIN] = function REQUEST_ENTER_SIM_PIN(length, options) {
-  this.sendDOMMessage({rilMessageType: "iccunlockcardlock",
-                       lockType: "pin",
-                       result: options.rilRequestError == 0 ? true : false,
-                       retryCount: length ? Buf.readUint32List()[0] : -1,
-                       requestId: options.requestId});
+  this._processEnterAndChangeICCResponses(length, options);
 };
 RIL[REQUEST_ENTER_SIM_PUK] = function REQUEST_ENTER_SIM_PUK(length, options) {
-  this.sendDOMMessage({rilMessageType: "iccunlockcardlock",
-                       lockType: "puk",
-                       result: options.rilRequestError == 0 ? true : false,
-                       retryCount: length ? Buf.readUint32List()[0] : -1,
-                       requestId: options.requestId});
+  this._processEnterAndChangeICCResponses(length, options);
 };
 RIL[REQUEST_ENTER_SIM_PIN2] = function REQUEST_ENTER_SIM_PIN2(length, options) {
-  this.sendDOMMessage({rilMessageType: "iccunlockcardlock",
-                       lockType: "pin2",
-                       result: options.rilRequestError == 0 ? true : false,
-                       retryCount: length ? Buf.readUint32List()[0] : -1,
-                       requestId: options.requestId});
+  this._processEnterAndChangeICCResponses(length, options);
 };
 RIL[REQUEST_ENTER_SIM_PUK2] = function REQUEST_ENTER_SIM_PUK(length, options) {
-  this.sendDOMMessage({rilMessageType: "iccunlockcardlock",
-                       lockType: "puk2",
-                       result: options.rilRequestError == 0 ? true : false,
-                       retryCount: length ? Buf.readUint32List()[0] : -1,
-                       requestId: options.requestId});
+  this._processEnterAndChangeICCResponses(length, options);
 };
 RIL[REQUEST_CHANGE_SIM_PIN] = function REQUEST_CHANGE_SIM_PIN(length, options) {
-  this.sendDOMMessage({rilMessageType: "iccsetcardlock",
-                       lockType: "pin",
-                       result: options.rilRequestError == 0 ? true : false,
-                       retryCount: length ? Buf.readUint32List()[0] : -1,
-                       requestId: options.requestId});
+  this._processEnterAndChangeICCResponses(length, options);
 };
 RIL[REQUEST_CHANGE_SIM_PIN2] = function REQUEST_CHANGE_SIM_PIN2(length, options) {
-  this.sendDOMMessage({rilMessageType: "iccsetcardlock",
-                       lockType: "pin2",
-                       result: options.rilRequestError == 0 ? true : false,
-                       retryCount: length ? Buf.readUint32List()[0] : -1,
-                       requestId: options.requestId});
+  this._processEnterAndChangeICCResponses(length, options);
 };
 RIL[REQUEST_ENTER_NETWORK_DEPERSONALIZATION] = null;
 RIL[REQUEST_GET_CURRENT_CALLS] = function REQUEST_GET_CURRENT_CALLS(length, options) {
   if (options.rilRequestError) {
     return;
   }
 
   let calls_length = 0;
@@ -3268,32 +3323,33 @@ RIL[REQUEST_DEACTIVATE_DATA_CALL] = func
 
   let datacall = this.currentDataCalls[options.cid];
   delete this.currentDataCalls[options.cid];
   datacall.state = GECKO_NETWORK_STATE_DISCONNECTED;
   datacall.rilMessageType = "datacallstatechange";
   this.sendDOMMessage(datacall);
 };
 RIL[REQUEST_QUERY_FACILITY_LOCK] = function REQUEST_QUERY_FACILITY_LOCK(length, options) {
-  if (options.rilRequestError) {
-    return;
+  options.success = options.rilRequestError == 0;
+  if (!options.success) {
+    options.errorMsg = RIL_ERROR_TO_GECKO_ERROR[options.rilRequestError];
   }
 
-  let response = Buf.readUint32List()[0];
-  this.sendDOMMessage({rilMessageType: "iccgetcardlock",
-                       lockType: "pin",
-                       enabled: response == 0 ? false : true,
-                       requestId: options.requestId});
+  if (length) {
+    options.enabled = Buf.readUint32List()[0] == 0 ? false : true;
+  }
+  this.sendDOMMessage(options);
 };
 RIL[REQUEST_SET_FACILITY_LOCK] = function REQUEST_SET_FACILITY_LOCK(length, options) {
-  this.sendDOMMessage({rilMessageType: "iccsetcardlock",
-                       lockType: "pin",
-                       result: options.rilRequestError == 0 ? true : false,
-                       retryCount: length ? Buf.readUint32List()[0] : -1,
-                       requestId: options.requestId});
+  options.success = options.rilRequestError == 0;
+  if (!options.success) {
+    options.errorMsg = RIL_ERROR_TO_GECKO_ERROR[options.rilRequestError];
+  }
+  options.retryCount = length ? Buf.readUint32List()[0] : -1;
+  this.sendDOMMessage(options);
 };
 RIL[REQUEST_CHANGE_BARRING_PASSWORD] = null;
 RIL[REQUEST_QUERY_NETWORK_SELECTION_MODE] = function REQUEST_QUERY_NETWORK_SELECTION_MODE(length, options) {
   this._receivedNetworkInfo(NETWORK_INFO_NETWORK_SELECTION_MODE);
 
   if (options.rilRequestError) {
     options.error = RIL_ERROR_TO_GECKO_ERROR[options.rilRequestError];
     this.sendDOMMessage(options);
--- a/dom/tests/mochitest/general/test_interfaces.html
+++ b/dom/tests/mochitest/general/test_interfaces.html
@@ -519,18 +519,18 @@ var interfaceNamesInGlobalScope =
     "HTMLLIElement",
     "SVGClipPathElement",
     "NavigatorGeolocation",
     "HTMLParagraphElement",
     "EventTarget",
     "File",
     "WebGLActiveInfo",
     "SVGGradientElement",
-    "ContactTelephone",
-    "ContactEmail",
+    "ContactTelField",
+    "ContactField",
     "SVGFitToViewBox",
     "SVGAElement",
     "NavigatorCamera",
     "CameraControl",
     "CameraCapabilities",
     "CameraManager",
     "CSSSupportsRule"
   ]
--- a/editor/libeditor/html/nsHTMLDataTransfer.cpp
+++ b/editor/libeditor/html/nsHTMLDataTransfer.cpp
@@ -47,30 +47,27 @@
 #include "nsIDOMHTMLLinkElement.h"
 #include "nsIDOMHTMLObjectElement.h"
 #include "nsIDOMHTMLScriptElement.h"
 #include "nsIDOMHTMLTableCellElement.h"
 #include "nsIDOMHTMLTableElement.h"
 #include "nsIDOMHTMLTableRowElement.h"
 #include "nsIDOMNode.h"
 #include "nsIDOMRange.h"
-#include "nsIDocShell.h"
-#include "nsIDocShellTreeItem.h"
 #include "nsIDocument.h"
 #include "nsIEditor.h"
 #include "nsIEditorIMESupport.h"
 #include "nsIEditorMailSupport.h"
 #include "nsIFile.h"
 #include "nsIInputStream.h"
 #include "nsIMIMEService.h"
 #include "nsINameSpaceManager.h"
 #include "nsINode.h"
 #include "nsIParserUtils.h"
 #include "nsIPlaintextEditor.h"
-#include "nsIPrincipal.h"
 #include "nsISelection.h"
 #include "nsISupportsImpl.h"
 #include "nsISupportsPrimitives.h"
 #include "nsISupportsUtils.h"
 #include "nsITransferable.h"
 #include "nsIURI.h"
 #include "nsIVariant.h"
 #include "nsLinebreakConverter.h"
@@ -1166,45 +1163,16 @@ nsHTMLEditor::ParseCFHTML(nsCString & aC
                                                            nsLinebreakConverter::eLinebreakContent, 
                                                            oldLengthInChars, &newLengthInChars);
   // it's ok for context to be empty.  frag might be whole doc and contain all its context.
 
   // we're done!
   return NS_OK;
 }
 
-bool nsHTMLEditor::IsSafeToInsertData(nsIDOMDocument* aSourceDoc)
-{
-  // Try to determine whether we should use a sanitizing fragment sink
-  bool isSafe = false;
-
-  nsCOMPtr<nsIDocument> destdoc = GetDocument();
-  NS_ASSERTION(destdoc, "Where is our destination doc?");
-  nsCOMPtr<nsISupports> container = destdoc->GetContainer();
-  nsCOMPtr<nsIDocShellTreeItem> dsti = do_QueryInterface(container);
-  nsCOMPtr<nsIDocShellTreeItem> root;
-  if (dsti)
-    dsti->GetRootTreeItem(getter_AddRefs(root));
-  nsCOMPtr<nsIDocShell> docShell = do_QueryInterface(root);
-  PRUint32 appType;
-  if (docShell && NS_SUCCEEDED(docShell->GetAppType(&appType)))
-    isSafe = appType == nsIDocShell::APP_TYPE_EDITOR;
-  if (!isSafe && aSourceDoc) {
-    nsCOMPtr<nsIDocument> srcdoc = do_QueryInterface(aSourceDoc);
-    NS_ASSERTION(srcdoc, "Where is our source doc?");
-
-    nsIPrincipal* srcPrincipal = srcdoc->NodePrincipal();
-    nsIPrincipal* destPrincipal = destdoc->NodePrincipal();
-    NS_ASSERTION(srcPrincipal && destPrincipal, "How come we don't have a principal?");
-    srcPrincipal->Subsumes(destPrincipal, &isSafe);
-  }
-
-  return isSafe;
-}
-
 nsresult nsHTMLEditor::InsertObject(const char* aType, nsISupports* aObject, bool aIsSafe,
                                     nsIDOMDocument *aSourceDoc,
                                     nsIDOMNode *aDestinationNode,
                                     PRInt32 aDestOffset,
                                     bool aDoDeleteSelection)
 {
   nsresult rv;
 
--- a/editor/libeditor/html/nsHTMLEditor.cpp
+++ b/editor/libeditor/html/nsHTMLEditor.cpp
@@ -4680,18 +4680,17 @@ nsHTMLEditor::SetCSSBackgroundColor(cons
     NS_ENSURE_SUCCESS(res, res);
     NS_ENSURE_TRUE(enumerator, NS_ERROR_FAILURE);
 
     // loop thru the ranges in the selection
     enumerator->First(); 
     nsCOMPtr<nsISupports> currentItem;
     nsAutoString bgcolor; bgcolor.AssignLiteral("bgcolor");
     nsCOMPtr<nsIDOMNode> cachedBlockParent = nullptr;
-    while ((NS_ENUMERATOR_FALSE == enumerator->IsDone()))
-    {
+    while (static_cast<nsresult>(NS_ENUMERATOR_FALSE) == enumerator->IsDone()) {
       res = enumerator->CurrentItem(getter_AddRefs(currentItem));
       NS_ENSURE_SUCCESS(res, res);
       NS_ENSURE_TRUE(currentItem, NS_ERROR_FAILURE);
       
       nsCOMPtr<nsIDOMRange> range( do_QueryInterface(currentItem) );
       
       // check for easy case: both range endpoints in same text node
       nsCOMPtr<nsIDOMNode> startNode, endNode;
--- a/editor/libeditor/html/nsHTMLEditor.h
+++ b/editor/libeditor/html/nsHTMLEditor.h
@@ -529,20 +529,16 @@ protected:
     *                        (usually true, unless those characters
     *                        have already been added.)
     * @return aNodeInserted  The node spanning the insertion, if applicable.
     *                        If aAddCites is false, this will be null.
     */
   NS_IMETHOD InsertAsPlaintextQuotation(const nsAString & aQuotedText,
                                         bool aAddCites,
                                         nsIDOMNode **aNodeInserted);
-  // Return true if the data is safe to insert as the source and destination
-  // principals match, or we are in a editor context where this doesn't matter.
-  // Otherwise, the data must be sanitized first.
-  bool IsSafeToInsertData(nsIDOMDocument* aSourceDoc);
 
   nsresult InsertObject(const char* aType, nsISupports* aObject, bool aIsSafe,
                         nsIDOMDocument *aSourceDoc,
                         nsIDOMNode *aDestinationNode,
                         PRInt32 aDestOffset,
                         bool aDoDeleteSelection);
 
   // factored methods for handling insertion of data from transferables (drag&drop or clipboard)
--- a/editor/libeditor/html/nsHTMLEditorStyle.cpp
+++ b/editor/libeditor/html/nsHTMLEditorStyle.cpp
@@ -139,17 +139,18 @@ nsHTMLEditor::SetInlineProperty(nsIAtom 
     // get selection range enumerator
     nsCOMPtr<nsIEnumerator> enumerator;
     res = selection->GetEnumerator(getter_AddRefs(enumerator));
     NS_ENSURE_SUCCESS(res, res);
     NS_ENSURE_TRUE(enumerator, NS_ERROR_FAILURE);
 
     // loop thru the ranges in the selection
     nsCOMPtr<nsISupports> currentItem;
-    for (enumerator->First(); NS_ENUMERATOR_FALSE == enumerator->IsDone();
+    for (enumerator->First();
+         static_cast<nsresult>(NS_ENUMERATOR_FALSE) == enumerator->IsDone();
          enumerator->Next()) {
       res = enumerator->CurrentItem(getter_AddRefs(currentItem));
       NS_ENSURE_SUCCESS(res, res);
       NS_ENSURE_TRUE(currentItem, NS_ERROR_FAILURE);
 
       nsCOMPtr<nsIDOMRange> range(do_QueryInterface(currentItem));
 
       // adjust range to include any ancestors whose children are entirely
@@ -1386,18 +1387,17 @@ nsresult nsHTMLEditor::RemoveInlinePrope
     nsCOMPtr<nsIEnumerator> enumerator;
     res = selection->GetEnumerator(getter_AddRefs(enumerator));
     NS_ENSURE_SUCCESS(res, res);
     NS_ENSURE_TRUE(enumerator, NS_ERROR_FAILURE);
 
     // loop thru the ranges in the selection
     enumerator->First(); 
     nsCOMPtr<nsISupports> currentItem;
-    while ((NS_ENUMERATOR_FALSE == enumerator->IsDone()))
-    {
+    while (static_cast<nsresult>(NS_ENUMERATOR_FALSE) == enumerator->IsDone()) {
       res = enumerator->CurrentItem(getter_AddRefs(currentItem));
       NS_ENSURE_SUCCESS(res, res);
       NS_ENSURE_TRUE(currentItem, NS_ERROR_FAILURE);
       
       nsCOMPtr<nsIDOMRange> range( do_QueryInterface(currentItem) );
 
       if (aProperty == nsEditProperty::name)
       {
@@ -1574,18 +1574,17 @@ nsHTMLEditor::RelativeFontChange( PRInt3
   nsCOMPtr<nsIEnumerator> enumerator;
   nsresult res = selection->GetEnumerator(getter_AddRefs(enumerator));
   NS_ENSURE_SUCCESS(res, res);
   NS_ENSURE_TRUE(enumerator, NS_ERROR_FAILURE);
 
   // loop thru the ranges in the selection
   enumerator->First(); 
   nsCOMPtr<nsISupports> currentItem;
-  while ((NS_ENUMERATOR_FALSE == enumerator->IsDone()))
-  {
+  while (static_cast<nsresult>(NS_ENUMERATOR_FALSE) == enumerator->IsDone()) {
     res = enumerator->CurrentItem(getter_AddRefs(currentItem));
     NS_ENSURE_SUCCESS(res, res);
     NS_ENSURE_TRUE(currentItem, NS_ERROR_FAILURE);
     
     nsCOMPtr<nsIDOMRange> range( do_QueryInterface(currentItem) );
 
     // adjust range to include any ancestors who's children are entirely selected
     res = PromoteInlineRange(range);
--- a/editor/libeditor/text/nsPlaintextDataTransfer.cpp
+++ b/editor/libeditor/text/nsPlaintextDataTransfer.cpp
@@ -23,16 +23,19 @@
 #include "nsIDOMNode.h"
 #include "nsIDOMRange.h"
 #include "nsIDOMUIEvent.h"
 #include "nsIDocument.h"
 #include "nsIDragService.h"
 #include "nsIDragSession.h"
 #include "nsIEditor.h"
 #include "nsIEditorIMESupport.h"
+#include "nsIDocShell.h"
+#include "nsIDocShellTreeItem.h"
+#include "nsIPrincipal.h"
 #include "nsIFormControl.h"
 #include "nsIPlaintextEditor.h"
 #include "nsISelection.h"
 #include "nsISupportsPrimitives.h"
 #include "nsITransferable.h"
 #include "nsIVariant.h"
 #include "nsLiteralString.h"
 #include "nsPlaintextEditor.h"
@@ -168,19 +171,31 @@ nsresult nsPlaintextEditor::InsertFromDr
 
   nsCOMPtr<nsIDOMDataTransfer> dataTransfer;
   nsresult rv = dragEvent->GetDataTransfer(getter_AddRefs(dataTransfer));
   NS_ENSURE_SUCCESS(rv, rv);
 
   nsCOMPtr<nsIDragSession> dragSession = nsContentUtils::GetDragSession();
   NS_ASSERTION(dragSession, "No drag session");
 
+  nsCOMPtr<nsIDOMNode> sourceNode;
+  dataTransfer->GetMozSourceNode(getter_AddRefs(sourceNode));
+
+  nsCOMPtr<nsIDOMDocument> srcdomdoc;
+  if (sourceNode) {
+    sourceNode->GetOwnerDocument(getter_AddRefs(srcdomdoc));
+    NS_ENSURE_TRUE(sourceNode, NS_ERROR_FAILURE);
+  }
+
   nsDragEvent* dragEventInternal = static_cast<nsDragEvent *>(aDropEvent->GetInternalNSEvent());
   if (nsContentUtils::CheckForSubFrameDrop(dragSession, dragEventInternal)) {
-    return NS_OK;
+    // Don't allow drags from subframe documents with different origins than
+    // the drop destination.
+    if (srcdomdoc && !IsSafeToInsertData(srcdomdoc))
+      return NS_OK;
   }
 
   // Current doc is destination
   nsCOMPtr<nsIDOMDocument> destdomdoc = GetDOMDocument();
   NS_ENSURE_TRUE(destdomdoc, NS_ERROR_NOT_INITIALIZED);
 
   PRUint32 numItems = 0;
   rv = dataTransfer->GetMozItemCount(&numItems);
@@ -208,25 +223,16 @@ nsresult nsPlaintextEditor::InsertFromDr
 
   nsCOMPtr<nsISelection> selection;
   rv = GetSelection(getter_AddRefs(selection));
   NS_ENSURE_SUCCESS(rv, rv);
   NS_ENSURE_TRUE(selection, NS_ERROR_FAILURE);
 
   bool isCollapsed = selection->Collapsed();
 
-  nsCOMPtr<nsIDOMNode> sourceNode;
-  dataTransfer->GetMozSourceNode(getter_AddRefs(sourceNode));
-
-  nsCOMPtr<nsIDOMDocument> srcdomdoc;
-  if (sourceNode) {
-    sourceNode->GetOwnerDocument(getter_AddRefs(srcdomdoc));
-    NS_ENSURE_TRUE(sourceNode, NS_ERROR_FAILURE);
-  }
-
   // Only the nsHTMLEditor::FindUserSelectAllNode returns a node.
   nsCOMPtr<nsIDOMNode> userSelectNode = FindUserSelectAllNode(newSelectionParent);
   if (userSelectNode)
   {
     // The drop is happening over a "-moz-user-select: all"
     // subtree so make sure the content we insert goes before
     // the root of the subtree.
     //
@@ -414,8 +420,38 @@ NS_IMETHODIMP nsPlaintextEditor::CanPast
                                                &dataLen);
   if (NS_SUCCEEDED(rv) && data)
     *aCanPaste = true;
   else
     *aCanPaste = false;
   
   return NS_OK;
 }
+
+bool nsPlaintextEditor::IsSafeToInsertData(nsIDOMDocument* aSourceDoc)
+{
+  // Try to determine whether we should use a sanitizing fragment sink
+  bool isSafe = false;
+
+  nsCOMPtr<nsIDocument> destdoc = GetDocument();
+  NS_ASSERTION(destdoc, "Where is our destination doc?");
+  nsCOMPtr<nsISupports> container = destdoc->GetContainer();
+  nsCOMPtr<nsIDocShellTreeItem> dsti = do_QueryInterface(container);
+  nsCOMPtr<nsIDocShellTreeItem> root;
+  if (dsti)
+    dsti->GetRootTreeItem(getter_AddRefs(root));
+  nsCOMPtr<nsIDocShell> docShell = do_QueryInterface(root);
+  PRUint32 appType;
+  if (docShell && NS_SUCCEEDED(docShell->GetAppType(&appType)))
+    isSafe = appType == nsIDocShell::APP_TYPE_EDITOR;
+  if (!isSafe && aSourceDoc) {
+    nsCOMPtr<nsIDocument> srcdoc = do_QueryInterface(aSourceDoc);
+    NS_ASSERTION(srcdoc, "Where is our source doc?");
+
+    nsIPrincipal* srcPrincipal = srcdoc->NodePrincipal();
+    nsIPrincipal* destPrincipal = destdoc->NodePrincipal();
+    NS_ASSERTION(srcPrincipal && destPrincipal, "How come we don't have a principal?");
+    srcPrincipal->Subsumes(destPrincipal, &isSafe);
+  }
+
+  return isSafe;
+}
+
--- a/editor/libeditor/text/nsPlaintextEditor.h
+++ b/editor/libeditor/text/nsPlaintextEditor.h
@@ -149,16 +149,21 @@ public:
   /**
    * Extends the selection for given deletion operation
    * If done, also update aAction to what's actually left to do after the
    * extension.
    */
   nsresult ExtendSelectionForDelete(nsISelection* aSelection,
                                     nsIEditor::EDirection *aAction);
 
+  // Return true if the data is safe to insert as the source and destination
+  // principals match, or we are in a editor context where this doesn't matter.
+  // Otherwise, the data must be sanitized first.
+  bool IsSafeToInsertData(nsIDOMDocument* aSourceDoc);
+
   static void GetDefaultEditorPrefs(PRInt32 &aNewLineHandling,
                                     PRInt32 &aCaretStyle);
 
 protected:
 
   NS_IMETHOD  InitRules();
   void        BeginEditorInit();
   nsresult    EndEditorInit();
--- a/editor/txmgr/tests/TestTXMgr.cpp
+++ b/editor/txmgr/tests/TestTXMgr.cpp
@@ -4586,39 +4586,38 @@ main (int argc, char *argv[])
 
   nsresult result;
 
   //
   // quick_test() part:
   //
 
   result = simple_test();
-  NS_ENSURE_SUCCESS(result, result);
+  NS_ENSURE_SUCCESS(result, 1);
 
   result = aggregation_test();
-  NS_ENSURE_SUCCESS(result, result);
+  NS_ENSURE_SUCCESS(result, 1);
 
   //
   // quick_batch_test() part:
   //
 
   result = simple_batch_test();
-  NS_ENSURE_SUCCESS(result, result);
+  NS_ENSURE_SUCCESS(result, 1);
 
   result = aggregation_batch_test();
-  NS_ENSURE_SUCCESS(result, result);
+  NS_ENSURE_SUCCESS(result, 1);
 
   //
   // stress_test() part:
   //
 
   result = simple_stress_test();
-  NS_ENSURE_SUCCESS(result, result);
+  NS_ENSURE_SUCCESS(result, 1);
 
   result = aggregation_stress_test();
-  NS_ENSURE_SUCCESS(result, result);
+  NS_ENSURE_SUCCESS(result, 1);
 
   result = aggregation_batch_stress_test();
-  NS_ENSURE_SUCCESS(result, result);
-
-
-  return NS_OK;
+  NS_ENSURE_SUCCESS(result, 1);
+
+  return 0;
 }
--- a/embedding/browser/webBrowser/nsWebBrowser.cpp
+++ b/embedding/browser/webBrowser/nsWebBrowser.cpp
@@ -87,17 +87,17 @@ nsWebBrowser::~nsWebBrowser()
 {
    InternalDestroy();
 }
 
 NS_IMETHODIMP nsWebBrowser::InternalDestroy()
 {
 
    if (mInternalWidget) {
-     mInternalWidget->SetClientData(0);
+     mInternalWidget->SetWidgetListener(nullptr);
      mInternalWidget->Destroy();
      mInternalWidget = nullptr; // Force release here.
    }
 
    SetDocShell(nullptr);
 
    if(mDocShellTreeOwner)
       {
@@ -882,18 +882,18 @@ NS_IMETHODIMP nsWebBrowser::GetCurrentSt
     if (mPersist)
     {
         mPersist->GetCurrentState(&mPersistCurrentState);
     }
     *aCurrentState = mPersistCurrentState;
     return NS_OK;
 }
 
-/* readonly attribute unsigned long result; */
-NS_IMETHODIMP nsWebBrowser::GetResult(PRUint32 *aResult)
+/* readonly attribute nsresult result; */
+NS_IMETHODIMP nsWebBrowser::GetResult(nsresult *aResult)
 {
     NS_ENSURE_ARG_POINTER(aResult);
     if (mPersist)
     {
         mPersist->GetResult(&mPersistResult);
     }
     *aResult = mPersistResult;
     return NS_OK;
@@ -1113,19 +1113,18 @@ NS_IMETHODIMP nsWebBrowser::Create()
       docShellParentWidget = mInternalWidget;
       nsWidgetInitData  widgetInit;
 
       widgetInit.clipChildren = true;
 
       widgetInit.mWindowType = eWindowType_child;
       nsIntRect bounds(mInitInfo->x, mInitInfo->y, mInitInfo->cx, mInitInfo->cy);
       
-      mInternalWidget->SetClientData(static_cast<nsWebBrowser *>(this));
-      mInternalWidget->Create(nullptr, mParentNativeWindow, bounds, nsWebBrowser::HandleEvent,
-                              nullptr, &widgetInit);  
+      mInternalWidget->SetWidgetListener(this);
+      mInternalWidget->Create(nullptr, mParentNativeWindow, bounds, nullptr, &widgetInit);
       }
 
     nsCOMPtr<nsIDocShell> docShell(do_CreateInstance("@mozilla.org/docshell;1", &rv));
     NS_ENSURE_SUCCESS(rv, rv);
     rv = SetDocShell(docShell);
     NS_ENSURE_SUCCESS(rv, rv);
 
     // get the system default window background colour
@@ -1654,79 +1653,55 @@ static void DrawThebesLayer(ThebesLayer*
   nscolor* color = static_cast<nscolor*>(aCallbackData);
   aContext->NewPath();
   aContext->SetColor(gfxRGBA(*color));
   nsIntRect dirtyRect = aRegionToDraw.GetBounds();
   aContext->Rectangle(gfxRect(dirtyRect.x, dirtyRect.y, dirtyRect.width, dirtyRect.height));
   aContext->Fill();  
 }
 
-/* static */
-nsEventStatus nsWebBrowser::HandleEvent(nsGUIEvent *aEvent)
+void nsWebBrowser::WindowRaised(nsIWidget* aWidget)
 {
-  nsWebBrowser  *browser = nullptr;
-  void          *data = nullptr;
-  nsIWidget     *widget = aEvent->widget;
-
-  if (!widget)
-    return nsEventStatus_eIgnore;
-
-  widget->GetClientData(data);
-  if (!data)
-    return nsEventStatus_eIgnore;
-
-  browser = static_cast<nsWebBrowser *>(data);
-
-  switch(aEvent->message) {
-
-  case NS_PAINT: {
-      LayerManager* layerManager = widget->GetLayerManager();
-      NS_ASSERTION(layerManager, "Must be in paint event");
+#if defined(DEBUG_smaug)
+  nsCOMPtr<nsIDOMDocument> domDocument = do_GetInterface(mDocShell);
+  nsAutoString documentURI;
+  domDocument->GetDocumentURI(documentURI);
+  printf("nsWebBrowser::NS_ACTIVATE %p %s\n", (void*)browser,
+         NS_ConvertUTF16toUTF8(documentURI).get());
+#endif
+  Activate();
+}
 
-      layerManager->BeginTransaction();
-      nsRefPtr<ThebesLayer> root = layerManager->CreateThebesLayer();
-      nsPaintEvent* paintEvent = static_cast<nsPaintEvent*>(aEvent);
-      nsIntRect dirtyRect = paintEvent->region.GetBounds();
-      if (root) {
-          root->SetVisibleRegion(dirtyRect);
-          layerManager->SetRoot(root);
-      }
-      layerManager->EndTransaction(DrawThebesLayer, &browser->mBackgroundColor);
-      return nsEventStatus_eConsumeDoDefault;
-    }
+void nsWebBrowser::WindowLowered(nsIWidget* aWidget)
+{
+#if defined(DEBUG_smaug)
+  nsCOMPtr<nsIDOMDocument> domDocument = do_GetInterface(mDocShell);
+  nsAutoString documentURI;
+  domDocument->GetDocumentURI(documentURI);
+  printf("nsWebBrowser::NS_DEACTIVATE %p %s\n", (void*)browser,
+         NS_ConvertUTF16toUTF8(documentURI).get());
+#endif
+  Deactivate();
+}
 
-  case NS_ACTIVATE: {
-#if defined(DEBUG_smaug)
-    nsCOMPtr<nsIDOMDocument> domDocument = do_GetInterface(browser->mDocShell);
-    nsAutoString documentURI;
-    domDocument->GetDocumentURI(documentURI);
-    printf("nsWebBrowser::NS_ACTIVATE %p %s\n", (void*)browser,
-           NS_ConvertUTF16toUTF8(documentURI).get());
-#endif
-    browser->Activate();
-    break;
+bool nsWebBrowser::PaintWindow(nsIWidget* aWidget, bool isRequest, nsIntRegion aRegion, bool aWillSendDidPaint)
+{
+  LayerManager* layerManager = aWidget->GetLayerManager();
+  NS_ASSERTION(layerManager, "Must be in paint event");
+
+  layerManager->BeginTransaction();
+  nsRefPtr<ThebesLayer> root = layerManager->CreateThebesLayer();
+  if (root) {
+    nsIntRect dirtyRect = aRegion.GetBounds();
+    root->SetVisibleRegion(dirtyRect);
+    layerManager->SetRoot(root);
   }
 
-  case NS_DEACTIVATE: {
-#if defined(DEBUG_smaug)
-    nsCOMPtr<nsIDOMDocument> domDocument = do_GetInterface(browser->mDocShell);
-    nsAutoString documentURI;
-    domDocument->GetDocumentURI(documentURI);
-    printf("nsWebBrowser::NS_DEACTIVATE %p %s\n", (void*)browser,
-           NS_ConvertUTF16toUTF8(documentURI).get());
-#endif
-    browser->Deactivate();
-    break;
-  }
-
-  default:
-    break;
-  }
-
-  return nsEventStatus_eIgnore;
+  layerManager->EndTransaction(DrawThebesLayer, &mBackgroundColor);
+  return true;
 }
 
 NS_IMETHODIMP nsWebBrowser::GetPrimaryContentWindow(nsIDOMWindow** aDOMWindow)
 {
   *aDOMWindow = 0;
 
   nsCOMPtr<nsIDocShellTreeItem> item;
   NS_ENSURE_TRUE(mDocShellTreeOwner, NS_ERROR_FAILURE);
--- a/embedding/browser/webBrowser/nsWebBrowser.h
+++ b/embedding/browser/webBrowser/nsWebBrowser.h
@@ -31,16 +31,17 @@
 #include "nsIWebNavigation.h"
 #include "nsIWebBrowserSetup.h"
 #include "nsIWebBrowserPersist.h"
 #include "nsIWebBrowserFocus.h"
 #include "nsIWebBrowserStream.h"
 #include "nsIWindowWatcher.h"
 #include "nsIPrintSettings.h"
 #include "nsEmbedStream.h"
+#include "nsIWidgetListener.h"
 
 #include "nsTArray.h"
 #include "nsWeakPtr.h"
 
 class nsIContentViewerFile;
 
 class nsWebBrowserInitInfo
 {
@@ -79,16 +80,17 @@ class nsWebBrowser : public nsIWebBrowse
                      public nsIBaseWindow,
                      public nsIScrollable, 
                      public nsITextScroll, 
                      public nsIInterfaceRequestor,
                      public nsIWebBrowserPersist,
                      public nsIWebBrowserFocus,
                      public nsIWebProgressListener,
                      public nsIWebBrowserStream,
+                     public nsIWidgetListener,
                      public nsSupportsWeakReference
 {
 friend class nsDocShellTreeOwner;
 public:
     nsWebBrowser();
 
     NS_DECL_ISUPPORTS
 
@@ -114,17 +116,20 @@ protected:
     // XXXbz why are these NS_IMETHOD?  They're not interface methods!
     NS_IMETHOD SetDocShell(nsIDocShell* aDocShell);
     NS_IMETHOD EnsureDocShellTreeOwner();
     NS_IMETHOD GetPrimaryContentWindow(nsIDOMWindow **aDomWindow);
     NS_IMETHOD BindListener(nsISupports *aListener, const nsIID& aIID);
     NS_IMETHOD UnBindListener(nsISupports *aListener, const nsIID& aIID);
     NS_IMETHOD EnableGlobalHistory(bool aEnable);
 
-    static nsEventStatus HandleEvent(nsGUIEvent *aEvent);
+    // nsIWidgetListener
+    virtual void WindowRaised(nsIWidget* aWidget);
+    virtual void WindowLowered(nsIWidget* aWidget);
+    virtual bool PaintWindow(nsIWidget* aWidget, bool isRequest, nsIntRegion aRegion, bool aWillSendDidPaint);
 
 protected:
    nsDocShellTreeOwner*       mDocShellTreeOwner;
    nsCOMPtr<nsIDocShell>      mDocShell;
    nsCOMPtr<nsIInterfaceRequestor> mDocShellAsReq;
    nsCOMPtr<nsIBaseWindow>    mDocShellAsWin;
    nsCOMPtr<nsIDocShellTreeItem> mDocShellAsItem;
    nsCOMPtr<nsIWebNavigation> mDocShellAsNav;
@@ -144,17 +149,17 @@ protected:
    nsCOMPtr<nsIPrintSettings> mPrintSettings;
 
    // cached background color
    nscolor                       mBackgroundColor;
 
    // persistence object
    nsCOMPtr<nsIWebBrowserPersist> mPersist;
    PRUint32                       mPersistCurrentState;
-   PRUint32                       mPersistResult;
+   nsresult                       mPersistResult;
    PRUint32                       mPersistFlags;
 
    // stream
    nsEmbedStream                 *mStream;
    nsCOMPtr<nsISupports>          mStreamGuard;
 
    //Weak Reference interfaces...
    nsIWidget*                            mParentWidget;
--- a/embedding/components/webbrowserpersist/public/nsIWebBrowserPersist.idl
+++ b/embedding/components/webbrowserpersist/public/nsIWebBrowserPersist.idl
@@ -93,17 +93,17 @@ interface nsIWebBrowserPersist : nsICanc
   /**
    * Value indicating the success or failure of the persist
    * operation.
    *
    * @return NS_OK Operation was successful or is still ongoing.
    * @return NS_BINDING_ABORTED Operation cancelled.
    * @return NS_ERROR_FAILURE Non-specific failure.
    */
-  readonly attribute unsigned long result;
+  readonly attribute nsresult result;
 
   /**
    * Callback listener for progress notifications. The object that the
    * embbedder supplies may also implement nsIInterfaceRequestor and be
    * prepared to return nsIAuthPrompt or other interfaces that may be required
    * to download data.
    *
    * @see nsIAuthPrompt
--- a/embedding/components/webbrowserpersist/src/nsWebBrowserPersist.cpp
+++ b/embedding/components/webbrowserpersist/src/nsWebBrowserPersist.cpp
@@ -298,17 +298,17 @@ NS_IMETHODIMP nsWebBrowserPersist::GetCu
     else
     {
         *aCurrentState = PERSIST_STATE_READY;
     }
     return NS_OK;
 }
 
 /* readonly attribute unsigned long result; */
-NS_IMETHODIMP nsWebBrowserPersist::GetResult(PRUint32 *aResult)
+NS_IMETHODIMP nsWebBrowserPersist::GetResult(nsresult *aResult)
 {
     NS_ENSURE_ARG_POINTER(aResult);
     *aResult = mPersistResult;
     return NS_OK;
 }
 
 /* attribute nsIWebBrowserPersistProgress progressListener; */
 NS_IMETHODIMP nsWebBrowserPersist::GetProgressListener(
@@ -987,18 +987,18 @@ NS_IMETHODIMP nsWebBrowserPersist::OnSta
         case NS_NET_STATUS_RESOLVED_HOST:
         case NS_NET_STATUS_BEGIN_FTP_TRANSACTION:
         case NS_NET_STATUS_END_FTP_TRANSACTION:
         case NS_NET_STATUS_CONNECTING_TO:
         case NS_NET_STATUS_CONNECTED_TO:
         case NS_NET_STATUS_SENDING_TO:
         case NS_NET_STATUS_RECEIVING_FROM:
         case NS_NET_STATUS_WAITING_FOR:
-        case nsITransport::STATUS_READING:
-        case nsITransport::STATUS_WRITING:
+        case NS_NET_STATUS_READING:
+        case NS_NET_STATUS_WRITING:
             break;
 
         default:
             // Pass other notifications (for legitimate errors) along.
             mProgressListener->OnStatusChange(nullptr, request, status, statusArg);
             break;
         }
 
--- a/embedding/components/webbrowserpersist/src/nsWebBrowserPersist.h
+++ b/embedding/components/webbrowserpersist/src/nsWebBrowserPersist.h
@@ -198,17 +198,17 @@ private:
     bool                      mFirstAndOnlyUse;
     bool                      mCancel;
     bool                      mJustStartedLoading;
     bool                      mCompleted;
     bool                      mStartSaving;
     bool                      mReplaceExisting;
     bool                      mSerializingOutput;
     PRUint32                  mPersistFlags;
-    PRUint32                  mPersistResult;
+    nsresult                  mPersistResult;
     PRInt64                   mTotalCurrentProgress;
     PRInt64                   mTotalMaxProgress;
     PRInt16                   mWrapColumn;
     PRUint32                  mEncodingFlags;
     nsString                  mContentType;
 };
 
 // Helper class does node fixup during persistence
--- a/extensions/cookie/nsPermissionManager.cpp
+++ b/extensions/cookie/nsPermissionManager.cpp
@@ -1170,17 +1170,17 @@ nsPermissionManager::Import()
     // Split the line at tabs
     ParseString(buffer, '\t', lineArray);
     
     if (lineArray[0].EqualsLiteral(kMatchTypeHost) &&
         lineArray.Length() == 4) {
       
       nsresult error;
       PRUint32 permission = lineArray[2].ToInteger(&error);
-      if (error)
+      if (NS_FAILED(error))
         continue;
 
       // hosts might be encoded in UTF8; switch them to ACE to be consistent
       if (!IsASCII(lineArray[3])) {
         rv = NormalizeToACE(lineArray[3]);
         if (NS_FAILED(rv))
           continue;
       }
--- a/gfx/2d/2D.h
+++ b/gfx/2d/2D.h
@@ -1,46 +1,30 @@
 /* -*- Mode: C++; tab-width: 20; 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/. */
 
 #ifndef _MOZILLA_GFX_2D_H
 #define _MOZILLA_GFX_2D_H
 
+#include "Types.h"
 #include "Point.h"
 #include "Rect.h"
 #include "Matrix.h"
 #include "UserData.h"
 // This RefPtr class isn't ideal for usage in Azure, as it doesn't allow T**
 // outparams using the &-operator. But it will have to do as there's no easy
 // solution.
 #include "mozilla/RefPtr.h"
 
 #ifdef MOZ_ENABLE_FREETYPE
 #include <string>
 #endif
 
-/**
- * Use C++11 nullptr if available; otherwise use a C++ typesafe template; and
- * for C, fall back to longs.  See bugs 547964 and 626472.
- * Copy and paste job from nscore.h, see bug 781943
- */
-#if defined(MOZ_GFX) && !defined(HAVE_NULLPTR)
-#ifndef __cplusplus
-# define nullptr ((void*)0)
-#elif defined(__GNUC__)
-# define nullptr __null
-#elif defined(_WIN64)
-# define nullptr 0LL
-#else
-# define nullptr 0L
-#endif
-#endif /* defined(MOZ_GFX) && !defined(HAVE_NULLPTR) */
-
 struct _cairo_surface;
 typedef _cairo_surface cairo_surface_t;
 
 struct _cairo_scaled_font;
 typedef _cairo_scaled_font cairo_scaled_font_t;
 
 struct ID3D10Device1;
 struct ID3D10Texture2D;
--- a/gfx/2d/Blur.cpp
+++ b/gfx/2d/Blur.cpp
@@ -325,17 +325,17 @@ RoundUpToMultipleOf4(int32_t aVal)
 
 AlphaBoxBlur::AlphaBoxBlur(const Rect& aRect,
                            const IntSize& aSpreadRadius,
                            const IntSize& aBlurRadius,
                            const Rect* aDirtyRect,
                            const Rect* aSkipRect)
  : mSpreadRadius(aSpreadRadius),
    mBlurRadius(aBlurRadius),
-   mData(NULL)
+   mData(nullptr)
 {
   Rect rect(aRect);
   rect.Inflate(Size(aBlurRadius + aSpreadRadius));
   rect.RoundOut();
 
   if (aDirtyRect) {
     // If we get passed a dirty rect from layout, we can minimize the
     // shadow size and make painting faster.
@@ -419,17 +419,17 @@ AlphaBoxBlur::GetRect()
 
 Rect*
 AlphaBoxBlur::GetDirtyRect()
 {
   if (mHasDirtyRect) {
     return &mDirtyRect;
   }
 
-  return NULL;
+  return nullptr;
 }
 
 void
 AlphaBoxBlur::Blur()
 {
   if (!mData) {
     return;
   }
--- a/gfx/2d/Blur.h
+++ b/gfx/2d/Blur.h
@@ -40,21 +40,21 @@ public:
    * @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.
+   *   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.
+   *   speed reasons. It is safe to pass nullptr here.
    */
   AlphaBoxBlur(const Rect& aRect,
                const IntSize& aSpreadRadius,
                const IntSize& aBlurRadius,
                const Rect* aDirtyRect,
                const Rect* aSkipRect);
 
   ~AlphaBoxBlur();
@@ -79,17 +79,17 @@ public:
   int32_t GetStride();
 
   /**
    * Returns the device-space rectangle the 8-bit alpha surface covers.
    */
   IntRect GetRect();
 
   /**
-   * Return a pointer to a dirty rect, as passed in to the constructor, or NULL
+   * Return a pointer to a dirty rect, as passed in to the constructor, or nullptr
    * if none was passed in.
    */
   Rect* GetDirtyRect();
 
   /**
    * Perform the blur in-place on the surface backed by the pointer returned by
    * GetData().
    */
--- a/gfx/2d/DrawTargetCG.cpp
+++ b/gfx/2d/DrawTargetCG.cpp
@@ -72,17 +72,17 @@ CGBlendMode ToBlendMode(CompositionOp op
     default:
       mode = kCGBlendModeNormal;
   }
   return mode;
 }
 
 
 
-DrawTargetCG::DrawTargetCG() : mSnapshot(NULL)
+DrawTargetCG::DrawTargetCG() : mSnapshot(nullptr)
 {
 }
 
 DrawTargetCG::~DrawTargetCG()
 {
   MarkChanged();
 
   // We need to conditionally release these because Init can fail without initializing these.
@@ -123,30 +123,30 @@ TemporaryRef<DrawTarget>
 DrawTargetCG::CreateSimilarDrawTarget(const IntSize &aSize, SurfaceFormat aFormat) const
 {
   // XXX: in thebes we use CGLayers to do this kind of thing. It probably makes sense
   // to add that in somehow, but at a higher level
   RefPtr<DrawTargetCG> newTarget = new DrawTargetCG();
   if (newTarget->Init(GetType(), aSize, aFormat)) {
     return newTarget;
   } else {
-    return NULL;
+    return nullptr;
   }
 }
 
 TemporaryRef<SourceSurface>
 DrawTargetCG::CreateSourceSurfaceFromData(unsigned char *aData,
                                            const IntSize &aSize,
                                            int32_t aStride,
                                            SurfaceFormat aFormat) const
 {
   RefPtr<SourceSurfaceCG> newSurf = new SourceSurfaceCG();
 
  if (!newSurf->InitFromData(aData, aSize, aStride, aFormat)) {
-    return NULL;
+    return nullptr;
   }
 
   return newSurf;
 }
 
 static CGImageRef
 GetImageFromSourceSurface(SourceSurface *aSurface)
 {
@@ -157,38 +157,38 @@ GetImageFromSourceSurface(SourceSurface 
   else if (aSurface->GetType() == SURFACE_DATA)
     return static_cast<DataSourceSurfaceCG*>(aSurface)->GetImage();
   abort();
 }
 
 TemporaryRef<SourceSurface>
 DrawTargetCG::OptimizeSourceSurface(SourceSurface *aSurface) const
 {
-  return NULL;
+  return nullptr;
 }
 
 class UnboundnessFixer
 {
     CGRect mClipBounds;
     CGLayerRef mLayer;
     CGContextRef mCg;
   public:
-    UnboundnessFixer() : mCg(NULL) {}
+    UnboundnessFixer() : mCg(nullptr) {}
 
     CGContextRef Check(CGContextRef baseCg, CompositionOp blend)
     {
       if (!IsOperatorBoundByMask(blend)) {
         mClipBounds = CGContextGetClipBoundingBox(baseCg);
         // TransparencyLayers aren't blended using the blend mode so
         // we are forced to use CGLayers
 
         //XXX: The size here is in default user space units, of the layer relative to the graphics context.
         // is the clip bounds still correct if, for example, we have a scale applied to the context?
-        mLayer = CGLayerCreateWithContext(baseCg, mClipBounds.size, NULL);
-        //XXX: if the size is 0x0 we get a NULL CGContext back from GetContext
+        mLayer = CGLayerCreateWithContext(baseCg, mClipBounds.size, nullptr);
+        //XXX: if the size is 0x0 we get a nullptr CGContext back from GetContext
         mCg = CGLayerGetContext(mLayer);
         // CGContext's default to have the origin at the bottom left
         // so flip it to the top left and adjust for the origin
         // of the layer
         CGContextTranslateCTM(mCg, -mClipBounds.origin.x, mClipBounds.origin.y + mClipBounds.size.height);
         CGContextScaleCTM(mCg, 1, -1);
 
         return mCg;
@@ -214,17 +214,17 @@ DrawTargetCG::DrawSurface(SourceSurface 
                            const Rect &aDest,
                            const Rect &aSource,
                            const DrawSurfaceOptions &aSurfOptions,
                            const DrawOptions &aDrawOptions)
 {
   MarkChanged();
 
   CGImageRef image;
-  CGImageRef subimage = NULL;
+  CGImageRef subimage = nullptr;
   CGContextSaveGState(mCg);
 
   CGContextSetBlendMode(mCg, ToBlendMode(aDrawOptions.mCompositionOp));
   UnboundnessFixer fixer;
   CGContextRef cg = fixer.Check(mCg, aDrawOptions.mCompositionOp);
   CGContextSetAlpha(cg, aDrawOptions.mAlpha);
 
   CGContextConcatCTM(cg, GfxMatrixToCGAffineTransform(mTransform));
@@ -424,17 +424,17 @@ SetFillFromPattern(CGContextRef cg, CGCo
     const Color& color = static_cast<const ColorPattern&>(aPattern).mColor;
     //XXX: we should cache colors
     CGColorRef cgcolor = ColorToCGColor(aColorSpace, color);
     CGContextSetFillColorWithColor(cg, cgcolor);
     CGColorRelease(cgcolor);
   } else if (aPattern.GetType() == PATTERN_SURFACE) {
 
     CGColorSpaceRef patternSpace;
-    patternSpace = CGColorSpaceCreatePattern (NULL);
+    patternSpace = CGColorSpaceCreatePattern (nullptr);
     CGContextSetFillColorSpace(cg, patternSpace);
     CGColorSpaceRelease(patternSpace);
 
     CGPatternRef pattern = CreateCGPattern(aPattern, CGContextGetCTM(cg));
     CGFloat alpha = 1.;
     CGContextSetFillPattern(cg, pattern, &alpha);
     CGPatternRelease(pattern);
   }
@@ -447,17 +447,17 @@ SetStrokeFromPattern(CGContextRef cg, CG
   if (aPattern.GetType() == PATTERN_COLOR) {
     const Color& color = static_cast<const ColorPattern&>(aPattern).mColor;
     //XXX: we should cache colors
     CGColorRef cgcolor = ColorToCGColor(aColorSpace, color);
     CGContextSetStrokeColorWithColor(cg, cgcolor);
     CGColorRelease(cgcolor);
   } else if (aPattern.GetType() == PATTERN_SURFACE) {
     CGColorSpaceRef patternSpace;
-    patternSpace = CGColorSpaceCreatePattern (NULL);
+    patternSpace = CGColorSpaceCreatePattern (nullptr);
     CGContextSetStrokeColorSpace(cg, patternSpace);
     CGColorSpaceRelease(patternSpace);
 
     CGPatternRef pattern = CreateCGPattern(aPattern, CGContextGetCTM(cg));
     CGFloat alpha = 1.;
     CGContextSetStrokePattern(cg, pattern, &alpha);
     CGPatternRelease(pattern);
   }
@@ -751,17 +751,17 @@ CGContextResetClip(CGContextRef);
 void
 DrawTargetCG::CopySurface(SourceSurface *aSurface,
                           const IntRect& aSourceRect,
                           const IntPoint &aDestination)
 {
   MarkChanged();
 
   CGImageRef image;
-  CGImageRef subimage = NULL;
+  CGImageRef subimage = nullptr;
   if (aSurface->GetType() == SURFACE_COREGRAPHICS_IMAGE) {
     image = GetImageFromSourceSurface(aSurface);
     /* we have two options here:
      *  - create a subimage -- this is slower
      *  - fancy things with clip and different dest rects */
     {
       subimage = CGImageCreateWithImageInRect(image, IntRectToCGRect(aSourceRect));
       image = subimage;
@@ -825,45 +825,45 @@ DrawTargetCG::Init(BackendType aType,
                    SurfaceFormat aFormat)
 {
   // XXX: we should come up with some consistent semantics for dealing
   // with zero area drawtargets
   if (aSize.width <= 0 || aSize.height <= 0 ||
       // 32767 is the maximum size supported by cairo
       // we clamp to that to make it easier to interoperate
       aSize.width > 32767 || aSize.height > 32767) {
-    mColorSpace = NULL;
-    mCg = NULL;
-    mData = NULL;
+    mColorSpace = nullptr;
+    mCg = nullptr;
+    mData = nullptr;
     return false;
   }
 
   //XXX: handle SurfaceFormat
 
   //XXX: we'd be better off reusing the Colorspace across draw targets
   mColorSpace = CGColorSpaceCreateDeviceRGB();
 
-  if (aData == NULL && aType != BACKEND_COREGRAPHICS_ACCELERATED) {
+  if (aData == nullptr && aType != BACKEND_COREGRAPHICS_ACCELERATED) {
     // XXX: Currently, Init implicitly clears, that can often be a waste of time
     mData = calloc(aSize.height * aStride, 1);
     aData = static_cast<unsigned char*>(mData);  
   } else {
-    // mData == NULL means DrawTargetCG doesn't own the image data and will not
+    // mData == nullptr means DrawTargetCG doesn't own the image data and will not
     // delete it in the destructor
-    mData = NULL;
+    mData = nullptr;
   }
 
   mSize = aSize;
 
   if (aType == BACKEND_COREGRAPHICS_ACCELERATED) {
     RefPtr<MacIOSurface> ioSurface = MacIOSurface::CreateIOSurface(aSize.width, aSize.height);
     mCg = ioSurface->CreateIOSurfaceContext();
     // If we don't have the symbol for 'CreateIOSurfaceContext' mCg will be null
     // and we will fallback to software below
-    mData = NULL;
+    mData = nullptr;
   }
 
   if (!mCg || aType == BACKEND_COREGRAPHICS) {
     int bitsPerComponent = 8;
 
     CGBitmapInfo bitinfo;
     bitinfo = kCGBitmapByteOrder32Host | kCGImageAlphaPremultipliedFirst;
 
@@ -911,32 +911,32 @@ DrawTargetCG::Flush()
 }
 
 bool
 DrawTargetCG::Init(CGContextRef cgContext, const IntSize &aSize)
 {
   // XXX: we should come up with some consistent semantics for dealing
   // with zero area drawtargets
   if (aSize.width == 0 || aSize.height == 0) {
-    mColorSpace = NULL;
-    mCg = NULL;
-    mData = NULL;
+    mColorSpace = nullptr;
+    mCg = nullptr;
+    mData = nullptr;
     return false;
   }
 
   //XXX: handle SurfaceFormat
 
   //XXX: we'd be better off reusing the Colorspace across draw targets
   mColorSpace = CGColorSpaceCreateDeviceRGB();
 
   mSize = aSize;
 
   mCg = cgContext;
 
-  mData = NULL;
+  mData = nullptr;
 
   assert(mCg);
   // CGContext's default to have the origin at the bottom left
   // so flip it to the top left
   CGContextTranslateCTM(mCg, 0, mSize.height);
   CGContextScaleCTM(mCg, 1, -1);
 
   //XXX: set correct format
@@ -945,35 +945,35 @@ DrawTargetCG::Init(CGContextRef cgContex
   return true;
 }
 
 bool
 DrawTargetCG::Init(BackendType aType, const IntSize &aSize, SurfaceFormat &aFormat)
 {
   int stride = aSize.width*4;
   
-  // Calling Init with aData == NULL will allocate.
-  return Init(aType, NULL, aSize, stride, aFormat);
+  // Calling Init with aData == nullptr will allocate.
+  return Init(aType, nullptr, aSize, stride, aFormat);
 }
 
 TemporaryRef<PathBuilder>
 DrawTargetCG::CreatePathBuilder(FillRule aFillRule) const
 {
   RefPtr<PathBuilderCG> pb = new PathBuilderCG(aFillRule);
   return pb;
 }
 
 void*
 DrawTargetCG::GetNativeSurface(NativeSurfaceType aType)
 {
   if (aType == NATIVE_SURFACE_CGCONTEXT && GetContextType(mCg) == CG_CONTEXT_TYPE_BITMAP ||
       aType == NATIVE_SURFACE_CGCONTEXT_ACCELERATED && GetContextType(mCg) == CG_CONTEXT_TYPE_IOSURFACE) {
     return mCg;
   } else {
-    return NULL;
+    return nullptr;
   }
 }
 
 void
 DrawTargetCG::Mask(const Pattern &aSource,
                    const Pattern &aMask,
                    const DrawOptions &aDrawOptions)
 {
@@ -1061,16 +1061,16 @@ DrawTargetCG::PopClip()
 void
 DrawTargetCG::MarkChanged()
 {
   if (mSnapshot) {
     if (mSnapshot->refCount() > 1) {
       // We only need to worry about snapshots that someone else knows about
       mSnapshot->DrawTargetWillChange();
     }
-    mSnapshot = NULL;
+    mSnapshot = nullptr;
   }
 }
 
 
 
 }
 }
--- a/gfx/2d/DrawTargetCG.h
+++ b/gfx/2d/DrawTargetCG.h
@@ -119,17 +119,17 @@ public:
   virtual void Fill(const Path *, const Pattern &, const DrawOptions &);
   virtual void FillGlyphs(ScaledFont *, const GlyphBuffer&, const Pattern &, const DrawOptions &, const GlyphRenderingOptions *);
   virtual void Mask(const Pattern &aSource,
                     const Pattern &aMask,
                     const DrawOptions &aOptions = DrawOptions());
   virtual void PushClip(const Path *);
   virtual void PushClipRect(const Rect &aRect);
   virtual void PopClip();
-  virtual TemporaryRef<SourceSurface> CreateSourceSurfaceFromNativeSurface(const NativeSurface&) const { return NULL;}
+  virtual TemporaryRef<SourceSurface> CreateSourceSurfaceFromNativeSurface(const NativeSurface&) const { return nullptr;}
   virtual TemporaryRef<DrawTarget> CreateSimilarDrawTarget(const IntSize &, SurfaceFormat) const;
   virtual TemporaryRef<PathBuilder> CreatePathBuilder(FillRule) const;
   virtual TemporaryRef<GradientStops> CreateGradientStops(GradientStop *, uint32_t,
                                                           ExtendMode aExtendMode = EXTEND_CLAMP) const;
 
   virtual void *GetNativeSurface(NativeSurfaceType);
 
   virtual IntSize GetSize() { return mSize; }
@@ -150,17 +150,17 @@ private:
   IntSize mSize;
   CGColorSpaceRef mColorSpace;
   CGContextRef mCg;
 
   GLuint mIOSurfaceTexture;
 
   /**
    * A pointer to the image buffer if the buffer is owned by this class (set to
-   * NULL otherwise).
+   * nullptr otherwise).
    * The data is not considered owned by DrawTargetCG if the DrawTarget was 
    * created for a pre-existing buffer or if the buffer's lifetime is managed
    * by CoreGraphics.
    * Data owned by DrawTargetCG will be deallocated in the destructor. 
    */
   void *mData;
 
   RefPtr<SourceSurfaceCGContext> mSnapshot;
--- a/gfx/2d/DrawTargetCairo.cpp
+++ b/gfx/2d/DrawTargetCairo.cpp
@@ -159,17 +159,17 @@ GetCairoSurfaceForSourceSurface(SourceSu
                                         data->Stride());
   cairo_surface_set_user_data(surf,
  				                      &surfaceDataKey,
  				                      data.forget().drop(),
  				                      ReleaseData);
   return surf;
 }
 
-// Never returns NULL. As such, you must always pass in Cairo-compatible
+// Never returns nullptr. As such, you must always pass in Cairo-compatible
 // patterns, most notably gradients with a GradientStopCairo.
 // The pattern returned must have cairo_pattern_destroy() called on it by the
 // caller.
 // As the cairo_pattern_t returned may depend on the Pattern passed in, the
 // lifetime of the cairo_pattern_t returned must not exceed the lifetime of the
 // Pattern passed in.
 static cairo_pattern_t*
 GfxPatternToCairoPattern(const Pattern& aPattern, Float aAlpha)
@@ -270,17 +270,17 @@ NeedIntermediateSurface(const Pattern& a
 
   if (aOptions.mAlpha == 1.0)
     return false;
 
   return true;
 }
 
 DrawTargetCairo::DrawTargetCairo()
-  : mContext(NULL)
+  : mContext(nullptr)
 {
 }
 
 DrawTargetCairo::~DrawTargetCairo()
 {
   MarkSnapshotsIndependent();
   if (mPathObserver) {
     mPathObserver->ForgetDrawTarget();
@@ -313,17 +313,17 @@ DrawTargetCairo::Snapshot()
 void
 DrawTargetCairo::Flush()
 {
   cairo_surface_t* surf = cairo_get_target(mContext);
   cairo_surface_flush(surf);
 }
 
 void
-DrawTargetCairo::PrepareForDrawing(cairo_t* aContext, const Path* aPath /* = NULL */)
+DrawTargetCairo::PrepareForDrawing(cairo_t* aContext, const Path* aPath /* = nullptr */)
 {
   WillChange(aPath);
 }
 
 void
 DrawTargetCairo::DrawSurface(SourceSurface *aSurface,
                              const Rect &aDest,
                              const Rect &aSource,
@@ -386,17 +386,17 @@ DrawTargetCairo::DrawSurfaceWithShadow(S
   WillChange();
 
   Float width = aSurface->GetSize().width;
   Float height = aSurface->GetSize().height;
   Rect extents(0, 0, width, height);
 
   AlphaBoxBlur blur(extents, IntSize(0, 0),
                     AlphaBoxBlur::CalculateBlurRadius(Point(aSigma, aSigma)),
-                    NULL, NULL);
+                    nullptr, nullptr);
   if (!blur.GetData()) {
     return;
   }
 
   IntSize blursize = blur.GetSize();
   cairo_surface_t* blursurf = cairo_image_surface_create_for_data(blur.GetData(),
                                                                   CAIRO_FORMAT_A8,
                                                                   blursize.width,
@@ -781,33 +781,33 @@ DrawTargetCairo::CreateSourceSurfaceFrom
     cairo_surface_t* surf = static_cast<cairo_surface_t*>(aSurface.mSurface);
     if (GetCairoSurfaceSize(surf, size)) {
       RefPtr<SourceSurfaceCairo> source =
         new SourceSurfaceCairo(surf, size, aSurface.mFormat);
       return source;
     }
   }
 
-  return NULL;
+  return nullptr;
 }
 
 TemporaryRef<DrawTarget>
 DrawTargetCairo::CreateSimilarDrawTarget(const IntSize &aSize, SurfaceFormat aFormat) const
 {
   cairo_surface_t* similar = cairo_surface_create_similar(cairo_get_target(mContext),
                                                           GfxFormatToCairoContent(aFormat),
                                                           aSize.width, aSize.height);
 
   if (!cairo_surface_status(similar)) {
     RefPtr<DrawTargetCairo> target = new DrawTargetCairo();
     target->Init(similar, aSize);
     return target;
   }
 
-  return NULL;
+  return nullptr;
 }
 
 bool
 DrawTargetCairo::Init(cairo_surface_t* aSurface, const IntSize& aSize)
 {
   mContext = cairo_create(aSurface);
   mSurface = aSurface;
   cairo_surface_reference(mSurface);
@@ -819,17 +819,17 @@ DrawTargetCairo::Init(cairo_surface_t* a
 
 void *
 DrawTargetCairo::GetNativeSurface(NativeSurfaceType aType)
 {
   if (aType == NATIVE_SURFACE_CAIRO_SURFACE) {
     return cairo_get_target(mContext);
   }
 
-  return NULL;
+  return nullptr;
 }
 
 void
 DrawTargetCairo::MarkSnapshotsIndependent()
 {
   // Make a copy of the vector, since MarkIndependent implicitly modifies mSnapshots.
   std::vector<SourceSurfaceCairo*> snapshots = mSnapshots;
   for (std::vector<SourceSurfaceCairo*>::iterator iter = snapshots.begin();
@@ -852,31 +852,31 @@ DrawTargetCairo::RemoveSnapshot(SourceSu
                                                               mSnapshots.end(),
                                                               aSnapshot);
   if (iter != mSnapshots.end()) {
     mSnapshots.erase(iter);
   }
 }
 
 void
-DrawTargetCairo::WillChange(const Path* aPath /* = NULL */)
+DrawTargetCairo::WillChange(const Path* aPath /* = nullptr */)
 {
   if (!mSnapshots.empty()) {
     for (std::vector<SourceSurfaceCairo*>::iterator iter = mSnapshots.begin();
          iter != mSnapshots.end(); ++iter) {
       (*iter)->DrawTargetWillChange();
     }
     // All snapshots will now have copied data.
     mSnapshots.clear();
   }
 
   if (mPathObserver &&
       (!aPath || !mPathObserver->ContainsPath(aPath))) {
     mPathObserver->PathWillChange();
-    mPathObserver = NULL;
+    mPathObserver = nullptr;
   }
 }
 
 void
 DrawTargetCairo::SetPathObserver(CairoPathContext* aPathObserver)
 {
   if (mPathObserver && mPathObserver != aPathObserver) {
     mPathObserver->PathWillChange();
--- a/gfx/2d/DrawTargetCairo.h
+++ b/gfx/2d/DrawTargetCairo.h
@@ -90,17 +90,17 @@ public:
   virtual void Fill(const Path *aPath,
                     const Pattern &aPattern,
                     const DrawOptions &aOptions = DrawOptions());
 
   virtual void FillGlyphs(ScaledFont *aFont,
                           const GlyphBuffer &aBuffer,
                           const Pattern &aPattern,
                           const DrawOptions &aOptions,
-                          const GlyphRenderingOptions *aRenderingOptions = NULL);
+                          const GlyphRenderingOptions *aRenderingOptions = nullptr);
   virtual void Mask(const Pattern &aSource,
                     const Pattern &aMask,
                     const DrawOptions &aOptions = DrawOptions());
 
   virtual void PushClip(const Path *aPath);
   virtual void PushClipRect(const Rect &aRect);
   virtual void PopClip();
 
@@ -127,34 +127,34 @@ public:
 
   void SetPathObserver(CairoPathContext* aPathObserver);
 
   virtual void SetTransform(const Matrix& aTransform);
 
   // Call to set up aContext for drawing (with the current transform, etc).
   // Pass the path you're going to be using if you have one.
   // Implicitly calls WillChange(aPath).
-  void PrepareForDrawing(cairo_t* aContext, const Path* aPath = NULL);
+  void PrepareForDrawing(cairo_t* aContext, const Path* aPath = nullptr);
 
 private: // methods
   enum DrawPatternType { DRAW_FILL, DRAW_STROKE };
   void DrawPattern(const Pattern& aPattern,
                    const StrokeOptions& aStrokeOptions,
                    const DrawOptions& aOptions,
                    DrawPatternType aDrawType);
 
   // Copy-on-write support for snapshot surfaces.
   friend class SourceSurfaceCairo;
   void AppendSnapshot(SourceSurfaceCairo* aSnapshot);
   void RemoveSnapshot(SourceSurfaceCairo* aSnapshot);
 
   // Call before you make any changes to the backing surface with which this
   // context is associated. Pass the path you're going to be using if you have
   // one.
-  void WillChange(const Path* aPath = NULL);
+  void WillChange(const Path* aPath = nullptr);
 
   // Call if there is any reason to disassociate all snapshots from this draw
   // target; for example, because we're going to be destroyed.
   void MarkSnapshotsIndependent();
 
   // If the current operator is "source" then clear the destination before we
   // draw into it, to simulate the effect of an unbounded source operator.
   void ClearSurfaceForUnboundedSource(const CompositionOp &aOperator);
--- a/gfx/2d/DrawTargetD2D.cpp
+++ b/gfx/2d/DrawTargetD2D.cpp
@@ -74,17 +74,17 @@ public:
     RefPtr<ID3D10Texture2D> tmpTexture;
     IntSize size = mDT->mSize;
     SurfaceFormat format = mDT->mFormat;
 
     CD3D10_TEXTURE2D_DESC desc(DXGIFormat(format), size.width, size.height,
                                1, 1);
     desc.BindFlags = D3D10_BIND_RENDER_TARGET | D3D10_BIND_SHADER_RESOURCE;
 
-    HRESULT hr = mDT->mDevice->CreateTexture2D(&desc, NULL, byRef(tmpTexture));
+    HRESULT hr = mDT->mDevice->CreateTexture2D(&desc, nullptr, byRef(tmpTexture));
     if (FAILED(hr)) {
       gfxWarning() << "Failed to create temporary texture to hold surface data.";
     }
     mDT->mDevice->CopyResource(tmpTexture, mDT->mTexture);
 
     D2D1_BITMAP_PROPERTIES props =
       D2D1::BitmapProperties(D2D1::PixelFormat(DXGIFormat(format),
                              AlphaMode(format)));
@@ -123,17 +123,17 @@ public:
       D2D1::RectF(0, 0, float(mDT->mSize.width), float(mDT->mSize.height)),
       byRef(rectGeom));
 
     RefPtr<ID2D1PathGeometry> invClippedArea;
     factory()->CreatePathGeometry(byRef(invClippedArea));
     RefPtr<ID2D1GeometrySink> sink;
     invClippedArea->Open(byRef(sink));
 
-    rectGeom->CombineWithGeometry(mClippedArea, D2D1_COMBINE_MODE_EXCLUDE, NULL, sink);
+    rectGeom->CombineWithGeometry(mClippedArea, D2D1_COMBINE_MODE_EXCLUDE, nullptr, sink);
     sink->Close();
 
     RefPtr<ID2D1BitmapBrush> brush;
     rt->CreateBitmapBrush(mOldSurfBitmap, D2D1::BitmapBrushProperties(), D2D1::BrushProperties(), byRef(brush));                   
 
     rt->FillGeometry(invClippedArea, brush);
   }
 
@@ -146,17 +146,17 @@ private:
   RefPtr<ID2D1Bitmap> mOldSurfBitmap;
   // This contains the area drawing is clipped to.
   RefPtr<ID2D1Geometry> mClippedArea;
 };
 
 DrawTargetD2D::DrawTargetD2D()
   : mCurrentCachedLayer(0)
   , mClipsArePushed(false)
-  , mPrivateData(NULL)
+  , mPrivateData(nullptr)
 {
 }
 
 DrawTargetD2D::~DrawTargetD2D()
 {
   if (mRT) {  
     PopAllClips();
 
@@ -178,17 +178,17 @@ DrawTargetD2D::~DrawTargetD2D()
     // mSnapshot can be treated as independent of this DrawTarget since we know
     // this DrawTarget won't change again.
     deathGrip->MarkIndependent();
     // mSnapshot will be cleared now.
   }
 
   for (int i = 0; i < kLayerCacheSize; i++) {
     if (mCachedLayers[i]) {
-      mCachedLayers[i] = NULL;
+      mCachedLayers[i] = nullptr;
       mVRAMUsageDT -= GetByteSize();
     }
   }
 
   // Targets depending on us can break that dependency, since we're obviously not going to
   // be modified in the future.
   for (TargetSet::iterator iter = mDependentTargets.begin();
        iter != mDependentTargets.end(); iter++) {
@@ -315,17 +315,17 @@ DrawTargetD2D::DrawSurface(SourceSurface
 void
 DrawTargetD2D::DrawSurfaceWithShadow(SourceSurface *aSurface,
                                      const Point &aDest,
                                      const Color &aColor,
                                      const Point &aOffset,
                                      Float aSigma,
                                      CompositionOp aOperator)
 {
-  RefPtr<ID3D10ShaderResourceView> srView = NULL;
+  RefPtr<ID3D10ShaderResourceView> srView = nullptr;
   if (aSurface->GetType() != SURFACE_D2D1_DRAWTARGET) {
     return;
   }
 
   // XXX - This function is way too long, it should be split up soon to make
   // it more graspable!
 
   Flush();
@@ -337,17 +337,17 @@ DrawTargetD2D::DrawSurfaceWithShadow(Sou
   }
 
   srView = static_cast<SourceSurfaceD2DTarget*>(aSurface)->GetSRView();
 
   EnsureViews();
 
   if (!mTempRTView) {
     // This view is only needed in this path.
-    HRESULT hr = mDevice->CreateRenderTargetView(mTempTexture, NULL, byRef(mTempRTView));
+    HRESULT hr = mDevice->CreateRenderTargetView(mTempTexture, nullptr, byRef(mTempRTView));
 
     if (FAILED(hr)) {
       gfxWarning() << "Failure to create RenderTargetView. Code: " << hr;
       return;
     }
   }
 
 
@@ -355,17 +355,17 @@ DrawTargetD2D::DrawSurfaceWithShadow(Sou
   RefPtr<ID3D10Texture2D> destTexture;
   HRESULT hr;
 
   RefPtr<ID3D10Texture2D> maskTexture;
   RefPtr<ID3D10ShaderResourceView> maskSRView;
   if (mPushedClips.size()) {
     EnsureClipMaskTexture();
 
-    mDevice->CreateShaderResourceView(mCurrentClipMaskTexture, NULL, byRef(maskSRView));
+    mDevice->CreateShaderResourceView(mCurrentClipMaskTexture, nullptr, byRef(maskSRView));
   }
 
   IntSize srcSurfSize;
   ID3D10RenderTargetView *rtViews;
   D3D10_VIEWPORT viewport;
 
   UINT stride = sizeof(Vertex);
   UINT offset = 0;
@@ -397,17 +397,17 @@ DrawTargetD2D::DrawSurfaceWithShadow(Sou
     
     CD3D10_TEXTURE2D_DESC desc(DXGI_FORMAT_B8G8R8A8_UNORM,
                                aSurface->GetSize().width,
                                aSurface->GetSize().height);
     desc.BindFlags = D3D10_BIND_RENDER_TARGET | D3D10_BIND_SHADER_RESOURCE;
     desc.MiscFlags = D3D10_RESOURCE_MISC_GENERATE_MIPS;
 
     RefPtr<ID3D10Texture2D> mipTexture;
-    hr = mDevice->CreateTexture2D(&desc, NULL, byRef(mipTexture));
+    hr = mDevice->CreateTexture2D(&desc, nullptr, byRef(mipTexture));
 
     if (FAILED(hr)) {
       gfxWarning() << "Failure to create temporary texture. Size: " <<
         aSurface->GetSize() << " Code: " << hr;
       return;
     }
 
     IntSize dsSize = IntSize(int32_t(aSurface->GetSize().width * (1.7f / aSigma)),
@@ -425,59 +425,59 @@ DrawTargetD2D::DrawSurfaceWithShadow(Sou
     correctedOffset.x *= dsFactorX;
     correctedOffset.y *= dsFactorY;
 
     desc = CD3D10_TEXTURE2D_DESC(DXGI_FORMAT_B8G8R8A8_UNORM,
                                  dsSize.width,
                                  dsSize.height, 1, 1);
     desc.BindFlags = D3D10_BIND_RENDER_TARGET | D3D10_BIND_SHADER_RESOURCE;
     RefPtr<ID3D10Texture2D> tmpDSTexture;
-    hr = mDevice->CreateTexture2D(&desc, NULL, byRef(tmpDSTexture));
+    hr = mDevice->CreateTexture2D(&desc, nullptr, byRef(tmpDSTexture));
 
     if (FAILED(hr)) {
       gfxWarning() << "Failure to create temporary texture. Size: " << dsSize << " Code: " << hr;
       return;
     }
 
     D3D10_BOX box;
     box.left = box.top = box.front = 0;
     box.back = 1;
     box.right = aSurface->GetSize().width;
     box.bottom = aSurface->GetSize().height;
     mDevice->CopySubresourceRegion(mipTexture, 0, 0, 0, 0, static_cast<SourceSurfaceD2DTarget*>(aSurface)->mTexture, 0, &box);
 
-    mDevice->CreateShaderResourceView(mipTexture, NULL,  byRef(srView));
+    mDevice->CreateShaderResourceView(mipTexture, nullptr,  byRef(srView));
     mDevice->GenerateMips(srView);
 
     RefPtr<ID3D10RenderTargetView> dsRTView;
     RefPtr<ID3D10ShaderResourceView> dsSRView;
-    mDevice->CreateRenderTargetView(tmpDSTexture, NULL,  byRef(dsRTView));
-    mDevice->CreateShaderResourceView(tmpDSTexture, NULL,  byRef(dsSRView));
+    mDevice->CreateRenderTargetView(tmpDSTexture, nullptr,  byRef(dsRTView));
+    mDevice->CreateShaderResourceView(tmpDSTexture, nullptr,  byRef(dsSRView));
 
     // We're not guaranteed the texture we created will be empty, we've
     // seen old content at least on NVidia drivers.
     float color[4] = { 0, 0, 0, 0 };
     mDevice->ClearRenderTargetView(dsRTView, color);
 
     rtViews = dsRTView;
-    mDevice->OMSetRenderTargets(1, &rtViews, NULL);
+    mDevice->OMSetRenderTargets(1, &rtViews, nullptr);
 
     viewport.MaxDepth = 1;
     viewport.MinDepth = 0;
     viewport.Height = dsSize.height;
     viewport.Width = dsSize.width;
     viewport.TopLeftX = 0;
     viewport.TopLeftY = 0;
 
     mDevice->RSSetViewports(1, &viewport);
     mPrivateData->mEffect->GetVariableByName("tex")->AsShaderResource()->SetResource(srView);
     mPrivateData->mEffect->GetTechniqueByName("SampleTexture")->
       GetPassByIndex(0)->Apply(0);
 
-    mDevice->OMSetBlendState(GetBlendStateForOperator(OP_OVER), NULL, 0xffffffff);
+    mDevice->OMSetBlendState(GetBlendStateForOperator(OP_OVER), nullptr, 0xffffffff);
 
     mDevice->Draw(4, 0);
     
     srcSurfSize = dsSize;
 
     srView = dsSRView;
   } else {
     // In this case generate a kernel to draw the blur directly to the temp
@@ -536,25 +536,25 @@ DrawTargetD2D::DrawSurfaceWithShadow(Sou
     mDevice->ClearRenderTargetView(tmpRTView, color);
   } else {
     CD3D10_TEXTURE2D_DESC desc(DXGI_FORMAT_B8G8R8A8_UNORM,
                                srcSurfSize.width,
                                srcSurfSize.height,
                                1, 1);
     desc.BindFlags = D3D10_BIND_RENDER_TARGET | D3D10_BIND_SHADER_RESOURCE;
 
-    mDevice->CreateTexture2D(&desc, NULL,  byRef(tmpTexture));
-    mDevice->CreateRenderTargetView(tmpTexture, NULL,  byRef(tmpRTView));
-    mDevice->CreateShaderResourceView(tmpTexture, NULL,  byRef(tmpSRView));
+    mDevice->CreateTexture2D(&desc, nullptr,  byRef(tmpTexture));
+    mDevice->CreateRenderTargetView(tmpTexture, nullptr,  byRef(tmpRTView));
+    mDevice->CreateShaderResourceView(tmpTexture, nullptr,  byRef(tmpSRView));
 
     tmpSurfSize = srcSurfSize;
   }
 
   rtViews = tmpRTView;
-  mDevice->OMSetRenderTargets(1, &rtViews, NULL);
+  mDevice->OMSetRenderTargets(1, &rtViews, nullptr);
 
   mPrivateData->mEffect->GetVariableByName("tex")->AsShaderResource()->SetResource(srView);
 
   // Premultiplied!
   float shadowColor[4] = { aColor.r * aColor.a, aColor.g * aColor.a,
                            aColor.b * aColor.a, aColor.a };
   mPrivateData->mEffect->GetVariableByName("ShadowColor")->AsVector()->
     SetFloatVector(shadowColor);
@@ -588,17 +588,17 @@ DrawTargetD2D::DrawSurfaceWithShadow(Sou
   viewport.TopLeftX = 0;
   viewport.TopLeftY = 0;
 
   mDevice->RSSetViewports(1, &viewport);
 
   mPrivateData->mEffect->GetVariableByName("tex")->AsShaderResource()->SetResource(tmpSRView);
 
   rtViews = destRTView;
-  mDevice->OMSetRenderTargets(1, &rtViews, NULL);
+  mDevice->OMSetRenderTargets(1, &rtViews, nullptr);
 
   Point shadowDest = aDest + aOffset;
 
   mPrivateData->mEffect->GetVariableByName("QuadDesc")->AsVector()->
     SetFloatVector(ShaderConstantRectD3D10(-1.0f + ((shadowDest.x / mSize.width) * 2.0f),
                                            1.0f - (shadowDest.y / mSize.height * 2.0f),
                                            (Float(aSurface->GetSize().width) / mSize.width) * 2.0f,
                                            (-Float(aSurface->GetSize().height) / mSize.height) * 2.0f));
@@ -614,17 +614,17 @@ DrawTargetD2D::DrawSurfaceWithShadow(Sou
                                              Float(aSurface->GetSize().height) / mSize.height));
     mPrivateData->mEffect->GetTechniqueByName("SampleTextureWithShadow")->
       GetPassByIndex(2)->Apply(0);
   } else {
     mPrivateData->mEffect->GetTechniqueByName("SampleTextureWithShadow")->
       GetPassByIndex(1)->Apply(0);
   }
 
-  mDevice->OMSetBlendState(GetBlendStateForOperator(aOperator), NULL, 0xffffffff);
+  mDevice->OMSetBlendState(GetBlendStateForOperator(aOperator), nullptr, 0xffffffff);
 
   mDevice->Draw(4, 0);
 
   mPrivateData->mEffect->GetVariableByName("QuadDesc")->AsVector()->
     SetFloatVector(ShaderConstantRectD3D10(-1.0f + ((aDest.x / mSize.width) * 2.0f),
                                            1.0f - (aDest.y / mSize.height * 2.0f),
                                            (Float(aSurface->GetSize().width) / mSize.width) * 2.0f,
                                            (-Float(aSurface->GetSize().height) / mSize.height) * 2.0f));
@@ -639,17 +639,17 @@ DrawTargetD2D::DrawSurfaceWithShadow(Sou
                                              Float(aSurface->GetSize().height) / mSize.height));
     mPrivateData->mEffect->GetTechniqueByName("SampleMaskedTexture")->
       GetPassByIndex(0)->Apply(0);
   } else {
     mPrivateData->mEffect->GetTechniqueByName("SampleTexture")->
       GetPassByIndex(0)->Apply(0);
   }
 
-  mDevice->OMSetBlendState(GetBlendStateForOperator(aOperator), NULL, 0xffffffff);
+  mDevice->OMSetBlendState(GetBlendStateForOperator(aOperator), nullptr, 0xffffffff);
 
   mDevice->Draw(4, 0);
 }
 
 void
 DrawTargetD2D::ClearRect(const Rect &aRect)
 {
   MarkChanged();
@@ -863,17 +863,17 @@ DrawTargetD2D::FillGlyphs(ScaledFont *aF
 {
   if (aFont->GetType() != FONT_DWRITE) {
     gfxDebug() << *this << ": Ignoring drawing call for incompatible font.";
     return;
   }
 
   ScaledFontDWrite *font = static_cast<ScaledFontDWrite*>(aFont);
 
-  IDWriteRenderingParams *params = NULL;
+  IDWriteRenderingParams *params = nullptr;
   if (aRenderOptions) {
     if (aRenderOptions->GetType() != FONT_DWRITE) {
       gfxDebug() << *this << ": Ignoring incompatible GlyphRenderingOptions.";
       // This should never happen.
       MOZ_ASSERT(false);
     } else {
       params = static_cast<const GlyphRenderingOptionsDWrite*>(aRenderOptions)->mParams;
     }
@@ -922,17 +922,17 @@ DrawTargetD2D::Mask(const Pattern &aSour
 
   RefPtr<ID2D1Brush> brush = CreateBrushForPattern(aSource, aOptions.mAlpha);
   RefPtr<ID2D1Brush> maskBrush = CreateBrushForPattern(aMask, 1.0f);
 
   RefPtr<ID2D1Layer> layer;
 
   layer = GetCachedLayer();
 
-  rt->PushLayer(D2D1::LayerParameters(D2D1::InfiniteRect(), NULL,
+  rt->PushLayer(D2D1::LayerParameters(D2D1::InfiniteRect(), nullptr,
                                       D2D1_ANTIALIAS_MODE_PER_PRIMITIVE,
                                       D2D1::IdentityMatrix(),
                                       1.0f, maskBrush),
                 layer);
 
   Rect rect(0, 0, mSize.width, mSize.height);
   Matrix mat = mTransform;
   mat.Invert();
@@ -946,18 +946,18 @@ DrawTargetD2D::Mask(const Pattern &aSour
 void
 DrawTargetD2D::PushClip(const Path *aPath)
 {
   if (aPath->GetBackendType() != BACKEND_DIRECT2D) {
     gfxDebug() << *this << ": Ignoring clipping call for incompatible path.";
     return;
   }
 
-  mCurrentClipMaskTexture = NULL;
-  mCurrentClippedGeometry = NULL;
+  mCurrentClipMaskTexture = nullptr;
+  mCurrentClippedGeometry = nullptr;
 
   RefPtr<PathD2D> pathD2D = static_cast<PathD2D*>(const_cast<Path*>(aPath));
 
   PushedClip clip;
   clip.mTransform = D2DMatrix(mTransform);
   clip.mPath = pathD2D;
   
   pathD2D->mGeometry->GetBounds(clip.mTransform, &clip.mBounds);
@@ -975,26 +975,26 @@ DrawTargetD2D::PushClip(const Path *aPat
     D2D1_LAYER_OPTIONS options = D2D1_LAYER_OPTIONS_NONE;
 
     if (mFormat == FORMAT_B8G8R8X8) {
       options = D2D1_LAYER_OPTIONS_INITIALIZE_FOR_CLEARTYPE;
     }
 
     mRT->PushLayer(D2D1::LayerParameters(D2D1::InfiniteRect(), pathD2D->mGeometry,
                                          D2D1_ANTIALIAS_MODE_PER_PRIMITIVE,
-                                         clip.mTransform, 1.0f, NULL,
+                                         clip.mTransform, 1.0f, nullptr,
                                          options), clip.mLayer);
   }
 }
 
 void
 DrawTargetD2D::PushClipRect(const Rect &aRect)
 {
-  mCurrentClipMaskTexture = NULL;
-  mCurrentClippedGeometry = NULL;
+  mCurrentClipMaskTexture = nullptr;
+  mCurrentClippedGeometry = nullptr;
   if (!mTransform.IsRectilinear()) {
     // Whoops, this isn't a rectangle in device space, Direct2D will not deal
     // with this transform the way we want it to.
     // See remarks: http://msdn.microsoft.com/en-us/library/dd316860%28VS.85%29.aspx
 
     RefPtr<PathBuilder> pathBuilder = CreatePathBuilder();
     pathBuilder->MoveTo(aRect.TopLeft());
     pathBuilder->LineTo(aRect.TopRight());
@@ -1016,18 +1016,18 @@ DrawTargetD2D::PushClipRect(const Rect &
   if (mClipsArePushed) {
     mRT->PushAxisAlignedClip(clip.mBounds, D2D1_ANTIALIAS_MODE_PER_PRIMITIVE);
   }
 }
 
 void
 DrawTargetD2D::PopClip()
 {
-  mCurrentClipMaskTexture = NULL;
-  mCurrentClippedGeometry = NULL;
+  mCurrentClipMaskTexture = nullptr;
+  mCurrentClippedGeometry = nullptr;
   if (mClipsArePushed) {
     if (mPushedClips.back().mLayer) {
       PopCachedLayer(mRT);
     } else {
       mRT->PopAxisAlignedClip();
     }
   }
   mPushedClips.pop_back();
@@ -1037,79 +1037,79 @@ TemporaryRef<SourceSurface>
 DrawTargetD2D::CreateSourceSurfaceFromData(unsigned char *aData,
                                            const IntSize &aSize,
                                            int32_t aStride,
                                            SurfaceFormat aFormat) const
 {
   RefPtr<SourceSurfaceD2D> newSurf = new SourceSurfaceD2D();
 
   if (!newSurf->InitFromData(aData, aSize, aStride, aFormat, mRT)) {
-    return NULL;
+    return nullptr;
   }
 
   return newSurf;
 }
 
 TemporaryRef<SourceSurface> 
 DrawTargetD2D::OptimizeSourceSurface(SourceSurface *aSurface) const
 {
   // Unsupported!
-  return NULL;
+  return nullptr;
 }
 
 TemporaryRef<SourceSurface>
 DrawTargetD2D::CreateSourceSurfaceFromNativeSurface(const NativeSurface &aSurface) const
 {
   if (aSurface.mType != NATIVE_SURFACE_D3D10_TEXTURE) {
     gfxDebug() << *this << ": Failure to create source surface from non-D3D10 texture native surface.";
-    return NULL;
+    return nullptr;
   }
   RefPtr<SourceSurfaceD2D> newSurf = new SourceSurfaceD2D();
 
   if (!newSurf->InitFromTexture(static_cast<ID3D10Texture2D*>(aSurface.mSurface),
                                 aSurface.mFormat,
                                 mRT))
   {
     gfxWarning() << *this << ": Failed to create SourceSurface from texture.";
-    return NULL;
+    return nullptr;
   }
 
   return newSurf;
 }
 
 TemporaryRef<DrawTarget>
 DrawTargetD2D::CreateSimilarDrawTarget(const IntSize &aSize, SurfaceFormat aFormat) const
 {
   RefPtr<DrawTargetD2D> newTarget =
     new DrawTargetD2D();
 
   if (!newTarget->Init(aSize, aFormat)) {
     gfxDebug() << *this << ": Failed to create optimal draw target. Size: " << aSize;
-    return NULL;
+    return nullptr;
   }
 
   return newTarget;
 }
 
 TemporaryRef<PathBuilder>
 DrawTargetD2D::CreatePathBuilder(FillRule aFillRule) const
 {
   RefPtr<ID2D1PathGeometry> path;
   HRESULT hr = factory()->CreatePathGeometry(byRef(path));
 
   if (FAILED(hr)) {
     gfxWarning() << "Failed to create Direct2D Path Geometry. Code: " << hr;
-    return NULL;
+    return nullptr;
   }
 
   RefPtr<ID2D1GeometrySink> sink;
   hr = path->Open(byRef(sink));
   if (FAILED(hr)) {
     gfxWarning() << "Failed to access Direct2D Path Geometry. Code: " << hr;
-    return NULL;
+    return nullptr;
   }
 
   if (aFillRule == FILL_WINDING) {
     sink->SetFillMode(D2D1_FILL_MODE_WINDING);
   }
 
   return new PathBuilderD2D(sink, path, aFillRule);
 }
@@ -1129,27 +1129,27 @@ DrawTargetD2D::CreateGradientStops(Gradi
   HRESULT hr =
     mRT->CreateGradientStopCollection(stops, aNumStops,
                                       D2D1_GAMMA_2_2, D2DExtend(aExtendMode),
                                       byRef(stopCollection));
   delete [] stops;
 
   if (FAILED(hr)) {
     gfxWarning() << "Failed to create GradientStopCollection. Code: " << hr;
-    return NULL;
+    return nullptr;
   }
 
   return new GradientStopsD2D(stopCollection);
 }
 
 void*
 DrawTargetD2D::GetNativeSurface(NativeSurfaceType aType)
 {
   if (aType != NATIVE_SURFACE_D3D10_TEXTURE) {
-    return NULL;
+    return nullptr;
   }
 
   return mTexture;
 }
 
 /*
  * Public functions
  */
@@ -1168,17 +1168,17 @@ DrawTargetD2D::Init(const IntSize &aSize
   mDevice = Factory::GetDirect3D10Device();
 
   CD3D10_TEXTURE2D_DESC desc(DXGIFormat(aFormat),
                              mSize.width,
                              mSize.height,
                              1, 1);
   desc.BindFlags = D3D10_BIND_RENDER_TARGET | D3D10_BIND_SHADER_RESOURCE;
 
-  hr = mDevice->CreateTexture2D(&desc, NULL, byRef(mTexture));
+  hr = mDevice->CreateTexture2D(&desc, nullptr, byRef(mTexture));
 
   if (FAILED(hr)) {
     gfxDebug() << "Failed to init Direct2D DrawTarget. Size: " << mSize << " Code: " << hr;
     return false;
   }
 
   if (!InitD2DRenderTarget()) {
     return false;
@@ -1238,17 +1238,17 @@ DrawTargetD2D::InitD3D10Data()
 
   mPrivateData = new PrivateD3D10DataD2D;
 
   D3D10CreateEffectFromMemoryFunc createD3DEffect;
   HMODULE d3dModule = LoadLibraryW(L"d3d10_1.dll");
   createD3DEffect = (D3D10CreateEffectFromMemoryFunc)
       GetProcAddress(d3dModule, "D3D10CreateEffectFromMemory");
 
-  hr = createD3DEffect((void*)d2deffect, sizeof(d2deffect), 0, mDevice, NULL, byRef(mPrivateData->mEffect));
+  hr = createD3DEffect((void*)d2deffect, sizeof(d2deffect), 0, mDevice, nullptr, byRef(mPrivateData->mEffect));
 
   if (FAILED(hr)) {
     gfxWarning() << "Failed to initialize Direct2D required effects. Code: " << hr;
     return false;
   }
 
   privateDataSize = sizeof(mPrivateData);
   mDevice->SetPrivateData(sPrivateDataD2D, privateDataSize, &mPrivateData);
@@ -1370,17 +1370,17 @@ DrawTargetD2D::PrepareForDrawing(ID2D1Re
 }
 
 void
 DrawTargetD2D::MarkChanged()
 {
   if (mSnapshot) {
     if (mSnapshot->hasOneRef()) {
       // Just destroy it, since no-one else knows about it.
-      mSnapshot = NULL;
+      mSnapshot = nullptr;
     } else {
       mSnapshot->DrawTargetWillChange();
       // The snapshot will no longer depend on this target.
       MOZ_ASSERT(!mSnapshot);
     }
   }
   if (mDependentTargets.size()) {
     // Copy mDependentTargets since the Flush()es below will modify it.
@@ -1528,17 +1528,17 @@ DrawTargetD2D::FinalizeRTForOperation(Co
   bool needsWriteBack =
     !IsOperatorBoundByMask(aOperator) && mPushedClips.size();
 
   if (needsWriteBack) {
     restoreClippedOut.Save();
   }
 
   ID3D10RenderTargetView *rtViews = mRTView;
-  mDevice->OMSetRenderTargets(1, &rtViews, NULL);
+  mDevice->OMSetRenderTargets(1, &rtViews, nullptr);
 
   UINT stride = sizeof(Vertex);
   UINT offset = 0;
   ID3D10Buffer *buff = mPrivateData->mVB;
 
   mDevice->IASetPrimitiveTopology(D3D10_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP);
   mDevice->IASetVertexBuffers(0, 1, &buff, &stride, &offset);
   mDevice->IASetInputLayout(mPrivateData->mInputLayout);
@@ -1568,17 +1568,17 @@ DrawTargetD2D::FinalizeRTForOperation(Co
       return;
     }
 
     mPrivateData->mEffect->GetVariableByName("mask")->AsShaderResource()->SetResource(mSRView);
 
     SetupEffectForRadialGradient(pat);
   }
 
-  mDevice->OMSetBlendState(GetBlendStateForOperator(aOperator), NULL, 0xffffffff);
+  mDevice->OMSetBlendState(GetBlendStateForOperator(aOperator), nullptr, 0xffffffff);
   
   mDevice->Draw(4, 0);
 }
 
 TemporaryRef<ID2D1Geometry>
 DrawTargetD2D::ConvertRectToGeometry(const D2D1_RECT_F& aRect)
 {
   RefPtr<ID2D1RectangleGeometry> rectGeom;
@@ -1666,17 +1666,17 @@ DrawTargetD2D::CreateRTForTexture(ID3D10
 
   RefPtr<IDXGISurface> surface;
   RefPtr<ID2D1RenderTarget> rt;
 
   hr = aTexture->QueryInterface((IDXGISurface**)byRef(surface));
 
   if (FAILED(hr)) {
     gfxWarning() << "Failed to QI texture to surface.";
-    return NULL;
+    return nullptr;
   }
 
   D3D10_TEXTURE2D_DESC desc;
   aTexture->GetDesc(&desc);
 
   D2D1_ALPHA_MODE alphaMode = D2D1_ALPHA_MODE_PREMULTIPLIED;
 
   if (aFormat == FORMAT_B8G8R8X8 && aTexture == mTexture) {
@@ -1684,17 +1684,17 @@ DrawTargetD2D::CreateRTForTexture(ID3D10
   }
 
   D2D1_RENDER_TARGET_PROPERTIES props =
     D2D1::RenderTargetProperties(D2D1_RENDER_TARGET_TYPE_DEFAULT, D2D1::PixelFormat(desc.Format, alphaMode));
   hr = factory()->CreateDxgiSurfaceRenderTarget(surface, props, byRef(rt));
 
   if (FAILED(hr)) {
     gfxWarning() << "Failed to create D2D render target for texture.";
-    return NULL;
+    return nullptr;
   }
 
   return rt;
 }
 
 void
 DrawTargetD2D::EnsureViews()
 {
@@ -1705,32 +1705,32 @@ DrawTargetD2D::EnsureViews()
   HRESULT hr;
 
   CD3D10_TEXTURE2D_DESC desc(DXGI_FORMAT_B8G8R8A8_UNORM,
                              mSize.width,
                              mSize.height,
                              1, 1);
   desc.BindFlags = D3D10_BIND_RENDER_TARGET | D3D10_BIND_SHADER_RESOURCE;
 
-  hr = mDevice->CreateTexture2D(&desc, NULL, byRef(mTempTexture));
+  hr = mDevice->CreateTexture2D(&desc, nullptr, byRef(mTempTexture));
 
   if (FAILED(hr)) {
     gfxWarning() << *this << "Failed to create temporary texture for rendertarget. Size: "
       << mSize << " Code: " << hr;
     return;
   }
 
-  hr = mDevice->CreateShaderResourceView(mTempTexture, NULL, byRef(mSRView));
+  hr = mDevice->CreateShaderResourceView(mTempTexture, nullptr, byRef(mSRView));
 
   if (FAILED(hr)) {
     gfxWarning() << *this << "Failed to create shader resource view for temp texture. Code: " << hr;
     return;
   }
 
-  hr = mDevice->CreateRenderTargetView(mTexture, NULL, byRef(mRTView));
+  hr = mDevice->CreateRenderTargetView(mTexture, nullptr, byRef(mRTView));
 
   if (FAILED(hr)) {
     gfxWarning() << *this << "Failed to create rendertarget view for temp texture. Code: " << hr;
   }
 }
 
 void
 DrawTargetD2D::PopAllClips()
@@ -1751,17 +1751,17 @@ DrawTargetD2D::PushClipsToRT(ID2D1Render
       D2D1_LAYER_OPTIONS options = D2D1_LAYER_OPTIONS_NONE;
 
       if (mFormat == FORMAT_B8G8R8X8) {
         options = D2D1_LAYER_OPTIONS_INITIALIZE_FOR_CLEARTYPE;
       }
 
       aRT->PushLayer(D2D1::LayerParameters(D2D1::InfiniteRect(), iter->mPath->mGeometry,
                                             D2D1_ANTIALIAS_MODE_PER_PRIMITIVE,
-                                            iter->mTransform, 1.0f, NULL,
+                                            iter->mTransform, 1.0f, nullptr,
                                             options), iter->mLayer);
     } else {
       aRT->PushAxisAlignedClip(iter->mBounds, D2D1_ANTIALIAS_MODE_PER_PRIMITIVE);
     }
   }
 }
 
 void
@@ -1784,17 +1784,17 @@ DrawTargetD2D::EnsureClipMaskTexture()
   }
   
   CD3D10_TEXTURE2D_DESC desc(DXGI_FORMAT_A8_UNORM,
                              mSize.width,
                              mSize.height,
                              1, 1);
   desc.BindFlags = D3D10_BIND_RENDER_TARGET | D3D10_BIND_SHADER_RESOURCE;
 
-  HRESULT hr = mDevice->CreateTexture2D(&desc, NULL, byRef(mCurrentClipMaskTexture));
+  HRESULT hr = mDevice->CreateTexture2D(&desc, nullptr, byRef(mCurrentClipMaskTexture));
 
   if (FAILED(hr)) {
     gfxWarning() << "Failed to create texture for ClipMask!";
     return;
   }
 
   RefPtr<ID2D1RenderTarget> rt = CreateRTForTexture(mCurrentClipMaskTexture, FORMAT_A8);
 
@@ -1904,17 +1904,17 @@ DrawTargetD2D::FillGlyphsManual(ScaledFo
 
   RefPtr<ID3D10Texture2D> tex = CreateTextureForAnalysis(analysis, rectBounds);
 
   if (!tex) {
     return false;
   }
 
   RefPtr<ID3D10ShaderResourceView> srView;
-  hr = mDevice->CreateShaderResourceView(tex, NULL, byRef(srView));
+  hr = mDevice->CreateShaderResourceView(tex, nullptr, byRef(srView));
 
   if (FAILED(hr)) {
     return false;
   }
 
   MarkChanged();
 
   // Prepare our background texture for drawing.
@@ -1955,17 +1955,17 @@ DrawTargetD2D::FillGlyphsManual(ScaledFo
       isMasking = true;
     }        
   }
   
   if (isMasking) {
     EnsureClipMaskTexture();
 
     RefPtr<ID3D10ShaderResourceView> srViewMask;
-    hr = mDevice->CreateShaderResourceView(mCurrentClipMaskTexture, NULL, byRef(srViewMask));
+    hr = mDevice->CreateShaderResourceView(mCurrentClipMaskTexture, nullptr, byRef(srViewMask));
 
     if (FAILED(hr)) {
       return false;
     }
 
     mPrivateData->mEffect->GetVariableByName("mask")->AsShaderResource()->SetResource(srViewMask);
 
     mPrivateData->mEffect->GetVariableByName("MaskTexCoords")->AsVector()->
@@ -1974,20 +1974,20 @@ DrawTargetD2D::FillGlyphsManual(ScaledFo
 
     technique->GetPassByIndex(1)->Apply(0);
   } else {
     technique->GetPassByIndex(0)->Apply(0);
   }  
 
   RefPtr<ID3D10RenderTargetView> rtView;
   ID3D10RenderTargetView *rtViews;
-  mDevice->CreateRenderTargetView(mTexture, NULL, byRef(rtView));
+  mDevice->CreateRenderTargetView(mTexture, nullptr, byRef(rtView));
 
   rtViews = rtView;
-  mDevice->OMSetRenderTargets(1, &rtViews, NULL);
+  mDevice->OMSetRenderTargets(1, &rtViews, nullptr);
 
   mDevice->Draw(4, 0);
   return true;
 }
 
 TemporaryRef<ID2D1Brush>
 DrawTargetD2D::CreateBrushForPattern(const Pattern &aPattern, Float aAlpha)
 {
@@ -2009,17 +2009,17 @@ DrawTargetD2D::CreateBrushForPattern(con
     RefPtr<ID2D1LinearGradientBrush> gradBrush;
     const LinearGradientPattern *pat =
       static_cast<const LinearGradientPattern*>(&aPattern);
 
     GradientStopsD2D *stops = static_cast<GradientStopsD2D*>(pat->mStops.get());
 
     if (!stops) {
       gfxDebug() << "No stops specified for gradient pattern.";
-      return NULL;
+      return nullptr;
     }
 
     if (pat->mBegin == pat->mEnd) {
       RefPtr<ID2D1SolidColorBrush> colBrush;
       uint32_t stopCount = stops->mStopCollection->GetGradientStopCount();
       vector<D2D1_GRADIENT_STOP> d2dStops(stopCount);
       stops->mStopCollection->GetGradientStops(&d2dStops.front(), stopCount);
       mRT->CreateSolidColorBrush(d2dStops.back().color,
@@ -2038,17 +2038,17 @@ DrawTargetD2D::CreateBrushForPattern(con
     RefPtr<ID2D1RadialGradientBrush> gradBrush;
     const RadialGradientPattern *pat =
       static_cast<const RadialGradientPattern*>(&aPattern);
 
     GradientStopsD2D *stops = static_cast<GradientStopsD2D*>(pat->mStops.get());
 
     if (!stops) {
       gfxDebug() << "No stops specified for gradient pattern.";
-      return NULL;
+      return nullptr;
     }
 
     // This will not be a complex radial gradient brush.
     mRT->CreateRadialGradientBrush(
       D2D1::RadialGradientBrushProperties(D2DPoint(pat->mCenter1),
                                           D2D1::Point2F(),
                                           pat->mRadius2, pat->mRadius2),
       D2D1::BrushProperties(aAlpha, D2DMatrix(pat->mMatrix)),
@@ -2058,32 +2058,32 @@ DrawTargetD2D::CreateBrushForPattern(con
     return gradBrush;
   } else if (aPattern.GetType() == PATTERN_SURFACE) {
     RefPtr<ID2D1BitmapBrush> bmBrush;
     const SurfacePattern *pat =
       static_cast<const SurfacePattern*>(&aPattern);
 
     if (!pat->mSurface) {
       gfxDebug() << "No source surface specified for surface pattern";
-      return NULL;
+      return nullptr;
     }
 
     RefPtr<ID2D1Bitmap> bitmap;
 
     Matrix mat = pat->mMatrix;
     
     switch (pat->mSurface->GetType()) {
     case SURFACE_D2D1_BITMAP:
       {
         SourceSurfaceD2D *surf = static_cast<SourceSurfaceD2D*>(pat->mSurface.get());
 
         bitmap = surf->mBitmap;
 
         if (!bitmap) {
-          return NULL;
+          return nullptr;
         }
       }
       break;
     case SURFACE_D2D1_DRAWTARGET:
       {
         SourceSurfaceD2DTarget *surf =
           static_cast<SourceSurfaceD2DTarget*>(pat->mSurface.get());
         bitmap = surf->GetBitmap(mRT);
@@ -2092,17 +2092,17 @@ DrawTargetD2D::CreateBrushForPattern(con
       break;
     case SURFACE_DATA:
       {
         DataSourceSurface *dataSurf =
           static_cast<DataSourceSurface*>(pat->mSurface.get());
         bitmap = CreatePartialBitmapForSurface(dataSurf, mat, pat->mExtendMode);
         
         if (!bitmap) {
-          return NULL;
+          return nullptr;
         }
       }
       break;
     default:
       break;
     }
     
     mRT->CreateBitmapBrush(bitmap,
@@ -2111,17 +2111,17 @@ DrawTargetD2D::CreateBrushForPattern(con
                                                        D2DFilter(pat->mFilter)),
                            D2D1::BrushProperties(aAlpha, D2DMatrix(mat)),
                            byRef(bmBrush));
 
     return bmBrush;
   }
 
   gfxWarning() << "Invalid pattern type detected.";
-  return NULL;
+  return nullptr;
 }
 
 TemporaryRef<ID2D1StrokeStyle>
 DrawTargetD2D::CreateStrokeStyleForOptions(const StrokeOptions &aStrokeOptions)
 {
   RefPtr<ID2D1StrokeStyle> style;
 
   D2D1_CAP_STYLE capStyle;
@@ -2178,17 +2178,17 @@ DrawTargetD2D::CreateStrokeStyleForOptio
                 // and VC10's STL
       dash.size(),
       byRef(style));
   } else {
     hr = factory()->CreateStrokeStyle(
       D2D1::StrokeStyleProperties(capStyle, capStyle,
                                   capStyle, joinStyle,
                                   aStrokeOptions.mMiterLimit),
-      NULL, 0, byRef(style));
+      nullptr, 0, byRef(style));
   }
 
   if (FAILED(hr)) {
     gfxWarning() << "Failed to create Direct2D stroke style.";
   }
 
   return style;
 }
@@ -2280,17 +2280,17 @@ DrawTargetD2D::CreateTextureForAnalysis(
 
   // Add one byte so we can safely read a 32-bit int when copying the last
   // 3 bytes.
   BYTE *texture = new BYTE[bufferSize + 1];
   hr = aAnalysis->CreateAlphaTexture(DWRITE_TEXTURE_CLEARTYPE_3x1, &bounds, texture, bufferSize);
 
   if (FAILED(hr)) {
     delete [] texture;
-    return NULL;
+    return nullptr;
   }
 
   int alignedBufferSize = aBounds.width * aBounds.height * 4;
 
   // Create a one-off immutable texture from system memory.
   BYTE *alignedTextureData = new BYTE[alignedBufferSize];
   for (int y = 0; y < aBounds.height; y++) {
     for (int x = 0; x < aBounds.width; x++) {
@@ -2319,17 +2319,17 @@ DrawTargetD2D::CreateTextureForAnalysis(
 
   RefPtr<ID3D10Texture2D> tex;
   hr = mDevice->CreateTexture2D(&desc, &data, byRef(tex));
 	
   delete [] alignedTextureData;
   delete [] texture;
 
   if (FAILED(hr)) {
-    return NULL;
+    return nullptr;
   }
 
   return tex;
 }
 
 TemporaryRef<ID2D1Bitmap>
 DrawTargetD2D::CreatePartialBitmapForSurface(DataSourceSurface *aSurface, Matrix &aMatrix, ExtendMode aExtendMode)
 {
@@ -2339,17 +2339,17 @@ DrawTargetD2D::CreatePartialBitmapForSur
   // created for a surface that was too large to fit in a texture.
   // We'll need to figure out if we can work with a partial upload
   // or downsample in software.
 
   Matrix transform = mTransform;
   Matrix invTransform = transform = aMatrix * transform;
   if (!invTransform.Invert()) {
     // Singular transform, nothing to be drawn.
-    return NULL;
+    return nullptr;
   }
 
   Rect rect(0, 0, mSize.width, mSize.height);
 
   // Calculate the rectangle of the source mapped to our surface.
   rect = invTransform.TransformBounds(rect);
   rect.RoundOut();
 
@@ -2407,17 +2407,17 @@ DrawTargetD2D::CreatePartialBitmapForSur
 
     return bitmap;
   } else {
     int Bpp = BytesPerPixel(aSurface->GetFormat());
 
     if (Bpp != 4) {
       // This shouldn't actually happen in practice!
       MOZ_ASSERT(false);
-      return NULL;
+      return nullptr;
     }
 
     ImageHalfScaler scaler(aSurface->GetData(), stride, size);
 
     // Calculate the maximum width/height of the image post transform.
     Point topRight = transform * Point(size.width, 0);
     Point topLeft = transform * Point(0, 0);
     Point bottomRight = transform * Point(size.width, size.height);
@@ -2464,17 +2464,17 @@ DrawTargetD2D::SetupEffectForRadialGradi
     SetFloatVector(dimensions);
 
   const GradientStopsD2D *stops =
     static_cast<const GradientStopsD2D*>(aPattern->mStops.get());
 
   RefPtr<ID3D10Texture2D> tex = CreateGradientTexture(stops);
 
   RefPtr<ID3D10ShaderResourceView> srView;
-  mDevice->CreateShaderResourceView(tex, NULL, byRef(srView));
+  mDevice->CreateShaderResourceView(tex, nullptr, byRef(srView));
 
   mPrivateData->mEffect->GetVariableByName("tex")->AsShaderResource()->SetResource(srView);
 
   Point dc = aPattern->mCenter2 - aPattern->mCenter1;
   float dr = aPattern->mRadius2 - aPattern->mRadius1;
 
   float diffv[] = { dc.x, dc.y, dr, 0 };
   mPrivateData->mEffect->GetVariableByName("diff")->AsVector()->
@@ -2558,17 +2558,17 @@ DrawTargetD2D::factory()
 
   D2D1CreateFactoryFunc createD2DFactory;
   HMODULE d2dModule = LoadLibraryW(L"d2d1.dll");
   createD2DFactory = (D2D1CreateFactoryFunc)
       GetProcAddress(d2dModule, "D2D1CreateFactory");
 
   if (!createD2DFactory) {
     gfxWarning() << "Failed to locate D2D1CreateFactory function.";
-    return NULL;
+    return nullptr;
   }
 
   D2D1_FACTORY_OPTIONS options;
 #ifdef _DEBUG
   options.debugLevel = D2D1_DEBUG_LEVEL_WARNING;
 #else
   options.debugLevel = D2D1_DEBUG_LEVEL_NONE;
 #endif
@@ -2594,17 +2594,17 @@ DrawTargetD2D::GetDWriteFactory()
 
   DWriteCreateFactoryFunc createDWriteFactory;
   HMODULE dwriteModule = LoadLibraryW(L"dwrite.dll");
   createDWriteFactory = (DWriteCreateFactoryFunc)
     GetProcAddress(dwriteModule, "DWriteCreateFactory");
 
   if (!createDWriteFactory) {
     gfxWarning() << "Failed to locate DWriteCreateFactory function.";
-    return NULL;
+    return nullptr;
   }
 
   HRESULT hr = createDWriteFactory(DWRITE_FACTORY_TYPE_SHARED, __uuidof(IDWriteFactory),
                                    reinterpret_cast<IUnknown**>(&mDWriteFactory));
 
   if (FAILED(hr)) {
     gfxWarning() << "Failed to create DWrite Factory.";
   }
--- a/gfx/2d/DrawTargetD2D.h
+++ b/gfx/2d/DrawTargetD2D.h
@@ -86,17 +86,17 @@ public:
                       const DrawOptions &aOptions = DrawOptions());
   virtual void Fill(const Path *aPath,
                     const Pattern &aPattern,
                     const DrawOptions &aOptions = DrawOptions());
   virtual void FillGlyphs(ScaledFont *aFont,
                           const GlyphBuffer &aBuffer,
                           const Pattern &aPattern,
                           const DrawOptions &aOptions = DrawOptions(),
-                          const GlyphRenderingOptions *aRenderingOptions = NULL);
+                          const GlyphRenderingOptions *aRenderingOptions = nullptr);
   virtual void Mask(const Pattern &aSource,
                     const Pattern &aMask,
                     const DrawOptions &aOptions = DrawOptions());
   virtual void PushClip(const Path *aPath);
   virtual void PushClipRect(const Rect &aRect);
   virtual void PopClip();
 
   virtual TemporaryRef<SourceSurface> CreateSourceSurfaceFromData(unsigned char *aData,
--- a/gfx/2d/DrawTargetDual.h
+++ b/gfx/2d/DrawTargetDual.h
@@ -119,20 +119,20 @@ public:
                         uint32_t aNumStops,
                         ExtendMode aExtendMode = EXTEND_CLAMP) const
   {
     return mA->CreateGradientStops(aStops, aNumStops, aExtendMode);
   }
      
   virtual void *GetNativeSurface(NativeSurfaceType aType)
   {
-    return NULL;
+    return nullptr;
   }
      
 private:
   RefPtr<DrawTarget> mA;
   RefPtr<DrawTarget> mB;
 };
      
 }
 }
      
-#endif /* MOZILLA_GFX_DRAWTARGETDUAL_H_ */ 
\ No newline at end of file
+#endif /* MOZILLA_GFX_DRAWTARGETDUAL_H_ */ 
--- a/gfx/2d/DrawTargetSkia.cpp
+++ b/gfx/2d/DrawTargetSkia.cpp
@@ -157,17 +157,17 @@ DrawTargetSkia::~DrawTargetSkia()
   }
 }
 
 TemporaryRef<SourceSurface>
 DrawTargetSkia::Snapshot()
 {
   RefPtr<SourceSurfaceSkia> source = new SourceSurfaceSkia();
   if (!source->InitWithBitmap(mBitmap, mFormat, this)) {
-    return NULL;
+    return nullptr;
   }
   AppendSnapshot(source);
   return source;
 }
 
 SkShader::TileMode
 ExtendModeToTileMode(ExtendMode aMode)
 {
@@ -306,17 +306,17 @@ struct AutoPaintSetup {
     // clear the clip rect. The other operators would be harder
     // but could be worth it to skip pushing a group.
     if (!IsOperatorBoundByMask(aOptions.mCompositionOp)) {
       mPaint.setXfermodeMode(SkXfermode::kSrcOver_Mode);
       SkPaint temp;
       temp.setXfermodeMode(GfxOpToSkiaOp(aOptions.mCompositionOp));
       temp.setAlpha(aOptions.mAlpha*255);
       //TODO: Get a rect here
-      mCanvas->saveLayer(NULL, &temp);
+      mCanvas->saveLayer(nullptr, &temp);
       mNeedsRestore = true;
     } else {
       mPaint.setAlpha(aOptions.mAlpha*255.0);
       mAlpha = aOptions.mAlpha;
     }
     mPaint.setFilterBitmap(true);
   }
 
@@ -586,42 +586,42 @@ DrawTargetSkia::CreateSourceSurfaceFromD
                                              const IntSize &aSize,
                                              int32_t aStride,
                                              SurfaceFormat aFormat) const
 {
   RefPtr<SourceSurfaceSkia> newSurf = new SourceSurfaceSkia();
 
   if (!newSurf->InitFromData(aData, aSize, aStride, aFormat)) {
     gfxDebug() << *this << ": Failure to create source surface from data. Size: " << aSize;
-    return NULL;
+    return nullptr;
   }
     
   return newSurf;
 }
 
 TemporaryRef<DrawTarget>
 DrawTargetSkia::CreateSimilarDrawTarget(const IntSize &aSize, SurfaceFormat aFormat) const
 {
   RefPtr<DrawTargetSkia> target = new DrawTargetSkia();
   if (!target->Init(aSize, aFormat)) {
-    return NULL;
+    return nullptr;
   }
   return target;
 }
 
 TemporaryRef<SourceSurface>
 DrawTargetSkia::OptimizeSourceSurface(SourceSurface *aSurface) const
 {
-  return NULL;
+  return nullptr;
 }
 
 TemporaryRef<SourceSurface>
 DrawTargetSkia::CreateSourceSurfaceFromNativeSurface(const NativeSurface &aSurface) const
 {
-  return NULL;
+  return nullptr;
 }
 
 void
 DrawTargetSkia::CopySurface(SourceSurface *aSurface,
                             const IntRect& aSourceRect,
                             const IntPoint &aDestination)
 {
   //TODO: We could just use writePixels() here if the sourceRect is the entire source
--- a/gfx/2d/DrawTargetSkia.h
+++ b/gfx/2d/DrawTargetSkia.h
@@ -61,17 +61,17 @@ public:
                       const DrawOptions &aOptions = DrawOptions());
   virtual void Fill(const Path *aPath,
                     const Pattern &aPattern,
                     const DrawOptions &aOptions = DrawOptions());
   virtual void FillGlyphs(ScaledFont *aFont,
                           const GlyphBuffer &aBuffer,
                           const Pattern &aPattern,
                           const DrawOptions &aOptions = DrawOptions(),
-                          const GlyphRenderingOptions *aRenderingOptions = NULL);
+                          const GlyphRenderingOptions *aRenderingOptions = nullptr);
   virtual void Mask(const Pattern &aSource,
                     const Pattern &aMask,
                     const DrawOptions &aOptions = DrawOptions());
   virtual void PushClip(const Path *aPath);
   virtual void PushClipRect(const Rect& aRect);
   virtual void PopClip();
   virtual TemporaryRef<SourceSurface> CreateSourceSurfaceFromData(unsigned char *aData,
                                                             const IntSize &aSize,
--- a/gfx/2d/Factory.cpp
+++ b/gfx/2d/Factory.cpp
@@ -191,22 +191,22 @@ Factory::CreateDrawTarget(BackendType aB
       if (newTarget->Init(aSize, aFormat)) {
         return newTarget;
       }
       break;
     }
 #endif
   default:
     gfxDebug() << "Invalid draw target type specified.";
-    return NULL;
+    return nullptr;
   }
 
   gfxDebug() << "Failed to create DrawTarget, Type: " << aBackend << " Size: " << aSize;
   // Failed
-  return NULL;
+  return nullptr;
 }
 
 TemporaryRef<DrawTarget>
 Factory::CreateDrawTargetForData(BackendType aBackend, 
                                  unsigned char *aData, 
                                  const IntSize &aSize, 
                                  int32_t aStride, 
                                  SurfaceFormat aFormat)
@@ -227,22 +227,22 @@ Factory::CreateDrawTargetForData(Backend
       RefPtr<DrawTargetCG> newTarget = new DrawTargetCG();
       if (newTarget->Init(aBackend, aData, aSize, aStride, aFormat))
         return newTarget;
       break;
     }
 #endif
   default:
     gfxDebug() << "Invalid draw target type specified.";
-    return NULL;
+    return nullptr;
   }
 
   gfxDebug() << "Failed to create DrawTarget, Type: " << aBackend << " Size: " << aSize;
   // Failed
-  return NULL;
+  return nullptr;
 }
 
 TemporaryRef<ScaledFont>
 Factory::CreateScaledFontForNativeFont(const NativeFont &aNativeFont, Float aSize)
 {
   switch (aNativeFont.mType) {
 #ifdef WIN32
   case NATIVE_FONT_DWRITE_FONT_FACE:
@@ -273,33 +273,33 @@ Factory::CreateScaledFontForNativeFont(c
     {
       ScaledFontBase* fontBase = new ScaledFontBase(aSize);
       fontBase->SetCairoScaledFont(static_cast<cairo_scaled_font_t*>(aNativeFont.mFont));
       return fontBase;
     }
 #endif
   default:
     gfxWarning() << "Invalid native font type specified.";
-    return NULL;
+    return nullptr;
   }
 }
 
 TemporaryRef<ScaledFont>
 Factory::CreateScaledFontWithCairo(const NativeFont& aNativeFont, Float aSize, cairo_scaled_font_t* aScaledFont)
 {
 #ifdef USE_CAIRO
   // In theory, we could pull the NativeFont out of the cairo_scaled_font_t*,
   // but that would require a lot of code that would be otherwise repeated in
   // various backends.
   // Therefore, we just reuse CreateScaledFontForNativeFont's implementation.
   RefPtr<ScaledFont> font = CreateScaledFontForNativeFont(aNativeFont, aSize);
   static_cast<ScaledFontBase*>(font.get())->SetCairoScaledFont(aScaledFont);
   return font;
 #else
-  return NULL;
+  return nullptr;
 #endif
 }
 
 #ifdef WIN32
 TemporaryRef<DrawTarget>
 Factory::CreateDrawTargetForD3D10Texture(ID3D10Texture2D *aTexture, SurfaceFormat aFormat)
 {
   RefPtr<DrawTargetD2D> newTarget;
@@ -307,37 +307,37 @@ Factory::CreateDrawTargetForD3D10Texture
   newTarget = new DrawTargetD2D();
   if (newTarget->Init(aTexture, aFormat)) {
     return newTarget;
   }
 
   gfxWarning() << "Failed to create draw target for D3D10 texture.";
 
   // Failed
-  return NULL;
+  return nullptr;
 }
 
 TemporaryRef<DrawTarget>
 Factory::CreateDualDrawTargetForD3D10Textures(ID3D10Texture2D *aTextureA,
                                               ID3D10Texture2D *aTextureB,
                                               SurfaceFormat aFormat)
 {
   RefPtr<DrawTargetD2D> newTargetA;
   RefPtr<DrawTargetD2D> newTargetB;
 
   newTargetA = new DrawTargetD2D();
   if (!newTargetA->Init(aTextureA, aFormat)) {
     gfxWarning() << "Failed to create draw target for D3D10 texture.";
-    return NULL;
+    return nullptr;
   }
 
   newTargetB = new DrawTargetD2D();
   if (!newTargetB->Init(aTextureB, aFormat)) {
     gfxWarning() << "Failed to create draw target for D3D10 texture.";
-    return NULL;
+    return nullptr;
   }
 
   RefPtr<DrawTarget> newTarget =
     new DrawTargetDual(newTargetA, newTargetB);
 
   return newTarget;
 }
 
@@ -381,27 +381,27 @@ Factory::CreateDrawTargetForCairoSurface
 {
 #ifdef USE_CAIRO
   RefPtr<DrawTargetCairo> newTarget = new DrawTargetCairo();
   if (newTarget->Init(aSurface, aSize)) {
     return newTarget;
   }
 
 #endif
-  return NULL;
+  return nullptr;
 }
 
 TemporaryRef<DataSourceSurface>
 Factory::CreateWrappingDataSourceSurface(uint8_t *aData, int32_t aStride,
                                          const IntSize &aSize,
                                          SurfaceFormat aFormat)
 {
   RefPtr<SourceSurfaceRawData> newSurf = new SourceSurfaceRawData();
 
   if (newSurf->InitWrappingData(aData, aSize, aStride, aFormat, false)) {
     return newSurf;
   }
 
-  return NULL;
+  return nullptr;
 }
 
 }
 }
--- a/gfx/2d/ImageScaling.h
+++ b/gfx/2d/ImageScaling.h
@@ -14,17 +14,17 @@
 namespace mozilla {
 namespace gfx {
 
 class ImageHalfScaler
 {
 public:
   ImageHalfScaler(uint8_t *aData, int32_t aStride, const IntSize &aSize)
     : mOrigData(aData), mOrigStride(aStride), mOrigSize(aSize)
-    , mDataStorage(NULL)
+    , mDataStorage(nullptr)
   {
   }
 
   ~ImageHalfScaler()
   {
     delete [] mDataStorage;
   }
 
--- a/gfx/2d/PathCG.cpp
+++ b/gfx/2d/PathCG.cpp
@@ -14,50 +14,50 @@ namespace gfx {
 PathBuilderCG::~PathBuilderCG()
 {
   CGPathRelease(mCGPath);
 }
 
 void
 PathBuilderCG::MoveTo(const Point &aPoint)
 {
-  CGPathMoveToPoint(mCGPath, NULL, aPoint.x, aPoint.y);
+  CGPathMoveToPoint(mCGPath, nullptr, aPoint.x, aPoint.y);
 }
 
 void
 PathBuilderCG::LineTo(const Point &aPoint)
 {
   if (CGPathIsEmpty(mCGPath))
     MoveTo(aPoint);
   else
-    CGPathAddLineToPoint(mCGPath, NULL, aPoint.x, aPoint.y);
+    CGPathAddLineToPoint(mCGPath, nullptr, aPoint.x, aPoint.y);
 }
 
 void
 PathBuilderCG::BezierTo(const Point &aCP1,
                          const Point &aCP2,
                          const Point &aCP3)
 {
 
   if (CGPathIsEmpty(mCGPath))
     MoveTo(aCP1);
-  CGPathAddCurveToPoint(mCGPath, NULL,
+  CGPathAddCurveToPoint(mCGPath, nullptr,
                           aCP1.x, aCP1.y,
                           aCP2.x, aCP2.y,
                           aCP3.x, aCP3.y);
 
 }
 
 void
 PathBuilderCG::QuadraticBezierTo(const Point &aCP1,
                                   const Point &aCP2)
 {
   if (CGPathIsEmpty(mCGPath))
     MoveTo(aCP1);
-  CGPathAddQuadCurveToPoint(mCGPath, NULL,
+  CGPathAddQuadCurveToPoint(mCGPath, nullptr,
                               aCP1.x, aCP1.y,
                               aCP2.x, aCP2.y);
 }
 
 void
 PathBuilderCG::Close()
 {
   if (!CGPathIsEmpty(mCGPath))
@@ -166,32 +166,32 @@ PathCG::ContainsPoint(const Point &aPoin
   Matrix inverse = aTransform;
   inverse.Invert();
   Point transformedPoint = inverse*aPoint;
   // We could probably drop the input transform and just transform the point at the caller?
   CGPoint point = {transformedPoint.x, transformedPoint.y};
 
   // The transform parameter of CGPathContainsPoint doesn't seem to work properly on OS X 10.5
   // so we transform aPoint ourselves.
-  return CGPathContainsPoint(mPath, NULL, point, mFillRule == FILL_EVEN_ODD);
+  return CGPathContainsPoint(mPath, nullptr, point, mFillRule == FILL_EVEN_ODD);
 }
 
 static size_t
 PutBytesNull(void *info, const void *buffer, size_t count)
 {
   return count;
 }
 
 /* The idea of a scratch context comes from WebKit */
 static CGContextRef
 CreateScratchContext()
 {
-  CGDataConsumerCallbacks callbacks = {PutBytesNull, NULL};
-  CGDataConsumerRef consumer = CGDataConsumerCreate(NULL, &callbacks);
-  CGContextRef cg = CGPDFContextCreate(consumer, NULL, NULL);
+  CGDataConsumerCallbacks callbacks = {PutBytesNull, nullptr};
+  CGDataConsumerRef consumer = CGDataConsumerCreate(nullptr, &callbacks);
+  CGContextRef cg = CGPDFContextCreate(consumer, nullptr, nullptr);
   CGDataConsumerRelease(consumer);
   return cg;
 }
 
 static CGContextRef
 ScratchContext()
 {
   static CGContextRef cg = CreateScratchContext();
--- a/gfx/2d/PathCairo.cpp
+++ b/gfx/2d/PathCairo.cpp
@@ -34,30 +34,30 @@ CairoPathContext::CairoPathContext(cairo
   } else if (mDrawTarget) {
     mDrawTarget->SetPathObserver(this);
   }
 }
 
 CairoPathContext::~CairoPathContext()
 {
   if (mDrawTarget) {
-    mDrawTarget->SetPathObserver(NULL);
+    mDrawTarget->SetPathObserver(nullptr);
   }
   cairo_destroy(mContext);
 }
 
 void
 CairoPathContext::ObserveTarget(DrawTargetCairo* aDrawTarget)
 {
   if (!aDrawTarget) {
     return;
   }
 
   if (mDrawTarget) {
-    mDrawTarget->SetPathObserver(NULL);
+    mDrawTarget->SetPathObserver(nullptr);
   }
   mDrawTarget = aDrawTarget;
 
   // If there is a transform on the path, then we must have a separate context
   // from the draw target, so we cannot be its observer
   if (!mTransform.IsIdentity()) {
     ForgetDrawTarget();
     return;
@@ -154,17 +154,17 @@ CairoPathContext::CopyPathTo(cairo_t* aT
 
     cairo_set_matrix(aToContext, &origMat);
   }
 }
 
 void
 CairoPathContext::ForgetDrawTarget()
 {
-  mDrawTarget = NULL;
+  mDrawTarget = nullptr;
 }
 
 bool
 CairoPathContext::ContainsPath(const Path* aPath)
 {
   if (aPath->GetBackendType() != BACKEND_CAIRO) {
     return false;
   }
--- a/gfx/2d/PathD2D.cpp
+++ b/gfx/2d/PathD2D.cpp
@@ -231,17 +231,17 @@ PathBuilderD2D::Finish()
 {
   if (mFigureActive) {
     mSink->EndFigure(D2D1_FIGURE_END_OPEN);
   }
 
   HRESULT hr = mSink->Close();
   if (FAILED(hr)) {
     gfxDebug() << "Failed to close PathSink. Code: " << hr;
-    return NULL;
+    return nullptr;
   }
 
   return new PathD2D(mGeometry, mFigureActive, mCurrentPoint, mFillRule);
 }
 
 TemporaryRef<PathBuilder>
 PathD2D::CopyToBuilder(FillRule aFillRule) const
 {
@@ -251,24 +251,24 @@ PathD2D::CopyToBuilder(FillRule aFillRul
 TemporaryRef<PathBuilder>
 PathD2D::TransformedCopyToBuilder(const Matrix &aTransform, FillRule aFillRule) const
 {
   RefPtr<ID2D1PathGeometry> path;
   HRESULT hr = DrawTargetD2D::factory()->CreatePathGeometry(byRef(path));
 
   if (FAILED(hr)) {
     gfxWarning() << "Failed to create PathGeometry. Code: " << hr;
-    return NULL;
+    return nullptr;
   }
 
   RefPtr<ID2D1GeometrySink> sink;
   hr = path->Open(byRef(sink));
   if (FAILED(hr)) {
     gfxWarning() << "Failed to open Geometry for writing. Code: " << hr;
-    return NULL;
+    return nullptr;
   }
 
   if (aFillRule == FILL_WINDING) {
     sink->SetFillMode(D2D1_FILL_MODE_WINDING);
   }
 
   if (mEndedActive) {
     OpeningGeometrySink wrapSink(sink);
--- a/gfx/2d/QuartzSupport.mm
+++ b/gfx/2d/QuartzSupport.mm
@@ -132,17 +132,17 @@ IOSurfaceGetHeightFunc        MacIOSurfa
 IOSurfaceGetWidthFunc         MacIOSurfaceLib::sHeight;
 IOSurfaceGetBytesPerRowFunc   MacIOSurfaceLib::sBytesPerRow;
 IOSurfaceLockFunc             MacIOSurfaceLib::sLock;
 IOSurfaceUnlockFunc           MacIOSurfaceLib::sUnlock;
 CGLTexImageIOSurface2DFunc    MacIOSurfaceLib::sTexImage;
 IOSurfaceContextCreateFunc    MacIOSurfaceLib::sIOSurfaceContextCreate;
 IOSurfaceContextCreateImageFunc   MacIOSurfaceLib::sIOSurfaceContextCreateImage;
 IOSurfaceContextGetSurfaceFunc    MacIOSurfaceLib::sIOSurfaceContextGetSurface;
-unsigned int                  (*MacIOSurfaceLib::sCGContextGetTypePtr) (CGContextRef) = NULL;
+unsigned int                  (*MacIOSurfaceLib::sCGContextGetTypePtr) (CGContextRef) = nullptr;
 
 CFStringRef                   MacIOSurfaceLib::kPropWidth;
 CFStringRef                   MacIOSurfaceLib::kPropHeight;
 CFStringRef                   MacIOSurfaceLib::kPropBytesPerElem;
 CFStringRef                   MacIOSurfaceLib::kPropBytesPerRow;
 CFStringRef                   MacIOSurfaceLib::kPropIsGlobal;
 
 bool MacIOSurfaceLib::isInit() {
@@ -203,29 +203,29 @@ CGLError MacIOSurfaceLib::CGLTexImageIOS
                    format, type, ioSurface, plane);
 }
 
 CGContextRef MacIOSurfaceLib::IOSurfaceContextCreate(IOSurfacePtr aIOSurfacePtr,
                              unsigned aWidth, unsigned aHeight,
                              unsigned aBitsPerComponent, unsigned aBytes,
                              CGColorSpaceRef aColorSpace, CGBitmapInfo bitmapInfo) {
   if (!sIOSurfaceContextCreate)
-    return NULL;
+    return nullptr;
   return sIOSurfaceContextCreate(aIOSurfacePtr, aWidth, aHeight, aBitsPerComponent, aBytes, aColorSpace, bitmapInfo);
 }
 
 CGImageRef MacIOSurfaceLib::IOSurfaceContextCreateImage(CGContextRef aContext) {
   if (!sIOSurfaceContextCreateImage)
-    return NULL;
+    return nullptr;
   return sIOSurfaceContextCreateImage(aContext);
 }
 
 IOSurfacePtr MacIOSurfaceLib::IOSurfaceContextGetSurface(CGContextRef aContext) {
   if (!sIOSurfaceContextGetSurface)
-    return NULL;
+    return nullptr;
   return sIOSurfaceContextGetSurface(aContext);
 }
 
 CFStringRef MacIOSurfaceLib::GetIOConst(const char* symbole) {
   CFStringRef *address = (CFStringRef*)dlsym(sIOSurfaceFramework, symbole);
   if (!address)
     return nullptr;
 
@@ -309,19 +309,19 @@ TemporaryRef<MacIOSurface> MacIOSurface:
   CFMutableDictionaryRef props = ::CFDictionaryCreateMutable(
                       kCFAllocatorDefault, 4,
                       &kCFTypeDictionaryKeyCallBacks,
                       &kCFTypeDictionaryValueCallBacks);
   if (!props)
     return nullptr;
 
   int32_t bytesPerElem = 4;
-  CFNumberRef cfWidth = ::CFNumberCreate(NULL, kCFNumberSInt32Type, &aWidth);
-  CFNumberRef cfHeight = ::CFNumberCreate(NULL, kCFNumberSInt32Type, &aHeight);
-  CFNumberRef cfBytesPerElem = ::CFNumberCreate(NULL, kCFNumberSInt32Type, &bytesPerElem);
+  CFNumberRef cfWidth = ::CFNumberCreate(nullptr, kCFNumberSInt32Type, &aWidth);
+  CFNumberRef cfHeight = ::CFNumberCreate(nullptr, kCFNumberSInt32Type, &aHeight);
+  CFNumberRef cfBytesPerElem = ::CFNumberCreate(nullptr, kCFNumberSInt32Type, &bytesPerElem);
   ::CFDictionaryAddValue(props, MacIOSurfaceLib::kPropWidth,
                                 cfWidth);
   ::CFRelease(cfWidth);
   ::CFDictionaryAddValue(props, MacIOSurfaceLib::kPropHeight,
                                 cfHeight);
   ::CFRelease(cfHeight);
   ::CFDictionaryAddValue(props, MacIOSurfaceLib::kPropBytesPerElem, 
                                 cfBytesPerElem);
@@ -377,21 +377,21 @@ size_t MacIOSurface::GetHeight() {
 }
 
 size_t MacIOSurface::GetBytesPerRow() { 
   return MacIOSurfaceLib::IOSurfaceGetBytesPerRow(mIOSurfacePtr);
 }
 
 #define READ_ONLY 0x1
 void MacIOSurface::Lock() {
-  MacIOSurfaceLib::IOSurfaceLock(mIOSurfacePtr, READ_ONLY, NULL);
+  MacIOSurfaceLib::IOSurfaceLock(mIOSurfacePtr, READ_ONLY, nullptr);
 }
 
 void MacIOSurface::Unlock() {
-  MacIOSurfaceLib::IOSurfaceUnlock(mIOSurfacePtr, READ_ONLY, NULL);
+  MacIOSurfaceLib::IOSurfaceUnlock(mIOSurfacePtr, READ_ONLY, nullptr);
 }
 
 #include "SourceSurfaceRawData.h"
 using mozilla::gfx::SourceSurface;
 using mozilla::gfx::SourceSurfaceRawData;
 using mozilla::gfx::IntSize;
 
 TemporaryRef<SourceSurface>
@@ -585,17 +585,17 @@ nsresult nsCARenderer::SetupRenderer(voi
       Destroy();
       return NS_ERROR_FAILURE;
     }
 
     CGColorSpaceRef colorSpace = CreateSystemColorSpace();
 
     mCGImage = ::CGImageCreate(aWidth, aHeight, 8, 32, aWidth * 4, colorSpace,
                 kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Host,
-                dataProvider, NULL, true, kCGRenderingIntentDefault);
+                dataProvider, nullptr, true, kCGRenderingIntentDefault);
 
     ::CGDataProviderRelease(dataProvider);
     if (colorSpace) {
       ::CGColorSpaceRelease(colorSpace);
     }
     if (!mCGImage) {
       mUnsupportedWidth = aWidth;
       mUnsupportedHeight = aHeight;
@@ -758,18 +758,18 @@ IOSurfaceID nsCARenderer::GetIOSurfaceID
 }
 
 nsresult nsCARenderer::Render(int aWidth, int aHeight, 
                               CGImageRef *aOutCGImage) {
   if (!aOutCGImage && !mIOSurface) {
     NS_ERROR("No target destination for rendering");
   } else if (aOutCGImage) {
     // We are expected to return a CGImageRef, we will set
-    // it to NULL in case we fail before the image is ready.
-    *aOutCGImage = NULL;
+    // it to nullptr in case we fail before the image is ready.
+    *aOutCGImage = nullptr;
   }
 
   if (aWidth == 0 || aHeight == 0)
     return NS_OK;
 
   if (!mCARenderer) {
     return NS_ERROR_FAILURE;
   }
@@ -808,17 +808,17 @@ nsresult nsCARenderer::Render(int aWidth
     return NS_ERROR_FAILURE;
   }
 
   ::glClearColor(0.0, 0.0, 0.0, 0.0);
   ::glClear(GL_COLOR_BUFFER_BIT);
 
   [CATransaction commit];
   double caTime = ::CACurrentMediaTime();
-  [caRenderer beginFrameAtTime:caTime timeStamp:NULL];
+  [caRenderer beginFrameAtTime:caTime timeStamp:nullptr];
   [caRenderer addUpdateRect:CGRectMake(0,0, aWidth, aHeight)];
   [caRenderer render];
   [caRenderer endFrame];
 
   // Read the data back either to the IOSurface or mCGImage.
   if (mIOSurface) {
     ::glFlush();
   } else {
@@ -862,25 +862,25 @@ nsresult nsCARenderer::DrawSurfaceToCGCo
       aY < 0 || aY >= ioHeight) {
     surf->Unlock();
     return NS_ERROR_FAILURE;
   }
 
   void* ioData = surf->GetBaseAddress();
   CGDataProviderRef dataProvider = ::CGDataProviderCreateWithData(ioData,
                                       ioData, ioHeight*(bytesPerRow)*4, 
-                                      NULL); //No release callback 
+                                      nullptr); //No release callback 
   if (!dataProvider) {
     surf->Unlock();
     return NS_ERROR_FAILURE;
   }
 
   CGImageRef cgImage = ::CGImageCreate(ioWidth, ioHeight, 8, 32, bytesPerRow,
               aColorSpace, kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Host,
-              dataProvider, NULL, true, kCGRenderingIntentDefault);
+              dataProvider, nullptr, true, kCGRenderingIntentDefault);
   ::CGDataProviderRelease(dataProvider);
   if (!cgImage) {
     surf->Unlock();
     return NS_ERROR_FAILURE;
   }
   CGImageRef subImage = ::CGImageCreateWithImageInRect(cgImage,
                                        ::CGRectMake(aX, aY, aWidth, aHeight));
   if (!subImage) {
@@ -920,50 +920,50 @@ int sSaveToDiskSequence = 0;
 void nsCARenderer::SaveToDisk(MacIOSurface *surf) {
   surf->Lock();
   size_t bytesPerRow = surf->GetBytesPerRow();
   size_t ioWidth = surf->GetWidth();
   size_t ioHeight = surf->GetHeight();
   void* ioData = surf->GetBaseAddress();
   CGDataProviderRef dataProvider = ::CGDataProviderCreateWithData(ioData,
                                       ioData, ioHeight*(bytesPerRow)*4, 
-                                      NULL); //No release callback 
+                                      nullptr); //No release callback 
   if (!dataProvider) {
     surf->Unlock();
     return;
   }
 
   CGColorSpaceRef colorSpace = CreateSystemColorSpace();
   CGImageRef cgImage = ::CGImageCreate(ioWidth, ioHeight, 8, 32, bytesPerRow,
               colorSpace, kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Host,
-              dataProvider, NULL, true, kCGRenderingIntentDefault);
+              dataProvider, nullptr, true, kCGRenderingIntentDefault);
   ::CGDataProviderRelease(dataProvider);
   ::CGColorSpaceRelease(colorSpace);
   if (!cgImage) {
     surf->Unlock();
     return;
   }
 
   char cstr[1000];
 
   sprintf(cstr, "file:///Users/benoitgirard/debug/iosurface_%i.png", ++sSaveToDiskSequence);
 
   CFStringRef cfStr = ::CFStringCreateWithCString(kCFAllocatorDefault, cstr, kCFStringEncodingMacRoman);
 
   printf("Exporting: %s\n", cstr);
-  CFURLRef url = ::CFURLCreateWithString( NULL, cfStr, NULL);
+  CFURLRef url = ::CFURLCreateWithString( nullptr, cfStr, nullptr);
   ::CFRelease(cfStr);
 
   CFStringRef type = kUTTypePNG;
   size_t count = 1;
-  CFDictionaryRef options = NULL;
+  CFDictionaryRef options = nullptr;
   CGImageDestinationRef dest = ::CGImageDestinationCreateWithURL(url, type, count, options);
   ::CFRelease(url);
 
-  ::CGImageDestinationAddImage(dest, cgImage, NULL);
+  ::CGImageDestinationAddImage(dest, cgImage, nullptr);
 
   ::CGImageDestinationFinalize(dest);
   ::CFRelease(dest);
   ::CGImageRelease(cgImage);
 
   surf->Unlock();
 
   return;
--- a/gfx/2d/ScaledFontBase.cpp
+++ b/gfx/2d/ScaledFontBase.cpp
@@ -32,20 +32,20 @@ ScaledFontBase::~ScaledFontBase()
   cairo_scaled_font_destroy(mScaledFont);
 #endif
 }
 
 ScaledFontBase::ScaledFontBase(Float aSize)
   : mSize(aSize)
 {
 #ifdef USE_SKIA
-  mTypeface = NULL;
+  mTypeface = nullptr;
 #endif
 #ifdef USE_CAIRO
-  mScaledFont = NULL;
+  mScaledFont = nullptr;
 #endif
 }
 
 TemporaryRef<Path>
 ScaledFontBase::GetPathForGlyphs(const GlyphBuffer &aBuffer, const DrawTarget *aTarget)
 {
 #ifdef USE_SKIA
   if (aTarget->GetType() == BACKEND_SKIA) {
@@ -90,17 +90,17 @@ ScaledFontBase::GetPathForGlyphs(const G
       glyphs[i].y = aBuffer.mGlyphs[i].mPosition.y;
     }
 
     cairo_glyph_path(*context, &glyphs[0], aBuffer.mNumGlyphs);
 
     return builder->Finish();
   }
 #endif
-  return NULL;
+  return nullptr;
 }
 
 void
 ScaledFontBase::CopyGlyphsToBuilder(const GlyphBuffer &aBuffer, PathBuilder *aBuilder)
 {
   // XXX - implement me
   MOZ_ASSERT(false);
   return;
--- a/gfx/2d/ScaledFontDWrite.cpp
+++ b/gfx/2d/ScaledFontDWrite.cpp
@@ -13,17 +13,17 @@ namespace mozilla {
 namespace gfx {
 
 TemporaryRef<Path>
 ScaledFontDWrite::GetPathForGlyphs(const GlyphBuffer &aBuffer, const DrawTarget *aTarget)
 {
   if (aTarget->GetType() != BACKEND_DIRECT2D) {
     // For now we only support Direct2D.
     gfxWarning() << "Attempt to use Direct Write font with non-Direct2D backend";
-    return NULL;
+    return nullptr;
   }
 
   RefPtr<PathBuilder> pathBuilder = aTarget->CreatePathBuilder();
 
   PathBuilderD2D *pathBuilderD2D =
     static_cast<PathBuilderD2D*>(pathBuilder.get());
 
   CopyGlyphsToSink(aBuffer, pathBuilderD2D->GetSink());
--- a/gfx/2d/ScaledFontMac.cpp
+++ b/gfx/2d/ScaledFontMac.cpp
@@ -33,17 +33,17 @@ ScaledFontMac::~ScaledFontMac()
 {
   CGFontRelease(mFont);
 }
 
 #ifdef USE_SKIA
 SkTypeface* ScaledFontMac::GetSkTypeface()
 {
   if (!mTypeface) {
-    CTFontRef fontFace = CTFontCreateWithGraphicsFont(mFont, mSize, NULL, NULL);
+    CTFontRef fontFace = CTFontCreateWithGraphicsFont(mFont, mSize, nullptr, nullptr);
     mTypeface = SkCreateTypefaceFromCTFont(fontFace);
     CFRelease(fontFace);
   }
   return mTypeface;
 }
 #endif
 
 // private API here are the public options on OS X
--- a/gfx/2d/SourceSurfaceCG.cpp
+++ b/gfx/2d/SourceSurfaceCG.cpp
@@ -48,19 +48,19 @@ static void releaseCallback(void *info, 
 
 bool
 SourceSurfaceCG::InitFromData(unsigned char *aData,
                                const IntSize &aSize,
                                int32_t aStride,
                                SurfaceFormat aFormat)
 {
   //XXX: we should avoid creating this colorspace everytime
-  CGColorSpaceRef colorSpace = NULL;
+  CGColorSpaceRef colorSpace = nullptr;
   CGBitmapInfo bitinfo = 0;
-  CGDataProviderRef dataProvider = NULL;
+  CGDataProviderRef dataProvider = nullptr;
   int bitsPerComponent = 0;
   int bitsPerPixel = 0;
 
   assert(aSize.width >= 0 && aSize.height >= 0);
 
   switch (aFormat) {
     case FORMAT_B8G8R8A8:
       colorSpace = CGColorSpaceCreateDeviceRGB();
@@ -105,25 +105,25 @@ SourceSurfaceCG::InitFromData(unsigned c
   } else {
     mImage = CGImageCreate (aSize.width, aSize.height,
 			    bitsPerComponent,
 			    bitsPerPixel,
 			    aStride,
 			    colorSpace,
 			    bitinfo,
 			    dataProvider,
-			    NULL,
+			    nullptr,
 			    true,
 			    kCGRenderingIntentDefault);
   }
 
   CGDataProviderRelease(dataProvider);
   CGColorSpaceRelease (colorSpace);
 
-  return mImage != NULL;
+  return mImage != nullptr;
 }
 
 DataSourceSurfaceCG::~DataSourceSurfaceCG()
 {
   CGImageRelease(mImage);
   free(CGBitmapContextGetData(mCg));
   CGContextRelease(mCg);
 }
@@ -139,19 +139,19 @@ DataSourceSurfaceCG::GetSize() const
 
 bool
 DataSourceSurfaceCG::InitFromData(unsigned char *aData,
                                const IntSize &aSize,
                                int32_t aStride,
                                SurfaceFormat aFormat)
 {
   //XXX: we should avoid creating this colorspace everytime
-  CGColorSpaceRef colorSpace = NULL;
+  CGColorSpaceRef colorSpace = nullptr;
   CGBitmapInfo bitinfo = 0;
-  CGDataProviderRef dataProvider = NULL;
+  CGDataProviderRef dataProvider = nullptr;
   int bitsPerComponent = 0;
   int bitsPerPixel = 0;
 
   switch (aFormat) {
     case FORMAT_B8G8R8A8:
       colorSpace = CGColorSpaceCreateDeviceRGB();
       bitinfo = kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Host;
       bitsPerComponent = 8;
@@ -194,17 +194,17 @@ DataSourceSurfaceCG::InitFromData(unsign
   } else {
     mImage = CGImageCreate (aSize.width, aSize.height,
 			    bitsPerComponent,
 			    bitsPerPixel,
 			    aStride,
 			    colorSpace,
 			    bitinfo,
 			    dataProvider,
-			    NULL,
+			    nullptr,
 			    true,
 			    kCGRenderingIntentDefault);
   }
 
   CGDataProviderRelease(dataProvider);
   CGColorSpaceRelease (colorSpace);
 
   return mImage;
@@ -220,20 +220,20 @@ CGContextRef CreateBitmapContextForImage
   int bitmapBytesPerRow = (width * 4);
   int bitmapByteCount   = (bitmapBytesPerRow * height);
 
   void *data = calloc(bitmapByteCount, 1);
   //XXX: which color space should we be using here?
   colorSpace = CGColorSpaceCreateDeviceRGB();
   assert(colorSpace);
 
-  // we'd like to pass NULL as the first parameter
+  // we'd like to pass nullptr as the first parameter
   // to let Quartz manage this memory for us. However,
   // on 10.5 and older CGBitmapContextGetData will return
-  // NULL instead of the associated buffer so we need
+  // nullptr instead of the associated buffer so we need
   // to manage it ourselves.
   CGContextRef cg = CGBitmapContextCreate(data,
                                           width,
                                           height,
                                           8,
                                           bitmapBytesPerRow,
                                           colorSpace,
                                           kCGBitmapByteOrder32Host | kCGImageAlphaPremultipliedFirst);
@@ -243,17 +243,17 @@ CGContextRef CreateBitmapContextForImage
 
   return cg;
 }
 
 DataSourceSurfaceCG::DataSourceSurfaceCG(CGImageRef aImage)
 {
   mImage = aImage;
   mCg = CreateBitmapContextForImage(aImage);
-  if (mCg == NULL) {
+  if (mCg == nullptr) {
     // error creating context
     return;
   }
 
   // Get image width, height. We'll use the entire image.
   CGFloat w = CGImageGetWidth(aImage);
   CGFloat h = CGImageGetHeight(aImage);
   CGRect rect = {{0,0},{w,h}};
@@ -290,45 +290,45 @@ SourceSurfaceCGBitmapContext::SourceSurf
   if (!mCg)
     abort();
 
   mSize.width = CGBitmapContextGetWidth(mCg);
   mSize.height = CGBitmapContextGetHeight(mCg);
   mStride = CGBitmapContextGetBytesPerRow(mCg);
   mData = CGBitmapContextGetData(mCg);
 
-  mImage = NULL;
+  mImage = nullptr;
 }
 
 void SourceSurfaceCGBitmapContext::EnsureImage() const
 {
   // Instead of using CGBitmapContextCreateImage we create
   // a CGImage around the data associated with the CGBitmapContext
   // we do this to avoid the vm_copy that CGBitmapContextCreateImage.
   // vm_copy tends to cause all sorts of unexpected performance problems
   // because of the mm tricks that vm_copy does. Using a regular
   // memcpy when the bitmap context is modified gives us more predictable
   // performance characteristics.
   if (!mImage) {
       //XXX: we should avoid creating this colorspace everytime
-      CGColorSpaceRef colorSpace = NULL;
+      CGColorSpaceRef colorSpace = nullptr;
       CGBitmapInfo bitinfo = 0;
-      CGDataProviderRef dataProvider = NULL;
+      CGDataProviderRef dataProvider = nullptr;
       int bitsPerComponent = 8;
       int bitsPerPixel = 32;
 
       colorSpace = CGColorSpaceCreateDeviceRGB();
       bitinfo = kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Host;
 
       void *info;
       if (mCg) {
           // if we have an mCg than it owns the data
           // and we don't want to tranfer ownership
           // to the CGDataProviderCreateWithData
-          info = NULL;
+          info = nullptr;
       } else {
           // otherwise we transfer ownership to
           // the dataProvider
           info = mData;
       }
 
       if (!mData) abort();
 
@@ -339,17 +339,17 @@ void SourceSurfaceCGBitmapContext::Ensur
 
       mImage = CGImageCreate (mSize.width, mSize.height,
                               bitsPerComponent,
                               bitsPerPixel,
                               mStride,
                               colorSpace,
                               bitinfo,
                               dataProvider,
-                              NULL,
+                              nullptr,
                               true,
                               kCGRenderingIntentDefault);
 
       CGDataProviderRelease(dataProvider);
       CGColorSpaceRelease (colorSpace);
   }
 }
 
@@ -373,20 +373,20 @@ SourceSurfaceCGBitmapContext::DrawTarget
     // copy out the data from the CGBitmapContext
     // we'll maintain ownership of mData until
     // we transfer it to mImage
     memcpy(mData, CGBitmapContextGetData(mCg), stride*height);
 
     // drop the current image for the data associated with the CGBitmapContext
     if (mImage)
       CGImageRelease(mImage);
-    mImage = NULL;
+    mImage = nullptr;
 
-    mCg = NULL;
-    mDrawTarget = NULL;
+    mCg = nullptr;
+    mDrawTarget = nullptr;
   }
 }
 
 SourceSurfaceCGBitmapContext::~SourceSurfaceCGBitmapContext()
 {
   if (!mImage && !mCg) {
     // neither mImage or mCg owns the data
     free(mData);
@@ -401,17 +401,17 @@ SourceSurfaceCGIOSurfaceContext::SourceS
 
   RefPtr<MacIOSurface> surf = MacIOSurface::IOSurfaceContextGetSurface(cg);
 
   mSize.width = surf->GetWidth();
   mSize.height = surf->GetHeight();
 
   // TODO use CreateImageFromIOSurfaceContext instead of reading back the surface
   //mImage = MacIOSurface::CreateImageFromIOSurfaceContext(cg);
-  mImage = NULL;
+  mImage = nullptr;
 
   aDrawTarget->Flush();
   surf->Lock();
   size_t bytesPerRow = surf->GetBytesPerRow();
   size_t ioHeight = surf->GetHeight();
   void* ioData = surf->GetBaseAddress();
   // XXX If the width is much less then the stride maybe
   //     we should repack the image?
@@ -429,19 +429,19 @@ void SourceSurfaceCGIOSurfaceContext::En
   // a CGImage around the data associated with the CGBitmapContext
   // we do this to avoid the vm_copy that CGBitmapContextCreateImage.
   // vm_copy tends to cause all sorts of unexpected performance problems
   // because of the mm tricks that vm_copy does. Using a regular
   // memcpy when the bitmap context is modified gives us more predictable
   // performance characteristics.
   if (!mImage) {
       //XXX: we should avoid creating this colorspace everytime
-      CGColorSpaceRef colorSpace = NULL;
+      CGColorSpaceRef colorSpace = nullptr;
       CGBitmapInfo bitinfo = 0;
-      CGDataProviderRef dataProvider = NULL;
+      CGDataProviderRef dataProvider = nullptr;
       int bitsPerComponent = 8;
       int bitsPerPixel = 32;
 
       colorSpace = CGColorSpaceCreateDeviceRGB();
       bitinfo = kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Host;
 
       void *info = mData;
 
@@ -452,17 +452,17 @@ void SourceSurfaceCGIOSurfaceContext::En
 
       mImage = CGImageCreate (mSize.width, mSize.height,
                               bitsPerComponent,
                               bitsPerPixel,
                               mStride,
                               colorSpace,
                               bitinfo,
                               dataProvider,
-                              NULL,
+                              nullptr,
                               true,
                               kCGRenderingIntentDefault);
 
       CGDataProviderRelease(dataProvider);
       CGColorSpaceRelease (colorSpace);
   }
 
 }
--- a/gfx/2d/SourceSurfaceCairo.cpp
+++ b/gfx/2d/SourceSurfaceCairo.cpp
@@ -26,17 +26,17 @@ CairoFormatToSurfaceFormat(cairo_format_
     default:
       return FORMAT_B8G8R8A8;
   }
 }
 
 SourceSurfaceCairo::SourceSurfaceCairo(cairo_surface_t* aSurface,
                                        const IntSize& aSize,
                                        const SurfaceFormat& aFormat,
-                                       DrawTargetCairo* aDrawTarget /* = NULL */)
+                                       DrawTargetCairo* aDrawTarget /* = nullptr */)
  : mSize(aSize)
  , mFormat(aFormat)
  , mSurface(aSurface)
  , mDrawTarget(aDrawTarget)
 {
   cairo_surface_reference(mSurface);
 }
 
@@ -87,17 +87,17 @@ SourceSurfaceCairo::GetSurface() const
 {
   return mSurface;
 }
 
 void
 SourceSurfaceCairo::DrawTargetWillChange()
 {
   if (mDrawTarget) {
-    mDrawTarget = NULL;
+    mDrawTarget = nullptr;
 
     // We're about to lose our version of the surface, so make a copy of it.
     cairo_surface_t* surface = cairo_surface_create_similar(mSurface,
                                                             GfxFormatToCairoContent(mFormat),
                                                             mSize.width, mSize.height);
     cairo_t* ctx = cairo_create(surface);
     cairo_pattern_t* pat = cairo_pattern_create_for_surface(mSurface);
     cairo_set_source(ctx, pat);
@@ -111,17 +111,17 @@ SourceSurfaceCairo::DrawTargetWillChange
   }
 }
 
 void
 SourceSurfaceCairo::MarkIndependent()
 {
   if (mDrawTarget) {
     mDrawTarget->RemoveSnapshot(this);
-    mDrawTarget = NULL;
+    mDrawTarget = nullptr;
   }
 }
 
 DataSourceSurfaceCairo::DataSourceSurfaceCairo(cairo_surface_t* imageSurf)
  : mImageSurface(imageSurf)
 {
   cairo_surface_reference(mImageSurface);
 }
--- a/gfx/2d/SourceSurfaceCairo.h
+++ b/gfx/2d/SourceSurfaceCairo.h
@@ -13,22 +13,22 @@ namespace gfx {
 
 class DrawTargetCairo;
 
 class SourceSurfaceCairo : public SourceSurface
 {
 public:
   // Create a SourceSurfaceCairo. The surface will not be copied, but simply
   // referenced.
-  // If aDrawTarget is non-NULL, it is assumed that this is a snapshot source
+  // If aDrawTarget is non-nullptr, it is assumed that this is a snapshot source
   // surface, and we'll call DrawTargetCairo::RemoveSnapshot(this) on it when
   // we're destroyed.
   SourceSurfaceCairo(cairo_surface_t* aSurface, const IntSize& aSize,
                      const SurfaceFormat& aFormat,
-                     DrawTargetCairo* aDrawTarget = NULL);
+                     DrawTargetCairo* aDrawTarget = nullptr);
   virtual ~SourceSurfaceCairo();
 
   virtual SurfaceType GetType() const { return SURFACE_CAIRO; }
   virtual IntSize GetSize() const;
   virtual SurfaceFormat GetFormat() const;
   virtual TemporaryRef<DataSourceSurface> GetDataSurface();
 
   cairo_surface_t* GetSurface() const;
--- a/gfx/2d/SourceSurfaceD2D.cpp
+++ b/gfx/2d/SourceSurfaceD2D.cpp
@@ -38,17 +38,17 @@ bool
 SourceSurfaceD2D::IsValid() const
 {
   return mDevice == Factory::GetDirect3D10Device();
 }
 
 TemporaryRef<DataSourceSurface>
 SourceSurfaceD2D::GetDataSurface()
 {
-  return NULL;
+  return nullptr;
 }
 
 bool
 SourceSurfaceD2D::InitFromData(unsigned char *aData,
                                const IntSize &aSize,
                                int32_t aStride,
                                SurfaceFormat aFormat,
                                ID2D1RenderTarget *aRT)
--- a/gfx/2d/SourceSurfaceD2DTarget.cpp
+++ b/gfx/2d/SourceSurfaceD2DTarget.cpp
@@ -59,35 +59,35 @@ SourceSurfaceD2DTarget::GetDataSurface()
   D3D10_TEXTURE2D_DESC desc;
   mTexture->GetDesc(&desc);
 
   desc.CPUAccessFlags = D3D10_CPU_ACCESS_READ;
   desc.Usage = D3D10_USAGE_STAGING;
   desc.BindFlags = 0;
   desc.MiscFlags = 0;
 
-  HRESULT hr = Factory::GetDirect3D10Device()->CreateTexture2D(&desc, NULL, byRef(dataSurf->mTexture));
+  HRESULT hr = Factory::GetDirect3D10Device()->CreateTexture2D(&desc, nullptr, byRef(dataSurf->mTexture));
 
   if (FAILED(hr)) {
     gfxDebug() << "Failed to create staging texture for SourceSurface. Code: " << hr;
-    return NULL;
+    return nullptr;
   }
   Factory::GetDirect3D10Device()->CopyResource(dataSurf->mTexture, mTexture);
 
   return dataSurf;
 }
 
 ID3D10ShaderResourceView*
 SourceSurfaceD2DTarget::GetSRView()
 {
   if (mSRView) {
     return mSRView;
   }
 
-  HRESULT hr = Factory::GetDirect3D10Device()->CreateShaderResourceView(mTexture, NULL, byRef(mSRView));
+  HRESULT hr = Factory::GetDirect3D10Device()->CreateShaderResourceView(mTexture, nullptr, byRef(mSRView));
 
   if (FAILED(hr)) {
     gfxWarning() << "Failed to create ShaderResourceView. Code: " << hr;
   }
 
   return mSRView;
 }
 
@@ -95,20 +95,20 @@ void
 SourceSurfaceD2DTarget::DrawTargetWillChange()
 {
   RefPtr<ID3D10Texture2D> oldTexture = mTexture;
 
   D3D10_TEXTURE2D_DESC desc;
   mTexture->GetDesc(&desc);
 
   // Get a copy of the surface data so the content at snapshot time was saved.
-  Factory::GetDirect3D10Device()->CreateTexture2D(&desc, NULL, byRef(mTexture));
+  Factory::GetDirect3D10Device()->CreateTexture2D(&desc, nullptr, byRef(mTexture));
   Factory::GetDirect3D10Device()->CopyResource(mTexture, oldTexture);
 
-  mBitmap = NULL;
+  mBitmap = nullptr;
 
   DrawTargetD2D::mVRAMUsageSS += desc.Width * desc.Height * BytesPerPixel(mFormat);
   mOwnsCopy = true;
 
   // We now no longer depend on the source surface content remaining the same.
   MarkIndependent();
 }
 
@@ -125,17 +125,17 @@ SourceSurfaceD2DTarget::GetBitmap(ID2D1R
 
   IntSize size(desc.Width, desc.Height);
   
   RefPtr<IDXGISurface> surf;
   hr = mTexture->QueryInterface((IDXGISurface**)byRef(surf));
 
   if (FAILED(hr)) {
     gfxWarning() << "Failed to query interface texture to DXGISurface. Code: " << hr;
-    return NULL;
+    return nullptr;
   }
 
   D2D1_BITMAP_PROPERTIES props =
     D2D1::BitmapProperties(D2D1::PixelFormat(DXGIFormat(mFormat), AlphaMode(mFormat)));
   hr = aRT->CreateSharedBitmap(IID_IDXGISurface, surf, &props, byRef(mBitmap));
 
   if (FAILED(hr)) {
     // This seems to happen for FORMAT_A8 sometimes...
@@ -155,43 +155,43 @@ SourceSurfaceD2DTarget::GetBitmap(ID2D1R
       // surface the only way we can get to a bitmap is by creating a
       // a rendertarget and from there copying to a bitmap! Terrible!
       RefPtr<IDXGISurface> surface;
 
       hr = mTexture->QueryInterface((IDXGISurface**)byRef(surface));
 
       if (FAILED(hr)) {
         gfxWarning() << "Failed to QI texture to surface.";
-        return NULL;
+        return nullptr;
       }
 
       D2D1_RENDER_TARGET_PROPERTIES props =
         D2D1::RenderTargetProperties(D2D1_RENDER_TARGET_TYPE_DEFAULT, D2D1::PixelFormat(DXGIFormat(mFormat), AlphaMode(mFormat)));
       hr = DrawTargetD2D::factory()->CreateDxgiSurfaceRenderTarget(surface, props, byRef(rt));
 
       if (FAILED(hr)) {
         gfxWarning() << "Failed to create D2D render target for texture.";
-        return NULL;
+        return nullptr;
       }
     }
 
-    mBitmap->CopyFromRenderTarget(NULL, rt, NULL);
+    mBitmap->CopyFromRenderTarget(nullptr, rt, nullptr);
     return mBitmap;
   }
 
   return mBitmap;
 }
 
 void
 SourceSurfaceD2DTarget::MarkIndependent()
 {
   if (mDrawTarget) {
     MOZ_ASSERT(mDrawTarget->mSnapshot == this);
-    mDrawTarget->mSnapshot = NULL;
-    mDrawTarget = NULL;
+    mDrawTarget->mSnapshot = nullptr;
+    mDrawTarget = nullptr;
   }
 }
 
 DataSourceSurfaceD2DTarget::DataSourceSurfaceD2DTarget()
   : mFormat(FORMAT_B8G8R8A8)
   , mMapped(false)
 {
 }
--- a/gfx/2d/SourceSurfaceDual.h
+++ b/gfx/2d/SourceSurfaceDual.h
@@ -22,17 +22,17 @@ public:
     , mB(aDTB->Snapshot())
   { }
 
   virtual SurfaceType GetType() const { return SURFACE_DUAL_DT; }
   virtual IntSize GetSize() const { return mA->GetSize(); }
   virtual SurfaceFormat GetFormat() const { return mA->GetFormat(); }
 
   /* Readback from this surface type is not supported! */
-  virtual TemporaryRef<DataSourceSurface> GetDataSurface() { return NULL; }
+  virtual TemporaryRef<DataSourceSurface> GetDataSurface() { return nullptr; }
 private:
   friend class DualSurface;
   friend class DualPattern;
 
   RefPtr<SourceSurface> mA;
   RefPtr<SourceSurface> mB;
 };
 
--- a/gfx/2d/SourceSurfaceSkia.cpp
+++ b/gfx/2d/SourceSurfaceSkia.cpp
@@ -10,17 +10,17 @@
 #include "skia/SkDevice.h"
 #include "HelpersSkia.h"
 #include "DrawTargetSkia.h"
 
 namespace mozilla {
 namespace gfx {
 
 SourceSurfaceSkia::SourceSurfaceSkia()
-  : mDrawTarget(NULL)
+  : mDrawTarget(nullptr)
 {
 }
 
 SourceSurfaceSkia::~SourceSurfaceSkia()
 {
   MarkIndependent();
 }
 
@@ -85,32 +85,32 @@ SourceSurfaceSkia::GetData()
   return pixels;
 
 }
 
 void
 SourceSurfaceSkia::DrawTargetWillChange()
 {
   if (mDrawTarget) {
-    mDrawTarget = NULL;
+    mDrawTarget = nullptr;
     SkBitmap temp = mBitmap;
     mBitmap.reset();
     temp.copyTo(&mBitmap, temp.getConfig());
   }
 }
 
 void
 SourceSurfaceSkia::DrawTargetDestroyed()
 {
-  mDrawTarget = NULL;
+  mDrawTarget = nullptr;
 }
 
 void
 SourceSurfaceSkia::MarkIndependent()
 {
   if (mDrawTarget) {
     mDrawTarget->RemoveSnapshot(this);
-    mDrawTarget = NULL;
+    mDrawTarget = nullptr;
   }
 }
 
 }
 }
--- a/gfx/2d/SourceSurfaceSkia.h
+++ b/gfx/2d/SourceSurfaceSkia.h
@@ -29,17 +29,17 @@ public:
   SkBitmap& GetBitmap() { return mBitmap; }
 
   bool InitFromData(unsigned char* aData,
                     const IntSize &aSize,
                     int32_t aStride,
                     SurfaceFormat aFormat);
 
   /**
-   * If aOwner is NULL, we make a copy of the pixel data in the bitmap, 
+   * If aOwner is nullptr, we make a copy of the pixel data in the bitmap, 
    * otherwise we just reference this data until DrawTargetWillChange is called.
    */
   bool InitWithBitmap(const SkBitmap& aBitmap,
                       SurfaceFormat aFormat,
                       DrawTargetSkia* aOwner);
 
 
   virtual unsigned char *GetData();
--- a/gfx/2d/Types.h
+++ b/gfx/2d/Types.h
@@ -1,16 +1,33 @@
 /* -*- Mode: C++; tab-width: 20; 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/. */
 
 #ifndef MOZILLA_GFX_TYPES_H_
 #define MOZILLA_GFX_TYPES_H_
 
+/**
+ * Use C++11 nullptr if available; otherwise use a C++ typesafe template; and
+ * for C, fall back to longs.  See bugs 547964 and 626472.
+ * Copy and paste job from nscore.h, see bug 781943
+ */
+#if defined(MOZ_GFX) && !defined(HAVE_NULLPTR)
+#ifndef __cplusplus
+# define nullptr ((void*)0)
+#elif defined(__GNUC__)
+# define nullptr __null
+#elif defined(_WIN64)
+# define nullptr 0LL
+#else
+# define nullptr 0L
+#endif
+#endif /* defined(MOZ_GFX) && !defined(HAVE_NULLPTR) */
+
 #include "mozilla/StandardInteger.h"
 
 #include <stddef.h>
 
 namespace mozilla {
 namespace gfx {
 
 typedef float Float;
--- a/gfx/2d/UserData.h
+++ b/gfx/2d/UserData.h
@@ -2,31 +2,32 @@
  * 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_GFX_USERDATA_H_
 #define MOZILLA_GFX_USERDATA_H_
 
 #include <stdlib.h>
+#include "Types.h"
 #include "mozilla/Assertions.h"
 
 namespace mozilla {
 namespace gfx {
 
 struct UserDataKey {
   int unused;
 };
 
 /* this class is basically a clone of the user data concept from cairo */
 class UserData
 {
   typedef void (*destroyFunc)(void *data);
 public:
-  UserData() : count(0), entries(NULL) {}
+  UserData() : count(0), entries(nullptr) {}
 
   /* Attaches untyped userData associated with key. destroy is called on destruction */
   void Add(UserDataKey *key, void *userData, destroyFunc destroy)
   {
     for (int i=0; i<count; i++) {
       if (key == entries[i].key) {
         if (entries[i].destroy) {
           entries[i].destroy(entries[i].userData);
@@ -63,28 +64,28 @@ public:
         // decrement before looping so entries[i+1] doesn't read past the end:
         --count;
         for (;i<count; i++) {
           entries[i] = entries[i+1];
         }
         return userData;
       }
     }
-    return NULL;
+    return nullptr;
   }
 
   /* Retrives the userData for the associated key */
   void *Get(UserDataKey *key)
   {
     for (int i=0; i<count; i++) {
       if (key == entries[i].key) {
         return entries[i].userData;
       }
     }
-    return NULL;
+    return nullptr;
   }
 
   bool Has(UserDataKey *key)
   {
     for (int i=0; i<count; i++) {
       if (key == entries[i].key) {
         return true;
       }
@@ -95,17 +96,17 @@ public:
   void Destroy()
   {
     for (int i=0; i<count; i++) {
       if (entries[i].destroy) {
         entries[i].destroy(entries[i].userData);
       }
     }
     free(entries);
-    entries = NULL;
+    entries = nullptr;
     count = 0;
   }
 
   ~UserData()
   {
     Destroy();
   }
 
--- a/gfx/2d/unittest/TestDrawTargetD2D.cpp
+++ b/gfx/2d/unittest/TestDrawTargetD2D.cpp
@@ -3,19 +3,19 @@
  * 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 "TestDrawTargetD2D.h"
 
 using namespace mozilla::gfx;
 TestDrawTargetD2D::TestDrawTargetD2D()
 {
-  ::D3D10CreateDevice1(NULL,
+  ::D3D10CreateDevice1(nullptr,
                        D3D10_DRIVER_TYPE_HARDWARE,
-                       NULL,
+                       nullptr,
                        D3D10_CREATE_DEVICE_BGRA_SUPPORT |
                        D3D10_CREATE_DEVICE_PREVENT_INTERNAL_THREADING_OPTIMIZATIONS,
                        D3D10_FEATURE_LEVEL_10_0,
                        D3D10_1_SDK_VERSION,
                        byRef(mDevice));
 
   Factory::SetDirect3D10Device(mDevice);
 
--- a/gfx/2d/unittest/TestDrawTargetD2D.h
+++ b/gfx/2d/unittest/TestDrawTargetD2D.h
@@ -11,9 +11,9 @@
 
 class TestDrawTargetD2D : public TestDrawTargetBase
 {
 public:
   TestDrawTargetD2D();
 
 private:
   mozilla::RefPtr<ID3D10Device1> mDevice;
-};
\ No newline at end of file
+};
--- a/gfx/layers/Layers.h
+++ b/gfx/layers/Layers.h
@@ -134,17 +134,21 @@ static void LayerManagerUserDataDestroy(
  * 
  * Layers are refcounted. The layer manager holds a reference to the
  * root layer, and each container layer holds a reference to its children.
  */
 class THEBES_API LayerManager {
   NS_INLINE_DECL_REFCOUNTING(LayerManager)
 
 public:
-  LayerManager() : mDestroyed(false), mSnapEffectiveTransforms(true), mId(0)
+  LayerManager()
+    : mDestroyed(false)
+    , mSnapEffectiveTransforms(true)
+    , mId(0)
+    , mInTransaction(false)
   {
     InitLog();
   }
   virtual ~LayerManager() {}
 
   /**
    * Release layers and resources held by this layer manager, and mark
    * it as destroyed.  Should do any cleanup necessary in preparation
@@ -450,29 +454,32 @@ public:
   static bool IsLogEnabled();
   static PRLogModuleInfo* GetLog() { return sLog; }
 
   bool IsCompositingCheap(LayersBackend aBackend)
   { return LAYERS_BASIC != aBackend; }
 
   virtual bool IsCompositingCheap() { return true; }
 
+  bool IsInTransaction() const { return mInTransaction; }
+
 protected:
   nsRefPtr<Layer> mRoot;
   gfx::UserData mUserData;
   bool mDestroyed;
   bool mSnapEffectiveTransforms;
 
   // Print interesting information about this into aTo.  Internally
   // used to implement Dump*() and Log*().
   virtual nsACString& PrintInfo(nsACString& aTo, const char* aPrefix);
 
   static void InitLog();
   static PRLogModuleInfo* sLog;
   uint64_t mId;
+  bool mInTransaction;
 private:
   TimeStamp mLastFrameTime;
   nsTArray<float> mFrameTimes;
 };
 
 class ThebesLayer;
 typedef InfallibleTArray<Animation> AnimationArray;
 
--- a/gfx/layers/basic/BasicLayerManager.cpp
+++ b/gfx/layers/basic/BasicLayerManager.cpp
@@ -147,16 +147,17 @@ void
 BasicLayerManager::SetDefaultTargetConfiguration(BufferMode aDoubleBuffering, ScreenRotation aRotation)
 {
   mDoubleBuffering = aDoubleBuffering;
 }
 
 void
 BasicLayerManager::BeginTransaction()
 {
+  mInTransaction = true;
   mUsingDefaultTarget = true;
   BeginTransactionWithTarget(mDefaultTarget);
 }
 
 already_AddRefed<gfxContext>
 BasicLayerManager::PushGroupWithCachedSurface(gfxContext *aTarget,
                                               gfxASurface::gfxContentType aContent)
 {
@@ -199,16 +200,18 @@ BasicLayerManager::PopGroupToSourceWithC
   } else {
     aTarget->PopGroupToSource();
   }
 }
 
 void
 BasicLayerManager::BeginTransactionWithTarget(gfxContext* aTarget)
 {
+  mInTransaction = true;
+
 #ifdef MOZ_LAYERS_HAVE_LOG
   MOZ_LAYERS_LOG(("[----- BeginTransaction"));
   Log();
 #endif
 
   NS_ASSERTION(!InTransaction(), "Nested transactions not allowed");
 #ifdef DEBUG
   mPhase = PHASE_CONSTRUCTION;
@@ -385,27 +388,30 @@ ApplyDoubleBuffering(Layer* aLayer, cons
   }
 }
 
 void
 BasicLayerManager::EndTransaction(DrawThebesLayerCallback aCallback,
                                   void* aCallbackData,
                                   EndTransactionFlags aFlags)
 {
+  mInTransaction = false;
+
   EndTransactionInternal(aCallback, aCallbackData, aFlags);
 }
 
 void
 BasicLayerManager::AbortTransaction()
 {
   NS_ASSERTION(InConstruction(), "Should be in construction phase");
 #ifdef DEBUG
   mPhase = PHASE_NONE;
 #endif
   mUsingDefaultTarget = false;
+  mInTransaction = false;
 }
 
 bool
 BasicLayerManager::EndTransactionInternal(DrawThebesLayerCallback aCallback,
                                           void* aCallbackData,
                                           EndTransactionFlags aFlags)
 {
   SAMPLE_LABEL("BasicLayerManager", "EndTranscationInternal");
@@ -524,16 +530,18 @@ BasicLayerManager::FlashWidgetUpdateArea
     aContext->SetColor(gfxRGBA(r, g, b, 0.2));
     aContext->Paint();
   }
 }
 
 bool
 BasicLayerManager::EndEmptyTransaction(EndTransactionFlags aFlags)
 {
+  mInTransaction = false;
+
   if (!mRoot) {
     return false;
   }
 
   return EndTransactionInternal(nullptr, nullptr, aFlags);
 }
 
 void
--- a/gfx/layers/d3d10/LayerManagerD3D10.cpp
+++ b/gfx/layers/d3d10/LayerManagerD3D10.cpp
@@ -317,43 +317,50 @@ void
 LayerManagerD3D10::SetRoot(Layer *aRoot)
 {
   mRoot = aRoot;
 }
 
 void
 LayerManagerD3D10::BeginTransaction()
 {
+  mInTransaction = true;
+
 #ifdef MOZ_LAYERS_HAVE_LOG
   MOZ_LAYERS_LOG(("[----- BeginTransaction"));
   Log();
 #endif
 }
 
 void
 LayerManagerD3D10::BeginTransactionWithTarget(gfxContext* aTarget)
 {
+  mInTransaction = true;
   mTarget = aTarget;
 }
 
 bool
 LayerManagerD3D10::EndEmptyTransaction(EndTransactionFlags aFlags)
 {
+  mInTransaction = false;
+
   if (!mRoot)
     return false;
 
   EndTransaction(nullptr, nullptr, aFlags);
   return true;
 }
 
 void
 LayerManagerD3D10::EndTransaction(DrawThebesLayerCallback aCallback,
                                   void* aCallbackData,
                                   EndTransactionFlags aFlags)
 {
+  mInTransaction = false;
+
   if (mRoot && !(aFlags & END_NO_IMMEDIATE_REDRAW)) {
     mCurrentCallbackInfo.Callback = aCallback;
     mCurrentCallbackInfo.CallbackData = aCallbackData;
 
     // The results of our drawing always go directly into a pixel buffer,
     // so we don't need to pass any global transform here.
     mRoot->ComputeEffectiveTransforms(gfx3DMatrix());
 
--- a/gfx/layers/d3d9/LayerManagerD3D9.cpp
+++ b/gfx/layers/d3d9/LayerManagerD3D9.cpp
@@ -102,48 +102,54 @@ LayerManagerD3D9::Destroy()
     mDeviceManager = nullptr;
   }
   LayerManager::Destroy();
 }
 
 void
 LayerManagerD3D9::BeginTransaction()
 {
+  mInTransaction = true;
 }
 
 void
 LayerManagerD3D9::BeginTransactionWithTarget(gfxContext *aTarget)
 {
+  mInTransaction = true;
   mTarget = aTarget;
 }
 
 void
 LayerManagerD3D9::EndConstruction()
 {
 }
 
 bool
 LayerManagerD3D9::EndEmptyTransaction(EndTransactionFlags aFlags)
 {
+  mInTransaction = false;
+
   // If the device reset count from our last EndTransaction doesn't match
   // the current device reset count, the device must have been reset one or
   // more times since our last transaction. In that case, an empty transaction
   // is not possible, because layers may need to be rerendered.
   if (!mRoot || mDeviceResetCount != mDeviceManager->GetDeviceResetCount())
     return false;
 
   EndTransaction(nullptr, nullptr, aFlags);
   return true;
 }
 
 void
 LayerManagerD3D9::EndTransaction(DrawThebesLayerCallback aCallback,
                                  void* aCallbackData,
                                  EndTransactionFlags aFlags)
 {
+  mInTransaction = false;
+
   mDeviceResetCount = mDeviceManager->GetDeviceResetCount();
 
   if (mRoot && !(aFlags & END_NO_IMMEDIATE_REDRAW)) {
     mCurrentCallbackInfo.Callback = aCallback;
     mCurrentCallbackInfo.CallbackData = aCallbackData;
 
     // The results of our drawing always go directly into a pixel buffer,
     // so we don't need to pass any global transform here.
--- a/gfx/layers/opengl/LayerManagerOGL.cpp
+++ b/gfx/layers/opengl/LayerManagerOGL.cpp
@@ -356,49 +356,56 @@ void
 LayerManagerOGL::SetClippingRegion(const nsIntRegion& aClippingRegion)
 {
   mClippingRegion = aClippingRegion;
 }
 
 void
 LayerManagerOGL::BeginTransaction()
 {
+  mInTransaction = true;
 }
 
 void
 LayerManagerOGL::BeginTransactionWithTarget(gfxContext *aTarget)
 {
+  mInTransaction = true;
+
 #ifdef MOZ_LAYERS_HAVE_LOG
   MOZ_LAYERS_LOG(("[----- BeginTransaction"));
   Log();
 #endif
 
   if (mDestroyed) {
     NS_WARNING("Call on destroyed layer manager");
     return;
   }
 
   mTarget = aTarget;
 }
 
 bool
 LayerManagerOGL::EndEmptyTransaction(EndTransactionFlags aFlags)
 {
+  mInTransaction = false;
+
   if (!mRoot)
     return false;
 
   EndTransaction(nullptr, nullptr, aFlags);
   return true;
 }
 
 void
 LayerManagerOGL::EndTransaction(DrawThebesLayerCallback aCallback,
                                 void* aCallbackData,
                                 EndTransactionFlags aFlags)
 {
+  mInTransaction = false;
+
 #ifdef MOZ_LAYERS_HAVE_LOG
   MOZ_LAYERS_LOG(("  ----- (beginning paint)"));
   Log();
 #endif
 
   if (mDestroyed) {
     NS_WARNING("Call on destroyed layer manager");
     return;
--- a/gfx/layers/opengl/ThebesLayerOGL.cpp
+++ b/gfx/layers/opengl/ThebesLayerOGL.cpp
@@ -999,16 +999,17 @@ ShadowThebesLayerOGL::Swap(const ThebesB
                            nsIntRegion* aNewBackValidRegion,
                            OptionalThebesBuffer* aReadOnlyFront,
                            nsIntRegion* aFrontUpdatedRegion)
 {
   if (mDestroyed) {
     // Don't drop buffers on the floor.
     *aNewBack = aNewFront;
     *aNewBackValidRegion = aNewFront.rect();
+    *aReadOnlyFront = null_t();
     return;
   }
 
   if (IsSurfaceDescriptorValid(mBufferDescriptor)) {
     AutoOpenSurface currentFront(OPEN_READ_ONLY, mBufferDescriptor);
     AutoOpenSurface newFront(OPEN_READ_ONLY, aNewFront.buffer());
     if (currentFront.Size() != newFront.Size()) {
       // The buffer changed size making the current front buffer
--- a/image/decoders/nsJPEGDecoder.cpp
+++ b/image/decoders/nsJPEGDecoder.cpp
@@ -184,19 +184,19 @@ nsJPEGDecoder::WriteInternal(const char 
 {
   mSegment = (const JOCTET *)aBuffer;
   mSegmentLen = aCount;
 
   NS_ABORT_IF_FALSE(!HasError(), "Shouldn't call WriteInternal after error!");
 
   /* Return here if there is a fatal error within libjpeg. */
   nsresult error_code;
-  // XXX: This cast to nsresult makes absolutely no sense and is thoroughly
-  // broken (bug 778103).  I hope this code path is never hit.
-  if ((error_code = (nsresult)setjmp(mErr.setjmp_buffer)) != 0) {
+  // This cast to nsresult makes sense because setjmp() returns whatever we
+  // passed to longjmp(), which was actually an nsresult.
+  if ((error_code = (nsresult)setjmp(mErr.setjmp_buffer)) != NS_OK) {
     if (error_code == NS_ERROR_FAILURE) {
       PostDataError();
       /* Error due to corrupt stream - return NS_OK and consume silently
          so that libpr0n doesn't throw away a partial image load */
       mState = JPEG_SINK_NON_JPEG_TRAILER;
       PR_LOG(gJPEGDecoderAccountingLog, PR_LOG_DEBUG,
              ("} (setjmp returned NS_ERROR_FAILURE)"));
       return;
@@ -652,18 +652,19 @@ my_error_exit (j_common_ptr cinfo)
   char buffer[JMSG_LENGTH_MAX];
 
   /* Create the message */
   (*err->pub.format_message) (cinfo, buffer);
 
   fprintf(stderr, "JPEG decoding error:\n%s\n", buffer);
 #endif
 
-  /* Return control to the setjmp point. */
-  longjmp(err->setjmp_buffer, error_code);
+  /* Return control to the setjmp point.  We pass an nsresult masquerading as
+   * an int, which works because the setjmp() caller casts it back. */
+  longjmp(err->setjmp_buffer, static_cast<int>(error_code));
 }
 
 /******************************************************************************/
 /*-----------------------------------------------------------------------------
  * This is the callback routine from the IJG JPEG library used to supply new
  * data to the decompressor when its input buffer is exhausted.  It juggles
  * multiple buffers in an attempt to avoid unnecessary copying of input data.
  *
--- a/image/encoders/jpeg/nsJPEGEncoder.cpp
+++ b/image/encoders/jpeg/nsJPEGEncoder.cpp
@@ -411,19 +411,21 @@ nsJPEGEncoder::emptyOutputBuffer(jpeg_co
                                          that->mImageBufferSize);
   if (! newBuf) {
     // can't resize, just zero (this will keep us from writing more)
     PR_Free(that->mImageBuffer);
     that->mImageBuffer = nullptr;
     that->mImageBufferSize = 0;
     that->mImageBufferUsed = 0;
 
-    // this seems to be the only way to do errors through the JPEG library
+    // This seems to be the only way to do errors through the JPEG library.  We
+    // pass an nsresult masquerading as an int, which works because the
+    // setjmp() caller casts it back.
     longjmp(((encoder_error_mgr*)(cinfo->err))->setjmp_buffer,
-            NS_ERROR_OUT_OF_MEMORY);
+            static_cast<int>(NS_ERROR_OUT_OF_MEMORY));
   }
   that->mImageBuffer = newBuf;
 
   cinfo->dest->next_output_byte = &that->mImageBuffer[that->mImageBufferUsed];
   cinfo->dest->free_in_buffer = that->mImageBufferSize - that->mImageBufferUsed;
   return 1;
 }
 
@@ -463,18 +465,19 @@ nsJPEGEncoder::errorExit(jpeg_common_str
   switch (cinfo->err->msg_code) {
     case JERR_OUT_OF_MEMORY:
       error_code = NS_ERROR_OUT_OF_MEMORY;
       break;
     default:
       error_code = NS_ERROR_FAILURE;
   }
 
-  // Return control to the setjmp point.
-  longjmp(err->setjmp_buffer, error_code);
+  // Return control to the setjmp point.  We pass an nsresult masquerading as
+  // an int, which works because the setjmp() caller casts it back.
+  longjmp(err->setjmp_buffer, static_cast<int>(error_code));
 }
 
 void
 nsJPEGEncoder::NotifyListener()
 {
   // We might call this function on multiple threads (any threads that call
   // AsyncWait and any that do encoding) so we lock to avoid notifying the
   // listener twice about the same data (which generally leads to a truncated
--- a/intl/strres/src/nsStringBundle.cpp
+++ b/intl/strres/src/nsStringBundle.cpp
@@ -755,17 +755,18 @@ nsStringBundleService::FormatWithBundle(
   if (NS_FAILED(rv)) {
     PRUint16 code = NS_ERROR_GET_CODE(aStatus);
     rv = bundle->FormatStringFromID(code, (const PRUnichar**)argArray, argCount, result);
   }
 
   // If the int key fails, try looking up the default error message. E.g. print:
   //   An unknown error has occurred (0x804B0003).
   if (NS_FAILED(rv)) {
-    nsAutoString statusStr; statusStr.AppendInt(aStatus, 16);
+    nsAutoString statusStr;
+    statusStr.AppendInt(static_cast<PRUint32>(aStatus), 16);
     const PRUnichar* otherArgArray[1];
     otherArgArray[0] = statusStr.get();
     PRUint16 code = NS_ERROR_GET_CODE(NS_ERROR_FAILURE);
     rv = bundle->FormatStringFromID(code, otherArgArray, 1, result);
   }
 
   return rv;
 }
--- a/js/src/configure.in
+++ b/js/src/configure.in
@@ -4393,20 +4393,18 @@ fi # MOZ_X11
 fi # COMPILE_ENVIRONMENT
 
 dnl Set various defines and substitutions
 dnl ========================================================
 
 if test "$OS_ARCH" = "Darwin"; then
   AC_DEFINE(XP_MACOSX)
   AC_DEFINE(XP_UNIX)
-  AC_DEFINE(UNIX_ASYNC_DNS)
 elif test "$OS_ARCH" != "WINNT" -a "$OS_ARCH" != "OS2"; then
   AC_DEFINE(XP_UNIX)
-  AC_DEFINE(UNIX_ASYNC_DNS)
 fi
 
 AC_ARG_ENABLE(threadsafe,
     [  --enable-threadsafe     Enable support for multiple threads.],
     [if test "x$enableval" = "xyes"; then
         AC_DEFINE(JS_THREADSAFE)
     fi],)
 
new file mode 100644
--- /dev/null
+++ b/js/src/jit-test/tests/basic/bug774859.js
@@ -0,0 +1,16 @@
+gczeal(4,1);
+function g()
+{
+    try {
+	return [];
+    } catch (e) {}
+}
+function f()
+{
+    for (var i=0; i<2; i++) {
+	var o = {a: g(),
+		 a: g()};
+	print(i);
+    }
+}
+f();
new file mode 100644
--- /dev/null
+++ b/js/src/jit-test/tests/basic/bug781393.js
@@ -0,0 +1,14 @@
+gczeal(4,1);
+function check(o)
+{
+    print(o);
+    assertEq(o.b, 3);
+}
+function f()
+{
+    for (var i=0; i<3; i++) {
+	var o = {b: 3};
+	check(o);
+    }
+}
+f();
--- a/js/src/js.msg
+++ b/js/src/js.msg
@@ -112,17 +112,17 @@ MSG_DEF(JSMSG_BAD_REGEXP_FLAG,         5
 MSG_DEF(JSMSG_NO_INPUT,                59, 5, JSEXN_SYNTAXERR, "no input for /{0}/{1}{2}{3}{4}")
 MSG_DEF(JSMSG_CANT_OPEN,               60, 2, JSEXN_ERR, "can't open {0}: {1}")
 MSG_DEF(JSMSG_TOO_MANY_FUN_APPLY_ARGS, 61, 0, JSEXN_RANGEERR, "arguments array passed to Function.prototype.apply is too large")
 MSG_DEF(JSMSG_UNMATCHED_RIGHT_PAREN,   62, 0, JSEXN_SYNTAXERR, "unmatched ) in regular expression")
 MSG_DEF(JSMSG_TOO_BIG_TO_ENCODE,       63, 0, JSEXN_INTERNALERR, "data are to big to encode")
 MSG_DEF(JSMSG_ARG_INDEX_OUT_OF_RANGE,  64, 1, JSEXN_RANGEERR, "argument {0} accesses an index that is out of range")
 MSG_DEF(JSMSG_SPREAD_TOO_LARGE,        65, 0, JSEXN_RANGEERR, "array too large due to spread operand(s)")
 MSG_DEF(JSMSG_SOURCE_TOO_LONG,         66, 0, JSEXN_RANGEERR, "source is too long")
-MSG_DEF(JSMSG_BAD_WEAKMAP_KEY,         67, 0, JSEXN_TYPEERR, "cannot use the given object as a weak map key")
+MSG_DEF(JSMSG_UNUSED67,                67, 0, JSEXN_NONE,    "")
 MSG_DEF(JSMSG_BAD_SCRIPT_MAGIC,        68, 0, JSEXN_INTERNALERR, "bad script XDR magic number")
 MSG_DEF(JSMSG_PAREN_BEFORE_FORMAL,     69, 0, JSEXN_SYNTAXERR, "missing ( before formal parameters")
 MSG_DEF(JSMSG_MISSING_FORMAL,          70, 0, JSEXN_SYNTAXERR, "missing formal parameter")
 MSG_DEF(JSMSG_PAREN_AFTER_FORMAL,      71, 0, JSEXN_SYNTAXERR, "missing ) after formal parameters")
 MSG_DEF(JSMSG_CURLY_BEFORE_BODY,       72, 0, JSEXN_SYNTAXERR, "missing { before function body")
 MSG_DEF(JSMSG_CURLY_AFTER_BODY,        73, 0, JSEXN_SYNTAXERR, "missing } after function body")
 MSG_DEF(JSMSG_PAREN_BEFORE_COND,       74, 0, JSEXN_SYNTAXERR, "missing ( before condition")
 MSG_DEF(JSMSG_PAREN_AFTER_COND,        75, 0, JSEXN_SYNTAXERR, "missing ) after condition")
--- a/js/src/jsapi.cpp
+++ b/js/src/jsapi.cpp
@@ -7102,27 +7102,35 @@ JS_SetGCZeal(JSContext *cx, uint8_t zeal
                    " 11: Verify post write barriers between instructions\n"
                    " 12: Verify post write barriers between paints\n");
         }
         const char *p = strchr(env, ',');
         zeal = atoi(env);
         frequency = p ? atoi(p + 1) : JS_DEFAULT_ZEAL_FREQ;
     }
 
+    JSRuntime *rt = cx->runtime;
+
     if (zeal == 0) {
-        if (cx->runtime->gcVerifyPreData)
-            VerifyBarriers(cx->runtime, PreBarrierVerifier);
-        if (cx->runtime->gcVerifyPostData)
-            VerifyBarriers(cx->runtime, PostBarrierVerifier);
+        if (rt->gcVerifyPreData)
+            VerifyBarriers(rt, PreBarrierVerifier);
+        if (rt->gcVerifyPostData)
+            VerifyBarriers(rt, PostBarrierVerifier);
     }
 
<