merge mozilla-central to b2g-inbound
authorCarsten "Tomcat" Book <cbook@mozilla.com>
Mon, 12 Aug 2013 11:52:02 +0200
changeset 142311 e999ab01a7eb434c9906b8a220b349d8e40ac5ea
parent 142310 6855c55668a70054129d6d61e77f41f0a5f37a25 (current diff)
parent 142224 87c1796bc46c6677b6aba9c56cf3796baa4c9d82 (diff)
child 142312 2f43e1f493c82d34dfa582d801d609161ea51778
push id32372
push userryanvm@gmail.com
push dateTue, 13 Aug 2013 01:59:20 +0000
treeherdermozilla-inbound@86b6480829c8 [default view] [failures only]
perfherder[talos] [build metrics] [platform microbench] (compared to previous push)
milestone26.0a1
first release with
nightly linux32
nightly linux64
nightly mac
nightly win32
nightly win64
last release without
nightly linux32
nightly linux64
nightly mac
nightly win32
nightly win64
merge mozilla-central to b2g-inbound
dom/base/nsDOMClassInfo.cpp
dom/base/nsDOMClassInfoClasses.h
dom/bindings/Bindings.conf
dom/interfaces/stylesheets/nsIDOMLinkStyle.idl
dom/webidl/WebIDL.mk
js/src/jsprvtd.h
js/xpconnect/src/Makefile.in
toolkit/mozapps/extensions/test/xpcshell/test_db_sanity.js
--- a/browser/app/blocklist.xml
+++ b/browser/app/blocklist.xml
@@ -1,10 +1,10 @@
 <?xml version="1.0"?>
-<blocklist xmlns="http://www.mozilla.org/2006/addons-blocklist" lastupdate="1375219877000">
+<blocklist xmlns="http://www.mozilla.org/2006/addons-blocklist" lastupdate="1376092730000">
   <emItems>
       <emItem  blockID="i350" id="sqlmoz@facebook.com">
                         <versionRange  minVersion="0" maxVersion="*" severity="3">
                     </versionRange>
                   </emItem>
       <emItem  blockID="i58" id="webmaster@buzzzzvideos.info">
                         <versionRange  minVersion="0" maxVersion="*">
                     </versionRange>
@@ -50,18 +50,18 @@
       <emItem  blockID="i400" id="{dd6b651f-dfb9-4142-b0bd-09912ad22674}">
                         <versionRange  minVersion="0" maxVersion="*" severity="1">
                     </versionRange>
                   </emItem>
       <emItem  blockID="i348" id="{13c9f1f9-2322-4d5c-81df-6d4bf8476ba4}">
                         <versionRange  minVersion="0" maxVersion="*" severity="1">
                     </versionRange>
                   </emItem>
-      <emItem  blockID="i6" id="{3f963a5b-e555-4543-90e2-c3908898db71}">
-                        <versionRange  minVersion=" " maxVersion="8.5">
+      <emItem  blockID="i440" id="{2d069a16-fca1-4e81-81ea-5d5086dcbd0c}">
+                        <versionRange  minVersion="0" maxVersion="*" severity="1">
                     </versionRange>
                   </emItem>
       <emItem  blockID="i392" id="{EEE6C361-6118-11DC-9C72-001320C79847}">
                         <versionRange  minVersion="0" maxVersion="1.7.999" severity="1">
                     </versionRange>
                                 <versionRange  minVersion="0" maxVersion="*" severity="1">
                     </versionRange>
                   </emItem>
@@ -79,20 +79,28 @@
       <emItem  blockID="i64" id="royal@facebook.com">
                         <versionRange  minVersion="0" maxVersion="*">
                     </versionRange>
                   </emItem>
       <emItem  blockID="i72" os="WINNT" id="{4ED1F68A-5463-4931-9384-8FFF5ED91D92}">
                         <versionRange  minVersion="3.4.1" maxVersion="3.4.1.194" severity="1">
                     </versionRange>
                   </emItem>
+      <emItem  blockID="i433" id="{c95a4e8e-816d-4655-8c79-d736da1adb6d}">
+                        <versionRange  minVersion="0" maxVersion="*" severity="1">
+                    </versionRange>
+                  </emItem>
       <emItem  blockID="i40" id="{28387537-e3f9-4ed7-860c-11e69af4a8a0}">
                         <versionRange  minVersion="0.1" maxVersion="4.3.1.00" severity="1">
                     </versionRange>
                   </emItem>
+      <emItem  blockID="i430" id="1chtw@facebook.com">
+                        <versionRange  minVersion="0" maxVersion="*" severity="3">
+                    </versionRange>
+                  </emItem>
       <emItem  blockID="i78" id="socialnetworktools@mozilla.doslash.org">
                         <versionRange  minVersion="0" maxVersion="*">
                     </versionRange>
                   </emItem>
       <emItem  blockID="i238" id="/^pink@.*\.info$/">
                         <versionRange  minVersion="0" maxVersion="*" severity="3">
                       <targetApplication  id="{ec8030f7-c20a-464f-9b0e-13a3a9e97384}">
                               <versionRange  minVersion="18.0" maxVersion="*" />
@@ -122,16 +130,20 @@
       <emItem  blockID="i360" id="ytd@mybrowserbar.com">
                         <versionRange  minVersion="0" maxVersion="*" severity="1">
                     </versionRange>
                   </emItem>
       <emItem  blockID="i5" id="support@daemon-tools.cc">
                         <versionRange  minVersion=" " maxVersion="1.0.0.5">
                     </versionRange>
                   </emItem>
+      <emItem  blockID="i436" id="/(\{7aeae561-714b-45f6-ace3-4a8aed6e227b\})|(\{01e86e69-a2f8-48a0-b068-83869bdba3d0\})|(\{77f5fe49-12e3-4cf5-abb4-d993a0164d9e\})/">
+                        <versionRange  minVersion="0" maxVersion="*" severity="1">
+                    </versionRange>
+                  </emItem>
       <emItem  blockID="i97" id="support3_en@adobe122.com">
                         <versionRange  minVersion="0" maxVersion="*">
                     </versionRange>
                   </emItem>
       <emItem  blockID="i382" id="{6926c7f7-6006-42d1-b046-eba1b3010315}">
                         <versionRange  minVersion="0" maxVersion="*" severity="1">
                     </versionRange>
                   </emItem>
@@ -153,16 +165,20 @@
       <emItem  blockID="i99" id="pfzPXmnzQRXX6@2iABkVe.com">
                         <versionRange  minVersion="0" maxVersion="*">
                     </versionRange>
                   </emItem>
       <emItem  blockID="i19" id="{46551EC9-40F0-4e47-8E18-8E5CF550CFB8}">
                         <versionRange  minVersion="1.1b1" maxVersion="1.1b1">
                     </versionRange>
                   </emItem>
+      <emItem  blockID="i438" id="{02edb56b-9b33-435b-b7df-b2843273a694}">
+                        <versionRange  minVersion="0" maxVersion="*" severity="1">
+                    </versionRange>
+                  </emItem>
       <emItem  blockID="i111" os="WINNT" id="{C3949AC2-4B17-43ee-B4F1-D26B9D42404D}">
                         <versionRange  minVersion="0" maxVersion="15.0.5" severity="1">
                     </versionRange>
                   </emItem>
       <emItem  blockID="i136" id="Adobe@flash.com">
                         <versionRange  minVersion="0" maxVersion="*" severity="1">
                     </versionRange>
                   </emItem>
@@ -199,16 +215,20 @@
                     </versionRange>
                   </emItem>
       <emItem  blockID="i142" id="{a3a5c777-f583-4fef-9380-ab4add1bc2a8}">
                         <versionRange  minVersion="2.0.3" maxVersion="2.0.3">
                     </versionRange>
                                 <versionRange  minVersion="4.2" maxVersion="4.2" severity="3">
                     </versionRange>
                   </emItem>
+      <emItem  blockID="i306" id="{ADFA33FD-16F5-4355-8504-DF4D664CFE10}">
+                        <versionRange  minVersion="0" maxVersion="*" severity="1">
+                    </versionRange>
+                  </emItem>
       <emItem  blockID="i63" id="youtube@youtuber.com">
                         <versionRange  minVersion="0" maxVersion="*">
                     </versionRange>
                   </emItem>
       <emItem  blockID="i46" id="{841468a1-d7f4-4bd3-84e6-bb0f13a06c64}">
                         <versionRange  minVersion="0.1" maxVersion="*">
                       <targetApplication  id="{ec8030f7-c20a-464f-9b0e-13a3a9e97384}">
                               <versionRange  minVersion="9.0a1" maxVersion="9.0" />
@@ -404,28 +424,36 @@
                     </versionRange>
                   </emItem>
       <emItem  blockID="i10" id="{8CE11043-9A15-4207-A565-0C94C42D590D}">
                         </emItem>
       <emItem  blockID="i76" id="crossriderapp3924@crossrider.com">
                         <versionRange  minVersion="0" maxVersion="*">
                     </versionRange>
                   </emItem>
-      <emItem  blockID="i262" id="{167d9323-f7cc-48f5-948a-6f012831a69f}">
+      <emItem  blockID="i432" id="lugcla21@gmail.com">
                         <versionRange  minVersion="0" maxVersion="*" severity="3">
                     </versionRange>
                   </emItem>
       <emItem  blockID="i196" id="info@wxdownloadmanager.com">
                         <versionRange  minVersion="0" maxVersion="*" severity="3">
                     </versionRange>
                   </emItem>
+      <emItem  blockID="i435" id="pluggets@gmail.com">
+                        <versionRange  minVersion="0" maxVersion="*" severity="3">
+                    </versionRange>
+                  </emItem>
       <emItem  blockID="i67" id="youtube2@youtube2.com">
                         <versionRange  minVersion="0" maxVersion="*">
                     </versionRange>
                   </emItem>
+      <emItem  blockID="i6" id="{3f963a5b-e555-4543-90e2-c3908898db71}">
+                        <versionRange  minVersion=" " maxVersion="8.5">
+                    </versionRange>
+                  </emItem>
       <emItem  blockID="i56" id="flash@adobe.com">
                         <versionRange  minVersion="0" maxVersion="*">
                     </versionRange>
                   </emItem>
       <emItem  blockID="i216" id="fdm_ffext@freedownloadmanager.org">
                         <versionRange  minVersion="1.0" maxVersion="1.3.1">
                       <targetApplication  id="{ec8030f7-c20a-464f-9b0e-13a3a9e97384}">
                               <versionRange  minVersion="3.0a1" maxVersion="*" />
@@ -509,32 +537,40 @@
       <emItem  blockID="i304" id="{f0e59437-6148-4a98-b0a6-60d557ef57f4}">
                         <versionRange  minVersion="0" maxVersion="*" severity="1">
                     </versionRange>
                   </emItem>
       <emItem  blockID="i86" id="{45147e67-4020-47e2-8f7a-55464fb535aa}">
                         <versionRange  minVersion="0" maxVersion="*">
                     </versionRange>
                   </emItem>
+      <emItem  blockID="i431" id="chinaescapeone@facebook.com">
+                        <versionRange  minVersion="0" maxVersion="*" severity="3">
+                    </versionRange>
+                  </emItem>
       <emItem  blockID="i312" id="extension21804@extension21804.com">
                         <versionRange  minVersion="0" maxVersion="*" severity="1">
                     </versionRange>
                   </emItem>
       <emItem  blockID="i324" id="/^((34qEOefiyYtRJT@IM5Munavn\.com)|(Mro5Fm1Qgrmq7B@ByrE69VQfZvZdeg\.com)|(KtoY3KGxrCe5ie@yITPUzbBtsHWeCdPmGe\.com)|(9NgIdLK5Dq4ZMwmRo6zk@FNt2GCCLGyUuOD\.com)|(NNux7bWWW@RBWyXdnl6VGls3WAwi\.com)|(E3wI2n@PEHTuuNVu\.com)|(2d3VuWrG6JHBXbQdbr@3BmSnQL\.com))$/">
                         <versionRange  minVersion="0" maxVersion="*" severity="3">
                     </versionRange>
                   </emItem>
       <emItem  blockID="i318" id="ffxtlbr@incredibar.com">
                         <versionRange  minVersion="0" maxVersion="*" severity="1">
                     </versionRange>
                   </emItem>
       <emItem  blockID="i108" id="{28bfb930-7620-11e1-b0c4-0800200c9a66}">
                         <versionRange  minVersion="0" maxVersion="*">
                     </versionRange>
                   </emItem>
+      <emItem  blockID="i262" id="{167d9323-f7cc-48f5-948a-6f012831a69f}">
+                        <versionRange  minVersion="0" maxVersion="*" severity="3">
+                    </versionRange>
+                  </emItem>
       <emItem  blockID="i61" id="youtube@youtube3.com">
                         <versionRange  minVersion="0" maxVersion="*">
                     </versionRange>
                                 <versionRange  minVersion="0" maxVersion="*">
                     </versionRange>
                   </emItem>
       <emItem  blockID="i91" id="crossriderapp4926@crossrider.com">
                         <versionRange  minVersion="0" maxVersion="0.81.43" severity="1">
@@ -543,16 +579,20 @@
       <emItem  blockID="i167" id="{b64982b1-d112-42b5-b1e4-d3867c4533f8}">
                         <versionRange  minVersion="0" maxVersion="*" severity="1">
                     </versionRange>
                   </emItem>
       <emItem  blockID="i101" id="{3a12052a-66ef-49db-8c39-e5b0bd5c83fa}">
                         <versionRange  minVersion="0" maxVersion="*">
                     </versionRange>
                   </emItem>
+      <emItem  blockID="i439" id="{d2cf9842-af95-48cd-b873-bfbb48cd7f5e}">
+                        <versionRange  minVersion="0" maxVersion="*" severity="1">
+                    </versionRange>
+                  </emItem>
       <emItem  blockID="i346" id="{a6e67e6f-8615-4fe0-a599-34a73fc3fba5}">
                         <versionRange  minVersion="0" maxVersion="*" severity="1">
                     </versionRange>
                   </emItem>
       <emItem  blockID="i220" id="pricepeep@getpricepeep.com">
                         <versionRange  minVersion="0" maxVersion="2.1.0.19.99" severity="1">
                     </versionRange>
                   </emItem>
@@ -567,18 +607,18 @@
       <emItem  blockID="i356" id="{341f4dac-1966-47ff-aacf-0ce175f1498a}">
                         <versionRange  minVersion="0" maxVersion="*" severity="1">
                     </versionRange>
                   </emItem>
       <emItem  blockID="i70" id="psid-vhvxQHMZBOzUZA@jetpack">
                         <versionRange  minVersion="0" maxVersion="*" severity="1">
                     </versionRange>
                   </emItem>
-      <emItem  blockID="i306" id="{ADFA33FD-16F5-4355-8504-DF4D664CFE10}">
-                        <versionRange  minVersion="0" maxVersion="*" severity="1">
+      <emItem  blockID="i437" id="{4933189D-C7F7-4C6E-834B-A29F087BFD23}">
+                        <versionRange  minVersion="0" maxVersion="*" severity="3">
                     </versionRange>
                   </emItem>
       <emItem  blockID="i165" id="{EEF73632-A085-4fd3-A778-ECD82C8CB297}">
                         <versionRange  minVersion="0" maxVersion="*" severity="3">
                     </versionRange>
                   </emItem>
       <emItem  blockID="i60" id="youtb3@youtb3.com">
                         <versionRange  minVersion="0" maxVersion="*">
@@ -590,24 +630,32 @@
                               <versionRange  minVersion="3.7a1pre" maxVersion="*" />
                           </targetApplication>
                     </versionRange>
                   </emItem>
       <emItem  blockID="i55" id="youtube@youtube7.com">
                         <versionRange  minVersion="0" maxVersion="*">
                     </versionRange>
                   </emItem>
+      <emItem  blockID="i434" id="afurladvisor@anchorfree.com">
+                        <versionRange  minVersion="0" maxVersion="*" severity="1">
+                    </versionRange>
+                  </emItem>
       <emItem  blockID="i90" id="videoplugin@player.com">
                         <versionRange  minVersion="0" maxVersion="*">
                     </versionRange>
                   </emItem>
       <emItem  blockID="i68" id="flashupdate@adobe.com">
                         <versionRange  minVersion="0" maxVersion="*">
                     </versionRange>
                   </emItem>
+      <emItem  blockID="i441" id="{49c53dce-afa0-49a1-a08b-2eb8e8444128}">
+                        <versionRange  minVersion="0" maxVersion="*" severity="1">
+                    </versionRange>
+                  </emItem>
       <emItem  blockID="i282" id="{33e0daa6-3af3-d8b5-6752-10e949c61516}">
                         <versionRange  minVersion="0" maxVersion="1.1.999" severity="1">
                     </versionRange>
                   </emItem>
       <emItem  blockID="i45" id="{22119944-ED35-4ab1-910B-E619EA06A115}">
                         <versionRange  minVersion="0.1" maxVersion="7.6.1">
                       <targetApplication  id="{ec8030f7-c20a-464f-9b0e-13a3a9e97384}">
                               <versionRange  minVersion="8.0a1" maxVersion="*" />
--- a/browser/components/sessionstore/src/DocumentUtils.jsm
+++ b/browser/components/sessionstore/src/DocumentUtils.jsm
@@ -1,12 +1,14 @@
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this file,
  * You can obtain one at http://mozilla.org/MPL/2.0/. */
 
+"use strict";
+
 this.EXPORTED_SYMBOLS = [ "DocumentUtils" ];
 
 const Cu = Components.utils;
 const Ci = Components.interfaces;
 
 Cu.import("resource://gre/modules/XPCOMUtils.jsm");
 Cu.import("resource:///modules/sessionstore/XPathGenerator.jsm");
 
--- a/browser/components/sessionstore/src/SessionMigration.jsm
+++ b/browser/components/sessionstore/src/SessionMigration.jsm
@@ -1,12 +1,14 @@
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this file,
  * You can obtain one at http://mozilla.org/MPL/2.0/. */
 
+"use strict";
+
 this.EXPORTED_SYMBOLS = ["SessionMigration"];
 
 const Cu = Components.utils;
 Cu.import("resource://gre/modules/XPCOMUtils.jsm", this);
 Cu.import("resource://gre/modules/Task.jsm", this);
 Cu.import("resource://gre/modules/osfile.jsm", this);
 
 // An encoder to UTF-8.
--- a/browser/components/sessionstore/src/SessionStorage.jsm
+++ b/browser/components/sessionstore/src/SessionStorage.jsm
@@ -1,12 +1,14 @@
 /* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this file,
 * You can obtain one at http://mozilla.org/MPL/2.0/. */
 
+"use strict";
+
 this.EXPORTED_SYMBOLS = ["SessionStorage"];
 
 const Cu = Components.utils;
 
 Cu.import("resource://gre/modules/Services.jsm");
 Cu.import("resource://gre/modules/XPCOMUtils.jsm");
 
 XPCOMUtils.defineLazyModuleGetter(this, "SessionStore",
--- a/browser/components/sessionstore/src/SessionStore.jsm
+++ b/browser/components/sessionstore/src/SessionStore.jsm
@@ -1,12 +1,14 @@
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this file,
  * You can obtain one at http://mozilla.org/MPL/2.0/. */
 
+"use strict";
+
 this.EXPORTED_SYMBOLS = ["SessionStore"];
 
 const Cu = Components.utils;
 const Cc = Components.classes;
 const Ci = Components.interfaces;
 const Cr = Components.results;
 
 const STATE_STOPPED = 0;
@@ -299,20 +301,16 @@ let SessionStoreInternal = {
 
   // time in milliseconds when the session was started (saved across sessions),
   // defaults to now if no session was restored or timestamp doesn't exist
   _sessionStartTime: Date.now(),
 
   // states for all currently opened windows
   _windows: {},
 
-  // internal states for all open windows (data we need to associate,
-  // but not write to disk)
-  _internalWindows: {},
-
   // states for all recently closed windows
   _closedWindows: [],
 
   // collection of session states yet to be restored
   _statesToRestore: {},
 
   // counts the number of crashes since the last clean start
   _recentCrashes: 0,
@@ -714,19 +712,16 @@ let SessionStoreInternal = {
       return;
 
     // assign it a unique identifier (timestamp)
     aWindow.__SSi = "window" + Date.now();
 
     // and create its data object
     this._windows[aWindow.__SSi] = { tabs: [], selected: 0, _closedTabs: [], busy: false };
 
-    // and create its internal data object
-    this._internalWindows[aWindow.__SSi] = { hosts: {} }
-
     let isPrivateWindow = false;
     if (PrivateBrowsingUtils.isWindowPrivate(aWindow))
       this._windows[aWindow.__SSi].isPrivate = isPrivateWindow = true;
     if (!this._isWindowLoaded(aWindow))
       this._windows[aWindow.__SSi]._restoring = true;
     if (!aWindow.toolbar.visible)
       this._windows[aWindow.__SSi].isPopup = true;
 
@@ -870,22 +865,22 @@ let SessionStoreInternal = {
   },
 
   /**
    * On window open
    * @param aWindow
    *        Window reference
    */
   onOpen: function ssi_onOpen(aWindow) {
-    var _this = this;
-    aWindow.addEventListener("load", function(aEvent) {
-      aEvent.currentTarget.removeEventListener("load", arguments.callee, false);
-      _this.onLoad(aEvent.currentTarget);
-    }, false);
-    return;
+    let onload = () => {
+      aWindow.removeEventListener("load", onload);
+      this.onLoad(aWindow);
+    };
+
+    aWindow.addEventListener("load", onload);
   },
 
   /**
    * On window close...
    * - remove event listeners from tabs
    * - save all window data
    * @param aWindow
    *        Window reference
@@ -930,19 +925,17 @@ let SessionStoreInternal = {
     if (this._loadState == STATE_RUNNING) { // window not closed during a regular shut-down
       // update all window data for a last time
       this._collectWindowData(aWindow);
 
       if (isFullyLoaded) {
         winData.title = aWindow.content.document.title || tabbrowser.selectedTab.label;
         winData.title = this._replaceLoadingTitle(winData.title, tabbrowser,
                                                   tabbrowser.selectedTab);
-        let windows = {};
-        windows[aWindow.__SSi] = winData;
-        this._updateCookies(windows);
+        this._updateCookies([winData]);
       }
 
 #ifndef XP_MACOSX
       // Until we decide otherwise elsewhere, this window is part of a series
       // of closing windows to quit.
       winData._shouldRestore = true;
 #endif
 
@@ -954,17 +947,16 @@ let SessionStoreInternal = {
         delete winData.busy;
 
         this._closedWindows.unshift(winData);
         this._capClosedWindows();
       }
 
       // clear this window from the list
       delete this._windows[aWindow.__SSi];
-      delete this._internalWindows[aWindow.__SSi];
 
       // save the state without this window to disk
       this.saveStateDelayed();
     }
 
     for (let i = 0; i < tabbrowser.tabs.length; i++) {
       this.onTabRemove(aWindow, tabbrowser.tabs[i], true);
     }
@@ -1050,43 +1042,37 @@ let SessionStoreInternal = {
     this._lastSessionState = null;
     let openWindows = {};
     this._forEachBrowserWindow(function(aWindow) {
       Array.forEach(aWindow.gBrowser.tabs, function(aTab) {
         TabStateCache.delete(aTab);
         delete aTab.linkedBrowser.__SS_data;
         delete aTab.linkedBrowser.__SS_tabStillLoading;
         delete aTab.linkedBrowser.__SS_formDataSaved;
-        delete aTab.linkedBrowser.__SS_hostSchemeData;
         if (aTab.linkedBrowser.__SS_restoreState)
           this._resetTabRestoringState(aTab);
-      });
+      }, this);
       openWindows[aWindow.__SSi] = true;
     });
     // also clear all data about closed tabs and windows
     for (let ix in this._windows) {
       if (ix in openWindows) {
         this._windows[ix]._closedTabs = [];
-      }
-      else {
+      } else {
         delete this._windows[ix];
-        delete this._internalWindows[ix];
       }
     }
     // also clear all data about closed windows
     this._closedWindows = [];
     // give the tabbrowsers a chance to clear their histories first
     var win = this._getMostRecentBrowserWindow();
     if (win)
       win.setTimeout(function() { _this.saveState(true); }, 0);
     else if (this._loadState == STATE_RUNNING)
       this.saveState(true);
-    // Delete the private browsing backed up state, if any
-    if ("_stateBackup" in this)
-      delete this._stateBackup;
 
     this._clearRestoringWindows();
   },
 
   /**
    * On purge of domain data
    * @param aData
    *        String domain data
@@ -1220,17 +1206,16 @@ let SessionStoreInternal = {
     browser.removeEventListener("load", this, true);
 
     let mm = browser.messageManager;
     MESSAGES.forEach(msg => mm.removeMessageListener(msg, this));
 
     delete browser.__SS_data;
     delete browser.__SS_tabStillLoading;
     delete browser.__SS_formDataSaved;
-    delete browser.__SS_hostSchemeData;
 
     // If this tab was in the middle of restoring or still needs to be restored,
     // we need to reset that state. If the tab was restoring, we will attempt to
     // restore the next tab.
     let previousState = browser.__SS_restoreState;
     if (previousState) {
       this._resetTabRestoringState(aTab);
       if (previousState == TAB_STATE_RESTORING)
@@ -1976,21 +1961,20 @@ let SessionStoreInternal = {
     if (history && browser.__SS_data &&
         browser.__SS_data.entries[history.index] &&
         browser.__SS_data.entries[history.index].url == browser.currentURI.spec &&
         history.index < this._sessionhistory_max_entries - 1 && !includePrivateData) {
       tabData = browser.__SS_data;
       tabData.index = history.index + 1;
     }
     else if (history && history.count > 0) {
-      browser.__SS_hostSchemeData = [];
       try {
         for (var j = 0; j < history.count; j++) {
           let entry = this._serializeHistoryEntry(history.getEntryAtIndex(j, false),
-                                                  includePrivateData, aTab.pinned, browser.__SS_hostSchemeData);
+                                                  includePrivateData, aTab.pinned);
           tabData.entries.push(entry);
         }
         // If we make it through the for loop, then we're ok and we should clear
         // any indicator of brokenness.
         delete aTab.__SS_broken_history;
       }
       catch (ex) {
         // In some cases, getEntryAtIndex will throw. This seems to be due to
@@ -2072,33 +2056,22 @@ let SessionStoreInternal = {
    * Get an object that is a serialized representation of a History entry
    * Used for data storage
    * @param aEntry
    *        nsISHEntry instance
    * @param aIncludePrivateData
    *        always return privacy sensitive data (use with care)
    * @param aIsPinned
    *        the tab is pinned and should be treated differently for privacy
-   * @param aHostSchemeData
-   *        an array of objects with host & scheme keys
    * @returns object
    */
   _serializeHistoryEntry:
-    function ssi_serializeHistoryEntry(aEntry, aIncludePrivateData, aIsPinned, aHostSchemeData) {
+    function ssi_serializeHistoryEntry(aEntry, aIncludePrivateData, aIsPinned) {
     var entry = { url: aEntry.URI.spec };
 
-    try {
-      // throwing is expensive, we know that about: pages will throw
-      if (entry.url.indexOf("about:") != 0)
-        aHostSchemeData.push({ host: aEntry.URI.host, scheme: aEntry.URI.scheme });
-    }
-    catch (ex) {
-      // We just won't attempt to get cookies for this entry.
-    }
-
     if (aEntry.title && aEntry.title != entry.url) {
       entry.title = aEntry.title;
     }
     if (aEntry.isSubFrame) {
       entry.subframe = true;
     }
     if (!(aEntry instanceof Ci.nsISHEntry)) {
       return entry;
@@ -2199,17 +2172,17 @@ let SessionStoreInternal = {
         if (child) {
           // don't try to restore framesets containing wyciwyg URLs (cf. bug 424689 and bug 450595)
           if (child.URI.schemeIs("wyciwyg")) {
             children = [];
             break;
           }
 
           children.push(this._serializeHistoryEntry(child, aIncludePrivateData,
-                                                    aIsPinned, aHostSchemeData));
+                                                    aIsPinned));
         }
       }
 
       if (children.length)
         entry.children = children;
     }
 
     return entry;
@@ -2420,18 +2393,18 @@ let SessionStoreInternal = {
     else if (aScheme == "file") {
       aHosts[aHost] = true;
     }
   },
 
   /**
    * Serialize cookie data
    * @param aWindows
-   *        JS object containing window data references
-   *        { id: winData, etc. }
+   *        An array of window data objects
+   *        { tabs: [ ... ], etc. }
    */
   _updateCookies: function ssi_updateCookies(aWindows) {
     function addCookieToHash(aHash, aHost, aPath, aName, aCookie) {
       // lazily build up a 3-dimensional hash, with
       // aHost, aPath, and aName as keys
       if (!aHash[aHost])
         aHash[aHost] = {};
       if (!aHash[aHost][aPath])
@@ -2439,22 +2412,28 @@ let SessionStoreInternal = {
       aHash[aHost][aPath][aName] = aCookie;
     }
 
     var jscookies = {};
     var _this = this;
     // MAX_EXPIRY should be 2^63-1, but JavaScript can't handle that precision
     var MAX_EXPIRY = Math.pow(2, 62);
 
-    for (let [id, window] in Iterator(aWindows)) {
+    for (let window of aWindows) {
       window.cookies = [];
-      let internalWindow = this._internalWindows[id];
-      if (!internalWindow.hosts)
-        return;
-      for (var [host, isPinned] in Iterator(internalWindow.hosts)) {
+
+      // Collect all hosts for the current window.
+      let hosts = {};
+      window.tabs.forEach(function(tab) {
+        tab.entries.forEach(function(entry) {
+          this._extractHostsForCookiesFromEntry(entry, hosts, true, tab.pinned);
+        }, this);
+      }, this);
+
+      for (var [host, isPinned] in Iterator(hosts)) {
         let list;
         try {
           list = Services.cookies.getCookiesFromHost(host);
         }
         catch (ex) {
           debug("getCookiesFromHost failed. Host: " + host);
         }
         while (list && list.hasMoreElements()) {
@@ -2537,30 +2516,34 @@ let SessionStoreInternal = {
         }
         else { // always update the window features (whose change alone never triggers a save operation)
           this._updateWindowFeatures(aWindow);
         }
       });
       DirtyWindows.clear();
     }
 
-    // collect the data for all windows
-    var total = [], windows = {}, ids = [];
+    // An array that at the end will hold all current window data.
+    var total = [];
+    // The ids of all windows contained in 'total' in the same order.
+    var ids = [];
+    // The number of window that are _not_ popups.
     var nonPopupCount = 0;
     var ix;
+
+    // collect the data for all windows
     for (ix in this._windows) {
       if (this._windows[ix]._restoring) // window data is still in _statesToRestore
         continue;
       total.push(this._windows[ix]);
       ids.push(ix);
-      windows[ix] = this._windows[ix];
       if (!this._windows[ix].isPopup)
         nonPopupCount++;
     }
-    this._updateCookies(windows);
+    this._updateCookies(total);
 
     // collect the data for all windows yet to be restored
     for (ix in this._statesToRestore) {
       for each (let winData in this._statesToRestore[ix].windows) {
         total.push(winData);
         if (!winData.isPopup)
           nonPopupCount++;
       }
@@ -2622,48 +2605,34 @@ let SessionStoreInternal = {
   _getWindowState: function ssi_getWindowState(aWindow) {
     if (!this._isWindowLoaded(aWindow))
       return this._statesToRestore[aWindow.__SS_restoreID];
 
     if (this._loadState == STATE_RUNNING) {
       this._collectWindowData(aWindow);
     }
 
-    var winData = this._windows[aWindow.__SSi];
-    let windows = {};
-    windows[aWindow.__SSi] = winData;
+    let windows = [this._windows[aWindow.__SSi]];
     this._updateCookies(windows);
 
-    return { windows: [winData] };
+    return { windows: windows };
   },
 
   _collectWindowData: function ssi_collectWindowData(aWindow) {
     if (!this._isWindowLoaded(aWindow))
       return;
 
     let tabbrowser = aWindow.gBrowser;
     let tabs = tabbrowser.tabs;
     let winData = this._windows[aWindow.__SSi];
     let tabsData = winData.tabs = [];
-    let hosts = this._internalWindows[aWindow.__SSi].hosts = {};
 
     // update the internal state data for this window
     for (let tab of tabs) {
       tabsData.push(this._collectTabData(tab));
-
-      // Since we are only ever called for open
-      // windows during a session, we can call into
-      // _extractHostsForCookiesFromHostScheme directly using data
-      // that is attached to each browser.
-      let hostSchemeData = tab.linkedBrowser.__SS_hostSchemeData || [];
-      for (let j = 0; j < hostSchemeData.length; j++) {
-        this._extractHostsForCookiesFromHostScheme(hostSchemeData[j].host,
-                                                   hostSchemeData[j].scheme,
-                                                   hosts, true, tab.pinned);
-      }
     }
     winData.selected = tabbrowser.mTabBox.selectedIndex + 1;
 
     this._updateWindowFeatures(aWindow);
 
     // Make sure we keep __SS_lastSessionWindowID around for cases like entering
     // or leaving PB mode.
     if (aWindow.__SS_lastSessionWindowID)
--- a/browser/components/sessionstore/src/XPathGenerator.jsm
+++ b/browser/components/sessionstore/src/XPathGenerator.jsm
@@ -1,12 +1,14 @@
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this file,
  * You can obtain one at http://mozilla.org/MPL/2.0/. */
 
+"use strict";
+
 this.EXPORTED_SYMBOLS = ["XPathGenerator"];
 
 this.XPathGenerator = {
   // these two hashes should be kept in sync
   namespaceURIs:     { "xhtml": "http://www.w3.org/1999/xhtml" },
   namespacePrefixes: { "http://www.w3.org/1999/xhtml": "xhtml" },
 
   /**
--- a/browser/components/sessionstore/src/nsSessionStartup.js
+++ b/browser/components/sessionstore/src/nsSessionStartup.js
@@ -1,12 +1,14 @@
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
+"use strict";
+
 /**
  * Session Storage and Restoration
  *
  * Overview
  * This service reads user's session file at startup, and makes a determination
  * as to whether the session should be restored. It will restore the session
  * under the circumstances described below.  If the auto-start Private Browsing
  * mode is active, however, the session is never restored.
--- a/browser/components/sessionstore/src/nsSessionStore.js
+++ b/browser/components/sessionstore/src/nsSessionStore.js
@@ -1,12 +1,14 @@
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
+"use strict";
+
 /**
  * Session Storage and Restoration
  *
  * Overview
  * This service keeps track of a user's session, storing the various bits
  * required to return the browser to its current state. The relevant data is
  * stored in memory, and is periodically saved to disk in a file in the
  * profile directory. The service is started at first window load, in
--- a/browser/config/mozconfigs/linux64/debug-static-analysis-clang
+++ b/browser/config/mozconfigs/linux64/debug-static-analysis-clang
@@ -4,9 +4,12 @@ ac_add_options --enable-debug
 
 # Use Clang as specified in manifest
 export CC="$topsrcdir/clang/bin/clang"
 export CXX="$topsrcdir/clang/bin/clang++"
 
 # Add the static checker
 ac_add_options --enable-clang-plugin
 
+# Avoid dependency on libstdc++ 4.7
+ac_add_options --enable-stdcxx-compat
+
 . "$topsrcdir/build/mozconfig.common.override"
--- a/browser/metro/base/content/ContextCommands.js
+++ b/browser/metro/base/content/ContextCommands.js
@@ -32,69 +32,76 @@ var ContextCommands = {
    * Context menu handlers
    */
 
   // Text specific
 
   cut: function cc_cut() {
     let target = ContextMenuUI.popupState.target;
 
-    if (!target)
+    if (!target) {
       return;
+    }
 
     if (target.localName === "browser") {
       // content
       if (ContextMenuUI.popupState.string) {
         this.sendCommand("cut");
 
         SelectionHelperUI.closeEditSession(true);
       }
     } else {
       // chrome
-      target.editor.cut();
+      CommandUpdater.doCommand("cmd_cut");
     }
 
     target.focus();
   },
 
   copy: function cc_copy() {
     let target = ContextMenuUI.popupState.target;
 
-    if (!target)
+    if (!target) {
       return;
+    }
 
     if (target.localName == "browser") {
       // content
       if (ContextMenuUI.popupState.string) {
         this.sendCommand("copy");
 
         SelectionHelperUI.closeEditSession(true);
       }
     } else if (ContextMenuUI.popupState.string) {
       this.clipboard.copyString(ContextMenuUI.popupState.string, this.docRef);
     } else {
       // chrome
-      target.editor.copy();
+      CommandUpdater.doCommand("cmd_copy");
     }
 
     target.focus();
   },
 
   paste: function cc_paste() {
     let target = ContextMenuUI.popupState.target;
+
+    if (!target) {
+      return;
+    }
+
     if (target.localName == "browser") {
       // content
       let x = ContextMenuUI.popupState.x;
       let y = ContextMenuUI.popupState.y;
       let json = {x: x, y: y, command: "paste" };
       target.messageManager.sendAsyncMessage("Browser:ContextCommand", json);
       SelectionHelperUI.closeEditSession();
     } else {
       // chrome
-      target.editor.paste(Ci.nsIClipboard.kGlobalClipboard);
+      CommandUpdater.doCommand("cmd_paste");
       target.focus();
     }
   },
 
   pasteAndGo: function cc_pasteAndGo() {
     let target = ContextMenuUI.popupState.target;
     target.editor.selectAll();
     target.editor.paste(Ci.nsIClipboard.kGlobalClipboard);
--- a/browser/metro/base/content/bindings/bindings.xml
+++ b/browser/metro/base/content/bindings/bindings.xml
@@ -255,20 +255,16 @@
         <body><![CDATA[
           let selectionStart = aTextbox.selectionStart;
           let selectionEnd = aTextbox.selectionEnd;
 
           let json = { types: ["input-text"], string: "" };
           if (selectionStart != selectionEnd) {
             json.types.push("cut");
             json.types.push("copy");
-            json.string = aTextbox.value.slice(selectionStart, selectionEnd);
-          } else if (aTextbox.value) {
-            json.types.push("copy-all");
-            json.string = aTextbox.value;
           }
 
           if (selectionStart > 0 || selectionEnd < aTextbox.textLength)
             json.types.push("select-all");
 
           let clipboard = Components.classes["@mozilla.org/widget/clipboard;1"].
                                             getService(Ci.nsIClipboard);
           let flavors = ["text/unicode"];
--- a/browser/metro/base/content/bindings/grid.xml
+++ b/browser/metro/base/content/bindings/grid.xml
@@ -795,33 +795,34 @@
       </handler>
     </handlers>
   </binding>
 
   <binding id="richgrid-item">
     <content>
       <html:div anonid="anon-tile" class="tile-content" xbl:inherits="customImage">
         <html:div class="tile-start-container" xbl:inherits="customImage">
-          <html:div class="tile-icon-box"><xul:image anonid="anon-tile-icon" xbl:inherits="src=iconURI"/></html:div>
+          <html:div class="tile-icon-box" anonid="anon-tile-icon-box"><xul:image anonid="anon-tile-icon" xbl:inherits="src=iconURI"/></html:div>
         </html:div>
         <html:div anonid="anon-tile-label" class="tile-desc" xbl:inherits="xbl:text=label"/>
       </html:div>
     </content>
 
     <implementation>
       <property name="isBound" readonly="true" onget="return !!this._icon"/>
       <constructor>
         <![CDATA[
             this.refresh();
         ]]>
       </constructor>
       <property name="_contentBox" onget="return document.getAnonymousElementByAttribute(this, 'class', 'tile-content');"/>
       <property name="_textbox" onget="return document.getAnonymousElementByAttribute(this, 'class', 'tile-desc');"/>
       <property name="_top" onget="return document.getAnonymousElementByAttribute(this, 'class', 'tile-start-container');"/>
       <property name="_icon" onget="return document.getAnonymousElementByAttribute(this, 'anonid', 'anon-tile-icon');"/>
+      <property name="_iconBox" onget="return document.getAnonymousElementByAttribute(this, 'anonid', 'anon-tile-icon-box');"/>
       <property name="_label" onget="return document.getAnonymousElementByAttribute(this, 'anonid', 'anon-tile-label');"/>
       <property name="iconSrc"
                 onset="this._icon.src = val; this.setAttribute('iconURI', val);"
                 onget="return this._icon.src;" />
 
       <property name="selected"
                 onget="return this.hasAttribute('selected');"
                 onset="if (val) this.setAttribute('selected', val); else this.removeAttribute('selected');" />
@@ -871,19 +872,31 @@
         ]]></getter>
       </property>
 
       <property name="color" onget="return this.getAttribute('customColor');">
         <setter><![CDATA[
           if (val) {
             this.setAttribute("customColor", val);
             this._contentBox.style.backgroundColor = val;
+
+            // overridden in tiles.css for non-thumbnail types
+            this._label.style.backgroundColor = val.replace(/rgb\(([^\)]+)\)/, 'rgba($1, 0.8)');
+
+            // Small icons get a border+background-color treatment.
+            // See tiles.css for large icon overrides
+            this._iconBox.style.borderColor = val.replace(/rgb\(([^\)]+)\)/, 'rgba($1, 0.6)');
+            this._iconBox.style.backgroundColor = this.hasAttribute("tintColor") ?
+                                                    this.getAttribute("tintColor") : "#fff";
           } else {
             this.removeAttribute("customColor");
             this._contentBox.style.removeProperty("background-color");
+            this._label.style.removeProperty("background-color");
+            this._iconBox.style.removeProperty("border-color");
+            this._iconBox.style.removeProperty("background-color");
           }
         ]]></setter>
       </property>
 
       <property name="backgroundImage" onget="return this.getAttribute('customImage');">
         <setter><![CDATA[
           if (val) {
             this.setAttribute("customImage", val);
--- a/browser/metro/base/content/bindings/urlbar.xml
+++ b/browser/metro/base/content/bindings/urlbar.xml
@@ -152,17 +152,17 @@
         </body>
       </method>
 
       <method name="_getSelectedValueForClipboard">
         <body>
           <![CDATA[
             // Grab the actual input field's value, not our value, which could include moz-action:
             let inputVal = this.inputField.value;
-            let selectedVal = inputVal.substring(this.selectionStart, this.electionEnd);
+            let selectedVal = inputVal.substring(this.selectionStart, this.selectionEnd);
 
             // If the selection doesn't start at the beginning or doesn't span the full domain or
             // the URL bar is modified, nothing else to do here.
             if (this.selectionStart > 0 || this.valueIsTyped)
               return selectedVal;
 
             // The selection doesn't span the full domain if it doesn't contain a slash and is
             // followed by some character other than a slash.
@@ -480,24 +480,27 @@
             return;
         ]]>
       </handler>
     </handlers>
   </binding>
 
   <binding id="urlbar-autocomplete">
     <content orient="horizontal">
-      <xul:vbox id="results-vbox" flex="1">
-        <xul:label class="meta-section-title" value="&autocompleteResultsHeader.label;"/>
-        <richgrid id="results-richgrid" rows="3" deferlayout="true" anonid="results" seltype="single" flex="1"/>
+      <xul:vbox id="results-vbox" anonid="results-container" flex="1">
+        <xul:label class="meta-section-title"
+                   value="&autocompleteResultsHeader.label;"/>
+        <richgrid id="results-richgrid" anonid="results" rows="3" flex="1"
+                  seltype="single" deferlayout="true"/>
       </xul:vbox>
 
       <xul:vbox id="searches-vbox" flex="1">
-        <xul:label class="meta-section-title" value="&autocompleteSearchesHeader.label;"/>
-        <richgrid id="searches-richgrid" rows="3" deferlayout="true" anonid="searches" seltype="single" flex="1"/>
+        <xul:label anonid="searches-header" class="meta-section-title"/>
+        <richgrid id="searches-richgrid" anonid="searches" rows="3" flex="1"
+                  seltype="single" deferlayout="true"/>
       </xul:vbox>
     </content>
 
     <implementation implements="nsIAutoCompletePopup, nsIObserver">
       <constructor>
         <![CDATA[
           this.hidden = true;
 
@@ -585,17 +588,21 @@
             Elements.urlbarState.removeAttribute("autocomplete");
           ]]>
         </body>
       </method>
 
       <!-- Updating grid content -->
 
       <field name="_grid">null</field>
+
       <field name="_results" readonly="true">document.getAnonymousElementByAttribute(this, 'anonid', 'results');</field>
+      <field name="_resultsContainer" readonly="true">document.getAnonymousElementByAttribute(this, 'anonid', 'results-container');</field>
+
+      <field name="_searchesHeader" readonly="true">document.getAnonymousElementByAttribute(this, 'anonid', 'searches-header');</field>
       <field name="_searches" readonly="true">document.getAnonymousElementByAttribute(this, 'anonid', 'searches');</field>
 
       <property name="_otherGrid" readonly="true">
         <getter>
           <![CDATA[
             if (this._grid == null)
               return null;
 
@@ -615,32 +622,39 @@
 
       <method name="invalidate">
         <body>
           <![CDATA[
             if (!this.popupOpen)
               return;
 
             this.updateResults();
-            this.updateSearchEngineSubtitles();
+            this.updateSearchEngineHeader();
           ]]>
         </body>
       </method>
 
       <!-- Updating grid content: results -->
 
       <method name="updateResults">
         <body>
           <![CDATA[
             if (!this._isGridBound(this._results))
               return;
 
             if (!this.input)
               return;
 
+            let haveNoResults = (this.matchCount == 0);
+            this._resultsContainer.hidden = haveNoResults;
+
+            if (haveNoResults) {
+              return;
+            }
+
             let controller = this.input.controller;
             let lastMatch = this.matchCount - 1;
             let iterCount = Math.max(this._results.itemCount, this.matchCount);
 
             // Swap out existing items for new search hit results
             for (let i = 0; i < iterCount; i++) {
               if (i > lastMatch) {
                 let lastItem = this._results.itemCount - 1;
@@ -701,30 +715,27 @@
               item.setAttribute("iconURI", iconURI);
             }.bind(this));
 
             this._searches.arrangeItems();
           ]]>
         </body>
       </method>
 
-      <method name="updateSearchEngineSubtitles">
+      <method name="updateSearchEngineHeader">
         <body>
           <![CDATA[
             if (!this._isGridBound(this._searches))
               return;
 
             let searchString = this.input.controller.searchString;
-            let label = Strings.browser.formatStringFromName("opensearch.search", [searchString], 1);
+            let label = Strings.browser.formatStringFromName(
+                              "opensearch.search.header", [searchString], 1);
 
-            for (let i = 0, len = this._searches.itemCount; i < len; i++) {
-              let item = this._searches.getItemAtIndex(i);
-              item.setAttribute("label", label);
-              item.refresh && item.refresh();
-            }
+            this._searchesHeader.value = label;
           ]]>
         </body>
       </method>
 
       <!-- Selecting results -->
 
       <method name="selectBy">
         <parameter name="aReverse"/>
--- a/browser/metro/base/content/startui/HistoryView.js
+++ b/browser/metro/base/content/startui/HistoryView.js
@@ -104,17 +104,17 @@ HistoryView.prototype = Util.extend(Obje
     let item = this._set.insertItemAt(aPos || 0, aTitle, aURI, this._inBatch);
     this._setContextActions(item);
     this._updateFavicon(item, aURI);
   },
 
   _setContextActions: function bv__setContextActions(aItem) {
     let uri = aItem.getAttribute("value");
     aItem.setAttribute("data-contextactions", "delete," + (this._pinHelper.isPinned(uri) ? "unpin" : "pin"));
-    if (aItem.refresh) aItem.refresh();
+    if ("refresh" in aItem) aItem.refresh();
   },
 
   _sendNeedsRefresh: function bv__sendNeedsRefresh(){
     // Event sent when all views need to refresh.
     let event = document.createEvent("Events");
     event.initEvent("HistoryNeedsRefresh", true, false);
     window.dispatchEvent(event);
   },
@@ -268,16 +268,18 @@ HistoryView.prototype = Util.extend(Obje
 
   onPageChanged: function(aURI, aWhat, aValue) {
     if (aWhat ==  Ci.nsINavHistoryObserver.ATTRIBUTE_FAVICON) {
       let changedItems = this._set.getItemsByUrl(aURI.spec);
       for (let item of changedItems) {
         let currIcon = item.getAttribute("iconURI");
         if (currIcon != aValue) {
           item.setAttribute("iconURI", aValue);
+          if("refresh" in item)
+            item.refresh();
         }
       }
     }
   },
 
   onDeleteVisits: function (aURI, aVisitTime, aGUID, aReason, aTransitionType) {
     if ((aReason ==  Ci.nsINavHistoryObserver.REASON_DELETED) && !this._inBatch) {
       this.populateGrid(true);
--- a/browser/metro/base/tests/mochiperf/browser_deck_01.js
+++ b/browser/metro/base/tests/mochiperf/browser_deck_01.js
@@ -1,11 +1,13 @@
 /* Any copyright is dedicated to the Public Domain.
    http://creativecommons.org/publicdomain/zero/1.0/ */
 
+"use strict";
+
 function test() {
   let testDir = gTestPath.substr(0, gTestPath.lastIndexOf("/"));
   Services.scriptloader.loadSubScript(testDir + "/perfhelpers.js", this);
   runTests();
 }
 
 gTests.push({
   desc: "deck offset",
--- a/browser/metro/base/tests/mochiperf/browser_firstx.js
+++ b/browser/metro/base/tests/mochiperf/browser_firstx.js
@@ -1,11 +1,13 @@
 /* Any copyright is dedicated to the Public Domain.
    http://creativecommons.org/publicdomain/zero/1.0/ */
 
+"use strict";
+
 function test() {
   let testDir = gTestPath.substr(0, gTestPath.lastIndexOf("/"));
   Services.scriptloader.loadSubScript(testDir + "/perfhelpers.js", this);
   runTests();
 }
 
 gTests.push({
   desc: "first x metrics",
--- a/browser/metro/base/tests/mochiperf/msgmanagerecho.js
+++ b/browser/metro/base/tests/mochiperf/msgmanagerecho.js
@@ -1,16 +1,18 @@
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 /*
  * TestEchoReceiver - receives json data, reserializes it and send it back.
  */ 
 
+"use strict";
+
 var TestEchoReceiver = {
   init: function init() {
     addMessageListener("Test:EchoRequest", this);
   },
 
   receiveMessage: function receiveMessage(aMessage) {
     let json = aMessage.json;
     switch (aMessage.name) {
--- a/browser/metro/base/tests/mochiperf/perfhelpers.js
+++ b/browser/metro/base/tests/mochiperf/perfhelpers.js
@@ -1,11 +1,13 @@
 /* Any copyright is dedicated to the Public Domain.
    http://creativecommons.org/publicdomain/zero/1.0/ */
 
+"use strict";
+
 // Misc. constants
 const kInfoHeader = "PERF-TEST | ";
 const kDeclareId = "DECLARE ";
 const kResultsId = "RESULTS ";
 
 // Mochitest log data format version
 const kDataSetVersion = "1";
 
--- a/browser/metro/base/tests/mochitest/browser_selection_urlbar.js
+++ b/browser/metro/base/tests/mochitest/browser_selection_urlbar.js
@@ -129,15 +129,46 @@ gTests.push({
     let editCoords = logicalCoordsForElement(edit);
     SelectionHelperUI.attachEditSession(ChromeSelectionHandler, editCoords.x, editCoords.y);
     edit.blur();
     ok(!SelectionHelperUI.isSelectionUIVisible, "selection no longer enabled");
     clearSelection(edit);
   }
 });
 
+function getClipboardCondition(aExpected) {
+  return () => aExpected == SpecialPowers.getClipboardData("text/unicode");
+}
+
+gTests.push({
+  desc: "bug 894715 - URLs selected by touch are copied with trimming",
+  run: function () {
+    gWindow = window;
+    yield showNavBar();
+
+    let edit = document.getElementById("urlbar-edit");
+    edit.value = "http://www.wikipedia.org/";
+
+    sendElementTap(window, edit);
+    edit.select();
+
+    let panel = ContextMenuUI._menuPopup._panel;
+    let promise = waitForEvent(panel, "popupshown")
+    sendContextMenuClickToElement(window, edit);
+    ok((yield promise), "show context menu");
+
+    let copy = document.getElementById("context-copy");
+    ok(!copy.hidden, "copy menu item is visible")
+
+    let condition = getClipboardCondition("http://www.wikipedia.org/");
+    let promise = waitForCondition(condition);
+    sendElementTap(window, copy);
+    ok((yield promise), "copy text onto clipboard")
+  }
+})
+
 function test() {
   if (!isLandscapeMode()) {
     todo(false, "browser_selection_tests need landscape mode to run.");
     return;
   }
   runTests();
 }
--- a/browser/metro/base/tests/unit/test_util_extend.js
+++ b/browser/metro/base/tests/unit/test_util_extend.js
@@ -1,8 +1,10 @@
+"use strict";
+
 load('Util.js');
 
 function run_test() {
   do_print("Testing Util.extend");
   
   do_print("Check if function is defined");
   do_check_true(!!Util.extend);
 
--- a/browser/metro/locales/en-US/chrome/browser.dtd
+++ b/browser/metro/locales/en-US/chrome/browser.dtd
@@ -8,17 +8,16 @@
 <!ENTITY urlbar.accesskey      "d">
 
 <!ENTITY back.label            "Back">
 <!ENTITY forward.label         "Forward">
 <!ENTITY newtab.label          "New Tab">
 <!ENTITY closetab.label        "Close Tab">
 
 <!ENTITY autocompleteResultsHeader.label  "Your Results">
-<!ENTITY autocompleteSearchesHeader.label "Internet Searches">
 
 <!ENTITY appbarErrorConsole.label   "Open error console">
 <!ENTITY appbarJSShell.label        "Open JavaScript shell">
 <!ENTITY appbarFindInPage2.label    "Find in page">
 <!ENTITY appbarViewOnDesktop2.label "View on desktop">
 
 <!ENTITY topSitesHeader.label        "Top Sites">
 <!ENTITY bookmarksHeader.label       "Bookmarks">
--- a/browser/metro/locales/en-US/chrome/browser.properties
+++ b/browser/metro/locales/en-US/chrome/browser.properties
@@ -123,18 +123,19 @@ offlineApps.wantsTo=%S wants to store da
 
 # IndexedDB Quota increases
 indexedDBQuota.allow=Allow
 indexedDBQuota.wantsTo=%S wants to store a lot of data on your device for offline use.
 
 tabs.emptyTabTitle=New Tab
 
 # Open Search
-# LOCALIZATION NOTE (opensearch.search): %S is the word or phrase typed by the user
-opensearch.search=Search: %S
+# LOCALIZATION NOTE (opensearch.search.header): %S is the word or phrase
+# typed by the user in the urlbar to search
+opensearch.search.header=Search for ā€œ%Sā€ on:
 
 # Check for Updates in the About Panel - button labels and accesskeys
 # LOCALIZATION NOTE - all of the following update buttons labels will only be
 # displayed one at a time. So, if a button is displayed nothing else will
 # be displayed alongside of the button. The button when displayed is located
 # directly under the Firefox version in the about dialog (see bug 596813 for
 # screenshots).
 update.checkInsideButton.label=Check for Updates
--- a/browser/metro/modules/View.jsm
+++ b/browser/metro/modules/View.jsm
@@ -53,16 +53,23 @@ View.prototype = {
       aIconUri = makeURI(aIconUri);
     }
     aItem.iconSrc = aIconUri.spec;
     let faviconURL = (PlacesUtils.favicons.getFaviconLinkForIcon(aIconUri)).spec;
     let xpFaviconURI = makeURI(faviconURL.replace("moz-anno:favicon:",""));
     let successAction = function(foreground, background) {
       aItem.style.color = foreground; //color text
       aItem.setAttribute("customColor", background);
+      let matteColor =  0xffffff; // white
+      let alpha = 0.04; // the tint weight
+      let [,r,g,b] = background.match(/rgb\((\d+),(\d+),(\d+)/);
+      // get the rgb value that represents this color at given opacity over a white matte
+      let tintColor = ColorUtils.addRgbColors(matteColor, ColorUtils.createDecimalColorWord(r,g,b,alpha));
+      aItem.setAttribute("tintColor", ColorUtils.convertDecimalToRgbColor(tintColor));
+
       if (aItem.refresh) {
         aItem.refresh();
       }
     };
     let failureAction = function() {};
     ColorUtils.getForegroundAndBackgroundIconColors(xpFaviconURI, successAction, failureAction);
   }
 
--- a/browser/metro/theme/browser.css
+++ b/browser/metro/theme/browser.css
@@ -444,17 +444,17 @@ documenttab[selected] .documenttab-selec
 #navbar {
   visibility: visible;
 }
 #navbar:not([hiding]):not([visible]) > #toolbar-overlay {
   visibility: hidden;
 }
 
 .circularprogressindicator-progressRing {
-  margin: 0 @toolbar_horizontal_spacing@;
+  margin: -2px 18px;
   pointer-events:none;
   position: absolute;
 }
 
 /* Progress meter ---------------------------------------------------------- */
 
 #progress-container {
   display: block;
index f0a4dbfdf948a8227a3076f6fa4876ee4b36b210..44de3fb173079de5bf89e9b94977d43f3e930e50
GIT binary patch
literal 363
zc%17D@N?(olHy`uVBq!ia0vp^Iv~u!1|;QLq8Nb`TavfC3&Vd9T(EcfWS|IVfk$L9
z1A}ZE2s6em5^e+vvX^-Jy0YKp;1uQ3?A@~=9Vqm})5S3);_%y<rv(oiaJZZeoA@dy
zW|g=2Io0+Uk<XEgpE@?T*SdLlD6k)ndmsGu?q|h7&6#|jZPQCGDD0ThXmxNY>l((W
zOJ*V`{e6z?er@`J`TnCKFN=A5q=ML9UzrpX(Y|cTVX3VXLxX-k|L}s}IKgz{zoG>;
zo7{Ytgc&(Kxu~^^D_5pla+*i`{4EZ<OLing7^s?kV7qrf`Uc;fg)?|0E-dnp=sMY3
zw8KdEU&i9IcO5IYJM4Hk@ux)S{#l#D92W8)i%*a0ck4<lot_<fGhXJ*mx3Q%ja##}
zM=d^(l@b4A*TWME+_S8v%;dDoeRGt}Us~tfof%xe8Em3@ohN<|s|1DtgQu&X%Q~lo
FCIA^ulwkk>
--- a/browser/metro/theme/platform.css
+++ b/browser/metro/theme/platform.css
@@ -572,33 +572,32 @@ arrowbox {
 
 .meta-section {
   margin: 0 @metro_spacing_large@;
 }
 
 .meta-section-title {
   font-size: @metro_font_large@;
   font-weight: 100;
-  display: none;
   cursor: default;
 }
 
 #start-container[viewstate="snapped"] {
   padding-top: 0;
 }
 
 #start-container[viewstate="snapped"] .meta-section-title,
 #start-container[viewstate="snapped"] richgrid {
   margin-top: @metro_spacing_xnormal@;
   padding: 0;
 }
 
-#start-container[viewstate="snapped"] .meta-section-title.narrow-title,
-#start-container:not([viewstate="snapped"]) .meta-section-title.wide-title {
-  display: block;
+#start-container:not([viewstate="snapped"]) .meta-section-title.narrow-title,
+#start-container[viewstate="snapped"] .meta-section-title.wide-title {
+  display: none;
 }
 
 .meta-section:not([expanded]) > .meta-section-title.narrow-title:-moz-locale-dir(ltr):after {
   content: ">";
 }
 
 .meta-section:not([expanded]) > .meta-section-title.narrow-title:-moz-locale-dir(rtl):before {
   content: "<";
--- a/browser/metro/theme/tiles.css
+++ b/browser/metro/theme/tiles.css
@@ -57,71 +57,98 @@ richgriditem {
   transition: 300ms height ease-out,
               150ms opacity ease-out,
               100ms transform ease-out;
 }
 
 .tile-content {
   display: block;
   position: absolute;
-  background-color: #fff;
+  /* background-color colors the tile-edge,
+     and will normally be overridden with a favicon-based color */
+  background-color: #ccc;
   background-origin: padding-box;
   /* content positioning within the grid "cell"
      gives us the gutters/spacing between tiles */
   top: 2px; right: 6px; bottom: 10px; left: 6px;
   border: @metro_border_thin@ solid @tile_border_color@;
   box-shadow: 0 0 5px 0 rgba(0, 0, 0, 0.1);
   transition: 150ms transform ease-out;
 }
 
 .tile-start-container {
   position: absolute;
   top: 0;
   bottom: 0;
   right: 0;
-  left: 20px;
-  background: hsla(0,2%,98%,.95);
+  left: 10px;
   padding: 8px;
+  background-color: #fff;
 }
 
 richgriditem:not([tiletype="thumbnail"]) .tile-start-container {
   background-image: none!important;
 }
 
 .tile-icon-box {
-  display: inline-block;
-  padding: 4px;
-  background: #fff;
+  position: absolute;
+  top: 50%;
+  margin-top: -17px;
+  padding: 8px;
+  /* default color, may be overriden by a favicon-based color */
+  background-color: white;
+  border: 1px solid #ccc;
+  border-radius: 1px;
   opacity: 1.0;
 }
 
 .tile-icon-box > image {
+  display: block;
+  width: 16px;
+  height: 16px;
+  list-style-image: url("chrome://browser/skin/images/identity-icons-generic.png");
+}
+
+/* for larger favicons (which includes the fallback icon) */
+richgriditem:not([iconURI]) .tile-icon-box,
+richgriditem[iconURI=""] .tile-icon-box,
+richgriditem[iconsize="large"] .tile-icon-box {
+  background-color: transparent!important;
+  border-color: transparent!important;
+  padding: 4px;
+}
+
+richgriditem[iconsize="large"] .tile-icon-box > image,
+.tile-icon-box > image[src=""] {
   width: 24px;
   height: 24px;
-  list-style-image: url("chrome://browser/skin/images/identity-icons-generic.png");
 }
 
 .tile-desc {
   display: block;
   position: absolute;
-  bottom: 0;
+  top: 6px;
+  left: 52px; /* label goes to the right of the favicon */
   right: 0;
-  left: 20px; /* the colored bar in the default tile is the background color peeking through */
-  z-index: 1;
-  padding: 4px 8px;
+  padding: 1em 6px 6px 12px;
   color: #333;
   margin: 0;
   -moz-margin-start: 0;
   display: block;
-  font-size: 20px;
+  font-size: 16px;
   overflow: hidden;
   white-space: nowrap;
   text-overflow: ellipsis;
 }
 
+richgriditem:not([tiletype="thumbnail"]) .tile-desc {
+  background-color: transparent!important;
+}
+
+
 richgriditem.collapsed {
   height: 0!important;
   overflow: hidden;
   opacity: 0;
 }
 
 richgriditem.collapsed > .tile-content {
   transform: scaleY(0);
@@ -142,40 +169,46 @@ richgriditem[tiletype="thumbnail"] {
   width: @grid_double_column_width@;
   height: @grid_double_row_height@;
   -moz-box-pack: end;
   padding: 0px;
   color: #1a1a1a;
 }
 
 richgriditem[tiletype="thumbnail"] .tile-desc {
-  background: transparent;
-  margin: 0px;
+  margin: 0;
+  top: auto;
+  bottom: 0;
   left: 0;
+  padding: 4px 8px 4px 56px;
 }
 
 richgriditem[tiletype="thumbnail"] > .tile-content > .tile-desc {
   /* ensure thumbnail labels get their color from the parent richgriditem element */
   color: inherit;
 }
 
-/* put the image in place of the icon if there is an image background */
+/* thumbnail tiles use a screenshot thumbnail as the background */
 richgriditem[tiletype="thumbnail"] > .tile-content > .tile-start-container {
   background-size: cover;
   background-position: top left;
   background-repeat: no-repeat;
   position: absolute;
   top: 0;
-  bottom: 32px; /* TODO: should be some em value? */;
+  bottom: 0;
   right: 0;
   left: 0;
-  background-color: hsla(0,2%,98%,.95);
 }
 richgriditem[tiletype="thumbnail"] .tile-icon-box {
-  visibility: collapse;
+  top: auto;
+  left: 10px;
+  bottom: 6px;
+  margin-top: 0;
+  z-index: 1;
+  box-shadow: 0px 0px 2px 2px rgba(0, 0, 0, 0.05), 0px 2px 0px rgba(0, 0, 0, 0.1);
 }
 
 /* selected tile indicator */
 richgriditem[selected] > .tile-content::after {
   content: "";
   pointer-events: none;
   display: block;
   position: absolute;
@@ -257,35 +290,17 @@ richgriditem[bending] > .tile-content {
 
   richgriditem {
     width: @grid_double_column_width@;
     overflow: hidden;
     height: @compactgrid_row_height@;
   }
 
   .tile-desc {
-    top: 0;
-    left: 44px; /* label goes to the right of the favicon */
-    right: 0;
-    padding: 8px;
-  }
-
-  .tile-start-container {
-    position: absolute;
-    top: 0;
-    bottom: 0;
-    right: 0;
-    left: 6px;
-    background: #fff;
-    padding: 8px;
-  }
-  .tile-icon-box {
-    padding: 2px;
-    background: #fff;
-    opacity: 1.0;
+    padding: 0.5em 4px 4px 4px;
   }
 
   .tile-content {
     left: 0;
     right: 0;
   }
 
   richgriditem {
--- a/config/config.mk
+++ b/config/config.mk
@@ -230,19 +230,20 @@ endif
 #
 _ENABLE_PIC=1
 
 # Determine if module being compiled is destined
 # to be merged into libxul
 
 ifdef LIBXUL_LIBRARY
 ifdef IS_COMPONENT
-ifndef MODULE_NAME
-$(error Component makefile does not specify MODULE_NAME.)
+$(error IS_COMPONENT is set, but is not compatible with LIBXUL_LIBRARY)
 endif
+ifdef MODULE_NAME
+$(error MODULE_NAME is $(MODULE_NAME) but MODULE_NAME and LIBXUL_LIBRARY are not compatible)
 endif
 ifdef FORCE_STATIC_LIB
 $(error Makefile sets FORCE_STATIC_LIB which was already implied by LIBXUL_LIBRARY)
 endif
 FORCE_STATIC_LIB=1
 ifneq ($(SHORT_LIBNAME),)
 $(error SHORT_LIBNAME is $(SHORT_LIBNAME) but SHORT_LIBNAME is not compatable with LIBXUL_LIBRARY)
 endif
new file mode 100644
--- /dev/null
+++ b/config/external/moz.build
@@ -0,0 +1,45 @@
+
+external_dirs = []
+if not CONFIG['MOZ_NATIVE_SQLITE']:
+    external_dirs += ['db/sqlite3/src']
+
+if not CONFIG['MOZ_NATIVE_JPEG']:
+    external_dirs += ['media/libjpeg']
+
+if CONFIG['MOZ_UPDATER']:
+    if not CONFIG['MOZ_NATIVE_BZ2']:
+        external_dirs += ['modules/libbz2']
+
+if CONFIG['MOZ_VORBIS']:
+    external_dirs += ['media/libvorbis']
+
+if CONFIG['MOZ_TREMOR']:
+    external_dirs += ['media/libtremor']
+
+if CONFIG['MOZ_OPUS']:
+    external_dirs += ['media/libopus']
+
+if CONFIG['MOZ_WEBM']:
+    external_dirs += ['media/libnestegg']
+
+if CONFIG['MOZ_VP8'] and not CONFIG['MOZ_NATIVE_LIBVPX']:
+    external_dirs += ['media/libvpx']
+
+if CONFIG['MOZ_OGG']:
+    external_dirs += ['media/libogg', 'media/libtheora']
+
+if CONFIG['MOZ_SPEEX_RESAMPLER']:
+    external_dirs += ['media/libspeex_resampler']
+
+if CONFIG['MOZ_SOUNDTOUCH']:
+    external_dirs += ['media/libsoundtouch']
+
+if CONFIG['MOZ_CUBEB']:
+    external_dirs += ['media/libcubeb']
+
+if not CONFIG['MOZ_NATIVE_PNG']:
+    external_dirs += ['media/libpng']
+
+external_dirs += ['media/kiss_fft']
+
+PARALLEL_DIRS += ['../../' + i for i in external_dirs]
new file mode 100644
--- /dev/null
+++ b/config/rebuild_check.py
@@ -0,0 +1,30 @@
+# 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/.
+
+import os
+
+def mtime(path):
+    return os.stat(path).st_mtime
+
+def rebuild_check(args):
+    target = args[0]
+    deps = args[1:]
+    if not os.path.exists(target):
+        print target
+        return
+    t = mtime(target)
+
+    newer = []
+    for dep in deps:
+        if mtime(dep) > t:
+            newer.append(dep)
+
+    if newer:
+        print 'Rebuilding %s because %s changed' % (target, ', '.join(newer))
+    else:
+        print 'Rebuilding %s for an unknown reason' % target
+
+if __name__ == '__main__':
+    import sys
+    rebuild_check(sys.argv[1:])
--- a/config/rules.mk
+++ b/config/rules.mk
@@ -86,17 +86,25 @@ endif
 endif
 endif
 
 ifdef SDK_HEADERS
 _EXTRA_EXPORTS := $(filter-out $(EXPORTS),$(SDK_HEADERS))
 EXPORTS += $(_EXTRA_EXPORTS)
 endif
 
-REPORT_BUILD = $(info $(notdir $<))
+ifdef REBUILD_CHECK
+ifdef .PYMAKE
+REPORT_BUILD = @%rebuild_check rebuild_check $@ $^
+else
+REPORT_BUILD = $(info $(shell $(PYTHON) $(MOZILLA_DIR)/config/rebuild_check.py $@ $^))
+endif
+else
+REPORT_BUILD = $(info $(notdir $@))
+endif
 
 ifeq ($(OS_ARCH),OS2)
 EXEC			=
 else
 EXEC			= exec
 endif
 
 # Don't copy xulrunner files at install time, when using system xulrunner
@@ -862,16 +870,17 @@ alltags:
 	$(RM) TAGS
 	find $(topsrcdir) -name dist -prune -o \( -name '*.[hc]' -o -name '*.cp' -o -name '*.cpp' -o -name '*.idl' \) -print | $(TAG_PROGRAM)
 
 #
 # PROGRAM = Foo
 # creates OBJS, links with LIBS to create Foo
 #
 $(PROGRAM): $(PROGOBJS) $(EXTRA_DEPS) $(EXE_DEF_FILE) $(RESFILE) $(GLOBAL_DEPS)
+	$(REPORT_BUILD)
 	@$(RM) $@.manifest
 ifeq (_WINNT,$(GNU_CC)_$(OS_ARCH))
 	$(EXPAND_LD) -NOLOGO -OUT:$@ -PDB:$(LINK_PDBFILE) $(WIN32_EXE_LDFLAGS) $(LDFLAGS) $(MOZ_GLUE_PROGRAM_LDFLAGS) $(PROGOBJS) $(RESFILE) $(LIBS) $(EXTRA_LIBS) $(OS_LIBS)
 ifdef MSMANIFEST_TOOL
 	@if test -f $@.manifest; then \
 		if test -f "$(srcdir)/$@.manifest"; then \
 			echo "Embedding manifest from $(srcdir)/$@.manifest and $@.manifest"; \
 			mt.exe -NOLOGO -MANIFEST "$(win_srcdir)/$@.manifest" $@.manifest -OUTPUTRESOURCE:$@\;1; \
@@ -897,16 +906,17 @@ endif # WINNT && !GNU_CC
 ifdef ENABLE_STRIP
 	$(STRIP) $@
 endif
 ifdef MOZ_POST_PROGRAM_COMMAND
 	$(MOZ_POST_PROGRAM_COMMAND) $@
 endif
 
 $(HOST_PROGRAM): $(HOST_PROGOBJS) $(HOST_LIBS_DEPS) $(HOST_EXTRA_DEPS) $(GLOBAL_DEPS)
+	$(REPORT_BUILD)
 ifeq (_WINNT,$(GNU_CC)_$(HOST_OS_ARCH))
 	$(HOST_LD) -NOLOGO -OUT:$@ -PDB:$(HOST_PDBFILE) $(HOST_OBJS) $(WIN32_EXE_LDFLAGS) $(HOST_LDFLAGS) $(HOST_LIBS) $(HOST_EXTRA_LIBS)
 ifdef MSMANIFEST_TOOL
 	@if test -f $@.manifest; then \
 		if test -f "$(srcdir)/$@.manifest"; then \
 			echo "Embedding manifest from $(srcdir)/$@.manifest and $@.manifest"; \
 			mt.exe -NOLOGO -MANIFEST "$(win_srcdir)/$@.manifest" $@.manifest -OUTPUTRESOURCE:$@\;1; \
 		else \
@@ -930,16 +940,17 @@ endif
 # This is an attempt to support generation of multiple binaries
 # in one directory, it assumes everything to compile Foo is in
 # Foo.o (from either Foo.c or Foo.cpp).
 #
 # SIMPLE_PROGRAMS = Foo Bar
 # creates Foo.o Bar.o, links with LIBS to create Foo, Bar.
 #
 $(SIMPLE_PROGRAMS): %$(BIN_SUFFIX): %.$(OBJ_SUFFIX) $(EXTRA_DEPS) $(GLOBAL_DEPS)
+	$(REPORT_BUILD)
 ifeq (_WINNT,$(GNU_CC)_$(OS_ARCH))
 	$(EXPAND_LD) -nologo -out:$@ -pdb:$(LINK_PDBFILE) $< $(WIN32_EXE_LDFLAGS) $(LDFLAGS) $(MOZ_GLUE_PROGRAM_LDFLAGS) $(LIBS) $(EXTRA_LIBS) $(OS_LIBS)
 ifdef MSMANIFEST_TOOL
 	@if test -f $@.manifest; then \
 		mt.exe -NOLOGO -MANIFEST $@.manifest -OUTPUTRESOURCE:$@\;1; \
 		rm -f $@.manifest; \
 	fi
 endif	# MSVC with manifest tool
@@ -951,38 +962,41 @@ endif # WINNT && !GNU_CC
 ifdef ENABLE_STRIP
 	$(STRIP) $@
 endif
 ifdef MOZ_POST_PROGRAM_COMMAND
 	$(MOZ_POST_PROGRAM_COMMAND) $@
 endif
 
 $(HOST_SIMPLE_PROGRAMS): host_%$(HOST_BIN_SUFFIX): host_%.$(OBJ_SUFFIX) $(HOST_LIBS_DEPS) $(HOST_EXTRA_DEPS) $(GLOBAL_DEPS)
+	$(REPORT_BUILD)
 ifeq (WINNT_,$(HOST_OS_ARCH)_$(GNU_CC))
 	$(HOST_LD) -NOLOGO -OUT:$@ -PDB:$(HOST_PDBFILE) $< $(WIN32_EXE_LDFLAGS) $(HOST_LIBS) $(HOST_EXTRA_LIBS)
 else
 ifneq (,$(HOST_CPPSRCS)$(USE_HOST_CXX))
 	$(HOST_CXX) $(HOST_OUTOPTION)$@ $(HOST_CXXFLAGS) $(INCLUDES) $< $(HOST_LIBS) $(HOST_EXTRA_LIBS)
 else
 	$(HOST_CC) $(HOST_OUTOPTION)$@ $(HOST_CFLAGS) $(INCLUDES) $< $(HOST_LIBS) $(HOST_EXTRA_LIBS)
 endif
 endif
 
 ifdef DTRACE_PROBE_OBJ
 EXTRA_DEPS += $(DTRACE_PROBE_OBJ)
 OBJS += $(DTRACE_PROBE_OBJ)
 endif
 
 $(filter %.$(LIB_SUFFIX),$(LIBRARY)): $(OBJS) $(LOBJS) $(EXTRA_DEPS) $(GLOBAL_DEPS)
+	$(REPORT_BUILD)
 	$(RM) $(LIBRARY)
 	$(EXPAND_AR) $(AR_FLAGS) $(OBJS) $(LOBJS) $(SHARED_LIBRARY_LIBS)
 	$(RANLIB) $@
 
 $(filter-out %.$(LIB_SUFFIX),$(LIBRARY)): $(filter %.$(LIB_SUFFIX),$(LIBRARY)) $(OBJS) $(LOBJS) $(EXTRA_DEPS) $(GLOBAL_DEPS)
 # When we only build a library descriptor, blow out any existing library
+	$(REPORT_BUILD)
 	$(if $(filter %.$(LIB_SUFFIX),$(LIBRARY)),,$(RM) $(REAL_LIBRARY) $(EXPORT_LIBRARY:%=%/$(REAL_LIBRARY)))
 	$(EXPAND_LIBS_GEN) -o $@ $(OBJS) $(LOBJS) $(SHARED_LIBRARY_LIBS)
 
 ifeq ($(OS_ARCH),WINNT)
 # Import libraries are created by the rules creating shared libraries.
 # The rules to copy them to $(DIST)/lib depend on $(IMPORT_LIBRARY),
 # but make will happily consider the import library before it is refreshed
 # when rebuilding the corresponding shared library. Defining an empty recipe
@@ -999,22 +1013,24 @@ ifeq ($(OS_ARCH),OS2)
 	echo PROTMODE >> $@
 	echo CODE    LOADONCALL MOVEABLE DISCARDABLE >> $@
 	echo DATA    PRELOAD MOVEABLE MULTIPLE NONSHARED >> $@
 	echo EXPORTS >> $@
 
 	$(ADD_TO_DEF_FILE)
 
 $(IMPORT_LIBRARY): $(SHARED_LIBRARY)
+	$(REPORT_BUILD)
 	$(RM) $@
 	$(IMPLIB) $@ $^
 	$(RANLIB) $@
 endif # OS/2
 
 $(HOST_LIBRARY): $(HOST_OBJS) Makefile
+	$(REPORT_BUILD)
 	$(RM) $@
 	$(HOST_AR) $(HOST_AR_FLAGS) $(HOST_OBJS)
 	$(HOST_RANLIB) $@
 
 ifdef HAVE_DTRACE
 ifndef XP_MACOSX
 ifdef DTRACE_PROBE_OBJ
 ifndef DTRACE_LIB_DEPENDENT
@@ -1027,17 +1043,17 @@ endif
 endif
 
 # On Darwin (Mac OS X), dwarf2 debugging uses debug info left in .o files,
 # so instead of deleting .o files after repacking them into a dylib, we make
 # symlinks back to the originals. The symlinks are a no-op for stabs debugging,
 # so no need to conditionalize on OS version or debugging format.
 
 $(SHARED_LIBRARY): $(OBJS) $(LOBJS) $(DEF_FILE) $(RESFILE) $(LIBRARY) $(EXTRA_DEPS) $(GLOBAL_DEPS)
-	$(info $(notdir $@))
+	$(REPORT_BUILD)
 ifndef INCREMENTAL_LINKER
 	$(RM) $@
 endif
 ifdef DTRACE_LIB_DEPENDENT
 ifndef XP_MACOSX
 	dtrace -G -C -s $(MOZILLA_DTRACE_SRC) -o  $(DTRACE_PROBE_OBJ) $(shell $(EXPAND_LIBS) $(MOZILLA_PROBE_LIBS))
 endif
 	$(EXPAND_MKSHLIB) $(SHLIB_LDSTARTFILE) $(OBJS) $(LOBJS) $(SUB_SHLOBJS) $(DTRACE_PROBE_OBJ) $(MOZILLA_PROBE_LIBS) $(RESFILE) $(LDFLAGS) $(WRAP_LDFLAGS) $(SHARED_LIBRARY_LIBS) $(EXTRA_DSO_LDOPTS) $(MOZ_GLUE_LDFLAGS) $(OS_LIBS) $(EXTRA_LIBS) $(DEF_FILE) $(SHLIB_LDENDFILE) $(if $(LIB_IS_C_ONLY),,$(STLPORT_LIBS))
@@ -1125,32 +1141,37 @@ endef
 	$(REPORT_BUILD)
 	@$(MAKE_DEPS_AUTO_CC)
 	$(ELOG) $(CC) $(OUTOPTION)$@ -c $(COMPILE_CFLAGS) $(TARGET_LOCAL_INCLUDES) $(_VPATH_SRCS)
 
 # DEFINES and ACDEFINES are needed here to enable conditional compilation of Q_OBJECTs:
 # 'moc' only knows about #defines it gets on the command line (-D...), not in
 # included headers like mozilla-config.h
 moc_%.cpp: %.h
+	$(REPORT_BUILD)
 	$(ELOG) $(MOC) $(DEFINES) $(ACDEFINES) $< $(OUTOPTION)$@
 
 moc_%.cc: %.cc
+	$(REPORT_BUILD)
 	$(ELOG) $(MOC) $(DEFINES) $(ACDEFINES) $(_VPATH_SRCS:.cc=.h) $(OUTOPTION)$@
 
 qrc_%.cpp: %.qrc
+	$(REPORT_BUILD)
 	$(ELOG) $(RCC) -name $* $< $(OUTOPTION)$@
 
 ifdef ASFILES
 # The AS_DASH_C_FLAG is needed cause not all assemblers (Solaris) accept
 # a '-c' flag.
 $(ASOBJS):
+	$(REPORT_BUILD)
 	$(AS) $(ASOUTOPTION)$@ $(ASFLAGS) $(AS_DASH_C_FLAG) $(_VPATH_SRCS)
 endif
 
 $(SOBJS):
+	$(REPORT_BUILD)
 	$(AS) -o $@ $(ASFLAGS) $(LOCAL_INCLUDES) $(TARGET_LOCAL_INCLUDES) -c $<
 
 $(CPPOBJS):
 	$(REPORT_BUILD)
 	@$(MAKE_DEPS_AUTO_CXX)
 	$(ELOG) $(CCC) $(OUTOPTION)$@ -c $(COMPILE_CXXFLAGS) $(TARGET_LOCAL_INCLUDES) $(_VPATH_SRCS)
 
 $(CMMOBJS):
@@ -1159,37 +1180,45 @@ endif
 	$(ELOG) $(CCC) -o $@ -c $(COMPILE_CXXFLAGS) $(COMPILE_CMMFLAGS) $(TARGET_LOCAL_INCLUDES) $(_VPATH_SRCS)
 
 $(CMOBJS):
 	$(REPORT_BUILD)
 	@$(MAKE_DEPS_AUTO_CC)
 	$(ELOG) $(CC) -o $@ -c $(COMPILE_CFLAGS) $(COMPILE_CMFLAGS) $(TARGET_LOCAL_INCLUDES) $(_VPATH_SRCS)
 
 %.s: %.cpp $(call mkdir_deps,$(MDDEPDIR))
+	$(REPORT_BUILD)
 	$(CCC) -S $(COMPILE_CXXFLAGS) $(TARGET_LOCAL_INCLUDES) $(_VPATH_SRCS)
 
 %.s: %.cc $(call mkdir_deps,$(MDDEPDIR))
+	$(REPORT_BUILD)
 	$(CCC) -S $(COMPILE_CXXFLAGS) $(TARGET_LOCAL_INCLUDES) $(_VPATH_SRCS)
 
 %.s: %.c $(call mkdir_deps,$(MDDEPDIR))
+	$(REPORT_BUILD)
 	$(CC) -S $(COMPILE_CFLAGS) $(TARGET_LOCAL_INCLUDES) $(_VPATH_SRCS)
 
 %.i: %.cpp $(call mkdir_deps,$(MDDEPDIR))
+	$(REPORT_BUILD)
 	$(CCC) -C -E $(COMPILE_CXXFLAGS) $(TARGET_LOCAL_INCLUDES) $(_VPATH_SRCS) > $*.i
 
 %.i: %.cc $(call mkdir_deps,$(MDDEPDIR))
+	$(REPORT_BUILD)
 	$(CCC) -C -E $(COMPILE_CXXFLAGS) $(TARGET_LOCAL_INCLUDES) $(_VPATH_SRCS) > $*.i
 
 %.i: %.c $(call mkdir_deps,$(MDDEPDIR))
+	$(REPORT_BUILD)
 	$(CC) -C -E $(COMPILE_CFLAGS) $(TARGET_LOCAL_INCLUDES) $(_VPATH_SRCS) > $*.i
 
 %.i: %.mm $(call mkdir_deps,$(MDDEPDIR))
+	$(REPORT_BUILD)
 	$(CCC) -C -E $(COMPILE_CXXFLAGS) $(COMPILE_CMMFLAGS) $(TARGET_LOCAL_INCLUDES) $(_VPATH_SRCS) > $*.i
 
 %.res: %.rc
+	$(REPORT_BUILD)
 	@echo Creating Resource file: $@
 ifeq ($(OS_ARCH),OS2)
 	$(RC) $(RCFLAGS:-D%=-d %) -i $(subst /,\,$(srcdir)) -r $< $@
 else
 ifdef GNU_CC
 	$(RC) $(RCFLAGS) $(filter-out -U%,$(DEFINES)) $(INCLUDES:-I%=--include-dir %) $(OUTOPTION)$@ $(_VPATH_SRCS)
 else
 	$(RC) $(RCFLAGS) -r $(DEFINES) $(INCLUDES) $(OUTOPTION)$@ $(_VPATH_SRCS)
@@ -1254,20 +1283,22 @@ else
 _JAVA_CLASSPATH = .
 endif
 
 _JAVA_DIR = _java
 $(_JAVA_DIR)::
 	$(NSINSTALL) -D $@
 
 $(_JAVA_DIR)/%.class: %.java $(GLOBAL_DEPS) $(_JAVA_DIR)
+	$(REPORT_BUILD)
 	$(JAVAC) $(JAVAC_FLAGS) -classpath $(_JAVA_CLASSPATH) \
 			-sourcepath $(_JAVA_SOURCEPATH) -d $(_JAVA_DIR) $(_VPATH_SRCS)
 
 $(JAVA_LIBRARY): $(addprefix $(_JAVA_DIR)/,$(JAVA_SRCS:.java=.class)) $(GLOBAL_DEPS)
+	$(REPORT_BUILD)
 	$(JAR) cf $@ -C $(_JAVA_DIR) .
 
 GARBAGE_DIRS += $(_JAVA_DIR)
 
 ###############################################################################
 # Update Files Managed by Build Backend
 ###############################################################################
 
--- a/content/base/public/nsINode.h
+++ b/content/base/public/nsINode.h
@@ -941,17 +941,17 @@ public:
     }
     else {
       UnsetFlags(NODE_IS_EDITABLE);
     }
   }
 
   bool IsEditable() const
   {
-#ifdef _IMPL_NS_LAYOUT
+#ifdef MOZILLA_INTERNAL_API
     return IsEditableInternal();
 #else
     return IsEditableExternal();
 #endif
   }
 
   /**
    * Returns true if |this| or any of its ancestors is native anonymous.
--- a/content/base/src/Makefile.in
+++ b/content/base/src/Makefile.in
@@ -46,17 +46,16 @@ LOCAL_INCLUDES += \
   -I$(topsrcdir)/layout/generic \
   -I$(topsrcdir)/layout/style \
   -I$(topsrcdir)/layout/svg \
   -I$(topsrcdir)/layout/xul/base/src \
   -I$(topsrcdir)/netwerk/base/src \
   -I$(topsrcdir)/js/xpconnect/wrappers \
   $(NULL)
 
-DEFINES += -D_IMPL_NS_LAYOUT
 DEFINES += -DHB_DONT_DEFINE_STDINT
 
 # gcc requires -msse2 for this file since it uses SSE2 intrinsics.  (See bug
 # 585538 comment 12.)
 ifneq (,$(INTEL_ARCHITECTURE))
 ifdef GNU_CC
 nsTextFragmentSSE2.$(OBJ_SUFFIX): CXXFLAGS+=-msse2
 endif
--- a/content/base/src/nsDocument.cpp
+++ b/content/base/src/nsDocument.cpp
@@ -493,17 +493,17 @@ struct nsRadioGroupStruct
   nsRadioGroupStruct()
     : mRequiredRadioCount(0)
     , mGroupSuffersFromValueMissing(false)
   {}
 
   /**
    * A strong pointer to the currently selected radio button.
    */
-  nsCOMPtr<nsIDOMHTMLInputElement> mSelectedRadioButton;
+  nsRefPtr<HTMLInputElement> mSelectedRadioButton;
   nsCOMArray<nsIFormControl> mRadioButtons;
   uint32_t mRequiredRadioCount;
   bool mGroupSuffersFromValueMissing;
 };
 
 
 nsDOMStyleSheetList::nsDOMStyleSheetList(nsIDocument *aDocument)
 {
@@ -1665,17 +1665,17 @@ static PLDHashOperator
 RadioGroupsTraverser(const nsAString& aKey, nsRadioGroupStruct* aData,
                      void* aClosure)
 {
   nsCycleCollectionTraversalCallback *cb =
     static_cast<nsCycleCollectionTraversalCallback*>(aClosure);
 
   NS_CYCLE_COLLECTION_NOTE_EDGE_NAME(*cb,
                                    "mRadioGroups entry->mSelectedRadioButton");
-  cb->NoteXPCOMChild(aData->mSelectedRadioButton);
+  cb->NoteXPCOMChild(ToSupports(aData->mSelectedRadioButton));
 
   uint32_t i, count = aData->mRadioButtons.Count();
   for (i = 0; i < count; ++i) {
     NS_CYCLE_COLLECTION_NOTE_EDGE_NAME(*cb,
                                        "mRadioGroups entry->mRadioButtons[i]");
     cb->NoteXPCOMChild(aData->mRadioButtons[i]);
   }
 
@@ -7267,78 +7267,76 @@ nsDocument::GetOrCreateRadioGroup(const 
   nsAutoPtr<nsRadioGroupStruct> newRadioGroup(new nsRadioGroupStruct());
   mRadioGroups.Put(tmKey, newRadioGroup);
 
   return newRadioGroup.forget();
 }
 
 void
 nsDocument::SetCurrentRadioButton(const nsAString& aName,
-                                  nsIDOMHTMLInputElement* aRadio)
+                                  HTMLInputElement* aRadio)
 {
   nsRadioGroupStruct* radioGroup = GetOrCreateRadioGroup(aName);
   radioGroup->mSelectedRadioButton = aRadio;
 }
 
-nsIDOMHTMLInputElement*
+HTMLInputElement*
 nsDocument::GetCurrentRadioButton(const nsAString& aName)
 {
   return GetOrCreateRadioGroup(aName)->mSelectedRadioButton;
 }
 
 NS_IMETHODIMP
 nsDocument::GetNextRadioButton(const nsAString& aName,
                                const bool aPrevious,
-                               nsIDOMHTMLInputElement*  aFocusedRadio,
-                               nsIDOMHTMLInputElement** aRadioOut)
+                               HTMLInputElement* aFocusedRadio,
+                               HTMLInputElement** aRadioOut)
 {
   // XXX Can we combine the HTML radio button method impls of
   //     nsDocument and nsHTMLFormControl?
   // XXX Why is HTML radio button stuff in nsDocument, as
   //     opposed to nsHTMLDocument?
   *aRadioOut = nullptr;
 
   nsRadioGroupStruct* radioGroup = GetOrCreateRadioGroup(aName);
 
   // Return the radio button relative to the focused radio button.
   // If no radio is focused, get the radio relative to the selected one.
-  nsCOMPtr<nsIDOMHTMLInputElement> currentRadio;
+  nsRefPtr<HTMLInputElement> currentRadio;
   if (aFocusedRadio) {
     currentRadio = aFocusedRadio;
   }
   else {
     currentRadio = radioGroup->mSelectedRadioButton;
     if (!currentRadio) {
       return NS_ERROR_FAILURE;
     }
   }
-  nsCOMPtr<nsIFormControl> radioControl(do_QueryInterface(currentRadio));
-  int32_t index = radioGroup->mRadioButtons.IndexOf(radioControl);
+  int32_t index = radioGroup->mRadioButtons.IndexOf(currentRadio);
   if (index < 0) {
     return NS_ERROR_FAILURE;
   }
 
   int32_t numRadios = radioGroup->mRadioButtons.Count();
-  bool disabled;
-  nsCOMPtr<nsIDOMHTMLInputElement> radio;
+  nsRefPtr<HTMLInputElement> radio;
   do {
     if (aPrevious) {
       if (--index < 0) {
         index = numRadios -1;
       }
     }
     else if (++index >= numRadios) {
       index = 0;
     }
-    radio = do_QueryInterface(radioGroup->mRadioButtons[index]);
-    NS_ASSERTION(radio, "mRadioButtons holding a non-radio button");
-    radio->GetDisabled(&disabled);
-  } while (disabled && radio != currentRadio);
-
-  NS_IF_ADDREF(*aRadioOut = radio);
+    NS_ASSERTION(static_cast<nsGenericHTMLFormElement*>(radioGroup->mRadioButtons[index])->IsHTML(nsGkAtoms::input),
+                 "mRadioButtons holding a non-radio button");
+    radio = static_cast<HTMLInputElement*>(radioGroup->mRadioButtons[index]);
+  } while (radio->Disabled() && radio != currentRadio);
+
+  radio.forget(aRadioOut);
   return NS_OK;
 }
 
 void
 nsDocument::AddToRadioGroup(const nsAString& aName,
                             nsIFormControl* aRadio)
 {
   nsRadioGroupStruct* radioGroup = GetOrCreateRadioGroup(aName);
--- a/content/base/src/nsDocument.h
+++ b/content/base/src/nsDocument.h
@@ -721,23 +721,26 @@ public:
   {
     return NS_ERROR_NOT_IMPLEMENTED;
   }
 
   // nsIRadioGroupContainer
   NS_IMETHOD WalkRadioGroup(const nsAString& aName,
                             nsIRadioVisitor* aVisitor,
                             bool aFlushContent) MOZ_OVERRIDE;
-  virtual void SetCurrentRadioButton(const nsAString& aName,
-                                     nsIDOMHTMLInputElement* aRadio) MOZ_OVERRIDE;
-  virtual nsIDOMHTMLInputElement* GetCurrentRadioButton(const nsAString& aName) MOZ_OVERRIDE;
-  NS_IMETHOD GetNextRadioButton(const nsAString& aName,
-                                const bool aPrevious,
-                                nsIDOMHTMLInputElement*  aFocusedRadio,
-                                nsIDOMHTMLInputElement** aRadioOut) MOZ_OVERRIDE;
+  virtual void
+    SetCurrentRadioButton(const nsAString& aName,
+                          mozilla::dom::HTMLInputElement* aRadio) MOZ_OVERRIDE;
+  virtual mozilla::dom::HTMLInputElement*
+    GetCurrentRadioButton(const nsAString& aName) MOZ_OVERRIDE;
+  NS_IMETHOD
+    GetNextRadioButton(const nsAString& aName,
+                       const bool aPrevious,
+                       mozilla::dom::HTMLInputElement*  aFocusedRadio,
+                       mozilla::dom::HTMLInputElement** aRadioOut) MOZ_OVERRIDE;
   virtual void AddToRadioGroup(const nsAString& aName,
                                nsIFormControl* aRadio) MOZ_OVERRIDE;
   virtual void RemoveFromRadioGroup(const nsAString& aName,
                                     nsIFormControl* aRadio) MOZ_OVERRIDE;
   virtual uint32_t GetRequiredRadioCount(const nsAString& aName) const MOZ_OVERRIDE;
   virtual void RadioRequiredChanged(const nsAString& aName,
                                     nsIFormControl* aRadio) MOZ_OVERRIDE;
   virtual bool GetValueMissingState(const nsAString& aName) const MOZ_OVERRIDE;
--- a/content/base/src/nsGkAtomList.h
+++ b/content/base/src/nsGkAtomList.h
@@ -44,17 +44,16 @@ GK_ATOM(mozeditorbogusnode, "_moz_editor
 GK_ATOM(mozgeneratedcontentbefore, "_moz_generated_content_before")
 GK_ATOM(mozgeneratedcontentafter, "_moz_generated_content_after")
 GK_ATOM(mozgeneratedcontentimage, "_moz_generated_content_image")
 GK_ATOM(mozquote, "_moz_quote")
 GK_ATOM(mozsignature, "moz-signature")
 GK_ATOM(_moz_is_glyph, "-moz-is-glyph")
 GK_ATOM(_moz_original_size, "_moz_original_size")
 GK_ATOM(_moz_target, "_moz_target")
-GK_ATOM(_moz_type, "_moz-type")
 GK_ATOM(menuactive, "_moz-menuactive")
 GK_ATOM(_poundDefault, "#default")
 GK_ATOM(_asterix, "*")
 GK_ATOM(a, "a")
 GK_ATOM(abbr, "abbr")
 GK_ATOM(abort, "abort")
 GK_ATOM(above, "above")
 GK_ATOM(acceltext, "acceltext")
--- a/content/base/src/nsStyleLinkElement.cpp
+++ b/content/base/src/nsStyleLinkElement.cpp
@@ -87,23 +87,16 @@ NS_IMETHODIMP
 nsStyleLinkElement::InitStyleLinkElement(bool aDontLoadStyle)
 {
   mDontLoadStyle = aDontLoadStyle;
 
   return NS_OK;
 }
 
 NS_IMETHODIMP
-nsStyleLinkElement::GetSheet(nsIDOMStyleSheet** aSheet)
-{
-  NS_IF_ADDREF(*aSheet = mStyleSheet);
-  return NS_OK;
-}
-
-NS_IMETHODIMP
 nsStyleLinkElement::SetEnableUpdates(bool aEnableUpdates)
 {
   mUpdatesEnabled = aEnableUpdates;
 
   return NS_OK;
 }
 
 NS_IMETHODIMP
--- a/content/base/src/nsStyleLinkElement.h
+++ b/content/base/src/nsStyleLinkElement.h
@@ -10,43 +10,38 @@
  * stylesheets (<style>, <link>, processing instructions, etc).
  */
 
 #ifndef nsStyleLinkElement_h___
 #define nsStyleLinkElement_h___
 
 #include "mozilla/Attributes.h"
 #include "nsCOMPtr.h"
-#include "nsIDOMLinkStyle.h"
 #include "nsIStyleSheetLinkingElement.h"
 #include "nsCSSStyleSheet.h"
 #include "nsTArray.h"
 #include "mozilla/CORSMode.h"
 
 #define PREFETCH      0x00000001
 #define DNS_PREFETCH  0x00000002
 #define STYLESHEET    0x00000004
 #define NEXT          0x00000008
 #define ALTERNATE     0x00000010
 
 class nsIDocument;
 class nsIURI;
 
-class nsStyleLinkElement : public nsIDOMLinkStyle,
-                           public nsIStyleSheetLinkingElement
+class nsStyleLinkElement : public nsIStyleSheetLinkingElement
 {
 public:
   nsStyleLinkElement();
   virtual ~nsStyleLinkElement();
 
   NS_IMETHOD QueryInterface(REFNSIID aIID, void** aInstancePtr) MOZ_OVERRIDE = 0;
 
-  // nsIDOMLinkStyle
-  NS_DECL_NSIDOMLINKSTYLE
-
   nsCSSStyleSheet* GetSheet() const { return mStyleSheet; }
 
   // nsIStyleSheetLinkingElement  
   NS_IMETHOD SetStyleSheet(nsCSSStyleSheet* aStyleSheet) MOZ_OVERRIDE;
   NS_IMETHOD GetStyleSheet(nsIStyleSheet*& aStyleSheet) MOZ_OVERRIDE;
   NS_IMETHOD InitStyleLinkElement(bool aDontLoadStyle) MOZ_OVERRIDE;
   NS_IMETHOD UpdateStyleSheet(nsICSSLoaderObserver* aObserver,
                               bool* aWillNotify,
--- a/content/canvas/src/Makefile.in
+++ b/content/canvas/src/Makefile.in
@@ -31,10 +31,8 @@ INCLUDES	+= \
 		-I$(srcdir)/../../../layout/style \
 		-I$(srcdir)/../../../layout/generic \
 		-I$(srcdir)/../../base/src \
 		-I$(srcdir)/../../html/content/src \
 		-I$(srcdir)/../../../js/xpconnect/src \
 		-I$(srcdir)/../../../dom/base \
 		-I$(topsrcdir)/content/xul/content/src \
 		$(NULL)
-
-DEFINES += -D_IMPL_NS_LAYOUT
--- a/content/events/src/Makefile.in
+++ b/content/events/src/Makefile.in
@@ -33,15 +33,13 @@ LOCAL_INCLUDES	+= \
              $(NULL)
 
 ifdef MOZ_B2G_RIL
 LOCAL_INCLUDES += \
               -I$(srcdir)/../../../dom/wifi \
               $(NULL)
 endif
 
-DEFINES += -D_IMPL_NS_LAYOUT
-
 ifdef MOZ_JSDEBUGGER
 DEFINES += -DMOZ_JSDEBUGGER
 endif
 
 
--- a/content/events/src/nsEventDispatcher.cpp
+++ b/content/events/src/nsEventDispatcher.cpp
@@ -49,37 +49,71 @@ private:
 #define NS_TARGET_CHAIN_MAY_HAVE_MANAGER        (1 << 2)
 
 // nsEventTargetChainItem represents a single item in the event target chain.
 class nsEventTargetChainItem
 {
 private:
   nsEventTargetChainItem(EventTarget* aTarget,
                          nsEventTargetChainItem* aChild = nullptr);
+
+  // This is the ETCI recycle pool, which is used to avoid some malloc/free
+  // churn.  It's implemented as a linked list.
+  static nsEventTargetChainItem* sEtciRecyclePool;
+  static uint32_t sNumRecycledEtcis;
+  static const uint32_t kMaxNumRecycledEtcis = 128;
+
 public:
-  nsEventTargetChainItem()
-  : mChild(nullptr), mParent(nullptr), mFlags(0), mItemFlags(0)
-  {
-  }
-
-  static nsEventTargetChainItem* Create(nsTArray<nsEventTargetChainItem>& aPool,
-                                        EventTarget* aTarget,
+  static nsEventTargetChainItem* Create(EventTarget* aTarget,
                                         nsEventTargetChainItem* aChild = nullptr)
   {
-    
-    return new (aPool.AppendElement()) nsEventTargetChainItem(aTarget, aChild);
+    // Allocate from the ETCI recycle pool if possible.
+    void* place = nullptr;
+    if (sNumRecycledEtcis > 0) {
+      MOZ_ASSERT(sEtciRecyclePool);
+      place = sEtciRecyclePool;
+      sEtciRecyclePool = sEtciRecyclePool->mNext;
+      --sNumRecycledEtcis;
+    } else {
+      place = malloc(sizeof(nsEventTargetChainItem));
+    }
+    return place
+      ? ::new (place) nsEventTargetChainItem(aTarget, aChild)
+      : nullptr;
   }
 
   static void Destroy(nsEventTargetChainItem* aItem)
   {
-    // nsEventTargetChainItem objects are deleted when the pool goes out of
-    // the scope.
-    if (aItem->mChild) {
-      aItem->mChild->mParent = nullptr;
-      aItem->mChild = nullptr;
+    // ::Destroy deletes ancestor chain.
+    nsEventTargetChainItem* item = aItem;
+    if (item->mChild) {
+      item->mChild->mParent = nullptr;
+      item->mChild = nullptr;
+    }
+    // Put destroyed ETCIs into the recycle pool if it's not already full.
+    while (item) {
+      nsEventTargetChainItem* parent = item->mParent;
+      item->~nsEventTargetChainItem();
+      if (sNumRecycledEtcis < kMaxNumRecycledEtcis) {
+        item->mNext = sEtciRecyclePool;
+        sEtciRecyclePool = item;
+        ++sNumRecycledEtcis;
+      } else {
+        free(item);
+      }
+      item = parent;
+    }
+  }
+
+  static void ShutdownRecyclePool()
+  {
+    while (sEtciRecyclePool) {
+      nsEventTargetChainItem* tmp = sEtciRecyclePool;
+      sEtciRecyclePool = sEtciRecyclePool->mNext;
+      free(tmp);
     }
   }
 
   bool IsValid()
   {
     NS_WARN_IF_FALSE(!!(mTarget), "Event target is not valid!");
     return !!(mTarget);
   }
@@ -194,28 +228,46 @@ public:
   }
 
   /**
    * Copies mItemFlags and mItemData to aVisitor and calls PostHandleEvent.
    */
   nsresult PostHandleEvent(nsEventChainPostVisitor& aVisitor,
                            nsCxPusher* aPusher);
 
+  static uint32_t MaxEtciCount() { return sMaxEtciCount; }
+
+  static void ResetMaxEtciCount()
+  {
+    MOZ_ASSERT(!sCurrentEtciCount, "Wrong time to call ResetMaxEtciCount()!");
+    sMaxEtciCount = 0;
+  }
+
   nsCOMPtr<EventTarget>             mTarget;
   nsEventTargetChainItem*           mChild;
-  nsEventTargetChainItem*           mParent;
+  union {
+    nsEventTargetChainItem*         mParent;
+     // This is used only when recycling ETCIs.
+    nsEventTargetChainItem*         mNext;
+  };
   uint16_t                          mFlags;
   uint16_t                          mItemFlags;
   nsCOMPtr<nsISupports>             mItemData;
   // Event retargeting must happen whenever mNewTarget is non-null.
   nsCOMPtr<EventTarget>             mNewTarget;
   // Cache mTarget's event listener manager.
   nsRefPtr<nsEventListenerManager>  mManager;
+
+  static uint32_t                   sMaxEtciCount;
+  static uint32_t                   sCurrentEtciCount;
 };
 
+nsEventTargetChainItem* nsEventTargetChainItem::sEtciRecyclePool = nullptr;
+uint32_t nsEventTargetChainItem::sNumRecycledEtcis = 0;
+
 nsEventTargetChainItem::nsEventTargetChainItem(EventTarget* aTarget,
                                                nsEventTargetChainItem* aChild)
 : mTarget(aTarget), mChild(aChild), mParent(nullptr), mFlags(0), mItemFlags(0)
 {
   MOZ_ASSERT(!aTarget || mTarget == aTarget->GetTargetForEventTargetChain());
   if (mChild) {
     mChild->mParent = this;
   }
@@ -348,32 +400,36 @@ nsEventTargetChainItem::HandleEventTarge
     // system group listeners don't affect to the event.
     aVisitor.mEvent->mFlags.mPropagationStopped = false;
     aVisitor.mEvent->mFlags.mImmediatePropagationStopped = false;
   }
 
   return NS_OK;
 }
 
+void NS_ShutdownEventTargetChainItemRecyclePool()
+{
+  nsEventTargetChainItem::ShutdownRecyclePool();
+}
+
 nsEventTargetChainItem*
-EventTargetChainItemForChromeTarget(nsTArray<nsEventTargetChainItem>& aPool,
-                                    nsINode* aNode,
+EventTargetChainItemForChromeTarget(nsINode* aNode,
                                     nsEventTargetChainItem* aChild = nullptr)
 {
   if (!aNode->IsInDoc()) {
     return nullptr;
   }
   nsPIDOMWindow* win = aNode->OwnerDoc()->GetInnerWindow();
   EventTarget* piTarget = win ? win->GetParentTarget() : nullptr;
   NS_ENSURE_TRUE(piTarget, nullptr);
 
   nsEventTargetChainItem* etci =
-    nsEventTargetChainItem::Create(aPool,
-                                   piTarget->GetTargetForEventTargetChain(),
+    nsEventTargetChainItem::Create(piTarget->GetTargetForEventTargetChain(),
                                    aChild);
+  NS_ENSURE_TRUE(etci, nullptr);
   if (!etci->IsValid()) {
     nsEventTargetChainItem::Destroy(etci);
     return nullptr;
   }
   return etci;
 }
 
 /* static */ nsresult
@@ -461,22 +517,20 @@ nsEventDispatcher::Dispatch(nsISupports*
 
   nsresult rv = NS_OK;
   bool externalDOMEvent = !!(aDOMEvent);
 
   // If we have a PresContext, make sure it doesn't die before
   // event dispatching is finished.
   nsRefPtr<nsPresContext> kungFuDeathGrip(aPresContext);
 
-  // Try to limit malloc/free churn by using an array as a pool.
-  nsTArray<nsEventTargetChainItem> pool(128);
-
   // Create the event target chain item for the event target.
   nsEventTargetChainItem* targetEtci =
-    nsEventTargetChainItem::Create(pool, target->GetTargetForEventTargetChain());
+    nsEventTargetChainItem::Create(target->GetTargetForEventTargetChain());
+  NS_ENSURE_TRUE(targetEtci, NS_ERROR_OUT_OF_MEMORY);
   if (!targetEtci->IsValid()) {
     nsEventTargetChainItem::Destroy(targetEtci);
     return NS_ERROR_FAILURE;
   }
 
   // Make sure that nsIDOMEvent::target and nsIDOMEvent::originalTarget
   // point to the last item in the chain.
   if (!aEvent->target) {
@@ -512,30 +566,34 @@ nsEventDispatcher::Dispatch(nsISupports*
   nsEventStatus status = aEventStatus ? *aEventStatus : nsEventStatus_eIgnore;
   nsEventChainPreVisitor preVisitor(aPresContext, aEvent, aDOMEvent, status,
                                     isInAnon);
   targetEtci->PreHandleEvent(preVisitor);
 
   if (!preVisitor.mCanHandle && preVisitor.mAutomaticChromeDispatch && content) {
     // Event target couldn't handle the event. Try to propagate to chrome.
     nsEventTargetChainItem::Destroy(targetEtci);
-    targetEtci = EventTargetChainItemForChromeTarget(pool, content);
+    targetEtci = EventTargetChainItemForChromeTarget(content);
     NS_ENSURE_STATE(targetEtci);
     targetEtci->PreHandleEvent(preVisitor);
   }
   if (preVisitor.mCanHandle) {
     // At least the original target can handle the event.
     // Setting the retarget to the |target| simplifies retargeting code.
     nsCOMPtr<EventTarget> t = do_QueryInterface(aEvent->target);
     targetEtci->SetNewTarget(t);
     nsEventTargetChainItem* topEtci = targetEtci;
     while (preVisitor.mParentTarget) {
       EventTarget* parentTarget = preVisitor.mParentTarget;
       nsEventTargetChainItem* parentEtci =
-        nsEventTargetChainItem::Create(pool, preVisitor.mParentTarget, topEtci);
+        nsEventTargetChainItem::Create(preVisitor.mParentTarget, topEtci);
+      if (!parentEtci) {
+        rv = NS_ERROR_OUT_OF_MEMORY;
+        break;
+      }
       if (!parentEtci->IsValid()) {
         rv = NS_ERROR_FAILURE;
         break;
       }
 
       // Item needs event retargetting.
       if (preVisitor.mEventTargetAtParent) {
         // Need to set the target of the event
@@ -550,18 +608,17 @@ nsEventDispatcher::Dispatch(nsISupports*
       } else {
         nsEventTargetChainItem::Destroy(parentEtci);
         parentEtci = nullptr;
         if (preVisitor.mAutomaticChromeDispatch && content) {
           // Even if the current target can't handle the event, try to
           // propagate to chrome.
           nsCOMPtr<nsINode> disabledTarget = do_QueryInterface(parentTarget);
           if (disabledTarget) {
-            parentEtci = EventTargetChainItemForChromeTarget(pool,
-                                                             disabledTarget,
+            parentEtci = EventTargetChainItemForChromeTarget(disabledTarget,
                                                              topEtci);
             if (parentEtci) {
               parentEtci->PreHandleEvent(preVisitor);
               if (preVisitor.mCanHandle) {
                 targetEtci->SetNewTarget(parentTarget);
                 topEtci = parentEtci;
                 continue;
               }
--- a/content/html/content/public/nsIRadioGroupContainer.h
+++ b/content/html/content/public/nsIRadioGroupContainer.h
@@ -2,21 +2,26 @@
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 #ifndef nsIRadioGroupContainer_h___
 #define nsIRadioGroupContainer_h___
 
 #include "nsISupports.h"
 
-class nsIDOMHTMLInputElement;
 class nsString;
 class nsIRadioVisitor;
 class nsIFormControl;
 
+namespace mozilla {
+namespace dom {
+class HTMLInputElement;
+}
+}
+
 #define NS_IRADIOGROUPCONTAINER_IID   \
 { 0x22924a01, 0x4360, 0x401b, \
   { 0xb1, 0xd1, 0x56, 0x8d, 0xf5, 0xa3, 0xda, 0x71 } }
 
 /**
  * A container that has multiple radio groups in it, defined by name.
  */
 class nsIRadioGroupContainer : public nsISupports
@@ -36,37 +41,37 @@ public:
                             nsIRadioVisitor* aVisitor,
                             bool aFlushContent) = 0;
 
   /**
    * Set the current radio button in a group
    * @param aName the group name
    * @param aRadio the currently selected radio button
    */
-  virtual void SetCurrentRadioButton(const nsAString& aName, 
-                                     nsIDOMHTMLInputElement* aRadio) = 0;
+  virtual void SetCurrentRadioButton(const nsAString& aName,
+                                     mozilla::dom::HTMLInputElement* aRadio) = 0;
 
   /**
    * Get the current radio button in a group
    * @param aName the group name
    * @return the currently selected radio button
    */
-  virtual nsIDOMHTMLInputElement* GetCurrentRadioButton(const nsAString& aName) = 0;
+  virtual mozilla::dom::HTMLInputElement* GetCurrentRadioButton(const nsAString& aName) = 0;
 
   /**
    * Get the next/prev radio button in a group
    * @param aName the group name
    * @param aPrevious, true gets previous radio button, false gets next
    * @param aFocusedRadio the currently focused radio button
    * @param aRadio the currently selected radio button [OUT]
    */
   NS_IMETHOD GetNextRadioButton(const nsAString& aName,
                                 const bool aPrevious,
-                                nsIDOMHTMLInputElement*  aFocusedRadio,
-                                nsIDOMHTMLInputElement** aRadio) = 0;
+                                mozilla::dom::HTMLInputElement*  aFocusedRadio,
+                                mozilla::dom::HTMLInputElement** aRadio) = 0;
 
   /**
    * Add radio button to radio group
    *
    * Note that forms do not do anything for this method since they already
    * store radio groups on their own.
    *
    * @param aName radio group's name
--- a/content/html/content/src/HTMLFormElement.cpp
+++ b/content/html/content/src/HTMLFormElement.cpp
@@ -33,17 +33,16 @@
 #include "nsIScriptSecurityManager.h"
 #include "nsNetUtil.h"
 #include "nsIWebProgress.h"
 #include "nsIDocShell.h"
 #include "nsFormData.h"
 #include "nsFormSubmissionConstants.h"
 
 // radio buttons
-#include "nsIDOMHTMLInputElement.h"
 #include "mozilla/dom/HTMLInputElement.h"
 #include "nsIRadioVisitor.h"
 
 #include "nsLayoutUtils.h"
 
 #include "nsEventDispatcher.h"
 
 #include "mozAutoDocUpdate.h"
@@ -281,23 +280,23 @@ HTMLFormElement::Init()
 
   return NS_OK;
 }
 
 
 // nsISupports
 
 static PLDHashOperator
-ElementTraverser(const nsAString& key, nsIDOMHTMLInputElement* element,
+ElementTraverser(const nsAString& key, HTMLInputElement* element,
                  void* userArg)
 {
-  nsCycleCollectionTraversalCallback *cb = 
+  nsCycleCollectionTraversalCallback *cb =
     static_cast<nsCycleCollectionTraversalCallback*>(userArg);
- 
-  cb->NoteXPCOMChild(element);
+
+  cb->NoteXPCOMChild(ToSupports(element));
   return PL_DHASH_NEXT;
 }
 
 NS_IMPL_CYCLE_COLLECTION_CLASS(HTMLFormElement)
 
 NS_IMPL_CYCLE_COLLECTION_TRAVERSE_BEGIN_INHERITED(HTMLFormElement,
                                                   nsGenericHTMLElement)
   NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mControls)
@@ -2114,85 +2113,78 @@ NS_IMETHODIMP_(int32_t)
 HTMLFormElement::IndexOfControl(nsIFormControl* aControl)
 {
   int32_t index = 0;
   return mControls->IndexOfControl(aControl, &index) == NS_OK ? index : 0;
 }
 
 void
 HTMLFormElement::SetCurrentRadioButton(const nsAString& aName,
-                                       nsIDOMHTMLInputElement* aRadio)
+                                       HTMLInputElement* aRadio)
 {
   mSelectedRadioButtons.Put(aName, aRadio);
 }
 
-nsIDOMHTMLInputElement*
+HTMLInputElement*
 HTMLFormElement::GetCurrentRadioButton(const nsAString& aName)
 {
   return mSelectedRadioButtons.GetWeak(aName);
 }
 
 NS_IMETHODIMP
 HTMLFormElement::GetNextRadioButton(const nsAString& aName,
                                     const bool aPrevious,
-                                    nsIDOMHTMLInputElement*  aFocusedRadio,
-                                    nsIDOMHTMLInputElement** aRadioOut)
+                                    HTMLInputElement* aFocusedRadio,
+                                    HTMLInputElement** aRadioOut)
 {
   // Return the radio button relative to the focused radio button.
   // If no radio is focused, get the radio relative to the selected one.
   *aRadioOut = nullptr;
 
-  nsCOMPtr<nsIDOMHTMLInputElement> currentRadio;
+  nsRefPtr<HTMLInputElement> currentRadio;
   if (aFocusedRadio) {
     currentRadio = aFocusedRadio;
   }
   else {
     mSelectedRadioButtons.Get(aName, getter_AddRefs(currentRadio));
   }
 
   nsCOMPtr<nsISupports> itemWithName = DoResolveName(aName, true);
   nsCOMPtr<nsINodeList> radioGroup(do_QueryInterface(itemWithName));
 
   if (!radioGroup) {
     return NS_ERROR_FAILURE;
   }
 
-  nsCOMPtr<nsIContent> currentRadioNode(do_QueryInterface(currentRadio));
-  NS_ASSERTION(currentRadioNode, "No nsIContent for current radio button");
-  int32_t index = radioGroup->IndexOf(currentRadioNode);
+  int32_t index = radioGroup->IndexOf(currentRadio);
   if (index < 0) {
     return NS_ERROR_FAILURE;
   }
 
   uint32_t numRadios;
   radioGroup->GetLength(&numRadios);
-  bool disabled = true;
-  nsCOMPtr<nsIDOMHTMLInputElement> radio;
-  nsCOMPtr<nsIFormControl> formControl;
+  nsRefPtr<HTMLInputElement> radio;
 
   do {
     if (aPrevious) {
       if (--index < 0) {
         index = numRadios -1;
       }
     }
     else if (++index >= (int32_t)numRadios) {
       index = 0;
     }
-    radio = do_QueryInterface(radioGroup->Item(index));
+    radio = HTMLInputElement::FromContentOrNull(radioGroup->Item(index));
     if (!radio)
       continue;
 
-    // XXXbz why is this formControl check needed, exactly?
-    formControl = do_QueryInterface(radio);
-    if (!formControl || formControl->GetType() != NS_FORM_INPUT_RADIO)
+    if (radio->GetType() != NS_FORM_INPUT_RADIO)
       continue;
 
-    radio->GetDisabled(&disabled);
-  } while (disabled && radio != currentRadio);
+  } while (radio->Disabled() && radio != currentRadio);
 
   NS_IF_ADDREF(*aRadioOut = radio);
   return NS_OK;
 }
 
 NS_IMETHODIMP
 HTMLFormElement::WalkRadioGroup(const nsAString& aName,
                                 nsIRadioVisitor* aVisitor,
--- a/content/html/content/src/HTMLFormElement.h
+++ b/content/html/content/src/HTMLFormElement.h
@@ -13,16 +13,17 @@
 #include "nsFormSubmission.h"
 #include "nsGenericHTMLElement.h"
 #include "nsIDOMHTMLFormElement.h"
 #include "nsIWebProgressListener.h"
 #include "nsIRadioGroupContainer.h"
 #include "nsIWeakReferenceUtils.h"
 #include "nsThreadUtils.h"
 #include "nsInterfaceHashtable.h"
+#include "nsRefPtrHashtable.h"
 #include "nsDataHashtable.h"
 #include "nsAsyncDOMEvent.h"
 
 class nsIMutableArray;
 class nsIURI;
 
 namespace mozilla {
 namespace dom {
@@ -61,22 +62,22 @@ public:
   // nsIForm
   NS_IMETHOD_(nsIFormControl*) GetElementAt(int32_t aIndex) const;
   NS_IMETHOD_(uint32_t) GetElementCount() const MOZ_OVERRIDE;
   NS_IMETHOD_(int32_t) IndexOfControl(nsIFormControl* aControl) MOZ_OVERRIDE;
   NS_IMETHOD_(nsIFormControl*) GetDefaultSubmitElement() const MOZ_OVERRIDE;
 
   // nsIRadioGroupContainer
   void SetCurrentRadioButton(const nsAString& aName,
-                             nsIDOMHTMLInputElement* aRadio) MOZ_OVERRIDE;
-  nsIDOMHTMLInputElement* GetCurrentRadioButton(const nsAString& aName) MOZ_OVERRIDE;
+                             HTMLInputElement* aRadio) MOZ_OVERRIDE;
+  HTMLInputElement* GetCurrentRadioButton(const nsAString& aName) MOZ_OVERRIDE;
   NS_IMETHOD GetNextRadioButton(const nsAString& aName,
                                 const bool aPrevious,
-                                nsIDOMHTMLInputElement*  aFocusedRadio,
-                                nsIDOMHTMLInputElement** aRadioOut) MOZ_OVERRIDE;
+                                HTMLInputElement* aFocusedRadio,
+                                HTMLInputElement** aRadioOut) MOZ_OVERRIDE;
   NS_IMETHOD WalkRadioGroup(const nsAString& aName, nsIRadioVisitor* aVisitor,
                             bool aFlushContent) MOZ_OVERRIDE;
   void AddToRadioGroup(const nsAString& aName, nsIFormControl* aRadio) MOZ_OVERRIDE;
   void RemoveFromRadioGroup(const nsAString& aName, nsIFormControl* aRadio) MOZ_OVERRIDE;
   virtual uint32_t GetRequiredRadioCount(const nsAString& aName) const MOZ_OVERRIDE;
   virtual void RadioRequiredChanged(const nsAString& aName,
                                     nsIFormControl* aRadio) MOZ_OVERRIDE;
   virtual bool GetValueMissingState(const nsAString& aName) const MOZ_OVERRIDE;
@@ -533,17 +534,17 @@ public:
 protected:
 
   //
   // Data members
   //
   /** The list of controls (form.elements as well as stuff not in elements) */
   nsRefPtr<nsFormControlList> mControls;
   /** The currently selected radio button of each group */
-  nsInterfaceHashtable<nsStringCaseInsensitiveHashKey,nsIDOMHTMLInputElement> mSelectedRadioButtons;
+  nsRefPtrHashtable<nsStringCaseInsensitiveHashKey, HTMLInputElement> mSelectedRadioButtons;
   /** The number of required radio button of each group */
   nsDataHashtable<nsStringCaseInsensitiveHashKey,uint32_t> mRequiredRadioButtonCounts;
   /** The value missing state of each group */
   nsDataHashtable<nsStringCaseInsensitiveHashKey,bool> mValueMissingRadioGroups;
   /** Whether we are currently processing a submit event or not */
   bool mGeneratingSubmit;
   /** Whether we are currently processing a reset event or not */
   bool mGeneratingReset;
--- a/content/html/content/src/HTMLInputElement.cpp
+++ b/content/html/content/src/HTMLInputElement.cpp
@@ -3106,31 +3106,28 @@ HTMLInputElement::PostHandleEvent(nsEven
                 // FALLTHROUGH
               case NS_VK_DOWN:
               case NS_VK_RIGHT:
               // Arrow key pressed, focus+select prev/next radio button
               nsIRadioGroupContainer* container = GetRadioGroupContainer();
               if (container) {
                 nsAutoString name;
                 GetAttr(kNameSpaceID_None, nsGkAtoms::name, name);
-                nsCOMPtr<nsIDOMHTMLInputElement> selectedRadioButton;
+                nsRefPtr<HTMLInputElement> selectedRadioButton;
                 container->GetNextRadioButton(name, isMovingBack, this,
                                               getter_AddRefs(selectedRadioButton));
-                nsCOMPtr<nsIContent> radioContent =
-                  do_QueryInterface(selectedRadioButton);
-                if (radioContent) {
-                  nsCOMPtr<nsIDOMHTMLElement> elem = do_QueryInterface(selectedRadioButton);
-                  rv = elem->Focus();
+                if (selectedRadioButton) {
+                  rv = selectedRadioButton->Focus();
                   if (NS_SUCCEEDED(rv)) {
                     nsEventStatus status = nsEventStatus_eIgnore;
                     nsMouseEvent event(aVisitor.mEvent->mFlags.mIsTrusted,
                                        NS_MOUSE_CLICK, nullptr,
                                        nsMouseEvent::eReal);
                     event.inputSource = nsIDOMMouseEvent::MOZ_SOURCE_KEYBOARD;
-                    rv = nsEventDispatcher::Dispatch(radioContent,
+                    rv = nsEventDispatcher::Dispatch(ToSupports(selectedRadioButton),
                                                      aVisitor.mPresContext,
                                                      &event, nullptr, &status);
                     if (NS_SUCCEEDED(rv)) {
                       aVisitor.mEventStatus = nsEventStatus_eConsumeNoDefault;
                     }
                   }
                 }
               }
@@ -4970,18 +4967,17 @@ HTMLInputElement::IsHTMLFocusable(bool a
   if (!container) {
     *aIsFocusable = defaultFocusable;
     return false;
   }
 
   nsAutoString name;
   GetAttr(kNameSpaceID_None, nsGkAtoms::name, name);
 
-  nsCOMPtr<nsIDOMHTMLInputElement> currentRadio = container->GetCurrentRadioButton(name);
-  if (currentRadio) {
+  if (container->GetCurrentRadioButton(name)) {
     *aTabIndex = -1;
   }
   *aIsFocusable = defaultFocusable;
   return false;
 }
 
 nsresult
 HTMLInputElement::VisitGroup(nsIRadioVisitor* aVisitor, bool aFlushContent)
--- a/content/html/content/src/HTMLLinkElement.cpp
+++ b/content/html/content/src/HTMLLinkElement.cpp
@@ -52,19 +52,18 @@ NS_IMPL_CYCLE_COLLECTION_UNLINK_BEGIN_IN
 NS_IMPL_CYCLE_COLLECTION_UNLINK_END
 
 NS_IMPL_ADDREF_INHERITED(HTMLLinkElement, Element)
 NS_IMPL_RELEASE_INHERITED(HTMLLinkElement, Element)
 
 
 // QueryInterface implementation for HTMLLinkElement
 NS_INTERFACE_TABLE_HEAD_CYCLE_COLLECTION_INHERITED(HTMLLinkElement)
-  NS_INTERFACE_TABLE_INHERITED4(HTMLLinkElement,
+  NS_INTERFACE_TABLE_INHERITED3(HTMLLinkElement,
                                 nsIDOMHTMLLinkElement,
-                                nsIDOMLinkStyle,
                                 nsIStyleSheetLinkingElement,
                                 Link)
 NS_INTERFACE_TABLE_TAIL_INHERITING(nsGenericHTMLElement)
 
 
 NS_IMPL_ELEMENT_CLONE(HTMLLinkElement)
 
 bool
--- a/content/html/content/src/HTMLSelectElement.cpp
+++ b/content/html/content/src/HTMLSelectElement.cpp
@@ -1663,17 +1663,17 @@ HTMLSelectElement::SubmitNamesValues(nsF
 
   //
   // Submit
   //
   uint32_t len = Length();
 
   nsAutoString mozType;
   nsCOMPtr<nsIFormProcessor> keyGenProcessor;
-  if (GetAttr(kNameSpaceID_None, nsGkAtoms::_moz_type, mozType) &&
+  if (GetAttr(kNameSpaceID_None, nsGkAtoms::moztype, mozType) &&
       mozType.EqualsLiteral("-mozilla-keygen")) {
     keyGenProcessor = do_GetService(kFormProcessorCID);
   }
 
   for (uint32_t optIndex = 0; optIndex < len; optIndex++) {
     HTMLOptionElement* option = Item(optIndex);
 
     // Don't send disabled options
--- a/content/html/content/src/HTMLStyleElement.cpp
+++ b/content/html/content/src/HTMLStyleElement.cpp
@@ -1,15 +1,14 @@
 /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 #include "mozilla/dom/HTMLStyleElement.h"
 #include "mozilla/dom/HTMLStyleElementBinding.h"
-#include "nsIDOMLinkStyle.h"
 #include "nsGkAtoms.h"
 #include "nsStyleConsts.h"
 #include "nsIDOMStyleSheet.h"
 #include "nsIStyleSheet.h"
 #include "nsNetUtil.h"
 #include "nsIDocument.h"
 #include "nsUnicharUtils.h"
 #include "nsThreadUtils.h"
@@ -44,19 +43,18 @@ NS_IMPL_CYCLE_COLLECTION_UNLINK_BEGIN_IN
 NS_IMPL_CYCLE_COLLECTION_UNLINK_END
 
 NS_IMPL_ADDREF_INHERITED(HTMLStyleElement, Element)
 NS_IMPL_RELEASE_INHERITED(HTMLStyleElement, Element)
 
 
 // QueryInterface implementation for HTMLStyleElement
 NS_INTERFACE_TABLE_HEAD_CYCLE_COLLECTION_INHERITED(HTMLStyleElement)
-  NS_INTERFACE_TABLE_INHERITED4(HTMLStyleElement,
+  NS_INTERFACE_TABLE_INHERITED3(HTMLStyleElement,
                                 nsIDOMHTMLStyleElement,
-                                nsIDOMLinkStyle,
                                 nsIStyleSheetLinkingElement,
                                 nsIMutationObserver)
 NS_INTERFACE_TABLE_TAIL_INHERITING(nsGenericHTMLElement)
 
 NS_IMPL_ELEMENT_CLONE(HTMLStyleElement)
 
 
 NS_IMETHODIMP
--- a/content/html/content/src/Makefile.in
+++ b/content/html/content/src/Makefile.in
@@ -33,12 +33,8 @@ INCLUDES	+= \
 		-I$(srcdir)/../../../../editor/libeditor/base \
 		-I$(srcdir)/../../../../editor/libeditor/text \
 		-I$(srcdir)/../../../../editor/txmgr/src \
 		-I$(srcdir)/../../../../netwerk/base/src \
 		-I$(srcdir) \
 		-I$(topsrcdir)/xpcom/ds \
 		-I$(topsrcdir)/content/media/ \
 		$(NULL)
-
-DEFINES		+= \
-		-D_IMPL_NS_LAYOUT \
-		$(NULL)
--- a/content/html/content/test/test_bug389797.html
+++ b/content/html/content/test/test_bug389797.html
@@ -160,17 +160,17 @@ HTML_TAG("input", "Input", [], [ "imgINo
                                  "nsIImageLoadingContent",
                                  "nsIDOMNSEditableElement" ]);
 HTML_TAG("ins", "Mod");
 HTML_TAG("kbd", "");
 HTML_TAG("keygen", "Span");
 HTML_TAG("label", "Label");
 HTML_TAG("legend", "Legend");
 HTML_TAG("li", "LI");
-HTML_TAG("link", "Link", [ "nsIDOMLinkStyle" ]);
+HTML_TAG("link", "Link");
 HTML_TAG("listing", "");
 HTML_TAG("main", "");
 HTML_TAG("map", "Map");
 HTML_TAG("mark", "");
 HTML_TAG("marquee", "Div");
 HTML_TAG("menu", "Menu");
 HTML_TAG("meta", "Meta");
 HTML_TAG("meter", "Meter");
@@ -194,17 +194,17 @@ HTML_TAG("s", "");
 HTML_TAG("samp", "");
 HTML_TAG("script", "Script", [ "nsIScriptLoaderObserver" ], []);
 HTML_TAG("section", "")
 HTML_TAG("select", "Select", ["nsIDOMHTMLSelectElement"]);
 HTML_TAG("small", "");
 HTML_TAG("span", "Span");
 HTML_TAG("strike", "");
 HTML_TAG("strong", "");
-HTML_TAG("style", "Style", [ "nsIDOMLinkStyle" ]);
+HTML_TAG("style", "Style");
 HTML_TAG("sub", "");
 HTML_TAG("sup", "");
 HTML_TAG("table", "Table");
 HTML_TAG("tbody", "TableSection");
 HTML_TAG("td", "TableCell");
 HTML_TAG("textarea", "TextArea", [], [ "nsIDOMNSEditableElement" ]);
 HTML_TAG("tfoot", "TableSection");
 HTML_TAG("th", "TableCell");
--- a/content/html/document/src/Makefile.in
+++ b/content/html/document/src/Makefile.in
@@ -20,10 +20,8 @@ LOCAL_INCLUDES += \
 		-I$(srcdir)/../../../base/src \
 		-I$(srcdir)/../../../events/src \
 		-I$(srcdir)/../../content/src \
 		-I$(topsrcdir)/layout/style \
 		-I$(topsrcdir)/dom/base \
 		-I$(topsrcdir)/caps/include \
 		-I$(topsrcdir)/xpcom/ds \
 		$(NULL)
-
-DEFINES += -D_IMPL_NS_LAYOUT
--- a/content/mathml/content/src/Makefile.in
+++ b/content/mathml/content/src/Makefile.in
@@ -17,10 +17,8 @@ FAIL_ON_WARNINGS = 1
 include $(topsrcdir)/config/config.mk
 
 include $(topsrcdir)/config/rules.mk
 include $(topsrcdir)/ipc/chromium/chromium-config.mk
 
 INCLUDES += \
   -I$(srcdir)/../../../base/src \
   $(NULL)
-
-DEFINES += -D_IMPL_NS_LAYOUT
--- a/content/media/Makefile.in
+++ b/content/media/Makefile.in
@@ -19,11 +19,10 @@ include $(topsrcdir)/config/rules.mk
 include $(topsrcdir)/ipc/chromium/chromium-config.mk
 
 INCLUDES  += \
   -I$(topsrcdir)/content/base/src \
   -I$(topsrcdir)/layout/generic \
   -I$(topsrcdir)/layout/xul/base/src \
   $(NULL)
 
-DEFINES  += -D_IMPL_NS_LAYOUT
 CFLAGS   += $(GSTREAMER_CFLAGS)
 CXXFLAGS += $(GSTREAMER_CFLAGS)
--- a/content/smil/Makefile.in
+++ b/content/smil/Makefile.in
@@ -18,10 +18,8 @@ include $(topsrcdir)/config/config.mk
 
 INCLUDES += 	\
 		-I$(srcdir)/../base/src \
 		-I$(srcdir)/../../layout/style \
 		-I$(srcdir)/../events/src \
 		$(NULL)
 
 include $(topsrcdir)/config/rules.mk
-
-DEFINES += -D_IMPL_NS_LAYOUT
--- a/content/smil/nsSMILCSSProperty.cpp
+++ b/content/smil/nsSMILCSSProperty.cpp
@@ -240,17 +240,16 @@ nsSMILCSSProperty::IsPropertyAnimatable(
     case eCSSProperty_stroke_dasharray:
     case eCSSProperty_stroke_dashoffset:
     case eCSSProperty_stroke_linecap:
     case eCSSProperty_stroke_linejoin:
     case eCSSProperty_stroke_miterlimit:
     case eCSSProperty_stroke_opacity:
     case eCSSProperty_stroke_width:
     case eCSSProperty_text_anchor:
-    case eCSSProperty_text_blink:
     case eCSSProperty_text_decoration:
     case eCSSProperty_text_decoration_line:
     case eCSSProperty_text_rendering:
     case eCSSProperty_vector_effect:
     case eCSSProperty_width:
     case eCSSProperty_visibility:
     case eCSSProperty_word_spacing:
       return true;
--- a/content/svg/content/src/Makefile.in
+++ b/content/svg/content/src/Makefile.in
@@ -27,10 +27,8 @@ INCLUDES += 	\
 		-I$(srcdir)/../../../../layout/xul/base/src \
 		-I$(srcdir)/../../../../layout/svg \
 		-I$(srcdir)/../../../../layout/style \
 		-I$(srcdir)/../../../events/src \
 		-I$(srcdir)/../../../html/content/src \
 		-I$(topsrcdir)/content/xbl/src \
 		-I$(srcdir)/../../../smil \
 		$(NULL)
-
-DEFINES += -D_IMPL_NS_LAYOUT
--- a/content/svg/content/src/SVGStyleElement.cpp
+++ b/content/svg/content/src/SVGStyleElement.cpp
@@ -21,17 +21,17 @@ SVGStyleElement::WrapNode(JSContext *aCx
 
 //----------------------------------------------------------------------
 // nsISupports methods
 
 NS_IMPL_ADDREF_INHERITED(SVGStyleElement, SVGStyleElementBase)
 NS_IMPL_RELEASE_INHERITED(SVGStyleElement, SVGStyleElementBase)
 
 NS_INTERFACE_TABLE_HEAD_CYCLE_COLLECTION_INHERITED(SVGStyleElement)
-  NS_INTERFACE_TABLE_INHERITED3(SVGStyleElement, nsIDOMLinkStyle,
+  NS_INTERFACE_TABLE_INHERITED2(SVGStyleElement,
                                 nsIStyleSheetLinkingElement,
                                 nsIMutationObserver)
 NS_INTERFACE_TABLE_TAIL_INHERITING(SVGStyleElementBase)
 
 NS_IMPL_CYCLE_COLLECTION_CLASS(SVGStyleElement)
 
 NS_IMPL_CYCLE_COLLECTION_TRAVERSE_BEGIN_INHERITED(SVGStyleElement,
                                                   SVGStyleElementBase)
--- a/content/svg/document/src/Makefile.in
+++ b/content/svg/document/src/Makefile.in
@@ -20,10 +20,8 @@ INCLUDES	+= \
 		-I$(srcdir)/../../../xml/document/src \
 		-I$(srcdir)/../../../html/document/src \
 		-I$(srcdir)/../../../../layout/style \
 		-I$(srcdir)/../../../base/src \
 		-I$(srcdir)/../../../events/src \
 		-I$(topsrcdir)/xpcom/ds \
 		-I$(topsrcdir)/content/svg/content/src \
 		$(NULL)
-
-DEFINES += -D_IMPL_NS_LAYOUT
--- a/content/xbl/src/Makefile.in
+++ b/content/xbl/src/Makefile.in
@@ -23,10 +23,8 @@ LOCAL_INCLUDES	= \
 		-I$(srcdir)/../../xml/document/src \
 		-I$(srcdir)/../../xul/content/src \
 		-I$(srcdir)/../../xul/document/src \
 		-I$(srcdir)/../../events/src \
 		-I$(srcdir)/../../../layout/style \
 		-I$(srcdir)/../../../dom/base \
 		-I$(topsrcdir)/xpcom/ds \
 		$(NULL)
-
-DEFINES += -D_IMPL_NS_LAYOUT
--- a/content/xml/content/src/Makefile.in
+++ b/content/xml/content/src/Makefile.in
@@ -23,10 +23,8 @@ INCLUDES	+= \
 EXPORT_RESOURCE_CONTENT = \
 		$(srcdir)/htmlmathml-f.ent \
 		$(NULL)
 libs::
 	$(INSTALL) $(EXPORT_RESOURCE_CONTENT) $(DIST)/bin/res/dtd
 
 install::
 	$(SYSINSTALL) $(IFLAGS1) $(EXPORT_RESOURCE_CONTENT) $(DESTDIR)$(mozappdir)/res/dtd
-
-DEFINES += -D_IMPL_NS_LAYOUT
--- a/content/xml/content/src/XMLStylesheetProcessingInstruction.cpp
+++ b/content/xml/content/src/XMLStylesheetProcessingInstruction.cpp
@@ -8,18 +8,18 @@
 #include "nsNetUtil.h"
 
 namespace mozilla {
 namespace dom {
 
 // nsISupports implementation
 
 NS_INTERFACE_TABLE_HEAD_CYCLE_COLLECTION_INHERITED(XMLStylesheetProcessingInstruction)
-  NS_INTERFACE_TABLE_INHERITED4(XMLStylesheetProcessingInstruction, nsIDOMNode,
-                                nsIDOMProcessingInstruction, nsIDOMLinkStyle,
+  NS_INTERFACE_TABLE_INHERITED3(XMLStylesheetProcessingInstruction, nsIDOMNode,
+                                nsIDOMProcessingInstruction,
                                 nsIStyleSheetLinkingElement)
 NS_INTERFACE_TABLE_TAIL_INHERITING(ProcessingInstruction)
 
 NS_IMPL_ADDREF_INHERITED(XMLStylesheetProcessingInstruction,
                          ProcessingInstruction)
 NS_IMPL_RELEASE_INHERITED(XMLStylesheetProcessingInstruction,
                           ProcessingInstruction)
 
--- a/content/xml/document/src/Makefile.in
+++ b/content/xml/document/src/Makefile.in
@@ -22,10 +22,8 @@ LOCAL_INCLUDES	= \
 		-I$(srcdir)/../../../../layout/style \
 		-I$(srcdir)/../../../base/src \
 		-I$(srcdir)/../../../xul/content/src \
 		-I$(srcdir)/../../../events/src \
 		-I$(srcdir)/../../../../dom/base \
 		-I$(srcdir)/../../../../caps/include \
 		-I$(topsrcdir)/xpcom/ds \
 		$(NULL)
-
-DEFINES += -D_IMPL_NS_LAYOUT
--- a/content/xslt/src/xpath/Makefile.in
+++ b/content/xslt/src/xpath/Makefile.in
@@ -15,10 +15,8 @@ FAIL_ON_WARNINGS = 1
 include $(topsrcdir)/config/rules.mk
 
 INCLUDES += \
 	-I$(srcdir)/../base \
 	-I$(srcdir)/../xml \
 	-I$(srcdir) \
 	-I$(srcdir)/../xslt \
 	$(NULL)
-
-DEFINES += -D_IMPL_NS_LAYOUT
--- a/content/xslt/src/xslt/Makefile.in
+++ b/content/xslt/src/xslt/Makefile.in
@@ -21,10 +21,8 @@ include $(topsrcdir)/config/rules.mk
 
 INCLUDES += \
 	-I$(srcdir) \
 	-I$(srcdir)/../base \
 	-I$(srcdir)/../xml \
 	-I$(srcdir)/../xpath \
 	-I$(srcdir)/../../../base/src \
 	$(NULL)
-
-DEFINES += -D_IMPL_NS_LAYOUT
--- a/content/xul/content/src/Makefile.in
+++ b/content/xul/content/src/Makefile.in
@@ -29,10 +29,8 @@ LOCAL_INCLUDES	= \
 	-I$(srcdir)/../../../../layout/generic \
 	-I$(srcdir)/../../../../layout/style \
 	-I$(srcdir)/../../../../layout/xul/base/src \
 	-I$(srcdir)/../../../html/content/src \
 	-I$(srcdir)/../../../events/src \
 	-I$(srcdir)/../../../xbl/src \
 	-I$(topsrcdir)/xpcom/ds \
 	$(NULL)
-
-DEFINES += -D_IMPL_NS_LAYOUT
--- a/content/xul/document/src/Makefile.in
+++ b/content/xul/document/src/Makefile.in
@@ -24,10 +24,8 @@ LOCAL_INCLUDES	= -I$(srcdir)/../../../ba
 		  -I$(srcdir)/../../../../layout/style \
 		  -I$(srcdir)/../../../../layout/xul/base/src \
 		  -I$(srcdir)/../../../xml/document/src \
 		  -I$(srcdir)/../../../xbl/src \
 		  -I$(srcdir)/../../../events/src \
 		  -I$(topsrcdir)/xpcom/ds \
 		  -I$(topsrcdir)/dom/base \
 		  $(NULL)
-
-DEFINES += -D_IMPL_NS_LAYOUT
--- a/content/xul/templates/src/Makefile.in
+++ b/content/xul/templates/src/Makefile.in
@@ -15,10 +15,8 @@ LIBXUL_LIBRARY	= 1
 
 include $(topsrcdir)/config/rules.mk
 
 LOCAL_INCLUDES	= -I$(srcdir)/../../../base/src \
 		  -I$(srcdir)/../../content/src \
 		  -I$(srcdir)/../../../../dom/base \
 		  -I$(srcdir)/../../../../layout/xul/tree/ \
 		  $(NULL)
-
-DEFINES += -D_IMPL_NS_LAYOUT
--- a/docshell/base/nsDocShell.cpp
+++ b/docshell/base/nsDocShell.cpp
@@ -4129,17 +4129,17 @@ nsDocShell::LoadURI(const PRUnichar * aU
 
     PopupControlState popupState;
     if (aLoadFlags & LOAD_FLAGS_ALLOW_POPUPS) {
         popupState = openAllowed;
         aLoadFlags &= ~LOAD_FLAGS_ALLOW_POPUPS;
     } else {
         popupState = openOverridden;
     }
-    nsAutoPopupStatePusher statePusher(mScriptGlobal, popupState);
+    nsAutoPopupStatePusher statePusher(popupState);
 
     // Don't pass certain flags that aren't needed and end up confusing
     // ConvertLoadTypeToDocShellLoadInfo.  We do need to ensure that they are
     // passed to LoadURI though, since it uses them.
     uint32_t extraFlags = (aLoadFlags & EXTRA_LOAD_FLAGS);
     aLoadFlags &= ~EXTRA_LOAD_FLAGS;
 
     nsCOMPtr<nsIDocShellLoadInfo> loadInfo;
@@ -10240,17 +10240,17 @@ nsDocShell::SetReferrerURI(nsIURI * aURI
     mReferrerURI = aURI;        // This assigment addrefs
 }
 
 //*****************************************************************************
 // nsDocShell: Session History
 //*****************************************************************************
 
 NS_IMETHODIMP
-nsDocShell::AddState(nsIVariant *aData, const nsAString& aTitle,
+nsDocShell::AddState(const JS::Value &aData, const nsAString& aTitle,
                      const nsAString& aURL, bool aReplace, JSContext* aCx)
 {
     // Implements History.pushState and History.replaceState
 
     // Here's what we do, roughly in the order specified by HTML5:
     // 1. Serialize aData using structured clone.
     // 2. If the third argument is present,
     //     a. Resolve the url, relative to the first script's base URL
@@ -10299,32 +10299,32 @@ nsDocShell::AddState(nsIVariant *aData, 
     NS_ENSURE_TRUE(document, NS_ERROR_FAILURE);
 
     // Step 1: Serialize aData using structured clone.
     nsCOMPtr<nsIStructuredCloneContainer> scContainer;
 
     // scContainer->Init might cause arbitrary JS to run, and this code might
     // navigate the page we're on, potentially to a different origin! (bug
     // 634834)  To protect against this, we abort if our principal changes due
-    // to the InitFromVariant() call.
+    // to the InitFromJSVal() call.
     {
         nsCOMPtr<nsIDocument> origDocument =
             do_GetInterface(GetAsSupports(this));
         if (!origDocument)
             return NS_ERROR_DOM_SECURITY_ERR;
         nsCOMPtr<nsIPrincipal> origPrincipal = origDocument->NodePrincipal();
 
         scContainer = new nsStructuredCloneContainer();
         JSContext *cx = aCx;
         nsCxPusher pusher;
         if (!cx) {
             cx = nsContentUtils::GetContextFromDocument(document);
             pusher.Push(cx);
         }
-        rv = scContainer->InitFromVariant(aData, cx);
+        rv = scContainer->InitFromJSVal(aData, cx);
 
         // If we're running in the document's context and the structured clone
         // failed, clear the context's pending exception.  See bug 637116.
         if (NS_FAILED(rv) && !aCx) {
             JS_ClearPendingException(aCx);
         }
         NS_ENSURE_SUCCESS(rv, rv);
 
@@ -12118,18 +12118,17 @@ public:
                    nsIURI* aURI,
                    const PRUnichar* aTargetSpec,
                    const nsAString& aFileName,
                    nsIInputStream* aPostDataStream,
                    nsIInputStream* aHeadersDataStream,
                    bool aIsTrusted);
 
   NS_IMETHOD Run() {
-    nsRefPtr<nsGlobalWindow> window = mHandler->mScriptGlobal.get();
-    nsAutoPopupStatePusher popupStatePusher(window, mPopupState);
+    nsAutoPopupStatePusher popupStatePusher(mPopupState);
 
     nsCxPusher pusher;
     if (mIsTrusted || pusher.Push(mContent)) {
       mHandler->OnLinkClickSync(mContent, mURI,
                                 mTargetSpec.get(), mFileName,
                                 mPostDataStream, mHeadersDataStream,
                                 nullptr, nullptr);
     }
--- a/docshell/base/nsIDocShell.idl
+++ b/docshell/base/nsIDocShell.idl
@@ -37,17 +37,17 @@ interface nsILayoutHistoryState;
 interface nsISecureBrowserUI;
 interface nsIDOMStorage;
 interface nsIPrincipal;
 interface nsIWebBrowserPrint;
 interface nsIVariant;
 interface nsIPrivacyTransitionObserver;
 interface nsIReflowObserver;
 
-[scriptable, builtinclass, uuid(cdeb1ed0-7794-4e5f-964e-bb9d753d1686)]
+[scriptable, builtinclass, uuid(b5bd6052-ec8c-45bf-b55c-409ad15cecfb)]
 interface nsIDocShell : nsIDocShellTreeItem
 {
   /**
    * Loads a given URI.  This will give priority to loading the requested URI
    * in the object implementing	this interface.  If it can't be loaded here
    * however, the URL dispatcher will go through its normal process of content
    * loading.
    *
@@ -151,17 +151,17 @@ interface nsIDocShell : nsIDocShellTreeI
                               out nsIDocShell aDocShell,
                               out nsIRequest aRequest);
 
   /**
    * Do either a history.pushState() or history.replaceState() operation,
    * depending on the value of aReplace.
    */
   [implicit_jscontext]
-  void addState(in nsIVariant aData, in DOMString aTitle,
+  void addState(in jsval aData, in DOMString aTitle,
                 in DOMString aURL, in boolean aReplace);
 
   /**
    * Creates a DocShellLoadInfo object that you can manipulate and then pass
    * to loadURI.
    */
   void createLoadInfo(out nsIDocShellLoadInfo loadInfo);
 
--- a/docshell/build/Makefile.in
+++ b/docshell/build/Makefile.in
@@ -3,18 +3,16 @@
 # License, v. 2.0. If a copy of the MPL was not distributed with this
 # file, You can obtain one at http://mozilla.org/MPL/2.0/.
 
 DEPTH		= @DEPTH@
 topsrcdir	= @top_srcdir@
 srcdir		= @srcdir@
 VPATH		= @srcdir@
 
-IS_COMPONENT = 1
-MODULE_NAME	= docshell_provider
 
 include $(DEPTH)/config/autoconf.mk
 
 EXPORT_LIBRARY = 1
 LIBXUL_LIBRARY	= 1
 
 
 SHARED_LIBRARY_LIBS= \
--- a/dom/base/DOMRequestHelper.jsm
+++ b/dom/base/DOMRequestHelper.jsm
@@ -1,15 +1,15 @@
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this file,
  * You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 /**
- * Helper object for APIs that deal with DOMRequests and need to release them
- * when the window goes out of scope.
+ * Helper object for APIs that deal with DOMRequests and Promises and need to
+ * release them when the window goes out of scope.
  */
 const Cu = Components.utils;
 const Cc = Components.classes;
 const Ci = Components.interfaces;
 
 this.EXPORTED_SYMBOLS = ["DOMRequestIpcHelper"];
 
 Cu.import("resource://gre/modules/XPCOMUtils.jsm");
@@ -129,34 +129,58 @@ DOMRequestIpcHelper.prototype = {
   },
 
   getRequestId: function(aRequest) {
     let id = "id" + this._getRandomId();
     this._requests[id] = aRequest;
     return id;
   },
 
+  getPromiseResolverId: function(aPromiseResolver) {
+    // Delegates to getRequest() since the lookup table is agnostic about
+    // storage.
+    return this.getRequestId(aPromiseResolver);
+  },
+
   getRequest: function(aId) {
     if (this._requests[aId])
       return this._requests[aId];
   },
 
+  getPromiseResolver: function(aId) {
+    // Delegates to getRequest() since the lookup table is agnostic about
+    // storage.
+    return this.getRequest(aId);
+  },
+
   removeRequest: function(aId) {
     if (this._requests[aId])
       delete this._requests[aId];
   },
 
+  removePromiseResolver: function(aId) {
+    // Delegates to getRequest() since the lookup table is agnostic about
+    // storage.
+    this.removeRequest(aId);
+  },
+
   takeRequest: function(aId) {
     if (!this._requests[aId])
       return null;
     let request = this._requests[aId];
     delete this._requests[aId];
     return request;
   },
 
+  takePromiseResolver: function(aId) {
+    // Delegates to getRequest() since the lookup table is agnostic about
+    // storage.
+    return this.takeRequest(aId);
+  },
+
   _getRandomId: function() {
     return Cc["@mozilla.org/uuid-generator;1"].getService(Ci.nsIUUIDGenerator).generateUUID().toString();
   },
 
   destroyDOMRequestHelper: function() {
     // This function is re-entrant --
     // DOMRequestIpcHelperMessageListener.destroy() calls back into this
     // function, and this.uninit() may also call it.
@@ -171,10 +195,19 @@ DOMRequestIpcHelper.prototype = {
 
     if(this.uninit) {
       this.uninit();
     }
   },
 
   createRequest: function() {
     return Services.DOMRequest.createRequest(this._window);
+  },
+
+  /**
+   * createPromise() creates a new Promise, with `aPromiseInit` as the
+   * PromiseInit callback. The promise constructor is obtained from the
+   * reference to window owned by this DOMRequestIPCHelper.
+   */
+  createPromise: function(aPromiseInit) {
+    return new this._window.Promise(aPromiseInit);
   }
 }
new file mode 100644
--- /dev/null
+++ b/dom/base/WindowNamedPropertiesHandler.cpp
@@ -0,0 +1,181 @@
+/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=2 sw=2 et tw=78: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#include "WindowNamedPropertiesHandler.h"
+#include "nsDOMClassInfo.h"
+#include "nsGlobalWindow.h"
+#include "nsHTMLDocument.h"
+#include "nsJSUtils.h"
+#include "xpcprivate.h"
+
+namespace mozilla {
+namespace dom {
+
+bool
+WindowNamedPropertiesHandler::getOwnPropertyDescriptor(JSContext* aCx,
+                                                       JS::Handle<JSObject*> aProxy,
+                                                       JS::Handle<jsid> aId,
+                                                       JS::MutableHandle<JSPropertyDescriptor> aDesc,
+                                                       unsigned aFlags)
+{
+  if (!JSID_IS_STRING(aId)) {
+    // Nothing to do if we're resolving a non-string property.
+    return true;
+  }
+
+  JSObject* global = JS_GetGlobalForObject(aCx, aProxy);
+  nsresult rv =
+    nsDOMClassInfo::ScriptSecurityManager()->CheckPropertyAccess(aCx, global,
+                                                                 "Window", aId,
+                                                                 nsIXPCSecurityManager::ACCESS_GET_PROPERTY);
+  if (NS_FAILED(rv)) {
+    // The security check failed. The security manager set a JS exception for
+    // us.
+    return false;
+  }
+
+  if (HasPropertyOnPrototype(aCx, aProxy, aId)) {
+    return true;
+  }
+
+  nsDependentJSString str(aId);
+
+  // Grab the DOM window.
+  XPCWrappedNative* wrapper = XPCWrappedNative::Get(global);
+  nsCOMPtr<nsPIDOMWindow> piWin = do_QueryWrappedNative(wrapper);
+  MOZ_ASSERT(piWin);
+  nsGlobalWindow* win = static_cast<nsGlobalWindow*>(piWin.get());
+  if (win->GetLength() > 0) {
+    nsCOMPtr<nsIDOMWindow> childWin = win->GetChildWindow(str);
+    if (childWin) {
+      // We found a subframe of the right name. Shadowing via |var foo| in
+      // global scope is still allowed, since |var| only looks up |own|
+      // properties. But unqualified shadowing will fail, per-spec.
+      JS::Rooted<JS::Value> v(aCx);
+      if (!WrapObject(aCx, aProxy, childWin, &v)) {
+        return false;
+      }
+      aDesc.object().set(aProxy);
+      aDesc.value().set(v);
+      aDesc.setAttributes(JSPROP_ENUMERATE);
+      return true;
+    }
+  }
+
+  // The rest of this function is for HTML documents only.
+  nsCOMPtr<nsIHTMLDocument> htmlDoc = do_QueryInterface(win->GetExtantDoc());
+  if (!htmlDoc) {
+    return true;
+  }
+  nsHTMLDocument* document = static_cast<nsHTMLDocument*>(htmlDoc.get());
+
+  Element* element = document->GetElementById(str);
+  if (element) {
+    JS::Rooted<JS::Value> v(aCx);
+    if (!WrapObject(aCx, aProxy, element, &v)) {
+      return false;
+    }
+    aDesc.object().set(aProxy);
+    aDesc.value().set(v);
+    aDesc.setAttributes(JSPROP_ENUMERATE);
+    return true;
+  }
+
+  nsWrapperCache* cache;
+  nsISupports* result = document->ResolveName(str, &cache);
+  if (!result) {
+    return true;
+  }
+
+  JS::Rooted<JS::Value> v(aCx);
+  if (!WrapObject(aCx, aProxy, result, cache, nullptr, &v)) {
+    return false;
+  }
+  aDesc.object().set(aProxy);
+  aDesc.value().set(v);
+  aDesc.setAttributes(JSPROP_ENUMERATE);
+  return true;
+}
+
+bool
+WindowNamedPropertiesHandler::defineProperty(JSContext* aCx,
+                                             JS::Handle<JSObject*> aProxy,
+                                             JS::Handle<jsid> aId,
+                                             JS::MutableHandle<JSPropertyDescriptor> aDesc)
+{
+  ErrorResult rv;
+  rv.ThrowTypeError(MSG_DEFINEPROPERTY_ON_GSP);
+  rv.ReportTypeError(aCx);
+  return false;
+}
+
+bool
+WindowNamedPropertiesHandler::getOwnPropertyNames(JSContext* aCx,
+                                                  JS::Handle<JSObject*> aProxy,
+                                                  JS::AutoIdVector& aProps)
+{
+  // Grab the DOM window.
+  JSObject* global = JS_GetGlobalForObject(aCx, aProxy);
+  XPCWrappedNative* wrapper = XPCWrappedNative::Get(global);
+  nsCOMPtr<nsPIDOMWindow> piWin = do_QueryWrappedNative(wrapper);
+  MOZ_ASSERT(piWin);
+  nsGlobalWindow* win = static_cast<nsGlobalWindow*>(piWin.get());
+  nsTArray<nsString> names;
+  win->GetSupportedNames(names);
+  if (!AppendNamedPropertyIds(aCx, aProxy, names, false, aProps)) {
+    return false;
+  }
+
+  names.Clear();
+  nsCOMPtr<nsIHTMLDocument> htmlDoc = do_QueryInterface(win->GetExtantDoc());
+  if (!htmlDoc) {
+    return true;
+  }
+  nsHTMLDocument* document = static_cast<nsHTMLDocument*>(htmlDoc.get());
+  document->GetSupportedNames(names);
+
+  JS::AutoIdVector docProps(aCx);
+  if (!AppendNamedPropertyIds(aCx, aProxy, names, false, docProps)) {
+    return false;
+  }
+
+  return js::AppendUnique(aCx, aProps, docProps);
+}
+
+bool
+WindowNamedPropertiesHandler::delete_(JSContext* aCx,
+                                      JS::Handle<JSObject*> aProxy,
+                                      JS::Handle<jsid> aId, bool* aBp)
+{
+  *aBp = false;
+  return true;
+}
+
+// static
+void
+WindowNamedPropertiesHandler::Install(JSContext* aCx,
+                                      JS::Handle<JSObject*> aProto)
+{
+  JS::Rooted<JSObject*> protoProto(aCx);
+  if (!::JS_GetPrototype(aCx, aProto, &protoProto)) {
+    return;
+  }
+
+  JS::Rooted<JSObject*> gsp(aCx);
+  gsp = js::NewProxyObject(aCx, WindowNamedPropertiesHandler::getInstance(),
+                           JS::NullHandleValue, protoProto,
+                           js::GetGlobalForObjectCrossCompartment(aProto));
+  if (!gsp) {
+    return;
+  }
+
+  // And then set the prototype of the interface prototype object to be the
+  // global scope polluter.
+  ::JS_SplicePrototype(aCx, aProto, gsp);
+}
+
+} // namespace dom
+} // namespace mozilla
new file mode 100644
--- /dev/null
+++ b/dom/base/WindowNamedPropertiesHandler.h
@@ -0,0 +1,74 @@
+/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=2 sw=2 et tw=78: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#ifndef mozilla_dom_WindowNamedPropertiesHandler_h
+#define mozilla_dom_WindowNamedPropertiesHandler_h
+
+#include "jsproxy.h"
+#include "mozilla/dom/DOMJSProxyHandler.h"
+
+namespace mozilla {
+namespace dom {
+
+class WindowNamedPropertiesHandler : public BaseDOMProxyHandler
+{
+public:
+  WindowNamedPropertiesHandler() : BaseDOMProxyHandler(nullptr)
+  {
+    setHasPrototype(true);
+  }
+  virtual bool
+  preventExtensions(JSContext* aCx, JS::Handle<JSObject*> aProxy) MOZ_OVERRIDE
+  {
+    // Throw a TypeError, per WebIDL.
+    JS_ReportErrorNumber(aCx, js_GetErrorMessage, nullptr,
+                         JSMSG_CANT_CHANGE_EXTENSIBILITY);
+    return false;
+  }
+  virtual bool
+  getOwnPropertyDescriptor(JSContext* aCx, JS::Handle<JSObject*> aProxy,
+                           JS::Handle<jsid> aId,
+                           JS::MutableHandle<JSPropertyDescriptor> aDesc,
+                           unsigned aFlags) MOZ_OVERRIDE;
+  virtual bool
+  defineProperty(JSContext* aCx, JS::Handle<JSObject*> aProxy,
+                 JS::Handle<jsid> aId,
+                 JS::MutableHandle<JSPropertyDescriptor> aDesc) MOZ_OVERRIDE;
+  virtual bool
+  getOwnPropertyNames(JSContext* aCx, JS::Handle<JSObject*> aProxy,
+                      JS::AutoIdVector& aProps) MOZ_OVERRIDE;
+  virtual bool
+  delete_(JSContext* aCx, JS::Handle<JSObject*> aProxy, JS::Handle<jsid> aId,
+          bool* aBp) MOZ_OVERRIDE;
+  virtual bool
+  isExtensible(JSContext* aCx, JS::Handle<JSObject*> aProxy,
+               bool* aIsExtensible) MOZ_OVERRIDE
+  {
+    *aIsExtensible = true;
+    return true;
+  }
+  virtual const char*
+  className(JSContext *aCx, JS::Handle<JSObject*> aProxy) MOZ_OVERRIDE
+  {
+    return "WindowProperties";
+  }
+
+  static WindowNamedPropertiesHandler*
+  getInstance()
+  {
+    static WindowNamedPropertiesHandler instance;
+    return &instance;
+  }
+
+  // For Install, aProto is the proto of the Window we're associated with.
+  static void
+  Install(JSContext *aCx, JS::Handle<JSObject*> aProto);
+};
+
+} // namespace dom
+} // namespace mozilla
+
+#endif /* mozilla_dom_WindowNamedPropertiesHandler_h */
--- a/dom/base/moz.build
+++ b/dom/base/moz.build
@@ -93,16 +93,17 @@ CPP_SOURCES += [
     'nsPluginArray.cpp',
     'nsQueryContentEventResult.cpp',
     'nsScreen.cpp',
     'nsScriptNameSpaceManager.cpp',
     'nsStructuredCloneContainer.cpp',
     'nsWindowMemoryReporter.cpp',
     'nsWindowRoot.cpp',
     'nsWrapperCache.cpp',
+    'WindowNamedPropertiesHandler.cpp',
 ]
 
 EXTRA_COMPONENTS += [
     'ConsoleAPI.js',
     'ConsoleAPI.manifest',
     'SiteSpecificUserAgent.js',
     'SiteSpecificUserAgent.manifest',
 ]
--- a/dom/base/nsDOMClassInfo.cpp
+++ b/dom/base/nsDOMClassInfo.cpp
@@ -10,17 +10,16 @@
 
 #ifdef XP_WIN
 #undef GetClassName
 #endif
 
 // JavaScript includes
 #include "jsapi.h"
 #include "jsfriendapi.h"
-#include "jsprvtd.h"    // we are using private JS typedefs...
 #include "jsdbgapi.h"
 #include "WrapperFactory.h"
 #include "AccessCheck.h"
 #include "XrayWrapper.h"
 
 #include "xpcpublic.h"
 #include "xpcprivate.h"
 #include "XPCWrapper.h"
@@ -50,17 +49,16 @@
 #include "prprf.h"
 #include "nsTArray.h"
 #include "nsCSSValue.h"
 #include "nsThreadUtils.h"
 #include "nsDOMEventTargetHelper.h"
 
 // General helper includes
 #include "nsGlobalWindow.h"
-#include "nsHistory.h"
 #include "nsIContent.h"
 #include "nsIDocument.h"
 #include "nsIDOMDocument.h"
 #include "nsIDOMEvent.h"
 #include "nsIDOMEventListener.h"
 #include "nsContentUtils.h"
 #include "nsCxPusher.h"
 #include "nsDOMWindowUtils.h"
@@ -83,17 +81,16 @@
 #include "nsJSEnvironment.h"
 
 // DOM base includes
 #include "nsIDOMLocation.h"
 #include "nsIDOMWindow.h"
 #include "nsPIDOMWindow.h"
 #include "nsIDOMJSWindow.h"
 #include "nsIDOMWindowCollection.h"
-#include "nsIDOMHistory.h"
 #include "nsIDOMMediaList.h"
 #include "nsIDOMChromeWindow.h"
 #include "nsIDOMConstructor.h"
 
 // DOM core includes
 #include "nsError.h"
 #include "nsIDOMDOMException.h"
 #include "nsIDOMNode.h"
@@ -138,17 +135,16 @@
 #include "nsXMLHttpRequest.h"
 #include "nsIDOMContactManager.h"
 #include "nsIDOMPermissionSettings.h"
 #include "nsIDOMApplicationRegistry.h"
 
 // includes needed for the prototype chain interfaces
 #include "nsIDOMDocumentXBL.h"
 #include "nsIDOMElementCSSInlineStyle.h"
-#include "nsIDOMLinkStyle.h"
 #include "nsIDOMHTMLDocument.h"
 #include "nsIDOMCSSCharsetRule.h"
 #include "nsIDOMCSSImportRule.h"
 #include "nsIDOMCSSMediaRule.h"
 #include "nsIDOMCSSFontFaceRule.h"
 #include "nsIDOMCSSMozDocumentRule.h"
 #include "nsIDOMCSSSupportsRule.h"
 #include "nsIDOMMozCSSKeyframeRule.h"
@@ -246,16 +242,17 @@ using mozilla::dom::workers::ResolveWork
 #include "nsIAsyncScrollEventDetail.h"
 #include "nsIDOMGlobalObjectConstructor.h"
 #include "nsIDOMCanvasRenderingContext2D.h"
 #include "LockedFile.h"
 #include "nsDebug.h"
 
 #include "mozilla/dom/BindingUtils.h"
 #include "mozilla/Likely.h"
+#include "WindowNamedPropertiesHandler.h"
 
 #ifdef MOZ_TIME_MANAGER
 #include "TimeManager.h"
 #endif
 
 using namespace mozilla;
 using namespace mozilla::dom;
 
@@ -403,19 +400,16 @@ static nsDOMClassInfoData sClassInfoData
                            DEFAULT_SCRIPTABLE_FLAGS |
                            WINDOW_SCRIPTABLE_FLAGS)
 
   NS_DEFINE_CLASSINFO_DATA(Location, nsLocationSH,
                            ((DOM_DEFAULT_SCRIPTABLE_FLAGS |
                              nsIXPCScriptable::WANT_ADDPROPERTY) &
                             ~nsIXPCScriptable::ALLOW_PROP_MODS_TO_PROTOTYPE))
 
-  NS_DEFINE_CLASSINFO_DATA(History, nsHistorySH,
-                           ARRAY_SCRIPTABLE_FLAGS |
-                           nsIXPCScriptable::WANT_PRECREATE)
   NS_DEFINE_CLASSINFO_DATA(DOMPrototype, nsDOMConstructorSH,
                            DOM_BASE_SCRIPTABLE_FLAGS |
                            nsIXPCScriptable::WANT_PRECREATE |
                            nsIXPCScriptable::WANT_NEWRESOLVE |
                            nsIXPCScriptable::WANT_HASINSTANCE |
                            nsIXPCScriptable::DONT_ENUM_QUERY_INTERFACE)
   NS_DEFINE_CLASSINFO_DATA(DOMConstructor, nsDOMConstructorSH,
                            DOM_BASE_SCRIPTABLE_FLAGS |
@@ -1210,20 +1204,16 @@ nsDOMClassInfo::Init()
   DOM_CLASSINFO_MAP_BEGIN(WindowUtils, nsIDOMWindowUtils)
     DOM_CLASSINFO_MAP_ENTRY(nsIDOMWindowUtils)
   DOM_CLASSINFO_MAP_END
 
   DOM_CLASSINFO_MAP_BEGIN(Location, nsIDOMLocation)
     DOM_CLASSINFO_MAP_ENTRY(nsIDOMLocation)
   DOM_CLASSINFO_MAP_END
 
-  DOM_CLASSINFO_MAP_BEGIN(History, nsIDOMHistory)
-    DOM_CLASSINFO_MAP_ENTRY(nsIDOMHistory)
-  DOM_CLASSINFO_MAP_END
-
   DOM_CLASSINFO_MAP_BEGIN_NO_CLASS_IF(DOMPrototype, nsIDOMDOMConstructor)
     DOM_CLASSINFO_MAP_ENTRY(nsIDOMDOMConstructor)
   DOM_CLASSINFO_MAP_END
 
   DOM_CLASSINFO_MAP_BEGIN(DOMConstructor, nsIDOMDOMConstructor)
     DOM_CLASSINFO_MAP_ENTRY(nsIDOMDOMConstructor)
   DOM_CLASSINFO_MAP_END
 
@@ -2299,261 +2289,37 @@ nsWindowSH::PreCreate(nsISupports *nativ
 
   // If we're bootstrapping, we don't have a JS object yet.
   if (win->GetOuterWindowInternal()->IsCreatingInnerWindow())
     return NS_OK;
 
   return SetParentToWindow(win, parentObj);
 }
 
-static JSClass sGlobalScopePolluterClass = {
-  "Global Scope Polluter",
-  JSCLASS_NEW_RESOLVE,
-  JS_PropertyStub,
-  JS_DeletePropertyStub,
-  nsWindowSH::GlobalScopePolluterGetProperty,
-  JS_StrictPropertyStub,
-  JS_EnumerateStub,
-  (JSResolveOp)nsWindowSH::GlobalScopePolluterNewResolve,
-  JS_ConvertStub,
-  nullptr
-};
-
-
-// static
-bool
-nsWindowSH::GlobalScopePolluterGetProperty(JSContext *cx, JS::Handle<JSObject*> obj,
-                                           JS::Handle<jsid> id, JS::MutableHandle<JS::Value> vp)
+NS_IMETHODIMP
+nsWindowSH::PostCreatePrototype(JSContext* aCx, JSObject* aProto)
 {
-  // Someone is accessing a element by referencing its name/id in the
-  // global scope, do a security check to make sure that's ok.
-
-  nsresult rv =
-    sSecMan->CheckPropertyAccess(cx, ::JS_GetGlobalForObject(cx, obj),
-                                 "Window", id,
-                                 nsIXPCSecurityManager::ACCESS_GET_PROPERTY);
-
-  if (NS_FAILED(rv)) {
-    // The security check failed. The security manager set a JS
-    // exception for us.
-
-    return false;
-  }
-
-  return true;
-}
-
-// Gets a subframe.
-static bool
-ChildWindowGetter(JSContext *cx, JS::Handle<JSObject*> obj, JS::Handle<jsid> id,
-                  JS::MutableHandle<JS::Value> vp)
-{
-  MOZ_ASSERT(JSID_IS_STRING(id));
-  // Grab the native DOM window.
-  vp.setUndefined();
-  nsCOMPtr<nsISupports> winSupports =
-    do_QueryInterface(nsDOMClassInfo::XPConnect()->GetNativeOfWrapper(cx, obj));
-  if (!winSupports)
-    return true;
-  nsGlobalWindow *win = nsGlobalWindow::FromSupports(winSupports);
-
-  // Find the child, if it exists.
-  nsDependentJSString name(id);
-  nsCOMPtr<nsIDOMWindow> child = win->GetChildWindow(name);
-  if (!child)
-    return true;
-
-  // Wrap the child for JS.
-  JS::Rooted<JS::Value> v(cx);
-  nsresult rv = WrapNative(cx, JS::CurrentGlobalOrNull(cx), child,
-                           /* aAllowWrapping = */ true, v.address());
-  NS_ENSURE_SUCCESS(rv, false);
-  vp.set(v);
-  return true;
+  nsresult rv = nsDOMClassInfo::PostCreatePrototype(aCx, aProto);
+  NS_ENSURE_SUCCESS(rv, rv);
+
+  // We should probably move this into the CreateInterfaceObjects for Window
+  // once it is on WebIDL bindings.
+  JS::Rooted<JSObject*> proto(aCx, aProto);
+  WindowNamedPropertiesHandler::Install(aCx, proto);
+  return NS_OK;
 }
 
 static nsHTMLDocument*
 GetDocument(JSObject *obj)
 {
   MOZ_ASSERT(js::GetObjectJSClass(obj) == &sHTMLDocumentAllClass);
   return static_cast<nsHTMLDocument*>(
     static_cast<nsINode*>(JS_GetPrivate(obj)));
 }
 
-// static
-bool
-nsWindowSH::GlobalScopePolluterNewResolve(JSContext *cx, JS::Handle<JSObject*> obj,
-                                          JS::Handle<jsid> id, unsigned flags,
-                                          JS::MutableHandle<JSObject*> objp)
-{
-  if (!JSID_IS_STRING(id)) {
-    // Nothing to do if we're resolving a non-string property.
-    return true;
-  }
-
-  // Crash reports from the wild seem to get here during shutdown when there's
-  // no more XPConnect singleton.
-  nsIXPConnect *xpc = XPConnect();
-  NS_ENSURE_TRUE(xpc, true);
-
-  // Grab the DOM window.
-  JSObject *global = JS_GetGlobalForObject(cx, obj);
-  nsISupports *globalNative = xpc->GetNativeOfWrapper(cx, global);
-  nsCOMPtr<nsPIDOMWindow> piWin = do_QueryInterface(globalNative);
-  MOZ_ASSERT(piWin);
-  nsGlobalWindow* win = static_cast<nsGlobalWindow*>(piWin.get());
-
-  if (win->GetLength() > 0) {
-    nsDependentJSString name(id);
-    nsCOMPtr<nsIDOMWindow> child_win = win->GetChildWindow(name);
-    if (child_win) {
-      // We found a subframe of the right name, so define the property
-      // on the GSP. This property is a read-only accessor. Shadowing via
-      // |var foo| in global scope is still allowed, since |var| only looks
-      // up |own| properties. But unqualified shadowing will fail, per-spec.
-      if (!JS_DefinePropertyById(cx, obj, id, JS::UndefinedValue(),
-                                 ChildWindowGetter, JS_StrictPropertyStub,
-                                 JSPROP_SHARED | JSPROP_ENUMERATE))
-      {
-        return false;
-      }
-
-      objp.set(obj);
-      return true;
-    }
-  }
-
-  JS::Rooted<JSObject*> proto(cx);
-  if (!::JS_GetPrototype(cx, obj, &proto)) {
-    return false;
-  }
-  bool hasProp;
-
-  if (!proto || !::JS_HasPropertyById(cx, proto, id, &hasProp) ||
-      hasProp) {
-    // No prototype, or the property exists on the prototype. Do
-    // nothing.
-
-    return true;
-  }
-
-  //
-  // The rest of this function is for HTML documents only.
-  //
-  nsCOMPtr<nsIHTMLDocument> htmlDoc =
-    do_QueryInterface(win->GetExtantDoc());
-  if (!htmlDoc)
-    return true;
-  nsHTMLDocument *document = static_cast<nsHTMLDocument*>(htmlDoc.get());
-
-  nsDependentJSString str(id);
-  nsCOMPtr<nsISupports> result;
-  nsWrapperCache *cache;
-  {
-    Element *element = document->GetElementById(str);
-    result = element;
-    cache = element;
-  }
-
-  if (!result) {
-    result = document->ResolveName(str, &cache);
-  }
-
-  if (result) {
-    JS::Rooted<JS::Value> v(cx);
-    nsCOMPtr<nsIXPConnectJSObjectHolder> holder;
-    nsresult rv = WrapNative(cx, obj, result, cache, true, v.address(),
-                             getter_AddRefs(holder));
-    NS_ENSURE_SUCCESS(rv, false);
-
-    if (!JS_WrapValue(cx, v.address()) ||
-        !JS_DefinePropertyById(cx, obj, id, v, JS_PropertyStub, JS_StrictPropertyStub, 0)) {
-      return false;
-    }
-
-    objp.set(obj);
-  }
-
-  return true;
-}
-
-// static
-bool
-nsWindowSH::InvalidateGlobalScopePolluter(JSContext *cx,
-                                          JS::Handle<JSObject*> aObj)
-{
-  JS::Rooted<JSObject*> proto(cx);
-  JS::Rooted<JSObject*> obj(cx, aObj);
-
-  for (;;) {
-    if (!::JS_GetPrototype(cx, obj, &proto)) {
-      return false;
-    }
-    if (!proto) {
-      break;
-    }
-
-    if (JS_GetClass(proto) == &sGlobalScopePolluterClass) {
-
-      JS::Rooted<JSObject*> proto_proto(cx);
-      if (!::JS_GetPrototype(cx, proto, &proto_proto)) {
-        return false;
-      }
-
-      // Pull the global scope polluter out of the prototype chain so
-      // that it can be freed.
-      ::JS_SplicePrototype(cx, obj, proto_proto);
-
-      break;
-    }
-
-    obj = proto;
-  }
-
-  return true;
-}
-
-// static
-nsresult
-nsWindowSH::InstallGlobalScopePolluter(JSContext *cx, JS::Handle<JSObject*> obj)
-{
-  JS::Rooted<JSObject*> gsp(cx, ::JS_NewObjectWithUniqueType(cx, &sGlobalScopePolluterClass, nullptr, obj));
-  if (!gsp) {
-    return NS_ERROR_OUT_OF_MEMORY;
-  }
-
-  JS::Rooted<JSObject*> o(cx, obj), proto(cx);
-
-  // Find the place in the prototype chain where we want this global
-  // scope polluter (right before Object.prototype).
-
-  for (;;) {
-    if (!::JS_GetPrototype(cx, o, &proto)) {
-      return NS_ERROR_OUT_OF_MEMORY;
-    }
-    if (!proto) {
-      break;
-    }
-    if (JS_GetClass(proto) == sObjectClass) {
-      // Set the global scope polluters prototype to Object.prototype
-      ::JS_SplicePrototype(cx, gsp, proto);
-
-      break;
-    }
-
-    o = proto;
-  }
-
-  // And then set the prototype of the object whose prototype was
-  // Object.prototype to be the global scope polluter.
-  ::JS_SplicePrototype(cx, o, gsp);
-
-  return NS_OK;
-}
-
 struct ResolveGlobalNameClosure
 {
   JSContext* cx;
   JS::Handle<JSObject*> obj;
   bool* retval;
 };
 
 static PLDHashOperator
@@ -4874,71 +4640,16 @@ nsStringArraySH::GetProperty(nsIXPConnec
   }
 
   NS_ENSURE_TRUE(xpc::NonVoidStringToJsval(cx, val, vp),
                  NS_ERROR_OUT_OF_MEMORY);
   return NS_SUCCESS_I_DID_SOMETHING;
 }
 
 
-// History helper
-
-NS_IMETHODIMP
-nsHistorySH::PreCreate(nsISupports *nativeObj, JSContext *cx,
-                       JSObject *globalObj, JSObject **parentObj)
-{
-  nsHistory *history = (nsHistory *)((nsIDOMHistory*)nativeObj);
-  nsCOMPtr<nsPIDOMWindow> innerWindow;
-  history->GetWindow(getter_AddRefs(innerWindow));
-  if (!innerWindow) {
-    NS_WARNING("refusing to create history object in the wrong scope");
-    return NS_ERROR_FAILURE;
-  }
-  return SetParentToWindow(static_cast<nsGlobalWindow *>(innerWindow.get()),
-                           parentObj);
-}
-
-NS_IMETHODIMP
-nsHistorySH::GetProperty(nsIXPConnectWrappedNative *wrapper, JSContext *cx,
-                         JSObject *aObj, jsid aId, jsval *vp, bool *_retval)
-{
-  JS::Rooted<JSObject*> obj(cx, aObj);
-  JS::Rooted<jsid> id(cx, aId);
-  bool is_number = false;
-  GetArrayIndexFromId(cx, id, &is_number);
-
-  if (!is_number) {
-    return NS_OK;
-  }
-
-  return nsStringArraySH::GetProperty(wrapper, cx, obj, id, vp, _retval);
-}
-
-nsresult
-nsHistorySH::GetStringAt(nsISupports *aNative, int32_t aIndex,
-                         nsAString& aResult)
-{
-  if (aIndex < 0) {
-    return NS_ERROR_DOM_INDEX_SIZE_ERR;
-  }
-
-  nsCOMPtr<nsIDOMHistory> history(do_QueryInterface(aNative));
-
-  nsresult rv = history->Item(aIndex, aResult);
-#ifdef DEBUG
-  if (DOMStringIsNull(aResult)) {
-    int32_t length = 0;
-    history->GetLength(&length);
-    NS_ASSERTION(aIndex >= length, "Item should only return null for out-of-bounds access");
-  }
-#endif
-  return rv;
-}
-
-
 // MediaList helper
 
 nsresult
 nsMediaListSH::GetStringAt(nsISupports *aNative, int32_t aIndex,
                            nsAString& aResult)
 {
   if (aIndex < 0) {
     return NS_ERROR_DOM_INDEX_SIZE_ERR;
--- a/dom/base/nsDOMClassInfo.h
+++ b/dom/base/nsDOMClassInfo.h
@@ -131,16 +131,20 @@ public:
   static bool ObjectIsNativeWrapper(JSContext* cx, JSObject* obj);
 
   static nsISupports *GetNative(nsIXPConnectWrappedNative *wrapper, JSObject *obj);
 
   static nsIXPConnect *XPConnect()
   {
     return sXPConnect;
   }
+  static nsIScriptSecurityManager *ScriptSecurityManager()
+  {
+    return sSecMan;
+  }
 
 protected:
   friend nsIClassInfo* NS_GetDOMClassInfoInstance(nsDOMClassInfoID aID);
 
   const nsDOMClassInfoData* mData;
 
   virtual void PreserveWrapper(nsISupports *aNative) MOZ_OVERRIDE
   {
@@ -302,16 +306,17 @@ protected:
 
   static nsresult GlobalResolve(nsGlobalWindow *aWin, JSContext *cx,
                                 JS::Handle<JSObject*> obj, JS::Handle<jsid> id,
                                 bool *did_resolve);
 
 public:
   NS_IMETHOD PreCreate(nsISupports *nativeObj, JSContext *cx,
                        JSObject *globalObj, JSObject **parentObj) MOZ_OVERRIDE;
+  NS_IMETHOD PostCreatePrototype(JSContext * cx, JSObject * proto) MOZ_OVERRIDE;
 #ifdef DEBUG
   NS_IMETHOD PostCreate(nsIXPConnectWrappedNative *wrapper, JSContext *cx,
                         JSObject *obj) MOZ_OVERRIDE
   {
     nsCOMPtr<nsIScriptGlobalObject> sgo(do_QueryWrappedNative(wrapper));
 
     NS_ASSERTION(!sgo || sgo->GetGlobalJSObject() == nullptr,
                  "Multiple wrappers created for global object!");
--- a/dom/base/nsDOMClassInfoClasses.h
+++ b/dom/base/nsDOMClassInfoClasses.h
@@ -1,16 +1,15 @@
 /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 DOMCI_CLASS(Window)
 DOMCI_CLASS(Location)
-DOMCI_CLASS(History)
 DOMCI_CLASS(DOMPrototype)
 DOMCI_CLASS(DOMConstructor)
 
 // Core classes
 DOMCI_CLASS(DOMException)
 
 DOMCI_CLASS(DeviceAcceleration)
 DOMCI_CLASS(DeviceRotationRate)
--- a/dom/base/nsDOMClassInfoID.h
+++ b/dom/base/nsDOMClassInfoID.h
@@ -76,17 +76,17 @@ namespace mozilla {
 namespace dom {
 class Element;
 class EventTarget;
 } // namespace dom
 } // namespace mozilla
 
 #define DOMCI_CASTABLE_NODECL_INTERFACE DOMCI_CASTABLE_INTERFACE
 
-#ifdef _IMPL_NS_LAYOUT
+#ifdef MOZILLA_INTERNAL_API
 
 #define DOMCI_CLASS(_dom_class)                                               \
   extern const uint32_t kDOMClassInfo_##_dom_class##_interfaces;
 
 #include "nsDOMClassInfoClasses.h"
 
 #undef DOMCI_CLASS
 
@@ -162,11 +162,11 @@ NS_GetDOMClassInfoInstance(nsDOMClassInf
       return NS_ERROR_OUT_OF_MEMORY;                                          \
     }                                                                         \
   } else
 
 #else
 
 // See nsIDOMClassInfo.h
 
-#endif // _IMPL_NS_LAYOUT
+#endif // MOZILLA_INTERNAL_API
 
 #endif // nsDOMClassInfoID_h__
--- a/dom/base/nsDOMWindowList.cpp
+++ b/dom/base/nsDOMWindowList.cpp
@@ -81,24 +81,19 @@ nsDOMWindowList::GetLength(uint32_t* aLe
 {
   *aLength = GetLength();
   return NS_OK;
 }
 
 already_AddRefed<nsIDOMWindow>
 nsDOMWindowList::IndexedGetter(uint32_t aIndex, bool& aFound)
 {
-  EnsureFresh();
+  aFound = false;
 
-  aFound = false;
-  NS_ENSURE_TRUE(mDocShellNode, nullptr);
-
-  nsCOMPtr<nsIDocShellTreeItem> item;
-  mDocShellNode->GetChildAt(aIndex, getter_AddRefs(item));
-
+  nsCOMPtr<nsIDocShellTreeItem> item = GetDocShellTreeItemAt(aIndex);
   if (!item) {
     return nullptr;
   }
 
   nsCOMPtr<nsIDOMWindow> window = do_GetInterface(item);
   MOZ_ASSERT(window);
 
   aFound = true;
--- a/dom/base/nsDOMWindowList.h
+++ b/dom/base/nsDOMWindowList.h
@@ -5,16 +5,17 @@
 #ifndef nsDOMWindowList_h___
 #define nsDOMWindowList_h___
 
 #include "nsCOMPtr.h"
 #include "nsISupports.h"
 #include "nsIDOMWindowCollection.h"
 #include "nsString.h"
 #include <stdint.h>
+#include "nsIDocShellTreeItem.h"
 
 class nsIDocShellTreeNode;
 class nsIDocShell;
 class nsIDOMWindow;
 
 class nsDOMWindowList : public nsIDOMWindowCollection
 {
 public:
@@ -24,16 +25,25 @@ public:
   NS_DECL_ISUPPORTS
   NS_DECL_NSIDOMWINDOWCOLLECTION
 
   uint32_t GetLength();
   already_AddRefed<nsIDOMWindow> IndexedGetter(uint32_t aIndex, bool& aFound);
 
   //local methods
   NS_IMETHOD SetDocShell(nsIDocShell* aDocShell);
+  already_AddRefed<nsIDocShellTreeItem> GetDocShellTreeItemAt(uint32_t aIndex)
+  {
+    EnsureFresh();
+    nsCOMPtr<nsIDocShellTreeItem> item;
+    if (mDocShellNode) {
+      mDocShellNode->GetChildAt(aIndex, getter_AddRefs(item));
+    }
+    return item.forget();
+  }
 
 protected:
   // Note: this function may flush and cause mDocShellNode to become null.
   void EnsureFresh();
 
   nsIDocShellTreeNode* mDocShellNode; //Weak Reference
 };
 
--- a/dom/base/nsGlobalWindow.cpp
+++ b/dom/base/nsGlobalWindow.cpp
@@ -2274,19 +2274,16 @@ nsGlobalWindow::SetNewDocument(nsIDocume
     // We're reusing the current inner window.
     NS_ASSERTION(!currentInner->IsFrozen(),
                  "We should never be reusing a shared inner window");
     newInnerWindow = currentInner;
 
     if (aDocument != oldDoc) {
       JS::Rooted<JSObject*> obj(cx, currentInner->mJSObject);
       xpc_UnmarkGrayObject(obj);
-      if (!nsWindowSH::InvalidateGlobalScopePolluter(cx, obj)) {
-        return NS_ERROR_FAILURE;
-      }
     }
 
     // We're reusing the inner window, but this still counts as a navigation,
     // so all expandos and such defined on the outer window should go away. Force
     // all Xray wrappers to be recomputed.
     xpc_UnmarkGrayObject(mJSObject);
     if (!JS_RefreshCrossCompartmentWrappers(cx, mJSObject)) {
       return NS_ERROR_FAILURE;
@@ -2494,32 +2491,16 @@ nsGlobalWindow::SetNewDocument(nsIDocume
         SuspendTimeouts(parentWindow->TimeoutSuspendCount());
       }
     }
   }
 
   // Add an extra ref in case we release mContext during GC.
   nsCOMPtr<nsIScriptContext> kungFuDeathGrip(mContext);
 
-  // Now that the prototype is all set up, install the global scope
-  // polluter. This must happen after the above prototype fixup. If
-  // the GSP was to be installed on the inner window's real
-  // prototype (as it would be if this was done before the prototype
-  // fixup above) we would end up holding the GSP alive (through
-  // XPConnect's internal marking of wrapper prototypes) as long as
-  // the inner window was around, and if the GSP had properties on
-  // it that held an element alive we'd hold the document alive,
-  // which could hold event handlers alive, which hold the context
-  // alive etc.
-
-  if ((!reUseInnerWindow || aDocument != oldDoc) && !aState) {
-    JS::Rooted<JSObject*> obj(cx, newInnerWindow->mJSObject);
-    nsWindowSH::InstallGlobalScopePolluter(cx, obj);
-  }
-
   aDocument->SetScriptGlobalObject(newInnerWindow);
 
   if (!aState) {
     if (reUseInnerWindow) {
       if (newInnerWindow->mDoc != aDocument) {
         newInnerWindow->mDoc = aDocument;
 
         // We're reusing the inner window for a new document. In this
@@ -3390,17 +3371,17 @@ nsGlobalWindow::GetScreen(nsIDOMScreen**
   }
 
   NS_IF_ADDREF(*aScreen = mScreen);
 
   return NS_OK;
 }
 
 NS_IMETHODIMP
-nsGlobalWindow::GetHistory(nsIDOMHistory** aHistory)
+nsGlobalWindow::GetHistory(nsISupports** aHistory)
 {
   FORWARD_TO_INNER(GetHistory, (aHistory), NS_ERROR_NOT_INITIALIZED);
 
   *aHistory = nullptr;
 
   if (!mHistory) {
     mHistory = new nsHistory(this);
     if (!mHistory) {
@@ -3838,16 +3819,33 @@ nsGlobalWindow::IndexedGetter(uint32_t a
   FORWARD_TO_OUTER(IndexedGetter, (aIndex, aFound), nullptr);
 
   nsDOMWindowList* windows = GetWindowList();
   NS_ENSURE_TRUE(windows, nullptr);
 
   return windows->IndexedGetter(aIndex, aFound);
 }
 
+void
+nsGlobalWindow::GetSupportedNames(nsTArray<nsString>& aNames)
+{
+  FORWARD_TO_OUTER_VOID(GetSupportedNames, (aNames));
+
+  nsDOMWindowList* windows = GetWindowList();
+  if (windows) {
+    uint32_t length = windows->GetLength();
+    nsString* name = aNames.AppendElements(length);
+    for (uint32_t i = 0; i < length; ++i, ++name) {
+      nsCOMPtr<nsIDocShellTreeItem> item =
+        windows->GetDocShellTreeItemAt(i);
+      item->GetName(*name);
+    }
+  }
+}
+
 NS_IMETHODIMP
 nsGlobalWindow::GetApplicationCache(nsIDOMOfflineResourceList **aApplicationCache)
 {
   FORWARD_TO_INNER(GetApplicationCache, (aApplicationCache), NS_ERROR_UNEXPECTED);
 
   NS_ENSURE_ARG_POINTER(aApplicationCache);
 
   if (!mApplicationCache) {
--- a/dom/base/nsGlobalWindow.h
+++ b/dom/base/nsGlobalWindow.h
@@ -465,16 +465,18 @@ public:
 
   // nsIInterfaceRequestor
   NS_DECL_NSIINTERFACEREQUESTOR
 
   // WebIDL interface.
   uint32_t GetLength();
   already_AddRefed<nsIDOMWindow> IndexedGetter(uint32_t aIndex, bool& aFound);
 
+  void GetSupportedNames(nsTArray<nsString>& aNames);
+
   // Object Management
   nsGlobalWindow(nsGlobalWindow *aOuterWindow);
 
   static nsGlobalWindow *FromSupports(nsISupports *supports)
   {
     // Make sure this matches the casts we do in QueryInterface().
     return (nsGlobalWindow *)(mozilla::dom::EventTarget *)supports;
   }
--- a/dom/base/nsHistory.cpp
+++ b/dom/base/nsHistory.cpp
@@ -1,230 +1,161 @@
 /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
 /* vim: set ts=2 sw=2 et tw=78: */
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #include "nsHistory.h"
-
+#include "mozilla/dom/HistoryBinding.h"
 #include "nsCOMPtr.h"
-#include "nscore.h"
 #include "nsPIDOMWindow.h"
-#include "nsIScriptGlobalObject.h"
 #include "nsIDocument.h"
 #include "nsIPresShell.h"
 #include "nsPresContext.h"
 #include "nsIDocShell.h"
 #include "nsIWebNavigation.h"
 #include "nsIHistoryEntry.h"
 #include "nsIURI.h"
-#include "nsIServiceManager.h"
 #include "nsIInterfaceRequestorUtils.h"
-#include "nsXPIDLString.h"
 #include "nsReadableUtils.h"
-#include "nsDOMClassInfoID.h"
-#include "nsError.h"
 #include "nsContentUtils.h"
 #include "nsISHistoryInternal.h"
 #include "mozilla/Preferences.h"
 
 using namespace mozilla;
+using namespace mozilla::dom;
 
-static const char* sAllowPushStatePrefStr  =
+static const char* sAllowPushStatePrefStr =
   "browser.history.allowPushState";
 static const char* sAllowReplaceStatePrefStr =
   "browser.history.allowReplaceState";
 
 //
-//  History class implementation 
+//  History class implementation
 //
+NS_IMPL_CYCLE_COLLECTION_WRAPPERCACHE_0(nsHistory)
+NS_IMPL_CYCLE_COLLECTING_ADDREF(nsHistory)
+NS_IMPL_CYCLE_COLLECTING_RELEASE(nsHistory)
+NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION(nsHistory)
+  NS_WRAPPERCACHE_INTERFACE_MAP_ENTRY
+  NS_INTERFACE_MAP_ENTRY(nsISupports)
+  NS_INTERFACE_MAP_ENTRY(nsIDOMHistory) // Empty, needed for extension compat
+NS_INTERFACE_MAP_END
+
 nsHistory::nsHistory(nsPIDOMWindow* aInnerWindow)
   : mInnerWindow(do_GetWeakReference(aInnerWindow))
 {
+  SetIsDOMBinding();
 }
 
 nsHistory::~nsHistory()
 {
 }
 
-
-DOMCI_DATA(History, nsHistory)
-
-// QueryInterface implementation for nsHistory
-NS_INTERFACE_MAP_BEGIN(nsHistory)
-  NS_INTERFACE_MAP_ENTRY_AMBIGUOUS(nsISupports, nsIDOMHistory)
-  NS_INTERFACE_MAP_ENTRY(nsIDOMHistory)
-  NS_DOM_INTERFACE_MAP_ENTRY_CLASSINFO(History)
-NS_INTERFACE_MAP_END
-
-
-NS_IMPL_ADDREF(nsHistory)
-NS_IMPL_RELEASE(nsHistory)
-
-
-NS_IMETHODIMP
-nsHistory::GetLength(int32_t* aLength)
+nsPIDOMWindow*
+nsHistory::GetParentObject() const
 {
   nsCOMPtr<nsPIDOMWindow> win(do_QueryReferent(mInnerWindow));
-  if (!win || !nsContentUtils::CanCallerAccess(win->GetOuterWindow()))
-    return NS_ERROR_DOM_SECURITY_ERR;
-
-  nsCOMPtr<nsISHistory>   sHistory;
-
-  // Get session History from docshell
-  GetSessionHistoryFromDocShell(GetDocShell(), getter_AddRefs(sHistory));
-  NS_ENSURE_TRUE(sHistory, NS_ERROR_FAILURE);
-  return sHistory->GetCount(aLength);
+  return win;
 }
 
-NS_IMETHODIMP
-nsHistory::GetCurrent(nsAString& aCurrent)
+JSObject*
+nsHistory::WrapObject(JSContext* aCx, JS::Handle<JSObject*> aScope)
 {
-  if (!nsContentUtils::IsCallerChrome())
-    return NS_ERROR_DOM_SECURITY_ERR;
-
-  int32_t curIndex=0;
-  nsAutoCString curURL;
-  nsCOMPtr<nsISHistory> sHistory;
-
-  // Get SessionHistory from docshell
-  GetSessionHistoryFromDocShell(GetDocShell(), getter_AddRefs(sHistory));
-  NS_ENSURE_TRUE(sHistory, NS_ERROR_FAILURE);
-
-  // Get the current index at session History
-  sHistory->GetIndex(&curIndex);
-  nsCOMPtr<nsIHistoryEntry> curEntry;
-  nsCOMPtr<nsIURI>     uri;
-
-  // Get the SH entry for the current index
-  sHistory->GetEntryAtIndex(curIndex, false, getter_AddRefs(curEntry));
-  NS_ENSURE_TRUE(curEntry, NS_ERROR_FAILURE);
-
-  // Get the URI for the current entry
-  curEntry->GetURI(getter_AddRefs(uri));
-  NS_ENSURE_TRUE(uri, NS_ERROR_FAILURE);
-  uri->GetSpec(curURL);
-  CopyUTF8toUTF16(curURL, aCurrent);
-
-  return NS_OK;
+  return HistoryBinding::Wrap(aCx, aScope, this);
 }
 
-NS_IMETHODIMP
-nsHistory::GetPrevious(nsAString& aPrevious)
+uint32_t
+nsHistory::GetLength(ErrorResult& aRv) const
 {
-  if (!nsContentUtils::IsCallerChrome())
-    return NS_ERROR_DOM_SECURITY_ERR;
+  nsCOMPtr<nsPIDOMWindow> win(do_QueryReferent(mInnerWindow));
+  if (!win || !nsContentUtils::CanCallerAccess(win->GetOuterWindow())) {
+    aRv.Throw(NS_ERROR_DOM_SECURITY_ERR);
 
-  int32_t curIndex;
-  nsAutoCString prevURL;
-  nsCOMPtr<nsISHistory>  sHistory;
+    return 0;
+  }
 
   // Get session History from docshell
-  GetSessionHistoryFromDocShell(GetDocShell(), getter_AddRefs(sHistory));
-  NS_ENSURE_TRUE(sHistory, NS_ERROR_FAILURE);
+  nsCOMPtr<nsISHistory> sHistory = GetSessionHistory();
+  if (!sHistory) {
+    aRv.Throw(NS_ERROR_FAILURE);
 
-  // Get the current index at session History
-  sHistory->GetIndex(&curIndex);
-  nsCOMPtr<nsIHistoryEntry> prevEntry;
-  nsCOMPtr<nsIURI>     uri;
+    return 0;
+  }
 
-  // Get the previous SH entry
-  sHistory->GetEntryAtIndex((curIndex-1), false, getter_AddRefs(prevEntry));
-  NS_ENSURE_TRUE(prevEntry, NS_ERROR_FAILURE);
+  int32_t len;
+  nsresult rv = sHistory->GetCount(&len);
 
-  // Get the URI for the previous entry
-  prevEntry->GetURI(getter_AddRefs(uri));
-  NS_ENSURE_TRUE(uri, NS_ERROR_FAILURE);
-  uri->GetSpec(prevURL);
-  CopyUTF8toUTF16(prevURL, aPrevious);
+  if (NS_FAILED(rv)) {
+    aRv.Throw(rv);
 
-  return NS_OK;
+    return 0;
+  }
+
+  return len >= 0 ? len : 0;
 }
 
-NS_IMETHODIMP
-nsHistory::GetNext(nsAString& aNext)
-{
-  if (!nsContentUtils::IsCallerChrome())
-    return NS_ERROR_DOM_SECURITY_ERR;
-
-  int32_t curIndex;
-  nsAutoCString nextURL;
-  nsCOMPtr<nsISHistory>  sHistory;
-
-  // Get session History from docshell
-  GetSessionHistoryFromDocShell(GetDocShell(), getter_AddRefs(sHistory));
-  NS_ENSURE_TRUE(sHistory, NS_ERROR_FAILURE);
-
-  // Get the current index at session History
-  sHistory->GetIndex(&curIndex);
-  nsCOMPtr<nsIHistoryEntry> nextEntry;
-  nsCOMPtr<nsIURI>     uri;
-
-  // Get the next SH entry
-  sHistory->GetEntryAtIndex((curIndex+1), false, getter_AddRefs(nextEntry));
-  NS_ENSURE_TRUE(nextEntry, NS_ERROR_FAILURE);
-
-  // Get the URI for the next entry
-  nextEntry->GetURI(getter_AddRefs(uri));
-  NS_ENSURE_TRUE(uri, NS_ERROR_FAILURE);
-  uri->GetSpec(nextURL); 
-  CopyUTF8toUTF16(nextURL, aNext);
-
-  return NS_OK;
-}
-
-NS_IMETHODIMP
-nsHistory::Back()
+JS::Value
+nsHistory::GetState(JSContext* aCx, ErrorResult& aRv) const
 {
   nsCOMPtr<nsPIDOMWindow> win(do_QueryReferent(mInnerWindow));
-  if (!win || !nsContentUtils::CanCallerAccess(win->GetOuterWindow()))
-    return NS_ERROR_DOM_SECURITY_ERR;
+  if (!win) {
+    aRv.Throw(NS_ERROR_NOT_AVAILABLE);
+
+    return JS::UndefinedValue();
+  }
+
+  if (!nsContentUtils::CanCallerAccess(win->GetOuterWindow())) {
+    aRv.Throw(NS_ERROR_DOM_SECURITY_ERR);
 
-  nsCOMPtr<nsISHistory>  sHistory;
+    return JS::UndefinedValue();
+  }
+
+  nsCOMPtr<nsIDocument> doc =
+    do_QueryInterface(win->GetExtantDoc());
+  if (!doc) {
+    aRv.Throw(NS_ERROR_NOT_AVAILABLE);
+
+    return JS::UndefinedValue();
+  }
 
-  GetSessionHistoryFromDocShell(GetDocShell(), getter_AddRefs(sHistory));
-  NS_ENSURE_TRUE(sHistory, NS_ERROR_FAILURE);
+  nsCOMPtr<nsIVariant> variant;
+  doc->GetStateObject(getter_AddRefs(variant));
+
+  if (variant) {
+    JS::Rooted<JS::Value> jsData(aCx);
+    aRv = variant->GetAsJSVal(jsData.address());
 
-  //QI SHistory to WebNavigation
-  nsCOMPtr<nsIWebNavigation> webNav(do_QueryInterface(sHistory));
-  NS_ENSURE_TRUE(webNav, NS_ERROR_FAILURE);
-  webNav->GoBack();
+    if (aRv.Failed()) {
+      return JS::UndefinedValue();
+    }
 
-  return NS_OK;
+    if (!JS_WrapValue(aCx, jsData.address())) {
+      aRv.Throw(NS_ERROR_OUT_OF_MEMORY);
+      return JS::UndefinedValue();
+    }
+
+    return jsData;
+  }
+
+  return JS::UndefinedValue();
 }
 
-NS_IMETHODIMP
-nsHistory::Forward()
+void
+nsHistory::Go(int32_t aDelta, ErrorResult& aRv)
 {
   nsCOMPtr<nsPIDOMWindow> win(do_QueryReferent(mInnerWindow));
-  if (!win || !nsContentUtils::CanCallerAccess(win->GetOuterWindow()))
-    return NS_ERROR_DOM_SECURITY_ERR;
-
-  nsCOMPtr<nsISHistory>  sHistory;
-
-  GetSessionHistoryFromDocShell(GetDocShell(), getter_AddRefs(sHistory));
-  NS_ENSURE_TRUE(sHistory, NS_ERROR_FAILURE);
+  if (!win || !nsContentUtils::CanCallerAccess(win->GetOuterWindow())) {
+    aRv.Throw(NS_ERROR_DOM_SECURITY_ERR);
 
-  //QI SHistory to WebNavigation
-  nsCOMPtr<nsIWebNavigation> webNav(do_QueryInterface(sHistory));
-  NS_ENSURE_TRUE(webNav, NS_ERROR_FAILURE);
-  webNav->GoForward();
-
-  return NS_OK;
-}
+    return;
+  }
 
-NS_IMETHODIMP
-nsHistory::Go(int32_t aDelta)
-{
-  nsCOMPtr<nsPIDOMWindow> win(do_QueryReferent(mInnerWindow));
-  if (!win || !nsContentUtils::CanCallerAccess(win->GetOuterWindow()))
-    return NS_ERROR_DOM_SECURITY_ERR;
-
-  if (aDelta == 0) {
+  if (!aDelta) {
     nsCOMPtr<nsPIDOMWindow> window(do_GetInterface(GetDocShell()));
 
     if (window && window->IsHandlingResizeEvent()) {
       // history.go(0) (aka location.reload()) was called on a window
       // that is handling a resize event. Sites do this since Netscape
       // 4.x needed it, but we don't, and it's a horrible experience
       // for nothing.  In stead of reloading the page, just clear
       // style data and reflow the page since some sites may use this
@@ -234,175 +165,353 @@ nsHistory::Go(int32_t aDelta)
       nsCOMPtr<nsIDocument> doc = window->GetExtantDoc();
 
       nsIPresShell *shell;
       nsPresContext *pcx;
       if (doc && (shell = doc->GetShell()) && (pcx = shell->GetPresContext())) {
         pcx->RebuildAllStyleData(NS_STYLE_HINT_REFLOW);
       }
 
-      return NS_OK;
+      return;
     }
   }
 
-  nsCOMPtr<nsISHistory> session_history;
-
-  GetSessionHistoryFromDocShell(GetDocShell(), getter_AddRefs(session_history));
-  NS_ENSURE_TRUE(session_history, NS_ERROR_FAILURE);
+  nsCOMPtr<nsISHistory> session_history = GetSessionHistory();
+  nsCOMPtr<nsIWebNavigation> webnav(do_QueryInterface(session_history));
+  if (!webnav) {
+    aRv.Throw(NS_ERROR_FAILURE);
 
-  // QI SHistory to nsIWebNavigation
-  nsCOMPtr<nsIWebNavigation> webnav(do_QueryInterface(session_history));
-  NS_ENSURE_TRUE(webnav, NS_ERROR_FAILURE);
+    return;
+  }
 
-  int32_t curIndex=-1;
+  int32_t curIndex = -1;
   int32_t len = 0;
   session_history->GetIndex(&curIndex);
   session_history->GetCount(&len);
 
   int32_t index = curIndex + aDelta;
-  if (index > -1  &&  index < len)
+  if (index > -1 && index < len)
     webnav->GotoIndex(index);
 
-  // We always want to return a NS_OK, since returning errors 
+  // Ignore the return value from GotoIndex(), since returning errors
   // from GotoIndex() can lead to exceptions and a possible leak
   // of history length
+}
 
-  return NS_OK;
+void
+nsHistory::Back(ErrorResult& aRv)
+{
+  nsCOMPtr<nsPIDOMWindow> win(do_QueryReferent(mInnerWindow));
+  if (!win || !nsContentUtils::CanCallerAccess(win->GetOuterWindow())) {
+    aRv.Throw(NS_ERROR_DOM_SECURITY_ERR);
+
+    return;
+  }
+
+  nsCOMPtr<nsISHistory> sHistory = GetSessionHistory();
+  nsCOMPtr<nsIWebNavigation> webNav(do_QueryInterface(sHistory));
+  if (!webNav) {
+    aRv.Throw(NS_ERROR_FAILURE);
+
+    return;
+  }
+
+  webNav->GoBack();
+}
+
+void
+nsHistory::Forward(ErrorResult& aRv)
+{
+  nsCOMPtr<nsPIDOMWindow> win(do_QueryReferent(mInnerWindow));
+  if (!win || !nsContentUtils::CanCallerAccess(win->GetOuterWindow())) {
+    aRv.Throw(NS_ERROR_DOM_SECURITY_ERR);
+
+    return;
+  }
+
+  nsCOMPtr<nsISHistory> sHistory = GetSessionHistory();
+  nsCOMPtr<nsIWebNavigation> webNav(do_QueryInterface(sHistory));
+  if (!webNav) {
+    aRv.Throw(NS_ERROR_FAILURE);
+
+    return;
+  }
+
+  webNav->GoForward();
+}
+
+void
+nsHistory::PushState(JSContext* aCx, JS::Handle<JS::Value> aData,
+                     const nsAString& aTitle, const nsAString& aUrl,
+                     ErrorResult& aRv)
+{
+  PushOrReplaceState(aCx, aData, aTitle, aUrl, aRv, false);
+}
+
+void
+nsHistory::ReplaceState(JSContext* aCx, JS::Handle<JS::Value> aData,
+                        const nsAString& aTitle, const nsAString& aUrl,
+                        ErrorResult& aRv)
+{
+  PushOrReplaceState(aCx, aData, aTitle, aUrl, aRv, true);
 }
 
-NS_IMETHODIMP
-nsHistory::PushState(nsIVariant *aData, const nsAString& aTitle,
-                     const nsAString& aURL, JSContext* aCx)
+void
+nsHistory::GetCurrent(nsString& aRetval, ErrorResult& aRv) const
 {
-  // Check that PushState hasn't been pref'ed off.
-  if (!Preferences::GetBool(sAllowPushStatePrefStr, false)) {
-    return NS_OK;
+  MOZ_ASSERT(nsContentUtils::IsCallerChrome());
+
+  aRetval.Truncate();
+
+  int32_t curIndex = 0;
+  nsAutoCString curURL;
+  nsCOMPtr<nsISHistory> sHistory = GetSessionHistory();
+  if (!sHistory) {
+    aRv.Throw(NS_ERROR_FAILURE);
+
+    return;
+  }
+
+  // Get the current index at session History
+  sHistory->GetIndex(&curIndex);
+  nsCOMPtr<nsIHistoryEntry> curEntry;
+  nsCOMPtr<nsIURI> uri;
+
+  // Get the SH entry for the current index
+  sHistory->GetEntryAtIndex(curIndex, false, getter_AddRefs(curEntry));
+  if (!curEntry) {
+    aRv.Throw(NS_ERROR_FAILURE);
+
+    return;
+  }
+
+  // Get the URI for the current entry
+  curEntry->GetURI(getter_AddRefs(uri));
+  if (!uri) {
+    aRv.Throw(NS_ERROR_FAILURE);
+
+    return;
+  }
+
+  uri->GetSpec(curURL);
+  CopyUTF8toUTF16(curURL, aRetval);
+}
+
+void
+nsHistory::GetPrevious(nsString& aRetval, ErrorResult& aRv) const
+{
+  MOZ_ASSERT(nsContentUtils::IsCallerChrome());
+
+  aRetval.Truncate();
+
+  int32_t curIndex;
+  nsAutoCString prevURL;
+  nsCOMPtr<nsISHistory> sHistory = GetSessionHistory();
+  if (!sHistory) {
+    aRv.Throw(NS_ERROR_FAILURE);
+
+    return;
+  }
+
+  // Get the current index at session History
+  sHistory->GetIndex(&curIndex);
+  nsCOMPtr<nsIHistoryEntry> prevEntry;
+  nsCOMPtr<nsIURI> uri;
+
+  // Get the previous SH entry
+  sHistory->GetEntryAtIndex((curIndex - 1), false, getter_AddRefs(prevEntry));
+  if (!prevEntry) {
+    aRv.Throw(NS_ERROR_FAILURE);
+
+    return;
+  }
+
+  // Get the URI for the previous entry
+  prevEntry->GetURI(getter_AddRefs(uri));
+  if (!uri) {
+    aRv.Throw(NS_ERROR_FAILURE);
+
+    return;
   }
 
-  nsCOMPtr<nsPIDOMWindow> win(do_QueryReferent(mInnerWindow));
-  if (!win)
-    return NS_ERROR_NOT_AVAILABLE;
+  uri->GetSpec(prevURL);
+  CopyUTF8toUTF16(prevURL, aRetval);
+}
+
+void
+nsHistory::GetNext(nsString& aRetval, ErrorResult& aRv) const
+{
+  MOZ_ASSERT(nsContentUtils::IsCallerChrome());
+
+  aRetval.Truncate();
 
-  if (!nsContentUtils::CanCallerAccess(win->GetOuterWindow()))
-    return NS_ERROR_DOM_SECURITY_ERR;
+  int32_t curIndex;
+  nsAutoCString nextURL;
+  nsCOMPtr<nsISHistory> sHistory = GetSessionHistory();
+  if (!sHistory) {
+    aRv.Throw(NS_ERROR_FAILURE);
+
+    return;
+  }
+
+  // Get the current index at session History
+  sHistory->GetIndex(&curIndex);
+  nsCOMPtr<nsIHistoryEntry> nextEntry;
+  nsCOMPtr<nsIURI> uri;
 
-  // AddState might run scripts, so we need to hold a strong reference to the
-  // docShell here to keep it from going away.
-  nsCOMPtr<nsIDocShell> docShell = win->GetDocShell();
+  // Get the next SH entry
+  sHistory->GetEntryAtIndex((curIndex+1), false, getter_AddRefs(nextEntry));
+  if (!nextEntry) {
+    aRv.Throw(NS_ERROR_FAILURE);
 
-  NS_ENSURE_TRUE(docShell, NS_ERROR_FAILURE);
+    return;
+  }
+
+  // Get the URI for the next entry
+  nextEntry->GetURI(getter_AddRefs(uri));
 
-  // false tells the docshell to add a new history entry instead of
-  // modifying the current one.
-  nsresult rv = docShell->AddState(aData, aTitle, aURL, false, aCx);
-  NS_ENSURE_SUCCESS(rv, rv);
+  if (!uri) {
+    aRv.Throw(NS_ERROR_FAILURE);
+
+    return;
+  }
 
-  return NS_OK;
+  uri->GetSpec(nextURL);
+  CopyUTF8toUTF16(nextURL, aRetval);
+}
+
+void
+nsHistory::Item(uint32_t aIndex, nsString& aRetval, ErrorResult& aRv)
+{
+  bool unused;
+  IndexedGetter(aIndex, unused, aRetval, aRv);
 }
 
-NS_IMETHODIMP
-nsHistory::ReplaceState(nsIVariant *aData, const nsAString& aTitle,
-                        const nsAString& aURL, JSContext* aCx)
+void
+nsHistory::IndexedGetter(uint32_t aIndex, bool &aFound, nsString& aRetval,
+                         ErrorResult& aRv)
 {
-  // Check that ReplaceState hasn't been pref'ed off
-  if (!Preferences::GetBool(sAllowReplaceStatePrefStr, false)) {
-    return NS_OK;
+  aRetval.Truncate();
+  aFound = false;
+
+  if (!nsContentUtils::IsCallerChrome()) {
+    aRv.Throw(NS_ERROR_DOM_SECURITY_ERR);
+
+    return;
+  }
+
+  nsCOMPtr<nsISHistory> session_history = GetSessionHistory();
+  if (!session_history) {
+    aRv.Throw(NS_ERROR_FAILURE);
+
+    return;
+  }
+
+  nsCOMPtr<nsIHistoryEntry> sh_entry;
+  nsCOMPtr<nsIURI> uri;
+
+  aRv = session_history->GetEntryAtIndex(aIndex, false,
+                                         getter_AddRefs(sh_entry));
+
+  if (aRv.Failed()) {
+    return;
+  }
+
+  if (sh_entry) {
+    aRv = sh_entry->GetURI(getter_AddRefs(uri));
   }
 
+  if (uri) {
+    nsAutoCString urlCString;
+    aRv = uri->GetSpec(urlCString);
+
+    if (aRv.Failed()) {
+      return;
+    }
+
+    CopyUTF8toUTF16(urlCString, aRetval);
+
+    aFound = true;
+  }
+}
+
+uint32_t
+nsHistory::Length()
+{
+  if (!nsContentUtils::IsCallerChrome()) {
+    return 0;
+  }
+
+  // Get session History from docshell
+  nsCOMPtr<nsISHistory> sHistory = GetSessionHistory();
+  if (!sHistory) {
+    return 0;
+  }
+
+  int32_t len;
+  nsresult rv = sHistory->GetCount(&len);
+
+  if (NS_FAILED(rv) || len < 0) {
+    return 0;
+  }
+
+  return len;
+}
+
+void
+nsHistory::PushOrReplaceState(JSContext* aCx, JS::Value aData,
+                              const nsAString& aTitle, const nsAString& aUrl,
+                              ErrorResult& aRv, bool aReplace)
+{
   nsCOMPtr<nsPIDOMWindow> win(do_QueryReferent(mInnerWindow));
-  if (!win)
-    return NS_ERROR_NOT_AVAILABLE;
+  if (!win) {
+    aRv.Throw(NS_ERROR_NOT_AVAILABLE);
+
+    return;
+  }
+
+  if (!nsContentUtils::CanCallerAccess(win->GetOuterWindow())) {
+    aRv.Throw(NS_ERROR_DOM_SECURITY_ERR);
 
-  if (!nsContentUtils::CanCallerAccess(win->GetOuterWindow()))
-    return NS_ERROR_DOM_SECURITY_ERR;
+    return;
+  }
+
+  // Check that PushState hasn't been pref'ed off.
+  if (!Preferences::GetBool(aReplace ? sAllowReplaceStatePrefStr :
+                            sAllowPushStatePrefStr, false)) {
+    return;
+  }
 
   // AddState might run scripts, so we need to hold a strong reference to the
   // docShell here to keep it from going away.
   nsCOMPtr<nsIDocShell> docShell = win->GetDocShell();
 
-  NS_ENSURE_TRUE(docShell, NS_ERROR_FAILURE);
-
-  // true tells the docshell to modify the current SHEntry, rather than
-  // create a new one.
-  return docShell->AddState(aData, aTitle, aURL, true, aCx);
-}
-
-NS_IMETHODIMP
-nsHistory::GetState(nsIVariant **aState)
-{
-  *aState = nullptr;
-
-  nsCOMPtr<nsPIDOMWindow> win(do_QueryReferent(mInnerWindow));
-  if (!win)
-    return NS_ERROR_NOT_AVAILABLE;
+  if (!docShell) {
+    aRv.Throw(NS_ERROR_FAILURE);
 
-  if (!nsContentUtils::CanCallerAccess(win->GetOuterWindow()))
-    return NS_ERROR_DOM_SECURITY_ERR;
-
-  nsCOMPtr<nsIDocument> doc = win->GetExtantDoc();
-  if (!doc)
-    return NS_ERROR_NOT_AVAILABLE;
-
-  return doc->GetStateObject(aState);
-}
-
-NS_IMETHODIMP
-nsHistory::Item(uint32_t aIndex, nsAString& aReturn)
-{
-  aReturn.Truncate();
-  if (!nsContentUtils::IsCallerChrome()) {
-    return NS_ERROR_DOM_SECURITY_ERR;
+    return;
   }
 
-  nsresult rv = NS_OK;
-  nsCOMPtr<nsISHistory>  session_history;
-
-  GetSessionHistoryFromDocShell(GetDocShell(), getter_AddRefs(session_history));
-  NS_ENSURE_TRUE(session_history, NS_ERROR_FAILURE);
-
-  nsCOMPtr<nsIHistoryEntry> sh_entry;
-  nsCOMPtr<nsIURI> uri;
-
-  rv = session_history->GetEntryAtIndex(aIndex, false,
-                                        getter_AddRefs(sh_entry));
+  // The "replace" argument tells the docshell to whether to add a new
+  // history entry or modify the current one.
 
-  if (sh_entry) {
-    rv = sh_entry->GetURI(getter_AddRefs(uri));
-  }
-
-  if (uri) {
-    nsAutoCString urlCString;
-    rv = uri->GetSpec(urlCString);
-
-    CopyUTF8toUTF16(urlCString, aReturn);
-  }
-
-  return rv;
+  aRv = docShell->AddState(aData, aTitle, aUrl, aReplace, aCx);
 }
 
-nsresult
-nsHistory::GetSessionHistoryFromDocShell(nsIDocShell * aDocShell, 
-                                         nsISHistory ** aReturn)
+already_AddRefed<nsISHistory>
+nsHistory::GetSessionHistory() const
 {
-
-  NS_ENSURE_TRUE(aDocShell, NS_ERROR_FAILURE);
-  /* The docshell we have may or may not be
-   * the root docshell. So, get a handle to
-   * SH from the root docshell
-   */
-  
-  // QI mDocShell to nsIDocShellTreeItem
-  NS_ENSURE_TRUE(aDocShell, NS_ERROR_FAILURE);
+  nsIDocShell *docShell = GetDocShell();
+  NS_ENSURE_TRUE(docShell, nullptr);
 
   // Get the root DocShell from it
   nsCOMPtr<nsIDocShellTreeItem> root;
-  aDocShell->GetSameTypeRootTreeItem(getter_AddRefs(root));
-  NS_ENSURE_TRUE(root, NS_ERROR_FAILURE);
-  
-  //QI root to nsIWebNavigation
-  nsCOMPtr<nsIWebNavigation>   webNav(do_QueryInterface(root));
-  NS_ENSURE_TRUE(webNav, NS_ERROR_FAILURE);
+  docShell->GetSameTypeRootTreeItem(getter_AddRefs(root));
+  nsCOMPtr<nsIWebNavigation> webNav(do_QueryInterface(root));
+  NS_ENSURE_TRUE(webNav, nullptr);
+
+  nsCOMPtr<nsISHistory> shistory;
 
-  //Get  SH from nsIWebNavigation
-  return webNav->GetSessionHistory(aReturn);
-  
+  // Get SH from nsIWebNavigation
+  webNav->GetSessionHistory(getter_AddRefs(shistory));
+
+  return shistory.forget();
 }
-
--- a/dom/base/nsHistory.h
+++ b/dom/base/nsHistory.h
@@ -1,51 +1,75 @@
 /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
 /* vim: set ts=2 sw=2 et tw=79: */
 /* 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 nsHistory_h___
 #define nsHistory_h___
 
+#include "mozilla/Attributes.h"
+#include "mozilla/ErrorResult.h"
+#include "mozilla/dom/BindingUtils.h"
+#include "nsCycleCollectionParticipant.h"
+#include "nsWrapperCache.h"
 #include "nsIDOMHistory.h"
-#include "nsISupports.h"
-#include "nscore.h"
-#include "nsIScriptContext.h"
+#include "nsString.h"
 #include "nsISHistory.h"
 #include "nsIWeakReference.h"
 #include "nsPIDOMWindow.h"
 
 class nsIDocShell;
 
 // Script "History" object
-class nsHistory : public nsIDOMHistory
+class nsHistory MOZ_FINAL : public nsIDOMHistory, // Empty, needed for extension
+                                                  // backwards compat
+                            public nsWrapperCache
 {
 public:
+  NS_DECL_CYCLE_COLLECTING_ISUPPORTS
+  NS_DECL_CYCLE_COLLECTION_SCRIPT_HOLDER_CLASS(nsHistory)
+
+public:
   nsHistory(nsPIDOMWindow* aInnerWindow);
   virtual ~nsHistory();
 
-  // nsISupports
-  NS_DECL_ISUPPORTS
+  nsPIDOMWindow* GetParentObject() const;
+  virtual JSObject* WrapObject(JSContext* aCx,
+                               JS::Handle<JSObject*> aScope) MOZ_OVERRIDE;
 
-  // nsIDOMHistory
-  NS_DECL_NSIDOMHISTORY
+  uint32_t GetLength(mozilla::ErrorResult& aRv) const;
+  JS::Value GetState(JSContext* aCx, mozilla::ErrorResult& aRv) const;
+  void Go(int32_t aDelta, mozilla::ErrorResult& aRv);
+  void Back(mozilla::ErrorResult& aRv);
+  void Forward(mozilla::ErrorResult& aRv);
+  void PushState(JSContext* aCx, JS::Handle<JS::Value> aData,
+                 const nsAString& aTitle, const nsAString& aUrl,
+                 mozilla::ErrorResult& aRv);
+  void ReplaceState(JSContext* aCx, JS::Handle<JS::Value> aData,
+                    const nsAString& aTitle, const nsAString& aUrl,
+                    mozilla::ErrorResult& aRv);
+  void GetCurrent(nsString& aRetval, mozilla::ErrorResult& aRv) const;
+  void GetPrevious(nsString& aRetval, mozilla::ErrorResult& aRv) const;
+  void GetNext(nsString& aRetval, mozilla::ErrorResult& aRv) const;
+  void Item(uint32_t aIndex, nsString& aRetval, mozilla::ErrorResult& aRv);
+  void IndexedGetter(uint32_t aIndex, bool &aFound, nsString& aRetval,
+                     mozilla::ErrorResult& aRv);
+  uint32_t Length();
 
-  nsIDocShell *GetDocShell() {
+protected:
+  nsIDocShell *GetDocShell() const {
     nsCOMPtr<nsPIDOMWindow> win(do_QueryReferent(mInnerWindow));
     if (!win)
       return nullptr;
     return win->GetDocShell();
   }
 
-  void GetWindow(nsPIDOMWindow **aWindow) {
-    nsCOMPtr<nsPIDOMWindow> win(do_QueryReferent(mInnerWindow));
-    *aWindow = win.forget().get();
-  }
+  void PushOrReplaceState(JSContext* aCx, JS::Value aData,
+                          const nsAString& aTitle, const nsAString& aUrl,
+                          mozilla::ErrorResult& aRv, bool aReplace);
 
-protected:
-  nsresult GetSessionHistoryFromDocShell(nsIDocShell * aDocShell,
-                                         nsISHistory ** aReturn);
+  already_AddRefed<nsISHistory> GetSessionHistory() const;
 
   nsCOMPtr<nsIWeakReference> mInnerWindow;
 };
 
 #endif /* nsHistory_h___ */
--- a/dom/base/nsIDOMClassInfo.h
+++ b/dom/base/nsIDOMClassInfo.h
@@ -29,17 +29,17 @@
    nsIXPCScriptable::WANT_PRECREATE)
 
 #define DOM_DEFAULT_SCRIPTABLE_FLAGS                                       \
   (DEFAULT_SCRIPTABLE_FLAGS |                                              \
    nsIXPCScriptable::DONT_ENUM_QUERY_INTERFACE |                           \
    nsIXPCScriptable::CLASSINFO_INTERFACES_ONLY)
 
 
-#ifdef _IMPL_NS_LAYOUT
+#ifdef MOZILLA_INTERNAL_API
 
 // See nsDOMClassInfoID.h
 
 #else
 
 #define NS_DOM_INTERFACE_MAP_ENTRY_CLASSINFO(_class)                       \
   if (aIID.Equals(NS_GET_IID(nsIClassInfo)) ||                             \
       aIID.Equals(NS_GET_IID(nsXPCClassInfo))) {                           \
@@ -52,17 +52,17 @@
       *aInstancePtr = nullptr;                                              \
       return rv;                                                           \
     }                                                                      \
                                                                            \
     foundInterface =                                                       \
       sof->GetClassInfoInstance(eDOMClassInfo_##_class##_id);              \
   } else
 
-#endif /* _IMPL_NS_LAYOUT */
+#endif /* MOZILLA_INTERNAL_API */
 
 // Looks up the nsIClassInfo for a class name registered with the 
 // nsScriptNamespaceManager. Remember to release NS_CLASSINFO_NAME(_class)
 // (eg. when your module unloads).
 #define NS_INTERFACE_MAP_ENTRY_EXTERNAL_DOM_CLASSINFO(_class)              \
   if (aIID.Equals(NS_GET_IID(nsIClassInfo)) ||                             \
       aIID.Equals(NS_GET_IID(nsXPCClassInfo))) {                           \
     extern nsISupports *NS_CLASSINFO_NAME(_class);                         \
--- a/dom/base/nsJSEnvironment.cpp
+++ b/dom/base/nsJSEnvironment.cpp
@@ -38,31 +38,30 @@
 #include "nsIContent.h"
 #include "nsCycleCollector.h"
 #include "nsNetUtil.h"
 #include "nsXPCOMCIDInternal.h"
 #include "nsIXULRuntime.h"
 
 #include "xpcpublic.h"
 
-#include "jsdbgapi.h"           // for JS_ClearWatchPointsForObject
+#include "jsdbgapi.h"
 #include "jswrapper.h"
 #include "nsIArray.h"
 #include "nsIObjectInputStream.h"
 #include "nsIObjectOutputStream.h"
 #include "prmem.h"
 #include "WrapperFactory.h"
 #include "nsGlobalWindow.h"
 #include "nsScriptNameSpaceManager.h"
 #include "StructuredCloneTags.h"
 #include "mozilla/dom/ImageData.h"
 #include "mozilla/dom/ImageDataBinding.h"
 
 #include "nsJSPrincipals.h"
-#include "jsdbgapi.h"
 
 #ifdef XP_MACOSX
 // AssertMacros.h defines 'check' and conflicts with AccessCheck.h
 #undef check
 #endif
 #include "AccessCheck.h"
 
 #ifdef MOZ_JSDEBUGGER
--- a/dom/base/nsPIDOMWindow.h
+++ b/dom/base/nsPIDOMWindow.h
@@ -722,17 +722,17 @@ protected:
   // This is only used by the inner window. Set to true once we've sent
   // the (chrome|content)-document-global-created notification.
   bool mHasNotifiedGlobalCreated;
 };
 
 
 NS_DEFINE_STATIC_IID_ACCESSOR(nsPIDOMWindow, NS_PIDOMWINDOW_IID)
 
-#ifdef _IMPL_NS_LAYOUT
+#ifdef MOZILLA_INTERNAL_API
 PopupControlState
 PushPopupControlState(PopupControlState aState, bool aForce);
 
 void
 PopPopupControlState(PopupControlState aState);
 
 #define NS_AUTO_POPUP_STATE_PUSHER nsAutoPopupStatePusherInternal
 #else
@@ -743,17 +743,17 @@ PopPopupControlState(PopupControlState a
 // state. Note that this class looks different from within code that's
 // part of the layout library than it does in code outside the layout
 // library.  We give the two object layouts different names so the symbols
 // don't conflict, but code should always use the name
 // |nsAutoPopupStatePusher|.
 class NS_AUTO_POPUP_STATE_PUSHER
 {
 public:
-#ifdef _IMPL_NS_LAYOUT
+#ifdef MOZILLA_INTERNAL_API
   NS_AUTO_POPUP_STATE_PUSHER(PopupControlState aState, bool aForce = false)
     : mOldState(::PushPopupControlState(aState, aForce))
   {
   }
 
   ~NS_AUTO_POPUP_STATE_PUSHER()
   {
     PopPopupControlState(mOldState);
@@ -771,17 +771,17 @@ public:
   {
     if (mWindow) {
       mWindow->PopPopupControlState(mOldState);
     }
   }
 #endif
 
 protected:
-#ifndef _IMPL_NS_LAYOUT
+#ifndef MOZILLA_INTERNAL_API
   nsCOMPtr<nsPIDOMWindow> mWindow;
 #endif
   PopupControlState mOldState;
 
 private:
   // Hide so that this class can only be stack-allocated
   static void* operator new(size_t /*size*/) CPP_THROW_NEW { return nullptr; }
   static void operator delete(void* /*memory*/) {}
--- a/dom/base/nsStructuredCloneContainer.cpp
+++ b/dom/base/nsStructuredCloneContainer.cpp
@@ -32,35 +32,30 @@ nsStructuredCloneContainer::nsStructured
 }
 
 nsStructuredCloneContainer::~nsStructuredCloneContainer()
 {
   free(mData);
 }
 
 nsresult
-nsStructuredCloneContainer::InitFromVariant(nsIVariant *aData, JSContext *aCx)
+nsStructuredCloneContainer::InitFromJSVal(const JS::Value & aData,
+                                          JSContext* aCx)
 {
   NS_ENSURE_STATE(!mData);
-  NS_ENSURE_ARG_POINTER(aData);
   NS_ENSURE_ARG_POINTER(aCx);
 
-  // First, try to extract a JS::Value from the variant |aData|.  This works only
-  // if the variant implements GetAsJSVal.
-  JS::Rooted<JS::Value> jsData(aCx);
-  nsresult rv = aData->GetAsJSVal(jsData.address());
-  NS_ENSURE_SUCCESS(rv, NS_ERROR_UNEXPECTED);
-
   // Make sure that we serialize in the right context.
   MOZ_ASSERT(aCx == nsContentUtils::GetCurrentJSContext());
+  JS::Rooted<JS::Value> jsData(aCx, aData);
   JS_WrapValue(aCx, jsData.address());
 
   uint64_t* jsBytes = nullptr;
   bool success = JS_WriteStructuredClone(aCx, jsData, &jsBytes, &mSize,
-                                           nullptr, nullptr, JSVAL_VOID);
+                                         nullptr, nullptr, JSVAL_VOID);
   NS_ENSURE_STATE(success);
   NS_ENSURE_STATE(jsBytes);
 
   // Copy jsBytes into our own buffer.
   mData = (uint64_t*) malloc(mSize);
   if (!mData) {
     mSize = 0;
     mVersion = 0;
@@ -109,31 +104,33 @@ nsStructuredCloneContainer::DeserializeT
   NS_ENSURE_STATE(mData);
   NS_ENSURE_ARG_POINTER(aData);
   *aData = nullptr;
 
   // Deserialize to a JS::Value.
   JS::Rooted<JS::Value> jsStateObj(aCx);
   bool hasTransferable = false;
   bool success = JS_ReadStructuredClone(aCx, mData, mSize, mVersion,
-                                        jsStateObj.address(), nullptr, nullptr) &&
+                                        jsStateObj.address(), nullptr,
+                                        nullptr) &&
                  JS_StructuredCloneHasTransferables(mData, mSize,
                                                     &hasTransferable);
   // We want to be sure that mData doesn't contain transferable objects
   MOZ_ASSERT(!hasTransferable);
   NS_ENSURE_STATE(success && !hasTransferable);
 
   // Now wrap the JS::Value as an nsIVariant.
   nsCOMPtr<nsIVariant> varStateObj;
   nsCOMPtr<nsIXPConnect> xpconnect = do_GetService(nsIXPConnect::GetCID());
   NS_ENSURE_STATE(xpconnect);
-  xpconnect->JSValToVariant(aCx, jsStateObj.address(), getter_AddRefs(varStateObj));
+  xpconnect->JSValToVariant(aCx, jsStateObj.address(),
+                            getter_AddRefs(varStateObj));
   NS_ENSURE_STATE(varStateObj);
 
-  NS_IF_ADDREF(*aData = varStateObj);
+  NS_ADDREF(*aData = varStateObj);
   return NS_OK;
 }
 
 nsresult
 nsStructuredCloneContainer::GetDataAsBase64(nsAString &aOut)
 {
   NS_ENSURE_STATE(mData);
   aOut.Truncate();
--- a/dom/base/test/Makefile.in
+++ b/dom/base/test/Makefile.in
@@ -31,12 +31,13 @@ MOCHITEST_FILES = \
   test_Image_constructor.html \
   test_setting_opener.html \
   test_error.html \
   $(NULL)
 
 MOCHITEST_CHROME_FILES = \
    test_bug715041.xul \
    test_bug715041_removal.xul \
+   test_domrequesthelper.xul \
    $(NULL)
 
 include $(topsrcdir)/config/rules.mk
 
new file mode 100644
--- /dev/null
+++ b/dom/base/test/test_domrequesthelper.xul
@@ -0,0 +1,124 @@
+<?xml version="1.0"?>
+<!--
+  Any copyright is dedicated to the Public Domain.
+  http://creativecommons.org/publicdomain/zero/1.0/
+-->
+<?xml-stylesheet href="chrome://global/skin" type="text/css"?>
+<?xml-stylesheet href="chrome://mochikit/content/tests/SimpleTest/test.css" type="text/css"?>
+
+<window title="DOMRequestHelper Test"
+        xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"
+        onload="start();">
+  <title>DOMRequestHelper Test</title>
+
+  <script type="application/javascript"
+          src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"/>
+
+  <script type="application/javascript">
+  <![CDATA[
+    Components.utils.import("resource://gre/modules/DOMRequestHelper.jsm");
+    function DummyHelperSubclass() {
+      this.initDOMRequestHelper(window, []);
+    }
+
+    DummyHelperSubclass.prototype = {
+      __proto__: DOMRequestIpcHelper.prototype
+    };
+
+    var dummy = new DummyHelperSubclass();
+
+    function createPromise() {
+      ok(Promise, "Promise object should exist");
+
+      var promise = dummy.createPromise(function(r) {
+        ok(r, "received PromiseResolver");
+        r.resolve(true);
+      });
+      ok(promise instanceof Promise, "returned a Promise");
+      promise.then(runTest);
+    }
+
+    function getResolver() {
+      var id;
+      var resolver;
+      var promise = dummy.createPromise(function(r) {
+        id = dummy.getPromiseResolverId(r);
+        resolver = r;
+        ok(typeof id === "string", "id should be string");
+        r.resolve(true);
+      }).then(function(unused) {
+        var r = dummy.getPromiseResolver(id);
+        ok(resolver === r, "get should succeed");
+        runTest();
+      });
+    }
+
+    function removeResolver() {
+      var id;
+      var promise = dummy.createPromise(function(r) {
+        id = dummy.getPromiseResolverId(r);
+        ok(typeof id === "string", "id should be string");
+
+        var resolver = dummy.getPromiseResolver(id);
+        ok(resolver === r, "resolver get should succeed");
+
+        r.resolve(true);
+      }).then(function(unused) {
+        dummy.removePromiseResolver(id);
+        var resolver = dummy.getPromiseResolver(id);
+        ok(resolver === undefined, "removeResolver: get should fail");
+        runTest();
+      });
+    }
+
+    function takeResolver() {
+      var id;
+      var resolver;
+      var promise = dummy.createPromise(function(r) {
+        id = dummy.getPromiseResolverId(r);
+        resolver = r;
+        ok(typeof id === "string", "id should be string");
+
+        var gotR = dummy.getPromiseResolver(id);
+        ok(gotR === r, "resolver get should succeed");
+
+        r.resolve(true);
+      }).then(function(unused) {
+        var r = dummy.takePromiseResolver(id);
+        ok(resolver === r, "take should succeed");
+
+        r = dummy.getPromiseResolver(id);
+        ok(r === undefined, "takeResolver: get should fail");
+        runTest();
+      });
+    }
+
+    var tests = [ createPromise,
+                  getResolver,
+                  removeResolver,
+                  takeResolver,
+                ];
+
+    function runTest() {
+      if (!tests.length) {
+        SimpleTest.finish();
+        return;
+      }
+
+      var test = tests.shift();
+      test();
+    }
+
+    function start() {
+      SimpleTest.waitForExplicitFinish();
+      runTest();
+    }
+  ]]>
+  </script>
+
+  <body xmlns="http://www.w3.org/1999/xhtml">
+    <p id="display"></p>
+    <div id="content" style="display: none"></div>
+    <pre id="test"></pre>
+  </body>
+</window>
--- a/dom/bindings/BindingDeclarations.h
+++ b/dom/bindings/BindingDeclarations.h
@@ -575,76 +575,16 @@ protected:
 template<typename T>
 class Sequence : public FallibleTArray<T>
 {
 public:
   Sequence() : FallibleTArray<T>()
   {}
 };
 
-class RootedJSValue
-{
-public:
-  RootedJSValue()
-    : mCx(nullptr)
-  {}
-
-  ~RootedJSValue()
-  {
-    if (mCx) {
-      JS_RemoveValueRoot(mCx, &mValue);
-    }
-  }
-
-  bool SetValue(JSContext* aCx, JS::Value aValue)
-  {
-    // We don't go ahead and root if v is null, because we want to allow
-    // null-initialization even when there is no cx.
-    MOZ_ASSERT_IF(!aValue.isNull(), aCx);
-
-    // Be careful to not clobber mCx if it's already set, just in case we're
-    // being null-initialized (with a null cx for some reason) after we have
-    // already been initialized properly with a non-null value.
-    if (!aValue.isNull() && !mCx) {
-      if (!JS_AddNamedValueRoot(aCx, &mValue, "RootedJSValue::mValue")) {
-        return false;
-      }
-      mCx = aCx;
-    }
-
-    mValue = aValue;
-    return true;
-  }
-
-  // Note: This operator can be const because we return by value, not
-  // by reference.
-  operator JS::Value() const
-  {
-    return mValue;
-  }
-
-  JS::Value* operator&()
-  {
-    return &mValue;
-  }
-
-  const JS::Value* operator&() const
-  {
-    return &mValue;
-  }
-
-private:
-  // Don't allow copy-construction of these objects, because it'll do the wrong
-  // thing with our flag mCx.
-  RootedJSValue(const RootedJSValue&) MOZ_DELETE;
-
-  JS::Value mValue;
-  JSContext* mCx;
-};
-
 inline nsWrapperCache*
 GetWrapperCache(nsWrapperCache* cache)
 {
   return cache;
 }
 
 inline nsWrapperCache*
 GetWrapperCache(nsGlobalWindow* not_allowed);
--- a/dom/bindings/BindingUtils.cpp
+++ b/dom/bindings/BindingUtils.cpp
@@ -1331,30 +1331,56 @@ GetPropertyOnPrototype(JSContext* cx, JS
   }
 
   *vp = value;
   return true;
 }
 
 bool
 HasPropertyOnPrototype(JSContext* cx, JS::Handle<JSObject*> proxy,
-                       DOMProxyHandler* handler,
                        JS::Handle<jsid> id)
 {
   JS::Rooted<JSObject*> obj(cx, proxy);
   Maybe<JSAutoCompartment> ac;
   if (xpc::WrapperFactory::IsXrayWrapper(obj)) {
     obj = js::UncheckedUnwrap(obj);
     ac.construct(cx, obj);
   }
-  MOZ_ASSERT(js::IsProxy(obj) && js::GetProxyHandler(obj) == handler);
 
   bool found;
-  // We ignore an error from GetPropertyOnPrototype.
-  return !GetPropertyOnPrototype(cx, obj, id, &found, NULL) || found;
+  // We ignore an error from GetPropertyOnPrototype.  We pass nullptr
+  // for vp so that GetPropertyOnPrototype won't actually do a get.
+  return !GetPropertyOnPrototype(cx, obj, id, &found, nullptr) || found;
+}
+
+bool
+AppendNamedPropertyIds(JSContext* cx, JS::Handle<JSObject*> proxy,
+                       nsTArray<nsString>& names,
+                       bool shadowPrototypeProperties,
+                       JS::AutoIdVector& props)
+{
+  for (uint32_t i = 0; i < names.Length(); ++i) {
+    JS::Rooted<JS::Value> v(cx);
+    if (!xpc::NonVoidStringToJsval(cx, names[i], v.address())) {
+      return false;
+    }
+
+    JS::Rooted<jsid> id(cx);
+    if (!JS_ValueToId(cx, v, id.address())) {
+      return false;
+    }
+
+    if (shadowPrototypeProperties || !HasPropertyOnPrototype(cx, proxy, id)) {
+      if (!props.append(id)) {
+        return false;
+      }
+    }
+  }
+
+  return true;
 }
 
 JSObject*
 GetXrayExpandoChain(JSObject* obj)
 {
   js::Class* clasp = js::GetObjectClass(obj);
   JS::Value v;
   if (IsDOMClass(clasp) || IsDOMIfaceAndProtoClass(clasp)) {
--- a/dom/bindings/BindingUtils.h
+++ b/dom/bindings/BindingUtils.h
@@ -1412,26 +1412,37 @@ WantsQueryInterface<T, true>
   {
     return IsChromeOrXBL(aCx, aGlobal);
   }
 };
 
 bool
 ThrowingConstructor(JSContext* cx, unsigned argc, JS::Value* vp);
 
+// vp is allowed to be null; in that case no get will be attempted,
+// and *found will simply indicate whether the property exists.
 bool
 GetPropertyOnPrototype(JSContext* cx, JS::Handle<JSObject*> proxy,
                        JS::Handle<jsid> id, bool* found,
                        JS::Value* vp);
 
 bool
 HasPropertyOnPrototype(JSContext* cx, JS::Handle<JSObject*> proxy,
-                       DOMProxyHandler* handler,
                        JS::Handle<jsid> id);
 
+
+// Append the property names in "names" to "props". If
+// shadowPrototypeProperties is false then skip properties that are also
+// present on the proto chain of proxy.  If shadowPrototypeProperties is true,
+// then the "proxy" argument is ignored.
+bool
+AppendNamedPropertyIds(JSContext* cx, JS::Handle<JSObject*> proxy,
+                       nsTArray<nsString>& names,
+                       bool shadowPrototypeProperties, JS::AutoIdVector& props);
+
 template<class T>
 class OwningNonNull
 {
 public:
   OwningNonNull()
 #ifdef DEBUG
     : inited(false)
 #endif
--- a/dom/bindings/Bindings.conf
+++ b/dom/bindings/Bindings.conf
@@ -426,16 +426,21 @@ DOMInterfaces = {
 'GainNode': {
     'resultNotAddRefed': [ 'gain' ],
 },
 
 'Geolocation': {
     'headerFile': 'nsGeolocation.h'
 },
 
+'History': {
+    'headerFile': 'nsHistory.h',
+    'nativeType': 'nsHistory'
+},
+
 'HTMLAppletElement': {
     'nativeType': 'mozilla::dom::HTMLSharedObjectElement'
 },
 
 'HTMLBaseElement': {
     'nativeType': 'mozilla::dom::HTMLSharedElement'
 },
 
--- a/dom/bindings/Codegen.py
+++ b/dom/bindings/Codegen.py
@@ -765,17 +765,19 @@ def UnionTypes(descriptors, dictionaries
         name = str(t)
         if not name in unionStructs:
             providers = getRelevantProviders(descriptor, dictionary,
                                              config)
             # FIXME: Unions are broken in workers.  See bug 809899.
             unionStructs[name] = CGUnionStruct(t, providers[0])
             # Unions cannot contain JSObject*.
             if not any(member.isObject() or member.isSpiderMonkeyInterface() for member in t.flatMemberTypes):
-                unionReturnValues[name] = CGUnionReturnValueStruct(t, providers[0])
+                unionReturnValues[name] = CGUnionStruct(t,
+                                                        providers[0],
+                                                        isReturnValue=True)
 
             for f in t.flatMemberTypes:
                 f = f.unroll()
                 if f.isInterface():
                     if f.isSpiderMonkeyInterface():
                         headers.add("jsfriendapi.h")
                         headers.add("mozilla/dom/TypedArray.h")
                     else:
@@ -1583,17 +1585,17 @@ class ConstDefiner(PropertyDefiner):
 
         def specData(const):
             return (const.identifier.name,
                     convertConstIDLValueToJSVal(const.value))
 
         return self.generatePrefableArray(
             array, name,
             '  { "%s", %s }',
-            '  { 0, JSVAL_VOID }',
+            '  { 0, JS::UndefinedValue() }',
             'ConstantSpec',
             PropertyDefiner.getControllingCondition, specData, doIdArrays)
 
 class PropertyArrays():
     def __init__(self, descriptor):
         self.staticMethods = MethodDefiner(descriptor, "StaticMethods",
                                            static=True)
         self.staticAttrs = AttrDefiner(descriptor, "StaticAttributes",
@@ -6023,332 +6025,136 @@ return true;"""
                 "holderType": conversionInfo.holderType.define() if conversionInfo.holderType else None
                 }
 
 def mapTemplate(template, templateVarArray):
     return map(lambda v: string.Template(template).substitute(v),
                templateVarArray)
 
 class CGUnionStruct(CGThing):
-    def __init__(self, type, descriptorProvider):
+    def __init__(self, type, descriptorProvider, isReturnValue=False):
         CGThing.__init__(self)
         self.type = type.unroll()
         self.descriptorProvider = descriptorProvider
-        self.templateVars = map(
-            lambda t: getUnionTypeTemplateVars(self.type, t, self.descriptorProvider),
-            self.type.flatMemberTypes)
-
+        self.isReturnValue = isReturnValue
+        self.struct = self.getStruct()
 
     def declare(self):
-        templateVars = self.templateVars
-
-        callDestructors = []
-        enumValues = []
-        methods = []
-        if self.type.hasNullableType:
-            callDestructors.append("      case eNull:\n"
-                                   "        break;")
-            enumValues.append("eNull")
-            methods.append("""  bool IsNull() const
-  {
-    return mType == eNull;
-  }""")
-
-        destructorTemplate = """  void Destroy${name}()
-  {
-    MOZ_ASSERT(Is${name}(), "Wrong type!");
-    mValue.m${name}.Destroy();
-    mType = eUninitialized;
-  }"""
-        destructors = mapTemplate(destructorTemplate, templateVars)
-        callDestructors.extend(mapTemplate("      case e${name}:\n"
-                                           "         Destroy${name}();\n"
-                                           "         break;", templateVars))
-        enumValues.extend(mapTemplate("e${name}", templateVars))
-        methodTemplate = """  bool Is${name}() const
-  {
-    return mType == e${name};
-  }
-  ${externalType} GetAs${name}() const
-  {
-    MOZ_ASSERT(Is${name}(), "Wrong type!");
-    return const_cast<${structType}&>(mValue.m${name}.Value());
-  }"""
-        methods.extend(mapTemplate(methodTemplate, templateVars))
-        # Now have to be careful: we do not want the SetAsObject() method!
-        setterTemplate = """  ${structType}& SetAs${name}()
-  {
-    mType = e${name};
-    return mValue.m${name}.SetValue();
-  }"""
-        methods.extend(mapTemplate(setterTemplate,
-                                   filter(lambda v: v["name"] != "Object",
-                                          templateVars)))
-        values = mapTemplate("UnionMember<${structType} > m${name};", templateVars)
-        return string.Template("""
-class ${structName} {
-public:
-  ${structName}() : mType(eUninitialized)
-  {
-  }
-  ~${structName}()
-  {
-    switch (mType) {
-${callDestructors}
-      case eUninitialized:
-        break;
-    }
-  }
-
-${methods}
-
-  bool ToJSVal(JSContext* cx, JS::Handle<JSObject*> scopeObj,
-               JS::MutableHandle<JS::Value> rval) const;
-
-private:
-  friend class ${structName}Argument;
-
-  // Disallow copy-construction and assignment
-  ${structName}(const ${structName}&) MOZ_DELETE;
-  void operator=(const ${structName}&) MOZ_DELETE;
-
-${destructors}
-
-  enum Type {
-    eUninitialized,
-    ${enumValues}
-  };
-  union Value {
-    ${values}
-  };
-
-  Type mType;
-  Value mValue;
-};
-
-""").substitute(
-    {
-       "structName": self.type.__str__(),
-       "callDestructors": "\n".join(callDestructors),
-       "destructors": "\n".join(destructors),
-       "methods": "\n\n".join(methods),
-       "enumValues": ",\n    ".join(enumValues),
-       "values": "\n    ".join(values)
-       })
+        return self.struct.declare()
 
     def define(self):
-        templateVars = self.templateVars
-        conversionsToJS = []
+        return self.struct.define()
+
+    def getStruct(self):
+
+        members = [ClassMember("mType", "Type", body="eUninitialized"),
+                   ClassMember("mValue", "Value")]
+        ctor = ClassConstructor([], bodyInHeader=True, visibility="public",
+                                explicit=True)
+
+        methods = []
+        enumValues = ["eUninitialized"]
+        toJSValCases = [CGCase("eUninitialized", CGGeneric("return false;"))]
+        destructorCases = [CGCase("eUninitialized", None)]
+        unionValues = []
         if self.type.hasNullableType:
-            conversionsToJS.append("    case eNull:\n"
-                                   "    {\n"
-                                   "      rval.setNull();\n"
-                                   "      return true;\n"
-                                   "    }")
-        conversionsToJS.extend(
-            map(self.getConversionToJS,
-                zip(templateVars, self.type.flatMemberTypes)))
-
-        return string.Template("""bool
-${structName}::ToJSVal(JSContext* cx, JS::Handle<JSObject*> scopeObj,
-                       JS::MutableHandle<JS::Value> rval) const
-{
-  switch (mType) {
-${doConversionsToJS}
-
-    case eUninitialized:
-    {
-      break;
-    }
-  }
-  return false;
-}
-""").substitute({
-                "structName": str(self.type),
-                "doConversionsToJS": "\n\n".join(conversionsToJS)
-                })
-
-    def getConversionToJS(self, arg):
-        (templateVars, type) = arg
+            enumValues.append("eNull")
+            methods.append(ClassMethod("IsNull", "bool", [], const=True, inline=True,
+                                       body="return mType == eNull;"))
+            methods.append(ClassMethod("SetNull", "void", [], inline=True,
+                                       body="mType = eNull;"))
+            destructorCases.append(CGCase("eNull", None))
+            toJSValCases.append(CGCase("eNull", CGGeneric("rval.setNull();\n"
+                                                          "return true;")))
+
+        for t in self.type.flatMemberTypes:
+            vars = getUnionTypeTemplateVars(self.type,
+                                            t, self.descriptorProvider,
+                                            isReturnValue=self.isReturnValue)
+            if vars["name"] != "Object":
+                body=string.Template("mType = e${name};\n"
+                                     "return mValue.m${name}.SetValue();").substitute(vars)
+                # bodyInHeader must be false for return values because they own
+                # their union members and we don't want include headers in
+                # UnionTypes.h just to call Addref/Release
+                methods.append(ClassMethod("SetAs" + vars["name"],
+                                           vars["structType"] + "&",
+                                           [],
+                                           bodyInHeader=not self.isReturnValue,
+                                           body=body))
+            body = string.Template('MOZ_ASSERT(Is${name}(), "Wrong type!");\n'
+                                   'mValue.m${name}.Destroy();\n'
+                                   'mType = eUninitialized;').substitute(vars)
+            methods.append(ClassMethod("Destroy" + vars["name"],
+                                       "void",
+                                       [],
+                                       visibility="private",
+                                       bodyInHeader=not self.isReturnValue,
+                                       body=body))
+            body = string.Template("return mType == e${name};").substitute(vars)
+            methods.append(ClassMethod("Is" + vars["name"],
+                                       "bool",
+                                       [],
+                                       const=True,
+                                       bodyInHeader=True,
+                                       body=body))
+            if not self.isReturnValue:
+                body = string.Template('MOZ_ASSERT(Is${name}(), "Wrong type!");\n'
+                                       'return const_cast<${structType}&>(mValue.m${name}.Value());').substitute(vars)
+                methods.append(ClassMethod("GetAs" + vars["name"],
+                                           vars["externalType"],
+                                           [],
+                                           const=True,
+                                           bodyInHeader=True,
+                                           body=body))
+            unionValues.append(string.Template("UnionMember<${structType} > "
+                                               "m${name}").substitute(vars))
+            enumValues.append("e" + vars["name"])
+
+            toJSValCases.append(CGCase("e" + vars["name"],
+                                       self.getConversionToJS(vars, t)))
+            destructorCases.append(CGCase("e" + vars["name"],
+                                          CGGeneric("Destroy%s();"
+                                                     % vars["name"])))
+
+        dtor = CGSwitch("mType", destructorCases).define()
+
+        methods.append(ClassMethod("ToJSVal", "bool", [
+                                   Argument("JSContext*", "cx"),
+                                   Argument("JS::Handle<JSObject*>", "scopeObj"),
+                                   Argument("JS::MutableHandle<JS::Value>", "rval")
+        ], body=CGSwitch("mType", toJSValCases,
+                         default=CGGeneric("return false;")).define(), const=True))
+
+        friend="  friend class %sArgument;\n" % str(self.type) if not self.isReturnValue else ""
+        return CGClass(str(self.type) + ("ReturnValue" if self.isReturnValue else ""),
+                       members=members,
+                       constructors=[ctor],
+                       methods=methods,
+                       disallowCopyConstruction=True,
+                       extradeclarations=friend,
+                       destructor=ClassDestructor(visibility="public",
+                                                  body=dtor,
+                                                  bodyInHeader=not self.isReturnValue),
+                       enums=[ClassEnum("Type", enumValues, visibility="private")],
+                       unions=[ClassUnion("Value", unionValues, visibility="private")])
+
+    def getConversionToJS(self, templateVars, type):
         assert not type.nullable() # flatMemberTypes never has nullable types
         val = "mValue.m%(name)s.Value()" % templateVars
         wrapCode = wrapForType(
             type, self.descriptorProvider,
             {
                 "jsvalRef": "rval",
                 "jsvalHandle": "rval",
                 "obj": "scopeObj",
                 "result": val,
                 "typedArraysAreStructs": True
                 })
-        return CGIndenter(CGList([CGGeneric("case e%(name)s:" % templateVars),
-                                  CGWrapper(CGIndenter(CGGeneric(wrapCode)),
-                                            pre="{\n",
-                                            post="\n}")],
-                                 "\n"),
-                          4).define()
-
-class CGUnionReturnValueStruct(CGThing):
-    def __init__(self, type, descriptorProvider):
-        CGThing.__init__(self)
-        self.type = type.unroll()
-        self.descriptorProvider = descriptorProvider
-        self.templateVars = map(
-            lambda t: getUnionTypeTemplateVars(self.type, t,
-                                               self.descriptorProvider,
-                                               isReturnValue=True),
-            self.type.flatMemberTypes)
-
-    def declare(self):
-        templateVars = self.templateVars
-
-        enumValues = []
-        methods = []
-        if self.type.hasNullableType:
-            enumValues.append("eNull")
-            methods.append("""  bool IsNull() const
-  {
-    return mType == eNull;
-  }
-
-  bool SetNull()
-  {
-    mType = eNull;
-    return true;
-  }""")
-
-        enumValues.extend(mapTemplate("e${name}", templateVars))
-        methodTemplate = "  ${structType}& SetAs${name}();"
-        methods.extend(mapTemplate(methodTemplate, templateVars))
-        values = mapTemplate("UnionMember<${structType} > m${name};", templateVars)
-        return string.Template("""
-class ${structName}ReturnValue {
-public:
-  ${structName}ReturnValue() : mType(eUninitialized)
-  {
-  }
-  ~${structName}ReturnValue();
-
-${methods}
-
-  bool ToJSVal(JSContext* cx, JS::Handle<JSObject*> scopeObj,
-               JS::MutableHandle<JS::Value> rval) const;
-
-private:
-  // Disallow copy-construction and assignment
-  ${structName}ReturnValue(const ${structName}ReturnValue&) MOZ_DELETE;
-  void operator=(const ${structName}ReturnValue&) MOZ_DELETE;
-
-  enum Type {
-    eUninitialized,
-    ${enumValues}
-  };
-  union Value {
-    ${values}
-  };
-
-  Type mType;
-  Value mValue;
-};
-
-""").substitute(
-    {
-       "structName": self.type.__str__(),
-       "methods": "\n\n".join(methods),
-       "enumValues": ",\n    ".join(enumValues),
-       "values": "\n    ".join(values)
-       })
-
-    def define(self):
-        templateVars = self.templateVars
-        conversionsToJS = []
-        if self.type.hasNullableType:
-            conversionsToJS.append("    case eNull:\n"
-                                   "    {\n"
-                                   "      rval.setNull();\n"
-                                   "      return true;\n"
-                                   "    }")
-        conversionsToJS.extend(
-            map(self.getConversionToJS,
-                zip(templateVars, self.type.flatMemberTypes)))
-
-        toJSVal = string.Template("""
-
-bool
-${structName}ReturnValue::ToJSVal(JSContext* cx, JS::Handle<JSObject*> scopeObj, JS::MutableHandle<JS::Value> rval) const
-{
-  switch (mType) {
-${doConversionsToJS}
-
-    case eUninitialized:
-    {
-      break;
-    }
-  }
-  return false;
-}
-""").substitute({
-                "structName": str(self.type),
-                "doConversionsToJS": "\n\n".join(conversionsToJS)
-                })
-        templateVars = self.templateVars
-
-        methods = []
-        methodTemplate = """${structType}&
-%sReturnValue::SetAs${name}()
-{
-  mType = e${name};
-  return mValue.m${name}.SetValue();
-}""" % str(self.type)
-        methods.extend(mapTemplate(methodTemplate, templateVars))
-
-        callDestructors = []
-        if self.type.hasNullableType:
-            callDestructors.append("      case eNull:\n"
-                                   "        break;")
-        callDestructors.extend(mapTemplate("    case e${name}:\n"
-                                           "       mValue.m${name}.Destroy();\n"
-                                           "       mType = eUninitialized;\n"
-                                           "       break;", templateVars))
-        destructor = string.Template("""
-${structName}ReturnValue::~${structName}ReturnValue()
-{
-  switch (mType) {
-${callDestructors}
-    case eUninitialized:
-      break;
-  }
-}
-
-""").substitute(
-    {
-       "structName": self.type.__str__(),
-       "callDestructors": "\n".join(callDestructors),
-       })
-
-        return destructor + "\n\n".join(methods) + toJSVal
-
-    def getConversionToJS(self, arg):
-        (templateVars, type) = arg
-        assert not type.nullable() # flatMemberTypes never has nullable types
-        val = "mValue.m%(name)s.Value()" % templateVars
-        wrapCode = wrapForType(
-            type, self.descriptorProvider,
-            {
-                "jsvalRef": "rval",
-                "jsvalHandle": "rval",
-                "obj": "scopeObj",
-                "result": val,
-                })
-        return CGIndenter(CGList([CGGeneric("case e%(name)s:" % templateVars),
-                                  CGWrapper(CGIndenter(CGGeneric(wrapCode)),
-                                            pre="{\n",
-                                            post="\n}")],
-                                 "\n"),
-                          4).define()
+        return CGGeneric(wrapCode)
 
 class CGUnionConversionStruct(CGThing):
     def __init__(self, type, descriptorProvider):
         CGThing.__init__(self)
         self.type = type.unroll()
         self.descriptorProvider = descriptorProvider
 
     def declare(self):
@@ -6745,48 +6551,61 @@ class ClassEnum(ClassItem):
     def __init__(self, name, entries, values=None, visibility="public"):
         self.entries = entries
         self.values = values
         ClassItem.__init__(self, name, visibility)
 
     def declare(self, cgClass):
         entries = []
         for i in range(0, len(self.entries)):
-            if i >= len(self.values):
+            if not self.values or i >= len(self.values):
                 entry = '%s' % self.entries[i]
             else:
                 entry = '%s = %s' % (self.entries[i], self.values[i])
             entries.append(entry)
         name = '' if not self.name else ' ' + self.name
         return 'enum%s\n{\n  %s\n};\n' % (name, ',\n  '.join(entries))
 
     def define(self, cgClass):
         # Only goes in the header
         return ''
 
+class ClassUnion(ClassItem):
+    def __init__(self, name, entries, visibility="public"):
+        self.entries = [entry + ";" for entry in entries]
+        ClassItem.__init__(self, name, visibility)
+
+    def declare(self, cgClass):
+        return 'union %s\n{\n  %s\n};\n' % (self.name, '\n  '.join(self.entries))
+
+    def define(self, cgClass):
+        # Only goes in the header
+        return ''
+
 class CGClass(CGThing):
     def __init__(self, name, bases=[], members=[], constructors=[],
                  destructor=None, methods=[],
-                 typedefs = [], enums=[], templateArgs=[],
+                 typedefs = [], enums=[], unions=[], templateArgs=[],
                  templateSpecialization=[], isStruct=False,
                  disallowCopyConstruction=False, indent='',
                  decorators='',
                  extradeclarations='',
                  extradefinitions=''):
         CGThing.__init__(self)
         self.name = name
         self.bases = bases
         self.members = members
         self.constructors = constructors
         # We store our single destructor in a list, since all of our
         # code wants lists of members.
         self.destructors = [destructor] if destructor else []
         self.methods = methods
         self.typedefs = typedefs
         self.enums = enums
+        self.unions = unions
         self.templateArgs = templateArgs
         self.templateSpecialization = templateSpecialization
         self.isStruct = isStruct
         self.disallowCopyConstruction = disallowCopyConstruction
         self.indent = indent
         self.defaultVisibility ='public' if isStruct else 'private'
         self.decorators = decorators
         self.extradeclarations = extradeclarations
@@ -6872,22 +6691,24 @@ class CGClass(CGThing):
             return (result, lastVisibility, itemCount)
 
         if self.disallowCopyConstruction:
             class DisallowedCopyConstructor(object):
                 def __init__(self):
                     self.visibility = "private"
                 def declare(self, cgClass):
                     name = cgClass.getNameString()
-                    return "%s(const %s&) MOZ_DELETE;\n" % (name, name)
+                    return ("%s(const %s&) MOZ_DELETE;\n"
+                            "void operator=(const %s) MOZ_DELETE;\n" % (name, name, name))
             disallowedCopyConstructors = [DisallowedCopyConstructor()]
         else:
             disallowedCopyConstructors = []
 
-        order = [(self.enums, ''), (self.typedefs, ''), (self.members, ''),
+        order = [(self.enums, ''), (self.unions, ''),
+                 (self.typedefs, ''), (self.members, ''),
                  (self.constructors + disallowedCopyConstructors, '\n'),
                  (self.destructors, '\n'), (self.methods, '\n')]
 
         lastVisibility = self.defaultVisibility
         itemCount = 0
         for (memberList, separator) in order:
             (memberString, lastVisibility, itemCount) = \
                 declareMembers(self, memberList, lastVisibility, itemCount,
@@ -6999,17 +6820,17 @@ class CGEnumerateOwnPropertiesViaGetOwnP
                 "ErrorResult rv;\n"
                 "self->GetOwnPropertyNames(cx, names, rv);\n"
                 "rv.WouldReportJSException();\n"
                 "if (rv.Failed()) {\n"
                 '  return ThrowMethodFailedWithDetails<true>(cx, rv, "%s", "enumerate");\n'
                 "}\n"
                 '// OK to pass null as "proxy" because it\'s ignored if\n'
                 "// shadowPrototypeProperties is true\n"
-                "return DOMProxyHandler::AppendNamedPropertyIds(cx, JS::NullPtr(), names, true, nullptr, props);"))
+                "return AppendNamedPropertyIds(cx, JS::NullPtr(), names, true, props);"))
 
 class CGPrototypeTraitsClass(CGClass):
     def __init__(self, descriptor, indent=''):
         templateArgs = [Argument('prototypes::ID', 'PrototypeID')]
         templateSpecialization = ['prototypes::id::' + descriptor.name]
         enums = [ClassEnum('', ['Depth'],
                            [descriptor.interface.inheritanceDepth()])]
         typedefs = [ClassTypedef('NativeType', descriptor.nativeType)]
@@ -7361,17 +7182,17 @@ MOZ_ASSERT_IF(desc.object(), desc.object
                                     "}\n\n")
             setOrIndexedGet += getUnforgeable
 
         if self.descriptor.supportsNamedProperties():
             readonly = toStringBool(self.descriptor.operations['NamedSetter'] is None)
             fillDescriptor = "FillPropertyDescriptor(desc, proxy, %s);\nreturn true;" % readonly
             templateValues = {'jsvalRef': 'desc.value()', 'jsvalHandle': 'desc.value()',
                               'obj': 'proxy', 'successCode': fillDescriptor}
-            condition = "!HasPropertyOnPrototype(cx, proxy, this, id)"
+            condition = "!HasPropertyOnPrototype(cx, proxy, id)"
             if self.descriptor.interface.getExtendedAttribute('OverrideBuiltins'):
                 condition = "(!isXray || %s)" % condition
             condition = "!(flags & JSRESOLVE_ASSIGNING) && " + condition
             if self.descriptor.supportsIndexedProperties():
                 condition = "!IsArrayIndex(index) && " + condition
             namedGet = ("\n" +
                         CGIfWrapper(CGProxyNamedGetter(self.descriptor, templateValues),
                                     condition).define() +
@@ -7532,17 +7353,17 @@ class CGDOMJSProxyHandler_delete(ClassMe
             # indexed properties, so we can just treat the id as a name
             # unconditionally here.
             delete += (CGGeneric(namedBody).define() + "\n"
                        "if (found) {\n"
                        "  return true;\n"
                        "}\n")
             if not self.descriptor.interface.getExtendedAttribute('OverrideBuiltins'):
                 delete = CGIfWrapper(CGGeneric(delete),
-                                     "!HasPropertyOnPrototype(cx, proxy, this, id)").define()
+                                     "!HasPropertyOnPrototype(cx, proxy, id)").define()
         delete += """
 
 return dom::DOMProxyHandler::delete_(cx, proxy, id, bp);"""
 
         return delete
 
 class CGDOMJSProxyHandler_getOwnPropertyNames(ClassMethod):
     def __init__(self, descriptor):
@@ -7569,17 +7390,17 @@ for (int32_t i = 0; i < int32_t(length);
         if self.descriptor.supportsNamedProperties():
             if self.descriptor.interface.getExtendedAttribute('OverrideBuiltins'):
                 shadow = "!isXray"
             else:
                 shadow = "false"
             addNames = """
 nsTArray<nsString> names;
 UnwrapProxy(proxy)->GetSupportedNames(names);
-if (!AppendNamedPropertyIds(cx, proxy, names, %s, this, props)) {
+if (!AppendNamedPropertyIds(cx, proxy, names, %s, props)) {
   return false;
 }
 """ % shadow
         else:
             addNames = ""
 
         if UseHolderForUnforgeable(self.descriptor):
             addUnforgeable = (
@@ -7633,17 +7454,17 @@ class CGDOMJSProxyHandler_hasOwn(ClassMe
 
         if self.descriptor.supportsNamedProperties():
             # If we support indexed properties we always return above for index
             # property names, so no need to check for those here.
             named = (CGProxyNamedPresenceChecker(self.descriptor).define() + "\n" +
                      "*bp = found;\n")
             if not self.descriptor.interface.getExtendedAttribute('OverrideBuiltins'):
                 named = CGIfWrapper(CGGeneric(named + "return true;\n"),
-                                    "!HasPropertyOnPrototype(cx, proxy, this, id)").define()
+                                    "!HasPropertyOnPrototype(cx, proxy, id)").define()
                 named += ("\n"
                           "*bp = false;")
         else:
             named = "*bp = false;"
 
         return """MOZ_ASSERT(!xpc::WrapperFactory::IsXrayWrapper(proxy),
           "Should not have a XrayWrapper here");
 
--- a/dom/bindings/DOMJSProxyHandler.cpp
+++ b/dom/bindings/DOMJSProxyHandler.cpp
@@ -155,18 +155,21 @@ bool
 DOMProxyHandler::preventExtensions(JSContext *cx, JS::Handle<JSObject*> proxy)
 {
   // Throw a TypeError, per WebIDL.
   JS_ReportErrorNumber(cx, js_GetErrorMessage, NULL, JSMSG_CANT_CHANGE_EXTENSIBILITY);
   return false;
 }
 
 bool
-DOMProxyHandler::getPropertyDescriptor(JSContext* cx, JS::Handle<JSObject*> proxy, JS::Handle<jsid> id,
-                                       MutableHandle<JSPropertyDescriptor> desc, unsigned flags)
+BaseDOMProxyHandler::getPropertyDescriptor(JSContext* cx,
+                                           JS::Handle<JSObject*> proxy,
+                                           JS::Handle<jsid> id,
+                                           MutableHandle<JSPropertyDescriptor> desc,
+                                           unsigned flags)
 {
   if (!getOwnPropertyDescriptor(cx, proxy, id, desc, flags)) {
     return false;
   }
   if (desc.object()) {
     return true;
   }
 
@@ -216,17 +219,18 @@ DOMProxyHandler::delete_(JSContext* cx, 
     return JS_DeletePropertyById2(cx, expando, id, bp);
   }
 
   *bp = true;
   return true;
 }
 
 bool
-DOMProxyHandler::enumerate(JSContext* cx, JS::Handle<JSObject*> proxy, AutoIdVector& props)
+BaseDOMProxyHandler::enumerate(JSContext* cx, JS::Handle<JSObject*> proxy,
+                               AutoIdVector& props)
 {
   JS::Rooted<JSObject*> proto(cx);
   if (!JS_GetPrototype(cx, proxy, &proto))  {
     return false;
   }
   return getOwnPropertyNames(cx, proxy, props) &&
          (!proto || js::GetPropertyNames(cx, proto, 0, &props));
 }
@@ -255,47 +259,16 @@ DOMProxyHandler::has(JSContext* cx, JS::
   bool protoHasProp;
   bool ok = JS_HasPropertyById(cx, proto, id, &protoHasProp);
   if (ok) {
     *bp = protoHasProp;
   }
   return ok;
 }
 
-/* static */
-bool
-DOMProxyHandler::AppendNamedPropertyIds(JSContext* cx,
-                                        JS::Handle<JSObject*> proxy,
-                                        nsTArray<nsString>& names,
-                                        bool shadowPrototypeProperties,
-                                        DOMProxyHandler* handler,
-                                        JS::AutoIdVector& props)
-{
-  for (uint32_t i = 0; i < names.Length(); ++i) {
-    JS::Rooted<JS::Value> v(cx);
-    if (!xpc::NonVoidStringToJsval(cx, names[i], v.address())) {
-      return false;
-    }
-
-    JS::Rooted<jsid> id(cx);
-    if (!JS_ValueToId(cx, v, id.address())) {
-      return false;
-    }
-
-    if (shadowPrototypeProperties ||
-        !HasPropertyOnPrototype(cx, proxy, handler, id)) {
-      if (!props.append(id)) {
-        return false;
-      }
-    }
-  }
-
-  return true;
-}
-
 int32_t
 IdToInt32(JSContext* cx, JS::Handle<jsid> id)
 {
   JS::Value idval;
   double array_index;
   int32_t i;
   if (!::JS_IdToValue(cx, id, &idval) ||
       !::JS_ValueToNumber(cx, idval, &array_index) ||
--- a/dom/bindings/DOMJSProxyHandler.h
+++ b/dom/bindings/DOMJSProxyHandler.h
@@ -22,39 +22,53 @@ namespace dom {
 
 enum {
   JSPROXYSLOT_EXPANDO = 0,
   JSPROXYSLOT_XRAY_EXPANDO
 };
 
 template<typename T> struct Prefable;
 
-class DOMProxyHandler : public js::BaseProxyHandler
+class BaseDOMProxyHandler : public js::BaseProxyHandler
+{
+public:
+  BaseDOMProxyHandler(void* aProxyFamily)
+    : js::BaseProxyHandler(aProxyFamily)
+  {}
+
+  // Implementations of traps that can be implemented in terms of
+  // fundamental traps.
+  bool enumerate(JSContext* cx, JS::Handle<JSObject*> proxy,
+                 JS::AutoIdVector& props) MOZ_OVERRIDE;
+  bool getPropertyDescriptor(JSContext* cx, JS::Handle<JSObject*> proxy,
+                             JS::Handle<jsid> id,
+                             JS::MutableHandle<JSPropertyDescriptor> desc,
+                             unsigned flags) MOZ_OVERRIDE;
+};
+
+class DOMProxyHandler : public BaseDOMProxyHandler
 {
 public:
   DOMProxyHandler(const DOMClass& aClass)
-    : js::BaseProxyHandler(ProxyFamily()),
+    : BaseDOMProxyHandler(ProxyFamily()),
       mClass(aClass)
   {
   }
 
   bool preventExtensions(JSContext *cx, JS::Handle<JSObject*> proxy) MOZ_OVERRIDE;
-  bool getPropertyDescriptor(JSContext* cx, JS::Handle<JSObject*> proxy, JS::Handle<jsid> id,
-                             JS::MutableHandle<JSPropertyDescriptor> desc, unsigned flags) MOZ_OVERRIDE;
   bool defineProperty(JSContext* cx, JS::Handle<JSObject*> proxy, JS::Handle<jsid> id,
                       JS::MutableHandle<JSPropertyDescriptor> desc) MOZ_OVERRIDE
   {
     bool unused;
     return defineProperty(cx, proxy, id, desc, &unused);
   }
   virtual bool defineProperty(JSContext* cx, JS::Handle<JSObject*> proxy, JS::Handle<jsid> id,
                               JS::MutableHandle<JSPropertyDescriptor> desc, bool* defined);
   bool delete_(JSContext* cx, JS::Handle<JSObject*> proxy,
                JS::Handle<jsid> id, bool* bp) MOZ_OVERRIDE;
-  bool enumerate(JSContext* cx, JS::Handle<JSObject*> proxy, JS::AutoIdVector& props) MOZ_OVERRIDE;
   bool has(JSContext* cx, JS::Handle<JSObject*> proxy, JS::Handle<jsid> id, bool* bp) MOZ_OVERRIDE;
   bool isExtensible(JSContext *cx, JS::Handle<JSObject*> proxy, bool *extensible) MOZ_OVERRIDE;
 
   static JSObject* GetExpandoObject(JSObject* obj)
   {
     MOZ_ASSERT(IsDOMProxy(obj), "expected a DOM proxy object");
     JS::Value v = js::GetProxyExtra(obj, JSPROXYSLOT_EXPANDO);
     if (v.isObject()) {
@@ -71,26 +85,16 @@ public:
     return v.isUndefined() ? nullptr : &v.toObject();
   }
   /* GetAndClearExpandoObject does not DROP or clear the preserving wrapper flag. */
   static JSObject* GetAndClearExpandoObject(JSObject* obj);
   static JSObject* EnsureExpandoObject(JSContext* cx,
                                        JS::Handle<JSObject*> obj);
 
   const DOMClass& mClass;
-
-  // Append the property names in "names" to "props". If
-  // shadowPrototypeProperties is false then skip properties that are also
-  // present on our proto chain.  If shadowPrototypeProperties is true,
-  // then the "proxy" and "handler" arguments are ignored.
-  static bool AppendNamedPropertyIds(JSContext* cx, JS::Handle<JSObject*> proxy,
-                                     nsTArray<nsString>& names,
-                                     bool shadowPrototypeProperties,
-                                     DOMProxyHandler* handler,
-                                     JS::AutoIdVector& props);
 };
 
 extern jsid s_length_id;
 
 int32_t IdToInt32(JSContext* cx, JS::Handle<jsid> id);
 
 // XXXbz this should really return uint32_t, with the maximum value
 // meaning "not an index"...
--- a/dom/bindings/Errors.msg
+++ b/dom/bindings/Errors.msg
@@ -40,8 +40,9 @@ MSG_DEF(MSG_GLOBAL_NOT_NATIVE, 0, "Globa
 MSG_DEF(MSG_ENCODING_NOT_SUPPORTED, 1, "The given encoding '{0}' is not supported.")
 MSG_DEF(MSG_DOM_ENCODING_NOT_UTF, 0, "The encoding must be utf-8, utf-16, or utf-16be.")
 MSG_DEF(MSG_NOT_FINITE, 1, "{0} is not a finite floating-point value.")
 MSG_DEF(MSG_INVALID_VERSION, 0, "0 (Zero) is not a valid database version.")
 MSG_DEF(MSG_INVALID_BYTESTRING, 2, "Cannot convert string to ByteString because the character"
         " at index {0} has value {1} which is greater than 255.")
 MSG_DEF(MSG_NOT_DATE, 1, "{0} is not a date.")
 MSG_DEF(MSG_INVALID_ADVANCE_COUNT, 0, "0 (Zero) is not a valid advance count.")
+MSG_DEF(MSG_DEFINEPROPERTY_ON_GSP, 0, "Not allowed to define a property on the named properties object.")
--- a/dom/devicestorage/Makefile.in
+++ b/dom/devicestorage/Makefile.in
@@ -20,11 +20,8 @@ LOCAL_INCLUDES = \
 		-I$(topsrcdir)/dom/ipc \
 		-I$(topsrcdir)/content/base/src \
 		-I$(topsrcdir)/content/events/src \
 		$(NULL)
 
 include $(topsrcdir)/config/config.mk
 include $(topsrcdir)/config/rules.mk
 include $(topsrcdir)/ipc/chromium/chromium-config.mk
-
-DEFINES += -D_IMPL_NS_LAYOUT
-
--- a/dom/dom-config.mk
+++ b/dom/dom-config.mk
@@ -56,9 +56,8 @@ ifdef MOZ_B2G_BT
 DOM_SRCDIRS += dom/bluetooth
 endif
 
 ifdef MOZ_WEBSPEECH
 DOM_SRCDIRS += content/media/webspeech
 endif
 
 LOCAL_INCLUDES += $(DOM_SRCDIRS:%=-I$(topsrcdir)/%)
-DEFINES += -D_IMPL_NS_LAYOUT
--- a/dom/imptests/failures/html/html/browsers/the-window-object/test_window-named-properties.html.json
+++ b/dom/imptests/failures/html/html/browsers/the-window-object/test_window-named-properties.html.json
@@ -1,5 +1,4 @@
 {
   "Static name on the prototype": true,
-  "constructor": true,
-  "Ghost name": true
+  "constructor": true
 }
--- a/dom/imptests/failures/html/html/browsers/the-window-object/test_window-prototype-chain.html.json
+++ b/dom/imptests/failures/html/html/browsers/the-window-object/test_window-prototype-chain.html.json
@@ -1,6 +1,5 @@
 {
   "Window.prototype": true,
-  "Global scope polluter": true,
   "EventTarget.prototype": true,
   "Object.prototype": true
 }
--- a/dom/indexedDB/Makefile.in
+++ b/dom/indexedDB/Makefile.in
@@ -19,16 +19,15 @@ LOCAL_INCLUDES = \
   -I$(topsrcdir)/content/events/src \
   -I$(topsrcdir)/db/sqlite3/src \
   -I$(topsrcdir)/dom/base \
   -I$(topsrcdir)/dom/src/storage \
   -I$(topsrcdir)/dom/quota \
   -I$(topsrcdir)/xpcom/build \
   $(NULL)
 
-DEFINES += -D_IMPL_NS_LAYOUT
 
 # Make sure to quickstub as much as possible here! See
 # js/xpconnect/src/dom_quickstubs.qsconf.
 include $(topsrcdir)/config/config.mk
 include $(topsrcdir)/config/rules.mk
 include $(topsrcdir)/ipc/chromium/chromium-config.mk
 
--- a/dom/indexedDB/ipc/Makefile.in
+++ b/dom/indexedDB/ipc/Makefile.in
@@ -14,18 +14,16 @@ include $(DEPTH)/config/autoconf.mk
 LIBRARY_NAME = dom_indexeddb_ipc_s
 LIBXUL_LIBRARY = 1
 
 LOCAL_INCLUDES += \
   -I$(topsrcdir)/dom/indexedDB \
   -I$(topsrcdir)/content/events/src \
   $(NULL)
 
-DEFINES += -D_IMPL_NS_LAYOUT
-
 MOCHITEST_FILES = test_ipc.html
 
 # bug: 866734 - move XPCSHEL_TESTS to moz.build
 
 # Need to enable these tests sometime soon.
 #DISABLED_XPCSHELL_TESTS = unit
 
 # We're copying tests from another directory so this check is wrong for us.
--- a/dom/interfaces/base/domstubs.idl
+++ b/dom/interfaces/base/domstubs.idl
@@ -32,26 +32,24 @@ interface nsIDOMDOMStringList;
 interface nsIDOMClientRect;
 interface nsIDOMClientRectList;
 
 // Needed for raises() in our IDL
 interface DOMException;
 
 // Style Sheets
 interface nsIDOMStyleSheetList;
-interface nsIDOMLinkStyle;
 interface nsIDOMStyleSheet;
 interface nsIDOMMediaList;
 
 // Base
 interface nsIDOMWindow;
 interface nsIDOMWindowCollection;
 interface nsIDOMNavigator;
 interface nsIDOMScreen;
-interface nsIDOMHistory;
 
 // Events
 interface nsIDOMEvent;
 interface nsIDOMEventTarget;
 interface nsIDOMEventListener;
 
 // HTML
 interface nsIDOMHTMLElement;
--- a/dom/interfaces/base/nsIDOMHistory.idl
+++ b/dom/interfaces/base/nsIDOMHistory.idl
@@ -4,34 +4,13 @@
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #include "domstubs.idl"
 
 %{ C++
 struct JSContext;
 %}
 
-interface nsIVariant;
-
-[scriptable, uuid(d5a3006b-dd6b-4ba3-81be-6559f8889e60)]
+[scriptable, uuid(55226663-fe68-48ba-addf-08e32eaab569)]
 interface nsIDOMHistory : nsISupports
 {
-  readonly attribute long             length;
-  readonly attribute DOMString        current;
-  readonly attribute DOMString        previous;
-  readonly attribute DOMString        next;
-
-  void                       back();
-  void                       forward();
-
-  void                       go([optional] in long aDelta);
-  DOMString                  item(in unsigned long index);
-  [implicit_jscontext]
-  void                       pushState(in nsIVariant aData,
-                                       in DOMString aTitle,
-                                       [optional] in DOMString aURL);
-  [implicit_jscontext]
-  void                       replaceState(in nsIVariant aData,
-                                          in DOMString aTitle,
-                                          [optional] in DOMString aURL);
-
-  readonly attribute nsIVariant state;
+  // Empty interface that exists only for extension backwards compat
 };
--- a/dom/interfaces/base/nsIDOMWindow.idl
+++ b/dom/interfaces/base/nsIDOMWindow.idl
@@ -20,17 +20,17 @@ interface nsIVariant;
  * The nsIDOMWindow interface is the primary interface for a DOM
  * window object. It represents a single window object that may
  * contain child windows if the document in the window contains a
  * HTML frameset document or if the document contains iframe elements.
  *
  * @see <http://www.whatwg.org/html/#window>
  */
 
-[scriptable, uuid(db8ea3c8-6997-460a-8715-0a1cbf20f15d)]
+[scriptable, uuid(e4610a67-ce3c-4dff-a5cf-b0e858452bf5)]
 interface nsIDOMWindow : nsISupports
 {
   // the current browsing context
   readonly attribute nsIDOMWindow                       window;
 
   /* [replaceable] self */
   readonly attribute nsIDOMWindow                       self;
 
@@ -44,17 +44,17 @@ interface nsIDOMWindow : nsISupports
    *
    * This attribute is "replaceable" in JavaScript
    */
            attribute DOMString                          name;
 
   /* The setter that takes a string argument needs to be special cased! */
   readonly attribute nsIDOMLocation                     location;
 
-  readonly attribute nsIDOMHistory                      history;
+  readonly attribute nsISupports                        history;
 
 
   /* [replaceable] locationbar */
   /* BarProp */
   readonly attribute nsISupports                        locationbar;
 
   /* [replaceable] menubar */
   /* BarProp */
--- a/dom/interfaces/base/nsIStructuredCloneContainer.idl
+++ b/dom/interfaces/base/nsIStructuredCloneContainer.idl
@@ -22,25 +22,25 @@ struct JSContext;
  * initFromVariant or initFromBase64.  It's an error to initialize an
  * nsIStructuredCloneContainer more than once.
  *
  * Once you've initialized the container, you can get a copy of the object it
  * stores by calling deserializeToVariant.  You can also get a base-64-encoded
  * string containing a copy of the container's serialized data, using
  * getDataAsBase64.
  */
-[scriptable, uuid(400a282d-7157-4ed0-85b4-8bdc2fa634cd)]
+[scriptable, uuid(c8852f01-4c05-47c3-acca-253a958f39f6)]
 interface nsIStructuredCloneContainer : nsISupports
 {
   /**
    * Initialize this structured clone container so it contains a clone of the
-   * given variant. aData must be backed by a jsval.
+   * given jsval.
    */
-  [implicit_jscontext]
-  void initFromVariant(in nsIVariant aData);
+  [noscript, implicit_jscontext]
+  void initFromJSVal(in jsval aData);
 
   /**
    * Initialize this structured clone container from a base-64-encoded byte
    * stream, stored in aData.  aFormatVersion should be the version of the
    * structured clone algorithm which was used to generate aData.
    */
   [implicit_jscontext]
   void initFromBase64(in AString aData,in unsigned long aFormatVersion);
--- a/dom/interfaces/stylesheets/moz.build
+++ b/dom/interfaces/stylesheets/moz.build
@@ -1,16 +1,15 @@
 # -*- Mode: python; c-basic-offset: 4; indent-tabs-mode: nil; tab-width: 40 -*-
 # vim: set filetype=python:
 # This Source Code Form is subject to the terms of the Mozilla Public
 # License, v. 2.0. If a copy of the MPL was not distributed with this
 # file, You can obtain one at http://mozilla.org/MPL/2.0/.
 
 XPIDL_SOURCES += [
-    'nsIDOMLinkStyle.idl',
     'nsIDOMMediaList.idl',
     'nsIDOMStyleSheet.idl',
     'nsIDOMStyleSheetList.idl',
 ]
 
 XPIDL_MODULE = 'dom_stylesheets'
 
 XPIDL_FLAGS += [
deleted file mode 100644
--- a/dom/interfaces/stylesheets/nsIDOMLinkStyle.idl
+++ /dev/null
@@ -1,12 +0,0 @@
-/* -*- Mode: IDL; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-#include "domstubs.idl"
-
-[scriptable, uuid(24d89a65-f598-481e-a297-23cc02599bbd)]
-interface nsIDOMLinkStyle : nsISupports
-{
-  readonly attribute nsIDOMStyleSheet       sheet;
-};
--- a/dom/ipc/TabChild.h
+++ b/dom/ipc/TabChild.h
@@ -2,19 +2,17 @@
 /* vim: set sw=4 ts=8 et tw=80 : */
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #ifndef mozilla_dom_TabChild_h
 #define mozilla_dom_TabChild_h
 
-#ifndef _IMPL_NS_LAYOUT
 #include "mozilla/dom/PBrowserChild.h"
-#endif
 #ifdef DEBUG
 #include "PCOMContentPermissionRequestChild.h"
 #endif /* DEBUG */
 #include "nsIWebNavigation.h"
 #include "nsCOMPtr.h"
 #include "nsAutoPtr.h"
 #include "nsEventDispatcher.h"
 #include "nsIWebBrowserChrome2.h"
--- a/dom/media/bridge/Makefile.in
+++ b/dom/media/bridge/Makefile.in
@@ -4,19 +4,17 @@
 
 DEPTH   = ../../..
 topsrcdir = @top_srcdir@
 srcdir    = @srcdir@
 VPATH   = @srcdir@
 
 include $(DEPTH)/config/autoconf.mk
 
-MODULE_NAME   = peerconnection
 
-IS_COMPONENT   = 1
 EXPORT_LIBRARY = 1
 LIBXUL_LIBRARY = 1
 
 LOCAL_INCLUDES += \
   -I$(topsrcdir)/media/mtransport \
   -I$(topsrcdir)/media/webrtc/signaling/include \
   -I$(topsrcdir)/media/webrtc/signaling/src/sipcc/include \
   -I$(topsrcdir)/media/webrtc/signaling/src/peerconnection \
--- a/dom/plugins/base/Makefile.in
+++ b/dom/plugins/base/Makefile.in
@@ -8,18 +8,16 @@ topsrcdir	= @top_srcdir@
 srcdir		= @srcdir@
 VPATH		= @srcdir@
 
 include $(DEPTH)/config/autoconf.mk
 
 LIBRARY_NAME	= gkplugin
 MSVC_ENABLE_PGO := 1
 EXPORT_LIBRARY = 1
-IS_COMPONENT    = 1
-MODULE_NAME	= nsPluginModule
 LIBXUL_LIBRARY = 1
 
 ifeq ($(MOZ_WIDGET_TOOLKIT),android)
 LOCAL_INCLUDES += -I$(topsrcdir)/dom/plugins/base/android
 else
 # android_npapi.h extends the NPNVariable and NPPVariable enums
 # using #defines, which results in Wswitch warnings in gcc-4.6.
 # Therefore, enable FAIL_ON_WARNINGS only on non-Android platforms.
--- a/dom/src/geolocation/Makefile.in
+++ b/dom/src/geolocation/Makefile.in
@@ -42,10 +42,8 @@ endif
 
 ifeq ($(MOZ_WIDGET_TOOLKIT),cocoa)
 LOCAL_INCLUDES  += -I$(topsrcdir)/dom/system/mac
 endif
 
 include $(topsrcdir)/config/config.mk
 include $(topsrcdir)/config/rules.mk
 include $(topsrcdir)/ipc/chromium/chromium-config.mk
-
-DEFINES += -D_IMPL_NS_LAYOUT
--- a/dom/src/json/Makefile.in
+++ b/dom/src/json/Makefile.in
@@ -12,11 +12,9 @@ FAIL_ON_WARNINGS := 1
 include $(DEPTH)/config/autoconf.mk
 
 LIBXUL_LIBRARY = 1
 
 LOCAL_INCLUDES = \
 		-I$(srcdir)/../base \
 		-I$(topsrcdir)/content/events/src
 
-DEFINES += -D_IMPL_NS_LAYOUT
-
 include $(topsrcdir)/config/rules.mk
--- a/dom/src/jsurl/Makefile.in
+++ b/dom/src/jsurl/Makefile.in
@@ -6,17 +6,16 @@
 DEPTH		= @DEPTH@
 topsrcdir	= @top_srcdir@
 srcdir		= @srcdir@
 VPATH		= @srcdir@
 FAIL_ON_WARNINGS := 1
 
 include $(DEPTH)/config/autoconf.mk
 
-MODULE_NAME	= javascript__protocol
 LIBXUL_LIBRARY	= 1
 
 LOCAL_INCLUDES += \
 		-I$(srcdir) \
 		-I$(topsrcdir)/dom/base \
 		-I$(topsrcdir)/netwerk/base/src \
 
 ifdef BUILD_DEBUG_GC
--- a/dom/src/jsurl/nsJSProtocolHandler.cpp
+++ b/dom/src/jsurl/nsJSProtocolHandler.cpp
@@ -192,29 +192,28 @@ nsresult nsJSThunk::EvaluateScript(nsICh
     }
 
     // Get the global object we should be running on.
     nsIScriptGlobalObject* global = GetGlobalObject(aChannel);
     if (!global) {
         return NS_ERROR_FAILURE;
     }
 
-    nsCOMPtr<nsPIDOMWindow> win(do_QueryInterface(global));
-
     // Sandboxed document check: javascript: URI's are disabled
     // in a sandboxed document unless 'allow-scripts' was specified.
     nsIDocument* doc = aOriginalInnerWindow->GetExtantDoc();
     if (doc && (doc->GetSandboxFlags() & SANDBOXED_SCRIPTS)) {
         return NS_ERROR_DOM_RETVAL_UNDEFINED;
     }
 
     // Push our popup control state
-    nsAutoPopupStatePusher popupStatePusher(win, aPopupState);
+    nsAutoPopupStatePusher popupStatePusher(aPopupState);
 
     // Make sure we still have the same inner window as we used to.
+    nsCOMPtr<nsPIDOMWindow> win = do_QueryInterface(global);
     nsPIDOMWindow *innerWin = win->GetCurrentInnerWindow();
 
     if (innerWin != aOriginalInnerWindow) {
         return NS_ERROR_UNEXPECTED;
     }
 
     nsCOMPtr<nsIScriptGlobalObject> innerGlobal = do_QueryInterface(innerWin);
 
--- a/dom/src/notification/Makefile.in
+++ b/dom/src/notification/Makefile.in
@@ -19,10 +19,8 @@ LOCAL_INCLUDES = \
   -I$(topsrcdir)/dom/ipc \
   -I$(topsrcdir)/content/base/src \
   -I$(topsrcdir)/content/events/src \
   $(NULL)
 
 include $(topsrcdir)/config/config.mk
 include $(topsrcdir)/config/rules.mk
 include $(topsrcdir)/ipc/chromium/chromium-config.mk
-
-DEFINES += -D_IMPL_NS_LAYOUT
--- a/dom/src/offline/Makefile.in
+++ b/dom/src/offline/Makefile.in
@@ -13,11 +13,9 @@ include $(DEPTH)/config/autoconf.mk
 LIBXUL_LIBRARY = 1
 FAIL_ON_WARNINGS := 1
 
 LOCAL_INCLUDES = \
 		-I$(topsrcdir)/dom/base \
 		-I$(topsrcdir)/content/base/src \
 		-I$(topsrcdir)/content/events/src
 
-DEFINES += -D_IMPL_NS_LAYOUT
-
 include $(topsrcdir)/config/rules.mk
--- a/dom/src/storage/Makefile.in
+++ b/dom/src/storage/Makefile.in
@@ -14,17 +14,15 @@ include $(DEPTH)/config/autoconf.mk
 LIBRARY_NAME   = jsdomstorage_s
 MSVC_ENABLE_PGO := 1
 LIBXUL_LIBRARY = 1
 
 LOCAL_INCLUDES = \
                 -I$(topsrcdir)/dom/base \
 		-I$(topsrcdir)/content/events/src
 
-DEFINES += -D_IMPL_NS_LAYOUT
-
 ifdef ENABLE_TESTS
 DEFINES += -DDOM_STORAGE_TESTS
 endif
 
 include $(topsrcdir)/config/config.mk
 include $(topsrcdir)/config/rules.mk
 include $(topsrcdir)/ipc/chromium/chromium-config.mk
--- a/dom/system/OSFileConstants.cpp
+++ b/dom/system/OSFileConstants.cpp
@@ -237,17 +237,17 @@ void CleanupOSFileConstants()
  * Produces a |ConstantSpec|.
  */
 #define INT_CONSTANT(name)      \
   { #name, INT_TO_JSVAL(name) }
 
 /**
  * End marker for ConstantSpec
  */
-#define PROP_END { NULL, JSVAL_VOID }
+#define PROP_END { NULL, JS::UndefinedValue() }
 
 
 // Define missing constants for Android
 #if !defined(S_IRGRP)
 #define S_IXOTH 0001
 #define S_IWOTH 0002
 #define S_IROTH 0004
 #define S_IRWXO 0007
@@ -264,17 +264,17 @@ void CleanupOSFileConstants()
 /**
  * The properties defined in libc.
  *
  * If you extend this list of properties, please
  * separate categories ("errors", "open", etc.),
  * keep properties organized by alphabetical order
  * and #ifdef-away properties that are not portable.
  */
-static dom::ConstantSpec gLibcProperties[] =
+static const dom::ConstantSpec gLibcProperties[] =
 {
   // Arguments for open
   INT_CONSTANT(O_APPEND),
   INT_CONSTANT(O_CREAT),
 #if defined(O_DIRECTORY)
   INT_CONSTANT(O_DIRECTORY),
 #endif // defined(O_DIRECTORY)
 #if defined(O_EVTONLY)
@@ -517,17 +517,17 @@ static dom::ConstantSpec gLibcProperties
 /**
  * The properties defined in windows.h.
  *
  * If you extend this list of properties, please
  * separate categories ("errors", "open", etc.),
  * keep properties organized by alphabetical order
  * and #ifdef-away properties that are not portable.
  */
-static dom::ConstantSpec gWinProperties[] =
+static const dom::ConstantSpec gWinProperties[] =
 {
   // FormatMessage flags
   INT_CONSTANT(FORMAT_MESSAGE_FROM_SYSTEM),
   INT_CONSTANT(FORMAT_MESSAGE_IGNORE_INSERTS),
 
   // The max length of paths
   INT_CONSTANT(MAX_PATH),
 
--- a/dom/tests/mochitest/bugs/test_bug664737.html
+++ b/dom/tests/mochitest/bugs/test_bug664737.html
@@ -14,26 +14,26 @@ https://bugzilla.mozilla.org/show_bug.cg
 <p id="display"></p>
 <div id="content" style="display: none">
   
 </div>
 <pre id="test">
 <script type="application/javascript">
 
 /** Test for Bug 664737 **/
-function shouldfail(name) {
+function isUndefined(name) {
     try {
         var rv = history[name];
-        fail(false, "able to access history." + name);
+        is(rv, undefined, "No value found for history." + name);
     } catch (e) {
-        ok(e.message.indexOf("Permission denied") >= 0, "cannot access history." + name);
+        ok(false, "Accessing history." + name + " threw: " + e);
     }
 }
 
-shouldfail("current");
-shouldfail("previous");
-shouldfail("next");
+isUndefined("current");
+isUndefined("previous");
+isUndefined("next");
 
 
 </script>
 </pre>
 </body>
 </html>
new file mode 100644
--- /dev/null
+++ b/dom/webidl/History.webidl
@@ -0,0 +1,39 @@
+/* -*- Mode: IDL; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/.
+ *
+ * The origin of this IDL file is
+ * http://www.whatwg.org/specs/web-apps/current-work/#the-history-interface
+ *
+ * © Copyright 2004-2011 Apple Computer, Inc., Mozilla Foundation, and
+ * Opera Software ASA. You are granted a license to use, reproduce
+ * and create derivative works of this document.
+ */
+
+interface History {
+  [Throws]
+  readonly attribute unsigned long length;
+  [Throws]
+  readonly attribute any state;
+  [Throws]
+  void go(optional long delta = 0);
+  [Throws]
+  void back();
+  [Throws]
+  void forward();
+  [Throws]
+  void pushState(any data, DOMString title, optional DOMString? url = null);
+  [Throws]
+  void replaceState(any data, DOMString title, optional DOMString? url = null);
+
+  // Chrome only methods.
+  [Throws, ChromeOnly]
+  readonly attribute DOMString current;
+  [Throws, ChromeOnly]
+  readonly attribute DOMString previous;
+  [Throws, ChromeOnly]
+  readonly attribute DOMString next;
+  [Throws, ChromeOnly]
+  getter DOMString? item(unsigned long index);
+};
--- a/dom/webidl/WebIDL.mk
+++ b/dom/webidl/WebIDL.mk
@@ -89,16 +89,17 @@ webidl_files = \
   FileReader.webidl \
   FileReaderSync.webidl \
   FileRequest.webidl \
   FocusEvent.webidl \
   FormData.webidl \
   Function.webidl \
   GainNode.webidl \
   Geolocation.webidl \
+  History.webidl \
   HTMLAnchorElement.webidl \
   HTMLAppletElement.webidl \
   HTMLAreaElement.webidl \
   HTMLAudioElement.webidl \
   HTMLBaseElement.webidl \
   HTMLBodyElement.webidl \
   HTMLBRElement.webidl \
   HTMLButtonElement.webidl \
--- a/dom/workers/test/test_recursion.html
+++ b/dom/workers/test/test_recursion.html
@@ -15,16 +15,21 @@ Tests of DOM Worker Threads
 <body>
 <p id="display"></p>
 <div id="content" style="display: none">
 
 </div>
 <pre id="test">
 <script class="testbody" type="text/javascript">
 
+  // Intermittently triggers one assertion on Mac (bug 848098).
+  if (navigator.platform.indexOf("Mac") == 0) {
+    SimpleTest.expectAssertions(0, 1);
+  }
+
   const testCount = 2;
   var errorCount = 0;
 
   var worker = new Worker("recursion_worker.js");
 
   function done() {
     worker.terminate();
     SimpleTest.finish();
--- a/editor/composer/src/Makefile.in
+++ b/editor/composer/src/Makefile.in
@@ -6,18 +6,16 @@
 DEPTH		= @DEPTH@
 topsrcdir	= @top_srcdir@
 srcdir		= @srcdir@
 VPATH		= @srcdir@
 
 include $(DEPTH)/config/autoconf.mk
 
 EXPORT_LIBRARY = 1
-IS_COMPONENT	= 1
-MODULE_NAME	= nsComposerModule
 LIBXUL_LIBRARY	= 1
 FAIL_ON_WARNINGS = 1
 
 
 include $(topsrcdir)/config/rules.mk
 
 INCLUDES        += \
 	$(NULL)
--- a/editor/libeditor/html/Makefile.in
+++ b/editor/libeditor/html/Makefile.in
@@ -15,18 +15,16 @@ LIBXUL_LIBRARY	= 1
 
 
 # Building the full blown HTML Editor  so add its source files and objects:
 
 ifdef ENABLE_EDITOR_API_LOG
 DEFINES += -DENABLE_EDITOR_API_LOG
 endif
 
-DEFINES += -D_IMPL_NS_LAYOUT
-
 include $(topsrcdir)/config/rules.mk
 
 INCLUDES        += -I$(topsrcdir)/editor/libeditor/base \
                    -I$(topsrcdir)/editor/libeditor/text \
                    -I$(topsrcdir)/editor/txmgr/src \
                    -I$(topsrcdir)/content/base/src \
                    -I$(topsrcdir)/layout/style \
                    $(NULL)
--- a/editor/txmgr/src/Makefile.in
+++ b/editor/txmgr/src/Makefile.in
@@ -7,15 +7,13 @@ DEPTH		= @DEPTH@
 topsrcdir	= @top_srcdir@
 srcdir		= @srcdir@
 VPATH		= @srcdir@
 FAIL_ON_WARNINGS = 1
 
 include $(DEPTH)/config/autoconf.mk
 
 EXPORT_LIBRARY = 1
-IS_COMPONENT	= 1
-MODULE_NAME	= nsTransactionManagerModule
 LIBXUL_LIBRARY	= 1
 
 
 include $(topsrcdir)/config/rules.mk
 
--- a/editor/txtsvc/src/Makefile.in
+++ b/editor/txtsvc/src/Makefile.in
@@ -6,14 +6,13 @@
 DEPTH		= @DEPTH@
 topsrcdir	= @top_srcdir@
 srcdir		= @srcdir@
 VPATH		= @srcdir@
 FAIL_ON_WARNINGS = 1
 
 include $(DEPTH)/config/autoconf.mk
 
-MODULE_NAME	= nsTextServicesModule
 LIBXUL_LIBRARY	= 1
 
 
 include $(topsrcdir)/config/rules.mk
 
--- a/embedding/browser/build/Makefile.in
+++ b/embedding/browser/build/Makefile.in
@@ -5,18 +5,16 @@
 
 DEPTH		= @DEPTH@
 topsrcdir	= @top_srcdir@
 srcdir		= @srcdir@
 VPATH		= @srcdir@
 
 include $(DEPTH)/config/autoconf.mk
 
-IS_COMPONENT	= 1
-MODULE_NAME	= Browser_Embedding_Module
 EXPORT_LIBRARY	= 1
 LIBXUL_LIBRARY	= 1
 FAIL_ON_WARNINGS = 1
 
 
 SHARED_LIBRARY_LIBS= \
 		../webBrowser/$(LIB_PREFIX)nsWebBrowser_s.$(LIB_SUFFIX) \
 		$(NULL)
--- a/embedding/components/build/Makefile.in
+++ b/embedding/components/build/Makefile.in
@@ -5,18 +5,16 @@
 DEPTH		= @DEPTH@
 topsrcdir	= @top_srcdir@
 srcdir		= @srcdir@
 VPATH		= @srcdir@
 
 include $(DEPTH)/config/autoconf.mk
 
 EXPORT_LIBRARY = 1
-IS_COMPONENT	= 1
-MODULE_NAME	= embedcomponents
 LIBXUL_LIBRARY	= 1
 FAIL_ON_WARNINGS = 1
 
 SHARED_LIBRARY_LIBS = \
 	../windowwatcher/src/$(LIB_PREFIX)windowwatcher_s.$(LIB_SUFFIX) \
 	../appstartup/src/$(LIB_PREFIX)appstartupnotifier_s.$(LIB_SUFFIX) \
 	../find/src/$(LIB_PREFIX)find_s.$(LIB_SUFFIX) \
 	../webbrowserpersist/src/$(LIB_PREFIX)webbrowserpersist_s.$(LIB_SUFFIX) \
--- a/embedding/components/windowwatcher/src/nsWindowWatcher.cpp
+++ b/embedding/components/windowwatcher/src/nsWindowWatcher.cpp
@@ -961,27 +961,20 @@ nsWindowWatcher::OpenWindowInternal(nsID
     nsCOMPtr<nsIDocShellTreeOwner> newTreeOwner;
     newDocShellItem->GetTreeOwner(getter_AddRefs(newTreeOwner));
     nsCOMPtr<nsIWebBrowserChrome> newChrome(do_GetInterface(newTreeOwner));
 
     // Throw an exception here if no web browser chrome is available,
     // we need that to show a modal window.
     NS_ENSURE_TRUE(newChrome, NS_ERROR_NOT_AVAILABLE);
 
-    nsCOMPtr<nsPIDOMWindow> modalContentWindow;
-
     // Dispatch dialog events etc, but we only want to do that if
     // we're opening a modal content window (the helper classes are
     // no-ops if given no window), for chrome dialogs we don't want to
     // do any of that (it's done elsewhere for us).
-
-    if (windowIsModalContentDialog) {
-      modalContentWindow = do_QueryInterface(*_retval);
-    }
-
     nsAutoWindowStateHelper windowStateHelper(aParent);
 
     if (!windowStateHelper.DefaultEnabled()) {
       // Default to cancel not opening the modal window.
       NS_RELEASE(*_retval);
 
       return NS_OK;
     }
@@ -995,17 +988,17 @@ nsWindowWatcher::OpenWindowInternal(nsID
         if (parentWidget) {
           parentWidget->SetModal(true);
         }
       }
     } else { 
       // Reset popup state while opening a modal dialog, and firing
       // events about the dialog, to prevent the current state from
       // being active the whole time a modal dialog is open.
-      nsAutoPopupStatePusher popupStatePusher(modalContentWindow, openAbused);
+      nsAutoPopupStatePusher popupStatePusher(openAbused);
   
       newChrome->ShowAsModal();
     }
   }
 
   return NS_OK;
 }
 
--- a/extensions/auth/Makefile.in
+++ b/extensions/auth/Makefile.in
@@ -5,19 +5,17 @@
 
 DEPTH		= @DEPTH@
 topsrcdir	= @top_srcdir@
 srcdir		= @srcdir@
 VPATH		= @srcdir@
 
 include $(DEPTH)/config/autoconf.mk
 
-IS_COMPONENT	= 1
 EXPORT_LIBRARY	= 1
-MODULE_NAME	= nsAuthModule
 LIBXUL_LIBRARY = 1
 
 
 ifeq ($(OS_ARCH),WINNT)
 LOCAL_INCLUDES	+= -DUSE_SSPI
 endif
 
 include $(topsrcdir)/config/rules.mk
--- a/extensions/cookie/Makefile.in
+++ b/extensions/cookie/Makefile.in
@@ -8,16 +8,14 @@ topsrcdir	= @top_srcdir@
 srcdir		= @srcdir@
 VPATH		= @srcdir@
 
 include $(DEPTH)/config/autoconf.mk
 
 LIBRARY_NAME	= cookie
 MSVC_ENABLE_PGO := 1
 EXPORT_LIBRARY = 1
-IS_COMPONENT	= 1
-MODULE_NAME	= nsCookieModule
 LIBXUL_LIBRARY = 1
 
 
 include $(topsrcdir)/config/config.mk
 include $(topsrcdir)/config/rules.mk
 include $(topsrcdir)/ipc/chromium/chromium-config.mk
--- a/extensions/gio/Makefile.in
+++ b/extensions/gio/Makefile.in
@@ -5,17 +5,15 @@
 
 DEPTH		= @DEPTH@
 topsrcdir	= @top_srcdir@
 srcdir		= @srcdir@
 VPATH		= @srcdir@
 
 include $(DEPTH)/config/autoconf.mk
 
-IS_COMPONENT	= 1
 EXPORT_LIBRARY	= 1
-MODULE_NAME	= nsGIOModule
 LIBXUL_LIBRARY	= 1
 FAIL_ON_WARNINGS = 1
 
 LOCAL_INCLUDES	= $(MOZ_GIO_CFLAGS)
 
 include $(topsrcdir)/config/rules.mk
--- a/extensions/permissions/Makefile.in
+++ b/extensions/permissions/Makefile.in
@@ -5,14 +5,12 @@
 DEPTH		= @DEPTH@
 topsrcdir	= @top_srcdir@
 srcdir		= @srcdir@
 VPATH		= @srcdir@
 
 include $(DEPTH)/config/autoconf.mk
 
 EXPORT_LIBRARY	= 1
-IS_COMPONENT	= 1
-MODULE_NAME	= nsPermissionsModule
 LIBXUL_LIBRARY = 1
 
 
 include $(topsrcdir)/config/rules.mk
--- a/extensions/pref/autoconfig/src/Makefile.in
+++ b/extensions/pref/autoconfig/src/Makefile.in
@@ -6,18 +6,16 @@ DEPTH            = @DEPTH@
 topsrcdir        = @top_srcdir@
 srcdir           = @srcdir@
 VPATH            = @srcdir@
 
 include $(DEPTH)/config/autoconf.mk
 
 LIBRARY_NAME     = autoconfig
 EXPORT_LIBRARY   = 1
-IS_COMPONENT     = 1
-MODULE_NAME      = nsAutoConfigModule
 LIBXUL_LIBRARY   = 1
 
 
 include $(topsrcdir)/config/config.mk
 
 AUTOCFG_JS_EXPORTS = \
 		$(srcdir)/prefcalls.js \
 		$(NULL)
--- a/extensions/spellcheck/src/Makefile.in
+++ b/extensions/spellcheck/src/Makefile.in
@@ -4,19 +4,17 @@
 
 DEPTH		= @DEPTH@
 topsrcdir	= @top_srcdir@
 srcdir		= @srcdir@
 VPATH		= @srcdir@
 
 include $(DEPTH)/config/autoconf.mk
 
-MODULE_NAME     = mozSpellCheckerModule
 EXPORT_LIBRARY  = 1
-IS_COMPONENT	= 1
 LIBXUL_LIBRARY  = 1
 
 
 SHARED_LIBRARY_LIBS += ../hunspell/src/$(LIB_PREFIX)hunspell_s.$(LIB_SUFFIX)
 
 include $(topsrcdir)/config/rules.mk
 
 LOCAL_INCLUDES += \
--- a/extensions/universalchardet/src/xpcom/Makefile.in
+++ b/extensions/universalchardet/src/xpcom/Makefile.in
@@ -6,18 +6,16 @@
 DEPTH		= @DEPTH@
 topsrcdir	= @top_srcdir@
 srcdir		= @srcdir@
 VPATH		= @srcdir@
 
 include $(DEPTH)/config/autoconf.mk
 
 EXPORT_LIBRARY	= 1
-IS_COMPONENT	= 1
-MODULE_NAME	= nsUniversalCharDetModule
 LIBXUL_LIBRARY = 1
 
 LOCAL_INCLUDES = -I$(srcdir)/../base
 
 SHARED_LIBRARY_LIBS = \
 		../base/$(LIB_PREFIX)universalchardet_s.$(LIB_SUFFIX) \
 		$(NULL)
 
--- a/gfx/layers/composite/AsyncCompositionManager.cpp
+++ b/gfx/layers/composite/AsyncCompositionManager.cpp
@@ -448,17 +448,17 @@ AsyncCompositionManager::ApplyAsyncConte
                      mIsFirstPaint, fixedLayerMargins, offset);
 
     mIsFirstPaint = false;
     mLayersUpdated = false;
 
     // Apply the render offset
     mLayerManager->GetCompositor()->SetScreenRenderOffset(offset);
 
-    gfx3DMatrix transform(gfx3DMatrix(treeTransform) * aLayer->GetTransform());
+    gfx3DMatrix transform(aLayer->GetTransform() * gfx3DMatrix(treeTransform));
     // The transform already takes the resolution scale into account.  Since we
     // will apply the resolution scale again when computing the effective
     // transform, we must apply the inverse resolution scale here.
     transform.Scale(1.0f/container->GetPreXScale(),
                     1.0f/container->GetPreYScale(),
                     1);
     transform.ScalePost(1.0f/aLayer->GetPostXScale(),
                         1.0f/aLayer->GetPostYScale(),
@@ -546,30 +546,30 @@ AsyncCompositionManager::TransformScroll
   mLayerManager->GetCompositor()->SetScreenRenderOffset(offset);
 
   // Handle transformations for asynchronous panning and zooming. We determine the
   // zoom used by Gecko from the transformation set on the root layer, and we
   // determine the scroll offset used by Gecko from the frame metrics of the
   // primary scrollable layer. We compare this to the user zoom and scroll
   // offset in the view transform we obtained from Java in order to compute the
   // transformation we need to apply.
-  LayerToScreenScale zoomAdjust = userZoom / geckoZoom;
+  LayoutDeviceToScreenScale zoomAdjust = userZoom / metrics.mDevPixelsPerCSSPixel;
 
-  LayerIntPoint geckoScroll(0, 0);
+  LayoutDevicePoint geckoScroll(0, 0);
   if (metrics.IsScrollable()) {
-    geckoScroll = scrollOffsetLayerPixels;
+    geckoScroll = metrics.mScrollOffset * metrics.mDevPixelsPerCSSPixel;
   }
 
-  LayerPoint translation = (userScroll / zoomAdjust) - geckoScroll;
+  LayoutDevicePoint translation = (userScroll / zoomAdjust) - geckoScroll;
   treeTransform = gfx3DMatrix(ViewTransform(-translation, userZoom / metrics.mDevPixelsPerCSSPixel));
 
   // The transform already takes the resolution scale into account.  Since we
   // will apply the resolution scale again when computing the effective
   // transform, we must apply the inverse resolution scale here.
-  gfx3DMatrix computedTransform = treeTransform * currentTransform;
+  gfx3DMatrix computedTransform = currentTransform * treeTransform;
   computedTransform.Scale(1.0f/container->GetPreXScale(),
                           1.0f/container->GetPreYScale(),
                           1);
   computedTransform.ScalePost(1.0f/container->GetPostXScale(),
                               1.0f/container->GetPostYScale(),
                               1);
   layerComposite->SetShadowTransform(computedTransform);
   NS_ASSERTION(!layerComposite->GetShadowTransformSetByAnimation(),
--- a/gfx/layers/composite/AsyncCompositionManager.h
+++ b/gfx/layers/composite/AsyncCompositionManager.h
@@ -22,17 +22,17 @@ namespace layers {
 
 class AsyncPanZoomController;
 class Layer;
 class LayerManagerComposite;
 class AutoResolveRefLayers;
 
 // Represents (affine) transforms that are calculated from a content view.
 struct ViewTransform {
-  ViewTransform(LayerPoint aTranslation = LayerPoint(),
+  ViewTransform(LayoutDevicePoint aTranslation = LayoutDevicePoint(),
                 LayoutDeviceToScreenScale aScale = LayoutDeviceToScreenScale())
     : mTranslation(aTranslation)
     , mScale(aScale)
   {}
 
   operator gfx3DMatrix() const
   {
     return
@@ -43,17 +43,17 @@ struct ViewTransform {
   bool operator==(const ViewTransform& rhs) const {
     return mTranslation == rhs.mTranslation && mScale == rhs.mScale;
   }
 
   bool operator!=(const ViewTransform& rhs) const {
     return !(*this == rhs);
   }
 
-  LayerPoint mTranslation;
+  LayoutDevicePoint mTranslation;
   LayoutDeviceToScreenScale mScale;
 };
 
 /**
  * Manage async composition effects. This class is only used with OMTC and only
  * lives on the compositor thread. It is a layer on top of the layer manager
  * (LayerManagerComposite) which deals with elements of composition which are
  * usually dealt with by dom or layout when main thread rendering, but which can
--- a/gfx/layers/composite/ImageLayerComposite.cpp
+++ b/gfx/layers/composite/ImageLayerComposite.cpp
@@ -130,18 +130,19 @@ ImageLayerComposite::ComputeEffectiveTra
       SnapTransform(local, sourceRect, nullptr) *
       SnapTransformTranslation(aTransformToSurface, nullptr);
   ComputeEffectiveTransformForMaskLayer(aTransformToSurface);
 }
 
 CompositableHost*
 ImageLayerComposite::GetCompositableHost()
 {
-  if (mImageHost->IsAttached())
+  if (mImageHost && mImageHost->IsAttached()) {
     return mImageHost.get();
+  }
 
   return nullptr;
 }
 
 void
 ImageLayerComposite::CleanupResources()
 {
   if (mImageHost) {
--- a/gfx/layers/ipc/AsyncPanZoomController.cpp
+++ b/gfx/layers/ipc/AsyncPanZoomController.cpp
@@ -1155,18 +1155,18 @@ bool AsyncPanZoomController::SampleConte
 ViewTransform AsyncPanZoomController::GetCurrentAsyncTransform() {
   ReentrantMonitorAutoEnter lock(mMonitor);
 
   CSSPoint lastPaintScrollOffset;
   if (mLastContentPaintMetrics.IsScrollable()) {
     lastPaintScrollOffset = mLastContentPaintMetrics.mScrollOffset;
   }
   CSSToScreenScale localScale = mFrameMetrics.CalculateResolution();
-  LayerPoint translation = (mFrameMetrics.mScrollOffset - lastPaintScrollOffset)
-                         * mLastContentPaintMetrics.LayersPixelsPerCSSPixel();
+  LayoutDevicePoint translation = (mFrameMetrics.mScrollOffset - lastPaintScrollOffset)
+                                * mLastContentPaintMetrics.mDevPixelsPerCSSPixel;
   return ViewTransform(-translation, localScale / mLastContentPaintMetrics.mDevPixelsPerCSSPixel);
 }
 
 void AsyncPanZoomController::NotifyLayersUpdated(const FrameMetrics& aLayerMetrics, bool aIsFirstPaint) {
   ReentrantMonitorAutoEnter lock(mMonitor);
 
   mLastContentPaintMetrics = aLayerMetrics;
 
--- a/gfx/src/Makefile.in
+++ b/gfx/src/Makefile.in
@@ -5,21 +5,19 @@
 
 DEPTH       = @DEPTH@
 topsrcdir   = @top_srcdir@
 srcdir      = @srcdir@
 VPATH       = @srcdir@
 
 include $(DEPTH)/config/autoconf.mk
 
-MODULE_NAME    = nsGfxModule
 MSVC_ENABLE_PGO := 1
 EXPORT_LIBRARY = 1
 LIBXUL_LIBRARY = 1
-IS_COMPONENT   = 1
 FAIL_ON_WARNINGS = 1
 
 include $(topsrcdir)/config/rules.mk
 
 CXXFLAGS += $(MOZ_CAIRO_CFLAGS) $(MOZ_PIXMAN_CFLAGS) $(TK_CFLAGS)
 
 ifdef MOZ_WIDGET_GTK
 CXXFLAGS += $(MOZ_PANGO_CFLAGS)
--- a/gfx/tests/gtest/Makefile.in
+++ b/gfx/tests/gtest/Makefile.in
@@ -9,19 +9,17 @@ srcdir         = @srcdir@
 VPATH          = @srcdir@ $(srcdir)/$(DEPTH)/gfx/2d/unittest
 relativesrcdir = @relativesrcdir@
 
 include $(DEPTH)/config/autoconf.mk
 
 CXXFLAGS += $(MOZ_CAIRO_CFLAGS) $(MOZ_PIXMAN_CFLAGS) $(TK_CFLAGS) 
 
 # Create a GTest library
-MODULE_NAME    = gfxtest
 LIBXUL_LIBRARY = 1
-IS_COMPONENT   = 1
 EXPORT_LIBRARY = 1
 
 LOCAL_INCLUDES = \
   -I$(topsrcdir)/gfx/layers \
   -I$(topsrcdir)/gfx/2d \
   -I$(topsrcdir)/gfx/2d/unittest \
   $(NULL)
 
--- a/gfx/tests/gtest/TestAsyncPanZoomController.cpp
+++ b/gfx/tests/gtest/TestAsyncPanZoomController.cpp
@@ -191,49 +191,49 @@ TEST(AsyncPanZoomController, ComplexTran
 
   // Both the parent and child layer should behave exactly the same here, because
   // the CSS transform on the child layer does not affect the SampleContentTransformForFrame code
 
   // initial transform
   apzc->SetFrameMetrics(metrics);
   apzc->NotifyLayersUpdated(metrics, true);
   apzc->SampleContentTransformForFrame(testStartTime, &viewTransformOut, pointOut);
-  EXPECT_EQ(ViewTransform(LayerPoint(), LayoutDeviceToScreenScale(2)), viewTransformOut);
+  EXPECT_EQ(ViewTransform(LayoutDevicePoint(), LayoutDeviceToScreenScale(2)), viewTransformOut);
   EXPECT_EQ(ScreenPoint(60, 60), pointOut);
 
   childApzc->SetFrameMetrics(childMetrics);
   childApzc->NotifyLayersUpdated(childMetrics, true);
   childApzc->SampleContentTransformForFrame(testStartTime, &viewTransformOut, pointOut);
-  EXPECT_EQ(ViewTransform(LayerPoint(), LayoutDeviceToScreenScale(2)), viewTransformOut);
+  EXPECT_EQ(ViewTransform(LayoutDevicePoint(), LayoutDeviceToScreenScale(2)), viewTransformOut);
   EXPECT_EQ(ScreenPoint(60, 60), pointOut);
 
   // do an async scroll by 5 pixels and check the transform
   metrics.mScrollOffset += CSSPoint(5, 0);
   apzc->SetFrameMetrics(metrics);
   apzc->SampleContentTransformForFrame(testStartTime, &viewTransformOut, pointOut);
-  EXPECT_EQ(ViewTransform(LayerPoint(-30, 0), LayoutDeviceToScreenScale(2)), viewTransformOut);
+  EXPECT_EQ(ViewTransform(LayoutDevicePoint(-15, 0), LayoutDeviceToScreenScale(2)), viewTransformOut);
   EXPECT_EQ(ScreenPoint(90, 60), pointOut);
 
   childMetrics.mScrollOffset += CSSPoint(5, 0);
   childApzc->SetFrameMetrics(childMetrics);
   childApzc->SampleContentTransformForFrame(testStartTime, &viewTransformOut, pointOut);
-  EXPECT_EQ(ViewTransform(LayerPoint(-30, 0), LayoutDeviceToScreenScale(2)), viewTransformOut);
+  EXPECT_EQ(ViewTransform(LayoutDevicePoint(-15, 0), LayoutDeviceToScreenScale(2)), viewTransformOut);
   EXPECT_EQ(ScreenPoint(90, 60), pointOut);
 
   // do an async zoom of 1.5x and check the transform
   metrics.mZoom.scale *= 1.5f;
   apzc->SetFrameMetrics(metrics);
   apzc->SampleContentTransformForFrame(testStartTime, &viewTransformOut, pointOut);
-  EXPECT_EQ(ViewTransform(LayerPoint(-30, 0), LayoutDeviceToScreenScale(3)), viewTransformOut);
+  EXPECT_EQ(ViewTransform(LayoutDevicePoint(-15, 0), LayoutDeviceToScreenScale(3)), viewTransformOut);
   EXPECT_EQ(ScreenPoint(135, 90), pointOut);
 
   childMetrics.mZoom.scale *= 1.5f;
   childApzc->SetFrameMetrics(childMetrics);
   childApzc->SampleContentTransformForFrame(testStartTime, &viewTransformOut, pointOut);
-  EXPECT_EQ(ViewTransform(LayerPoint(-30, 0), LayoutDeviceToScreenScale(3)), viewTransformOut);
+  EXPECT_EQ(ViewTransform(LayoutDevicePoint(-15, 0), LayoutDeviceToScreenScale(3)), viewTransformOut);
   EXPECT_EQ(ScreenPoint(135, 90), pointOut);
 }
 
 TEST(AsyncPanZoomController, Pan) {
   TimeStamp testStartTime = TimeStamp::Now();
   AsyncPanZoomController::SetFrameTime(testStartTime);
 
   nsRefPtr<MockContentController> mcc = new MockContentController();
--- a/image/build/Makefile.in
+++ b/image/build/Makefile.in
@@ -6,18 +6,16 @@
 DEPTH		= @DEPTH@
 topsrcdir	= @top_srcdir@
 srcdir		= @srcdir@
 VPATH		= @srcdir@
 
 include $(DEPTH)/config/autoconf.mk
 
 EXPORT_LIBRARY = 1
-IS_COMPONENT	= 1
-MODULE_NAME	= nsImageLib2Module
 LIBXUL_LIBRARY = 1
 FAIL_ON_WARNINGS = 1
 
 LOCAL_INCLUDES	= \
 		-I. \
 		-I$(srcdir)/../src \
 		-I$(srcdir)/../encoders/ico \
 		-I$(srcdir)/../encoders/png \
--- a/image/decoders/Makefile.in
+++ b/image/decoders/Makefile.in
@@ -5,17 +5,16 @@
 
 DEPTH		= @DEPTH@
 topsrcdir	= @top_srcdir@
 srcdir		= @srcdir@
 VPATH		= @srcdir@
 
 include $(DEPTH)/config/autoconf.mk
 
-MODULE_NAME = nsDecodersModule
 LIBXUL_LIBRARY  = 1
 FAIL_ON_WARNINGS = 1
 
 CSRCS   = iccjpeg.c \
           $(NULL)
 
 # Decoders need RasterImage.h
 LOCAL_INCLUDES += -I$(topsrcdir)/image/src/
--- a/image/decoders/icon/Makefile.in
+++ b/image/decoders/icon/Makefile.in
@@ -5,18 +5,16 @@
 
 DEPTH		= @DEPTH@
 topsrcdir	= @top_srcdir@
 srcdir		= @srcdir@
 VPATH		= @srcdir@
 
 include $(DEPTH)/config/autoconf.mk
 
-IS_COMPONENT	= 1
-MODULE_NAME	= nsIconDecoderModule
 LIBXUL_LIBRARY = 1
 EXPORT_LIBRARY = 1
 FAIL_ON_WARNINGS = 1
 
 ifdef MOZ_WIDGET_GTK
 PLATFORM = gtk
 endif
 
--- a/image/encoders/bmp/Makefile.in
+++ b/image/encoders/bmp/Makefile.in
@@ -4,17 +4,16 @@
 
 DEPTH		= @DEPTH@
 topsrcdir	= @top_srcdir@
 srcdir		= @srcdir@
 VPATH		= @srcdir@
 
 include $(DEPTH)/config/autoconf.mk
 
-MODULE_NAME	= imgEncoderBMPModule
 LIBXUL_LIBRARY = 1
 FAIL_ON_WARNINGS = 1
 
 LOCAL_INCLUDES += -I$(topsrcdir)/image/src/
 
 include $(topsrcdir)/config/rules.mk
 
 
--- a/image/encoders/ico/Makefile.in
+++ b/image/encoders/ico/Makefile.in
@@ -4,17 +4,16 @@
 
 DEPTH		= @DEPTH@
 topsrcdir	= @top_srcdir@
 srcdir		= @srcdir@
 VPATH		= @srcdir@
 
 include $(DEPTH)/config/autoconf.mk
 
-MODULE_NAME	= imgEncoderICOModule
 LIBXUL_LIBRARY = 1
 FAIL_ON_WARNINGS = 1
 
 # Decoders need RasterImage.h
 LOCAL_INCLUDES += -I$(topsrcdir)/image/src/
 LOCAL_INCLUDES += -I$(topsrcdir)/image/encoders/bmp/
 LOCAL_INCLUDES += -I$(topsrcdir)/image/encoders/png/
 
--- a/image/encoders/jpeg/Makefile.in
+++ b/image/encoders/jpeg/Makefile.in
@@ -4,15 +4,14 @@
 
 DEPTH		= @DEPTH@
 topsrcdir	= @top_srcdir@
 srcdir		= @srcdir@
 VPATH		= @srcdir@
 
 include $(DEPTH)/config/autoconf.mk
 
-MODULE_NAME	= imgEncoderJPEGModule
 LIBXUL_LIBRARY = 1
 FAIL_ON_WARNINGS = 1
 
 include $(topsrcdir)/config/rules.mk
 
 
--- a/image/encoders/png/Makefile.in
+++ b/image/encoders/png/Makefile.in
@@ -4,17 +4,16 @@
 
 DEPTH		= @DEPTH@
 topsrcdir	= @top_srcdir@
 srcdir		= @srcdir@
 VPATH		= @srcdir@
 
 include $(DEPTH)/config/autoconf.mk
 
-MODULE_NAME	= imgEncoderPNGModule
 LIBXUL_LIBRARY = 1
 FAIL_ON_WARNINGS = 1
 
 DEFINES		+= -DMOZ_PNG_WRITE \
 	-DMOZ_PNG_READ \
 	$(NULL)
 
 LOCAL_INCLUDES += -I$(topsrcdir)/image/src/
--- a/image/src/Makefile.in
+++ b/image/src/Makefile.in
@@ -6,17 +6,16 @@
 DEPTH		= @DEPTH@
 topsrcdir	= @top_srcdir@
 srcdir		= @srcdir@
 VPATH		= @srcdir@
 
 include $(DEPTH)/config/autoconf.mk
 
 LIBRARY_NAME	= imglib2_s
-MODULE_NAME	= nsImageLib2Module
 LIBXUL_LIBRARY  = 1
 FAIL_ON_WARNINGS = 1
 
 # We need to instantiate the decoders
 LOCAL_INCLUDES += -I$(topsrcdir)/image/decoders
 
 # For URI-related functionality
 LOCAL_INCLUDES += -I$(topsrcdir)/netwerk/base/src
--- a/intl/build/Makefile.in
+++ b/intl/build/Makefile.in
@@ -5,18 +5,16 @@
 DEPTH		= @DEPTH@
 topsrcdir	= @top_srcdir@
 srcdir		= @srcdir@
 VPATH		= @srcdir@
 
 include $(DEPTH)/config/autoconf.mk
 
 EXPORT_LIBRARY = 1
-IS_COMPONENT	= 1
-MODULE_NAME	= nsI18nModule
 LIBXUL_LIBRARY = 1
 
 # see also intl/locale/src/Makefile.in
 ifneq (,$(filter os2 windows, $(MOZ_WIDGET_TOOLKIT)))
 LOCALE_DIR		= $(MOZ_WIDGET_TOOLKIT)
 else
 ifeq ($(OS_ARCH), Darwin)
 LOCALE_DIR		= mac
--- a/intl/chardet/src/Makefile.in
+++ b/intl/chardet/src/Makefile.in
@@ -6,14 +6,12 @@
 DEPTH		= @DEPTH@
 topsrcdir	= @top_srcdir@
 srcdir		= @srcdir@
 VPATH		= @srcdir@
 
 include $(DEPTH)/config/autoconf.mk
 
 EXPORT_LIBRARY = 1
-IS_COMPONENT = 1
-MODULE_NAME = nsChardetModule
 LIBXUL_LIBRARY  = 1
 
 
 include $(topsrcdir)/config/rules.mk
--- a/intl/uconv/src/Makefile.in
+++ b/intl/uconv/src/Makefile.in
@@ -7,18 +7,16 @@ DEPTH		= @DEPTH@
 topsrcdir	= @top_srcdir@
 srcdir		= @srcdir@
 VPATH		= @srcdir@
 
 include $(DEPTH)/config/autoconf.mk
 
 MSVC_ENABLE_PGO := 1
 EXPORT_LIBRARY  = 1
-IS_COMPONENT	= 1
-MODULE_NAME	= nsUConvModule
 LIBXUL_LIBRARY = 1
 
 LOCAL_INCLUDES	= -I$(srcdir)/../util \
 		  -I$(srcdir)/../ucvlatin \
 		  -I$(srcdir)/../ucvibm \
 		  -I$(srcdir)/../ucvja \
 		  -I$(srcdir)/../ucvtw2 \
 		  -I$(srcdir)/../ucvtw \
--- a/intl/uconv/util/Makefile.in
+++ b/intl/uconv/util/Makefile.in
@@ -9,18 +9,16 @@ srcdir		= @srcdir@
 VPATH		= @srcdir@
 
 include $(DEPTH)/config/autoconf.mk
 
 MSVC_ENABLE_PGO := 1
 EXPORT_LIBRARY = 1
 LIBXUL_LIBRARY = 1
 
-MODULE_NAME	= nsUCUtil
-
 CSRCS		= \
 		ugen.c \
 		uscan.c \
 		umap.c \
 		$(NULL)
 
 include $(topsrcdir)/config/rules.mk
 
--- a/ipc/chromium/chromium-config.mk
+++ b/ipc/chromium/chromium-config.mk
@@ -63,21 +63,23 @@ OS_DRAGONFLY = 1
 OS_BSD = 1
 OS_LIBS += $(call EXPAND_LIBNAME,kvm)
 DEFINES += \
   -DOS_DRAGONFLY=1 \
   -DOS_BSD=1 \
   $(NULL)
 
 else # } {
-ifeq ($(OS_ARCH),FreeBSD) # {
+ifneq (,$(filter $(OS_ARCH),FreeBSD GNU_kFreeBSD)) # {
 
 OS_FREEBSD = 1
 OS_BSD = 1
+ifneq ($(OS_ARCH),GNU_kFreeBSD)
 OS_LIBS += $(call EXPAND_LIBNAME,kvm)
+endif
 DEFINES += \
   -DOS_FREEBSD=1 \
   -DOS_BSD=1 \
   $(NULL)
 
 else # } {
 ifeq ($(OS_ARCH),NetBSD) # {
 
--- a/ipc/chromium/moz.build
+++ b/ipc/chromium/moz.build
@@ -18,17 +18,17 @@ if CONFIG['OS_ARCH'] == 'WINNT':
     os_win = 1
 else:
     os_posix = 1
     if CONFIG['OS_ARCH'] == 'Darwin':
         os_macosx = 1
     elif CONFIG['OS_ARCH'] == 'DragonFly':
         os_dragonfly = 1
         os_bsd = 1
-    elif CONFIG['OS_ARCH'] == 'FreeBSD':
+    elif CONFIG['OS_ARCH'] in ['FreeBSD', 'GNU_kFreeBSD']:
         os_freebsd = 1
         os_bsd = 1
     elif CONFIG['OS_ARCH'] == 'NetBSD':
         os_netbsd = 1
         os_bsd = 1
     elif CONFIG['OS_ARCH'] == 'OpenBSD':
         os_openbsd = 1
         os_bsd = 1
@@ -200,19 +200,22 @@ if os_linux:
         CPP_SOURCES += [
             'moc_message_pump_qt.cc',
             'message_pump_qt.cc',
         ]
 
 if os_bsd:
     CPP_SOURCES += [
         'atomicops_internals_x86_gcc.cc',
-        'process_util_bsd.cc',
         'time_posix.cc',
     ]
+    if CONFIG['OS_ARCH'] == 'GNU_kFreeBSD':
+        CPP_SOURCES += ['process_util_linux.cc']
+    else:
+        CPP_SOURCES += ['process_util_bsd.cc']
     if CONFIG['MOZ_WIDGET_GTK']:
         CPP_SOURCES += [
             'message_pump_glib.cc',
         ]
     if CONFIG['MOZ_ENABLE_QT']:
         CPP_SOURCES += [
             'moc_message_pump_qt.cc',
             'message_pump_qt.cc',
--- a/ipc/chromium/src/base/dir_reader_posix.h
+++ b/ipc/chromium/src/base/dir_reader_posix.h
@@ -15,27 +15,27 @@
 // Mac note: OS X has getdirentries, but it only works if we restrict Chrome to
 // 32-bit inodes. There is a getdirentries64 syscall in 10.6, but it's not
 // wrapped and the direct syscall interface is unstable. Using an unstable API
 // seems worse than falling back to enumerating all file descriptors so we will
 // probably never implement this on the Mac.
 
 #if defined(OS_LINUX)
 #include "base/dir_reader_linux.h"
-#elif defined(OS_BSD)
+#elif defined(OS_BSD) && !defined(__GLIBC__)
 #include "base/dir_reader_bsd.h"
 #else
 #include "base/dir_reader_fallback.h"
 #endif
 
 namespace base {
 
 #if defined(OS_LINUX)
 typedef DirReaderLinux DirReaderPosix;
-#elif defined(OS_BSD)
+#elif defined(OS_BSD) && !defined(__GLIBC__)
 typedef DirReaderBSD DirReaderPosix;
 #else
 typedef DirReaderFallback DirReaderPosix;
 #endif
 
 }  // namespace base
 
 #endif // BASE_DIR_READER_POSIX_H_
--- a/ipc/chromium/src/base/platform_thread.h
+++ b/ipc/chromium/src/base/platform_thread.h
@@ -17,17 +17,17 @@
 // constructor can safely "value initialize" using () in the initializer list.
 #if defined(OS_WIN)
 #include <windows.h>
 typedef DWORD PlatformThreadId;
 typedef void* PlatformThreadHandle;  // HANDLE
 #elif defined(OS_POSIX)
 #include <pthread.h>
 typedef pthread_t PlatformThreadHandle;
-#if defined(OS_LINUX) || defined(OS_OPENBSD)
+#if defined(OS_LINUX) || defined(OS_OPENBSD) || defined(__GLIBC__)
 #include <unistd.h>
 typedef pid_t PlatformThreadId;
 #elif defined(OS_BSD)
 #include <sys/types.h>
 typedef lwpid_t PlatformThreadId;
 #elif defined(OS_MACOSX)
 #include <mach/mach.h>
 typedef mach_port_t PlatformThreadId;
--- a/ipc/chromium/src/base/platform_thread_posix.cc
+++ b/ipc/chromium/src/base/platform_thread_posix.cc
@@ -9,26 +9,26 @@
 
 #if defined(OS_MACOSX)
 #include <mach/mach.h>
 #elif defined(OS_NETBSD)
 #include <lwp.h>
 #elif defined(OS_LINUX)
 #include <sys/syscall.h>
 #include <sys/prctl.h>
-#elif defined(OS_FREEBSD)
+#elif defined(OS_FREEBSD) && !defined(__GLIBC__)
 #include <sys/param.h>
 #include <sys/thr.h>
 #endif
 
 #if !defined(OS_MACOSX)
 #include <unistd.h>
 #endif
 
-#if defined(OS_BSD) && !defined(OS_NETBSD)
+#if defined(OS_BSD) && !defined(OS_NETBSD) && !defined(__GLIBC__)
 #include <pthread_np.h>
 #endif
 
 #if defined(OS_MACOSX)
 namespace base {
 void InitThreading();
 }  // namespace
 #endif
@@ -43,32 +43,32 @@ static void* ThreadFunc(void* closure) {
 // static
 PlatformThreadId PlatformThread::CurrentId() {
   // Pthreads doesn't have the concept of a thread ID, so we have to reach down
   // into the kernel.
 #if defined(OS_MACOSX)
   mach_port_t port = mach_thread_self();
   mach_port_deallocate(mach_task_self(), port);
   return port;
+#elif defined(OS_LINUX)
+  return syscall(__NR_gettid);
+#elif defined(OS_OPENBSD) || defined(__GLIBC__)
+  return (intptr_t) (pthread_self());
 #elif defined(OS_NETBSD)
   return _lwp_self();
 #elif defined(OS_DRAGONFLY)
   return lwp_gettid();
 #elif defined(OS_FREEBSD)
 #  if __FreeBSD_version > 900030
     return pthread_getthreadid_np();
 #  else
     long lwpid;
     thr_self(&lwpid);
     return lwpid;
 #  endif
-#elif defined(OS_OPENBSD)
-  return (intptr_t) (pthread_self());
-#elif defined(OS_LINUX)
-  return syscall(__NR_gettid);
 #endif
 }
 
 // static
 void PlatformThread::YieldCurrentThread() {
   sched_yield();
 }
 
@@ -99,22 +99,23 @@ void PlatformThread::SetName(const char*
   if (PlatformThread::CurrentId() == getpid())
     return;
 
   // http://0pointer.de/blog/projects/name-your-threads.html
   // Set the name for the LWP (which gets truncated to 15 characters).
   // Note that glibc also has a 'pthread_setname_np' api, but it may not be
   // available everywhere and it's only benefit over using prctl directly is
   // that it can set the name of threads other than the current thread.
-#if defined(OS_BSD) && !defined(OS_NETBSD)
-  pthread_set_name_np(pthread_self(), name);
+#if defined(OS_LINUX)
+  prctl(PR_SET_NAME, reinterpret_cast<uintptr_t>(name), 0, 0, 0); 
 #elif defined(OS_NETBSD)
   pthread_setname_np(pthread_self(), "%s", (void *)name);
+#elif defined(OS_BSD) && !defined(__GLIBC__)
+  pthread_set_name_np(pthread_self(), name);
 #else
-  prctl(PR_SET_NAME, reinterpret_cast<uintptr_t>(name), 0, 0, 0); 
 #endif
 }
 #endif // !OS_MACOSX
 
 namespace {
 
 bool CreateThread(size_t stack_size, bool joinable,
                   PlatformThread::Delegate* delegate,
--- a/ipc/chromium/src/base/process_util.h
+++ b/ipc/chromium/src/base/process_util.h
@@ -8,17 +8,17 @@
 #ifndef BASE_PROCESS_UTIL_H_
 #define BASE_PROCESS_UTIL_H_
 
 #include "base/basictypes.h"
 
 #if defined(OS_WIN)
 #include <windows.h>
 #include <tlhelp32.h>
-#elif defined(OS_LINUX)
+#elif defined(OS_LINUX) || defined(__GLIBC__)
 #include <dirent.h>
 #include <limits.h>
 #include <sys/types.h>
 #elif defined(OS_MACOSX)
 #include <mach/mach.h>
 #endif
 
 #include <map>
@@ -293,17 +293,17 @@ class NamedProcessIterator {
   // If there's another process that matches the given executable name,
   // returns a const pointer to the corresponding PROCESSENTRY32.
   // If there are no more matching processes, returns NULL.
   // The returned pointer will remain valid until NextProcessEntry()
   // is called again or this NamedProcessIterator goes out of scope.
   const ProcessEntry* NextProcessEntry();
 
  private:
-#if !defined(OS_BSD)
+#if !defined(OS_BSD) || defined(__GLIBC__)
   // Determines whether there's another process (regardless of executable)
   // left in the list of all processes.  Returns true and sets entry_ to
   // that process's info if there is one, false otherwise.
   bool CheckForNextProcess();
 
   bool IncludeEntry();
 
   // Initializes a PROCESSENTRY32 data structure so that it's ready for
@@ -311,26 +311,26 @@ class NamedProcessIterator {
   void InitProcessEntry(ProcessEntry* entry);
 
   std::wstring executable_name_;
 #endif
 
 #if defined(OS_WIN)
   HANDLE snapshot_;
   bool started_iteration_;
-#elif defined(OS_LINUX)
+#elif defined(OS_LINUX) || defined(__GLIBC__)
   DIR *procfs_dir_;
 #elif defined(OS_BSD)
   std::vector<ProcessEntry> content;
   size_t nextEntry;
 #elif defined(OS_MACOSX)
   std::vector<kinfo_proc> kinfo_procs_;
   size_t index_of_kinfo_proc_;
 #endif
-#if !defined(OS_BSD)
+#if !defined(OS_BSD) || defined(__GLIBC__)
   ProcessEntry entry_;
   const ProcessFilter* filter_;
 #endif
 
   DISALLOW_EVIL_CONSTRUCTORS(NamedProcessIterator);
 };
 
 // Working Set (resident) memory usage broken down by
--- a/ipc/chromium/src/build/build_config.h
+++ b/ipc/chromium/src/build/build_config.h
@@ -16,17 +16,17 @@
 
 // A set of macros to use for platform detection.
 #if defined(__APPLE__)
 #define OS_MACOSX 1
 #elif defined(__linux__) || defined(ANDROID)
 #define OS_LINUX 1
 #elif defined(__DragonFly__)
 #define OS_DRAGONFLY 1
-#elif defined(__FreeBSD__)
+#elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
 #define OS_FREEBSD 1
 #elif defined(__NetBSD__)
 #define OS_NETBSD 1
 #elif defined(__OpenBSD__)
 #define OS_OPENBSD 1
 #elif defined(_WIN32)
 #define OS_WIN 1
 #else
--- a/js/ductwork/debugger/Makefile.in
+++ b/js/ductwork/debugger/Makefile.in
@@ -5,20 +5,17 @@
 DEPTH = @DEPTH@
 topsrcdir = @top_srcdir@
 srcdir = @srcdir@
 VPATH = @srcdir@
 relativesrcdir = @relativesrcdir@
 
 include $(DEPTH)/config/autoconf.mk
 
-MODULE_NAME = jsdebugger
-
 LIBXUL_LIBRARY = 1
 EXPORT_LIBRARY = 1
-IS_COMPONENT = 1
 
 EXTRA_DSO_LDOPTS += \
   $(MOZ_COMPONENT_LIBS) \
   $(MOZ_JS_LIBS) \
   $(NULL)
 
 include $(topsrcdir)/config/rules.mk
--- a/js/ipc/JavaScriptParent.cpp
+++ b/js/ipc/JavaScriptParent.cpp
@@ -57,23 +57,23 @@ class CPOWProxyHandler : public BaseProx
     virtual ~CPOWProxyHandler() {}
 
     virtual bool finalizeInBackground(Value priv) MOZ_OVERRIDE {
         return false;
     }
 
     virtual bool preventExtensions(JSContext *cx, HandleObject proxy) MOZ_OVERRIDE;
     virtual bool getPropertyDescriptor(JSContext *cx, HandleObject proxy, HandleId id,
-                                       MutableHandle<PropertyDescriptor> desc,
+                                       MutableHandle<JSPropertyDescriptor> desc,
                                        unsigned flags) MOZ_OVERRIDE;
     virtual bool getOwnPropertyDescriptor(JSContext *cx, HandleObject proxy,
-                                          HandleId id, MutableHandle<PropertyDescriptor> desc,
+                                          HandleId id, MutableHandle<JSPropertyDescriptor> desc,
                                           unsigned flags) MOZ_OVERRIDE;
     virtual bool defineProperty(JSContext *cx, HandleObject proxy, HandleId id,
-                                MutableHandle<PropertyDescriptor> desc) MOZ_OVERRIDE;
+                                MutableHandle<JSPropertyDescriptor> desc) MOZ_OVERRIDE;
     virtual bool getOwnPropertyNames(JSContext *cx, HandleObject proxy,
                                      AutoIdVector &props) MOZ_OVERRIDE;
     virtual bool delete_(JSContext *cx, HandleObject proxy, HandleId id, bool *bp) MOZ_OVERRIDE;
     virtual bool enumerate(JSContext *cx, HandleObject proxy, AutoIdVector &props) MOZ_OVERRIDE;
 
     virtual bool has(JSContext *cx, HandleObject proxy, HandleId id, bool *bp) MOZ_OVERRIDE;
     virtual bool hasOwn(JSContext *cx, HandleObject proxy, HandleId id, bool *bp) MOZ_OVERRIDE;
     virtual bool get(JSContext *cx, HandleObject proxy, HandleObject receiver,
@@ -108,24 +108,24 @@ JavaScriptParent::preventExtensions(JSCo
     if (!CallPreventExtensions(objId, &status))
         return ipcfail(cx);
 
     return ok(cx, status);
 }
 
 bool
 CPOWProxyHandler::getPropertyDescriptor(JSContext *cx, HandleObject proxy, HandleId id,
-                                        MutableHandle<PropertyDescriptor> desc, unsigned flags)
+                                        MutableHandle<JSPropertyDescriptor> desc, unsigned flags)
 {
     return ParentOf(proxy)->getPropertyDescriptor(cx, proxy, id, desc, flags);
 }
 
 bool
 JavaScriptParent::getPropertyDescriptor(JSContext *cx, HandleObject proxy, HandleId id,
-                                        MutableHandle<PropertyDescriptor> desc, unsigned flags)
+                                        MutableHandle<JSPropertyDescriptor> desc, unsigned flags)
 {
     ObjectId objId = idOf(proxy);
 
     nsString idstr;
     if (!convertIdToGeckoString(cx, id, &idstr))
         return false;
 
     ReturnStatus status;
@@ -135,25 +135,25 @@ JavaScriptParent::getPropertyDescriptor(
     if (!ok(cx, status))
         return false;
 
     return toDescriptor(cx, result, desc);
 }
 
 bool
 CPOWProxyHandler::getOwnPropertyDescriptor(JSContext *cx, HandleObject proxy,
-                                           HandleId id, MutableHandle<PropertyDescriptor> desc,
+                                           HandleId id, MutableHandle<JSPropertyDescriptor> desc,
                                            unsigned flags)
 {
     return ParentOf(proxy)->getOwnPropertyDescriptor(cx, proxy, id, desc, flags);
 }
 
 bool
 JavaScriptParent::getOwnPropertyDescriptor(JSContext *cx, HandleObject proxy, HandleId id,
-                                           MutableHandle<PropertyDescriptor> desc, unsigned flags)
+                                           MutableHandle<JSPropertyDescriptor> desc, unsigned flags)
 {
     ObjectId objId = idOf(proxy);
 
     nsString idstr;
     if (!convertIdToGeckoString(cx, id, &idstr))
         return false;
 
     ReturnStatus status;
@@ -163,24 +163,24 @@ JavaScriptParent::getOwnPropertyDescript
     if (!ok(cx, status))
         return false;
 
     return toDescriptor(cx, result, desc);
 }
 
 bool
 CPOWProxyHandler::defineProperty(JSContext *cx, HandleObject proxy, HandleId id,
-                                 MutableHandle<PropertyDescriptor> desc)
+                                 MutableHandle<JSPropertyDescriptor> desc)
 {
     return ParentOf(proxy)->defineProperty(cx, proxy, id, desc);
 }
 
 bool
 JavaScriptParent::defineProperty(JSContext *cx, HandleObject proxy, HandleId id,
-                                 MutableHandle<PropertyDescriptor> desc)
+                                 MutableHandle<JSPropertyDescriptor> desc)
 {
     ObjectId objId = idOf(proxy);
 
     nsString idstr;
     if (!convertIdToGeckoString(cx, id, &idstr))
         return false;
 
     PPropertyDescriptor descriptor;
--- a/js/jsd/Makefile.in
+++ b/js/jsd/Makefile.in
@@ -9,20 +9,18 @@
 DEPTH		= @DEPTH@
 topsrcdir	= @top_srcdir@
 VPATH		= @srcdir@
 srcdir		= @srcdir@
 relativesrcdir  = @relativesrcdir@
 
 include $(DEPTH)/config/autoconf.mk
 
-IS_COMPONENT = 1
 LIBXUL_LIBRARY = 1
 
-MODULE_NAME = JavaScript_Debugger
 EXPORT_LIBRARY = 1
 
 # REQUIRES	= java js
 
 ifdef JS_THREADSAFE
 DEFINES         += -DJS_THREADSAFE
 endif
 
--- a/js/jsd/jsd.h
+++ b/js/jsd/jsd.h
@@ -26,17 +26,16 @@
 #ifdef MOZILLA_CLIENT
 #define JSD_THREADSAFE 1
 /* define JSD_HAS_DANGEROUS_THREAD 1 */
 #define JSD_USE_NSPR_LOCKS 1
 #endif /* MOZILLA_CLIENT */
 
 #include "jstypes.h"
 #include "jsprf.h"
-#include "jsutil.h" /* Added by JSIFY */
 #include "jshash.h" /* Added by JSIFY */
 #include "jsclist.h"
 #include "jsdebug.h"
 #include "jsapi.h"
 #include "jsdbgapi.h"
 #include "jsd_lock.h"
 
 #include <stdio.h>
--- a/js/jsd/jsd_xpc.cpp
+++ b/js/jsd/jsd_xpc.cpp
@@ -1,16 +1,15 @@
 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*-
  * vim: set ts=8 sts=4 et sw=4 tw=99:
  * This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #include "jsdbgapi.h"
-#include "jslock.h"
 #include "jsd_xpc.h"
 
 #include "js/GCAPI.h"
 
 #include "nsIXPConnect.h"
 #include "mozilla/ModuleUtils.h"
 #include "nsIServiceManager.h"
 #include "nsIScriptGlobalObject.h"
--- a/js/jsd/jshash.cpp
+++ b/js/jsd/jshash.cpp
@@ -9,18 +9,20 @@
  */
 
 #include "jshash.h"
 
 #include "mozilla/MathAlgorithms.h"
 
 #include <stdlib.h>
 #include <string.h>
+
 #include "jstypes.h"
-#include "jsutil.h"
+
+#include "js/Utility.h"
 
 using namespace js;
 
 using mozilla::CeilingLog2Size;
 
 /* Compute the number of buckets in ht */
 #define NBUCKETS(ht)    JS_BIT(JS_HASH_BITS - (ht)->shift)
 
--- a/js/public/Value.h
+++ b/js/public/Value.h
@@ -328,30 +328,71 @@ typedef union jsval_layout
     size_t asWord;
     uintptr_t asUIntPtr;
 } JSVAL_ALIGNMENT jsval_layout;
 # endif /* JS_BITS_PER_WORD */
 #endif  /* defined(IS_LITTLE_ENDIAN) */
 
 JS_STATIC_ASSERT(sizeof(jsval_layout) == 8);
 
+/*
+ * For codesize purposes on some platforms, it's important that the
+ * compiler know that JS::Values constructed from constant values can be
+ * folded to constant bit patterns at compile time, rather than
+ * constructed at runtime.  Doing this requires a fair amount of C++11
+ * features, which are not supported on all of our compilers.  Set up
+ * some defines and helper macros in an attempt to confine the ugliness
+ * here, rather than scattering it all about the file.  The important
+ * features are:
+ *
+ * - constexpr;
+ * - defaulted functions;
+ * - C99-style designated initializers.
+ */
+#if defined(__clang__)
+#  if __has_feature(cxx_constexpr) && __has_feature(cxx_defaulted_functions)
+#    define JS_VALUE_IS_CONSTEXPR
+#  endif
+#elif defined(__GNUC__)
+/*
+ * We need 4.5 for defaulted functions, 4.6 for constexpr, 4.7 because 4.6
+ * doesn't understand |(X) { .field = ... }| syntax, and 4.7.3 because
+ * versions prior to that have bugs in the C++ front-end that cause crashes.
+ */
+#  if MOZ_GCC_VERSION_AT_LEAST(4, 7, 3)
+#    define JS_VALUE_IS_CONSTEXPR
+#  endif
+#endif
+
+#if defined(JS_VALUE_IS_CONSTEXPR)
+#  define JS_RETURN_LAYOUT_FROM_BITS(BITS) \
+    return (jsval_layout) { .asBits = (BITS) }
+#  define JS_VALUE_CONSTEXPR MOZ_CONSTEXPR
+#  define JS_VALUE_CONSTEXPR_VAR MOZ_CONSTEXPR_VAR
+#else
+#  define JS_RETURN_LAYOUT_FROM_BITS(BITS) \
+    jsval_layout l;                        \
+    l.asBits = (BITS);                     \
+    return l;
+#  define JS_VALUE_CONSTEXPR
+#  define JS_VALUE_CONSTEXPR_VAR const
+#endif
+
 #if JS_BITS_PER_WORD == 32
 
 /*
  * N.B. GCC, in some but not all cases, chooses to emit signed comparison of
  * JSValueTag even though its underlying type has been forced to be uint32_t.
  * Thus, all comparisons should explicitly cast operands to uint32_t.
  */
 
-static inline jsval_layout
+static inline JS_VALUE_CONSTEXPR jsval_layout
 BUILD_JSVAL(JSValueTag tag, uint32_t payload)
 {
-    jsval_layout l;
-    l.asBits = (((uint64_t)(uint32_t)tag) << 32) | payload;
-    return l;
+    JS_RETURN_LAYOUT_FROM_BITS((((uint64_t)(uint32_t)tag) << 32) | payload);
 }
 
 static inline bool
 JSVAL_IS_DOUBLE_IMPL(jsval_layout l)
 {
     return (uint32_t)l.s.tag <= (uint32_t)JSVAL_TAG_CLEAR;
 }
 
@@ -371,23 +412,27 @@ JSVAL_IS_INT32_IMPL(jsval_layout l)
 }
 
 static inline int32_t
 JSVAL_TO_INT32_IMPL(jsval_layout l)
 {
     return l.s.payload.i32;
 }
 
-static inline jsval_layout
+static inline JS_VALUE_CONSTEXPR jsval_layout
 INT32_TO_JSVAL_IMPL(int32_t i)
 {
+#if defined(JS_VALUE_IS_CONSTEXPR)
+    return BUILD_JSVAL(JSVAL_TAG_INT32, i);
+#else
     jsval_layout l;
     l.s.tag = JSVAL_TAG_INT32;
     l.s.payload.i32 = i;
     return l;
+#endif
 }
 
 static inline bool
 JSVAL_IS_NUMBER_IMPL(jsval_layout l)
 {
     JSValueTag tag = l.s.tag;
     MOZ_ASSERT(tag != JSVAL_TAG_CLEAR);
     return (uint32_t)tag <= (uint32_t)JSVAL_UPPER_INCL_TAG_OF_NUMBER_SET;
@@ -564,22 +609,20 @@ JSVAL_EXTRACT_NON_DOUBLE_TYPE_IMPL(jsval
 {
     uint32_t type = l.s.tag & 0xF;
     MOZ_ASSERT(type > JSVAL_TYPE_DOUBLE);
     return (JSValueType)type;
 }
 
 #elif JS_BITS_PER_WORD == 64
 
-static inline jsval_layout
+static inline JS_VALUE_CONSTEXPR jsval_layout
 BUILD_JSVAL(JSValueTag tag, uint64_t payload)
 {
-    jsval_layout l;
-    l.asBits = (((uint64_t)(uint32_t)tag) << JSVAL_TAG_SHIFT) | payload;
-    return l;
+    JS_RETURN_LAYOUT_FROM_BITS((((uint64_t)(uint32_t)tag) << JSVAL_TAG_SHIFT) | payload);
 }
 
 static inline bool
 JSVAL_IS_DOUBLE_IMPL(jsval_layout l)
 {
     return l.asBits <= JSVAL_SHIFTED_TAG_MAX_DOUBLE;
 }
 
@@ -599,22 +642,20 @@ JSVAL_IS_INT32_IMPL(jsval_layout l)
 }
 
 static inline int32_t
 JSVAL_TO_INT32_IMPL(jsval_layout l)
 {
     return (int32_t)l.asBits;
 }
 
-static inline jsval_layout
+static inline JS_VALUE_CONSTEXPR jsval_layout
 INT32_TO_JSVAL_IMPL(int32_t i32)
 {
-    jsval_layout l;
-    l.asBits = ((uint64_t)(uint32_t)i32) | JSVAL_SHIFTED_TAG_INT32;
-    return l;
+    JS_RETURN_LAYOUT_FROM_BITS(((uint64_t)(uint32_t)i32) | JSVAL_SHIFTED_TAG_INT32);
 }
 
 static inline bool
 JSVAL_IS_NUMBER_IMPL(jsval_layout l)
 {
     return l.asBits < JSVAL_UPPER_EXCL_SHIFTED_TAG_OF_NUMBER_SET;
 }
 
@@ -807,20 +848,22 @@ JS_CANONICALIZE_NAN(double d)
         jsval_layout l;
         l.asBits = 0x7FF8000000000000LL;
         return l.asDouble;
     }
     return d;
 }
 
 static inline jsval_layout JSVAL_TO_IMPL(JS::Value v);
-static inline JS::Value IMPL_TO_JSVAL(jsval_layout l);
+static inline JS_VALUE_CONSTEXPR JS::Value IMPL_TO_JSVAL(jsval_layout l);
 
 namespace JS {
 
+static inline JS_VALUE_CONSTEXPR JS::Value UndefinedValue();
+
 /*
  * JS::Value is the interface for a single JavaScript Engine value.  A few
  * general notes on JS::Value:
  *
  * - JS::Value has setX() and isX() members for X in
  *
  *     { Int32, Double, String, Boolean, Undefined, Null, Object, Magic }
  *
@@ -853,16 +896,20 @@ namespace JS {
  */
 class Value
 {
   public:
     /*
      * N.B. the default constructor leaves Value unitialized. Adding a default
      * constructor prevents Value from being stored in a union.
      */
+#if defined(JS_VALUE_IS_CONSTEXPR)
+    Value() = default;
+    Value(const Value& v) = default;
+#endif
 
     /*** Mutators ***/
 
     void setNull() {
         data.asBits = BUILD_JSVAL(JSVAL_TAG_NULL, 0).asBits;
     }
 
     void setUndefined() {
@@ -1157,25 +1204,30 @@ class Value
   // (bug 689101); the same is true for SPARC as well (bug 737344).  More
   // precisely, we don't want Value return values compiled as out params.
   private:
 #endif
 
     jsval_layout data;
 
   private:
+#if defined(JS_VALUE_IS_CONSTEXPR)
+    JS_VALUE_CONSTEXPR Value(jsval_layout layout) : data(layout) {}
+#endif
+
     void staticAssertions() {
         JS_STATIC_ASSERT(sizeof(JSValueType) == 1);
         JS_STATIC_ASSERT(sizeof(JSValueTag) == 4);
         JS_STATIC_ASSERT(sizeof(JSWhyMagic) <= 4);
         JS_STATIC_ASSERT(sizeof(Value) == 8);
     }
 
     friend jsval_layout (::JSVAL_TO_IMPL)(Value);
-    friend Value (::IMPL_TO_JSVAL)(jsval_layout l);
+    friend Value JS_VALUE_CONSTEXPR (::IMPL_TO_JSVAL)(jsval_layout l);
+    friend Value JS_VALUE_CONSTEXPR (JS::UndefinedValue)();
 };
 
 inline bool
 IsPoisonedValue(const Value &v)
 {
     if (v.isString())
         return IsPoisonedPtr(v.toString());
     if (v.isObject())
@@ -1188,22 +1240,26 @@ IsPoisonedValue(const Value &v)
 static inline Value
 NullValue()
 {
     Value v;
     v.setNull();
     return v;
 }
 
-static inline Value
+static inline JS_VALUE_CONSTEXPR Value
 UndefinedValue()
 {
-    Value v;
+#if defined(JS_VALUE_IS_CONSTEXPR)
+    return Value(BUILD_JSVAL(JSVAL_TAG_UNDEFINED, 0));
+#else
+    JS::Value v;
     v.setUndefined();
     return v;
+#endif
 }
 
 static inline Value
 Int32Value(int32_t i32)
 {
     Value v;
     v.setInt32(i32);
     return v;
@@ -1603,22 +1659,26 @@ class RootedBase<JS::Value> : public Mut
 } // namespace js
 
 inline jsval_layout
 JSVAL_TO_IMPL(JS::Value v)
 {
     return v.data;
 }
 
-inline JS::Value
+inline JS_VALUE_CONSTEXPR JS::Value
 IMPL_TO_JSVAL(jsval_layout l)
 {
+#if defined(JS_VALUE_IS_CONSTEXPR)
+    return JS::Value(l);
+#else
     JS::Value v;
     v.data = l;
     return v;
+#endif
 }
 
 namespace JS {
 
 #ifndef __GNUC__
 /*
  * The default assignment operator for |struct C| has the signature:
  *
@@ -1686,17 +1746,17 @@ JSVAL_IS_INT(jsval v)
 
 static inline int32_t
 JSVAL_TO_INT(jsval v)
 {
     MOZ_ASSERT(JSVAL_IS_INT(v));
     return JSVAL_TO_INT32_IMPL(JSVAL_TO_IMPL(v));
 }
 
-static inline jsval
+static inline JS_VALUE_CONSTEXPR jsval
 INT_TO_JSVAL(int32_t i)
 {
     return IMPL_TO_JSVAL(INT32_TO_JSVAL_IMPL(i));
 }
 
 static inline bool
 JSVAL_IS_DOUBLE(jsval v)
 {
@@ -1707,39 +1767,45 @@ static inline double
 JSVAL_TO_DOUBLE(jsval v)
 {
     jsval_layout l;
     MOZ_ASSERT(JSVAL_IS_DOUBLE(v));
     l = JSVAL_TO_IMPL(v);
     return l.asDouble;
 }
 
-static inline jsval
+static inline JS_VALUE_CONSTEXPR jsval
 DOUBLE_TO_JSVAL(double d)
 {
     /*
      * This is a manually inlined version of:
      *    d = JS_CANONICALIZE_NAN(d);
      *    return IMPL_TO_JSVAL(DOUBLE_TO_JSVAL_IMPL(d));
      * because GCC from XCode 3.1.4 miscompiles the above code.
      */
+#if defined(JS_VALUE_IS_CONSTEXPR)
+    return IMPL_TO_JSVAL(MOZ_UNLIKELY(d != d)
+                         ? (jsval_layout) { .asBits = 0x7FF8000000000000LL }
+                         : (jsval_layout) { .asDouble = d });
+#else
     jsval_layout l;
     if (MOZ_UNLIKELY(d != d))
         l.asBits = 0x7FF8000000000000LL;
     else
         l.asDouble = d;
     return IMPL_TO_JSVAL(l);
+#endif
 }
 
-static inline jsval
+static inline JS_VALUE_CONSTEXPR jsval
 UINT_TO_JSVAL(uint32_t i)
 {
-    if (i <= JSVAL_INT_MAX)
-        return INT_TO_JSVAL((int32_t)i);
-    return DOUBLE_TO_JSVAL((double)i);
+    return (i <= JSVAL_INT_MAX
+            ? INT_TO_JSVAL((int32_t)i)
+            : DOUBLE_TO_JSVAL((double)i));
 }
 
 static inline bool
 JSVAL_IS_NUMBER(jsval v)
 {
     return JSVAL_IS_NUMBER_IMPL(JSVAL_TO_IMPL(v));
 }
 
@@ -1825,9 +1891,12 @@ PRIVATE_TO_JSVAL(void *ptr)
 
 static inline void *
 JSVAL_TO_PRIVATE(jsval v)
 {
     MOZ_ASSERT(JSVAL_IS_DOUBLE(v));
     return JSVAL_TO_PRIVATE_PTR_IMPL(JSVAL_TO_IMPL(v));
 }
 
+#undef JS_VALUE_IS_CONSTEXPR
+#undef JS_RETURN_LAYOUT_FROM_BITS
+
 #endif /* js_Value_h */
--- a/js/src/TraceLogging.cpp
+++ b/js/src/TraceLogging.cpp
@@ -70,22 +70,22 @@ const char* const TraceLogging::type_nam
     "start,ion_compile",
     "stop,ion_compile",
     "start,yarr_jit_execute",
     "stop,yarr_jit_execute",
     "start,gc",
     "stop,gc",
     "start,minor_gc",
     "stop,minor_gc",
-    "start,parser,script",
-    "stop,parser,script",
-    "start,parser,lazy",
-    "stop,parser,lazy",
-    "start,parser,function",
-    "stop,parser,function",
+    "start,parser_script",
+    "stop,parser_script",
+    "start,parser_lazy",
+    "stop,parser_lazy",
+    "start,parser_function",
+    "stop,parser_function",
     "info,engine,interpreter",
     "info,engine,baseline",
     "info,engine,ionmonkey"
 };
 TraceLogging* TraceLogging::_defaultLogger = NULL;
 
 TraceLogging::TraceLogging()
   : loggingTime(0),
--- a/js/src/assembler/wtf/SegmentedVector.h
+++ b/js/src/assembler/wtf/SegmentedVector.h
@@ -24,17 +24,16 @@
  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 
 #ifndef assembler_wtf_SegmentedVector_h
 #define assembler_wtf_SegmentedVector_h
 
-#include "jsprvtd.h"
 #include "js/Vector.h"
 
 namespace WTF {
 
     // An iterator for SegmentedVector. It supports only the pre ++ operator
     template <typename T, size_t SegmentSize> class SegmentedVector;
     template <typename T, size_t SegmentSize> class SegmentedVectorIterator {
     private:
--- a/js/src/builtin/RegExp.h
+++ b/js/src/builtin/RegExp.h
@@ -2,18 +2,16 @@
  * vim: set ts=8 sts=4 et sw=4 tw=99:
  * 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 builtin_RegExp_h
 #define builtin_RegExp_h
 
-#include "jsprvtd.h"
-
 #include "vm/MatchPairs.h"
 #include "vm/RegExpObject.h"
 
 JSObject *
 js_InitRegExpClass(JSContext *cx, js::HandleObject obj);
 
 /*
  * The following builtin natives are extern'd for pointer comparison in
--- a/js/src/config/config.mk
+++ b/js/src/config/config.mk
@@ -230,19 +230,20 @@ endif
 #
 _ENABLE_PIC=1
 
 # Determine if module being compiled is destined
 # to be merged into libxul
 
 ifdef LIBXUL_LIBRARY
 ifdef IS_COMPONENT
-ifndef MODULE_NAME
-$(error Component makefile does not specify MODULE_NAME.)
+$(error IS_COMPONENT is set, but is not compatible with LIBXUL_LIBRARY)
 endif
+ifdef MODULE_NAME
+$(error MODULE_NAME is $(MODULE_NAME) but MODULE_NAME and LIBXUL_LIBRARY are not compatible)
 endif
 ifdef FORCE_STATIC_LIB
 $(error Makefile sets FORCE_STATIC_LIB which was already implied by LIBXUL_LIBRARY)
 endif
 FORCE_STATIC_LIB=1
 ifneq ($(SHORT_LIBNAME),)
 $(error SHORT_LIBNAME is $(SHORT_LIBNAME) but SHORT_LIBNAME is not compatable with LIBXUL_LIBRARY)
 endif
new file mode 100644
--- /dev/null
+++ b/js/src/config/rebuild_check.py
@@ -0,0 +1,30 @@
+# 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/.
+
+import os
+
+def mtime(path):
+    return os.stat(path).st_mtime
+
+def rebuild_check(args):
+    target = args[0]
+    deps = args[1:]
+    if not os.path.exists(target):
+        print target
+        return
+    t = mtime(target)
+
+    newer = []
+    for dep in deps:
+        if mtime(dep) > t:
+            newer.append(dep)
+
+    if newer:
+        print 'Rebuilding %s because %s changed' % (target, ', '.join(newer))
+    else:
+        print 'Rebuilding %s for an unknown reason' % target
+
+if __name__ == '__main__':
+    import sys
+    rebuild_check(sys.argv[1:])
--- a/js/src/config/rules.mk
+++ b/js/src/config/rules.mk
@@ -86,17 +86,25 @@ endif
 endif
 endif
 
 ifdef SDK_HEADERS
 _EXTRA_EXPORTS := $(filter-out $(EXPORTS),$(SDK_HEADERS))
 EXPORTS += $(_EXTRA_EXPORTS)
 endif
 
-REPORT_BUILD = $(info $(notdir $<))
+ifdef REBUILD_CHECK
+ifdef .PYMAKE
+REPORT_BUILD = @%rebuild_check rebuild_check $@ $^
+else
+REPORT_BUILD = $(info $(shell $(PYTHON) $(MOZILLA_DIR)/config/rebuild_check.py $@ $^))
+endif
+else
+REPORT_BUILD = $(info $(notdir $@))
+endif
 
 ifeq ($(OS_ARCH),OS2)
 EXEC			=
 else
 EXEC			= exec
 endif
 
 # Don't copy xulrunner files at install time, when using system xulrunner
@@ -862,16 +870,17 @@ alltags:
 	$(RM) TAGS
 	find $(topsrcdir) -name dist -prune -o \( -name '*.[hc]' -o -name '*.cp' -o -name '*.cpp' -o -name '*.idl' \) -print | $(TAG_PROGRAM)
 
 #
 # PROGRAM = Foo
 # creates OBJS, links with LIBS to create Foo
 #
 $(PROGRAM): $(PROGOBJS) $(EXTRA_DEPS) $(EXE_DEF_FILE) $(RESFILE) $(GLOBAL_DEPS)
+	$(REPORT_BUILD)
 	@$(RM) $@.manifest
 ifeq (_WINNT,$(GNU_CC)_$(OS_ARCH))
 	$(EXPAND_LD) -NOLOGO -OUT:$@ -PDB:$(LINK_PDBFILE) $(WIN32_EXE_LDFLAGS) $(LDFLAGS) $(MOZ_GLUE_PROGRAM_LDFLAGS) $(PROGOBJS) $(RESFILE) $(LIBS) $(EXTRA_LIBS) $(OS_LIBS)
 ifdef MSMANIFEST_TOOL
 	@if test -f $@.manifest; then \
 		if test -f "$(srcdir)/$@.manifest"; then \
 			echo "Embedding manifest from $(srcdir)/$@.manifest and $@.manifest"; \
 			mt.exe -NOLOGO -MANIFEST "$(win_srcdir)/$@.manifest" $@.manifest -OUTPUTRESOURCE:$@\;1; \
@@ -897,16 +906,17 @@ endif # WINNT && !GNU_CC
 ifdef ENABLE_STRIP
 	$(STRIP) $@
 endif
 ifdef MOZ_POST_PROGRAM_COMMAND
 	$(MOZ_POST_PROGRAM_COMMAND) $@
 endif
 
 $(HOST_PROGRAM): $(HOST_PROGOBJS) $(HOST_LIBS_DEPS) $(HOST_EXTRA_DEPS) $(GLOBAL_DEPS)
+	$(REPORT_BUILD)
 ifeq (_WINNT,$(GNU_CC)_$(HOST_OS_ARCH))
 	$(HOST_LD) -NOLOGO -OUT:$@ -PDB:$(HOST_PDBFILE) $(HOST_OBJS) $(WIN32_EXE_LDFLAGS) $(HOST_LDFLAGS) $(HOST_LIBS) $(HOST_EXTRA_LIBS)
 ifdef MSMANIFEST_TOOL
 	@if test -f $@.manifest; then \
 		if test -f "$(srcdir)/$@.manifest"; then \
 			echo "Embedding manifest from $(srcdir)/$@.manifest and $@.manifest"; \
 			mt.exe -NOLOGO -MANIFEST "$(win_srcdir)/$@.manifest" $@.manifest -OUTPUTRESOURCE:$@\;1; \
 		else \
@@ -930,16 +940,17 @@ endif
 # This is an attempt to support generation of multiple binaries
 # in one directory, it assumes everything to compile Foo is in
 # Foo.o (from either Foo.c or Foo.cpp).
 #
 # SIMPLE_PROGRAMS = Foo Bar
 # creates Foo.o Bar.o, links with LIBS to create Foo, Bar.
 #
 $(SIMPLE_PROGRAMS): %$(BIN_SUFFIX): %.$(OBJ_SUFFIX) $(EXTRA_DEPS) $(GLOBAL_DEPS)
+	$(REPORT_BUILD)
 ifeq (_WINNT,$(GNU_CC)_$(OS_ARCH))
 	$(EXPAND_LD) -nologo -out:$@ -pdb:$(LINK_PDBFILE) $< $(WIN32_EXE_LDFLAGS) $(LDFLAGS) $(MOZ_GLUE_PROGRAM_LDFLAGS) $(LIBS) $(EXTRA_LIBS) $(OS_LIBS)
 ifdef MSMANIFEST_TOOL
 	@if test -f $@.manifest; then \
 		mt.exe -NOLOGO -MANIFEST $@.manifest -OUTPUTRESOURCE:$@\;1; \
 		rm -f $@.manifest; \
 	fi
 endif	# MSVC with manifest tool
@@ -951,38 +962,41 @@ endif # WINNT && !GNU_CC
 ifdef ENABLE_STRIP
 	$(STRIP) $@
 endif
 ifdef MOZ_POST_PROGRAM_COMMAND
 	$(MOZ_POST_PROGRAM_COMMAND) $@
 endif
 
 $(HOST_SIMPLE_PROGRAMS): host_%$(HOST_BIN_SUFFIX): host_%.$(OBJ_SUFFIX) $(HOST_LIBS_DEPS) $(HOST_EXTRA_DEPS) $(GLOBAL_DEPS)
+	$(REPORT_BUILD)
 ifeq (WINNT_,$(HOST_OS_ARCH)_$(GNU_CC))
 	$(HOST_LD) -NOLOGO -OUT:$@ -PDB:$(HOST_PDBFILE) $< $(WIN32_EXE_LDFLAGS) $(HOST_LIBS) $(HOST_EXTRA_LIBS)
 else
 ifneq (,$(HOST_CPPSRCS)$(USE_HOST_CXX))
 	$(HOST_CXX) $(HOST_OUTOPTION)$@ $(HOST_CXXFLAGS) $(INCLUDES) $< $(HOST_LIBS) $(HOST_EXTRA_LIBS)
 else
 	$(HOST_CC) $(HOST_OUTOPTION)$@ $(HOST_CFLAGS) $(INCLUDES) $< $(HOST_LIBS) $(HOST_EXTRA_LIBS)
 endif
 endif
 
 ifdef DTRACE_PROBE_OBJ
 EXTRA_DEPS += $(DTRACE_PROBE_OBJ)
 OBJS += $(DTRACE_PROBE_OBJ)
 endif
 
 $(filter %.$(LIB_SUFFIX),$(LIBRARY)): $(OBJS) $(LOBJS) $(EXTRA_DEPS) $(GLOBAL_DEPS)
+	$(REPORT_BUILD)
 	$(RM) $(LIBRARY)
 	$(EXPAND_AR) $(AR_FLAGS) $(OBJS) $(LOBJS) $(SHARED_LIBRARY_LIBS)
 	$(RANLIB) $@
 
 $(filter-out %.$(LIB_SUFFIX),$(LIBRARY)): $(filter %.$(LIB_SUFFIX),$(LIBRARY)) $(OBJS) $(LOBJS) $(EXTRA_DEPS) $(GLOBAL_DEPS)
 # When we only build a library descriptor, blow out any existing library
+	$(REPORT_BUILD)
 	$(if $(filter %.$(LIB_SUFFIX),$(LIBRARY)),,$(RM) $(REAL_LIBRARY) $(EXPORT_LIBRARY:%=%/$(REAL_LIBRARY)))
 	$(EXPAND_LIBS_GEN) -o $@ $(OBJS) $(LOBJS) $(SHARED_LIBRARY_LIBS)
 
 ifeq ($(OS_ARCH),WINNT)
 # Import libraries are created by the rules creating shared libraries.
 # The rules to copy them to $(DIST)/lib depend on $(IMPORT_LIBRARY),
 # but make will happily consider the import library before it is refreshed
 # when rebuilding the corresponding shared library. Defining an empty recipe
@@ -999,22 +1013,24 @@ ifeq ($(OS_ARCH),OS2)
 	echo PROTMODE >> $@
 	echo CODE    LOADONCALL MOVEABLE DISCARDABLE >> $@
 	echo DATA    PRELOAD MOVEABLE MULTIPLE NONSHARED >> $@
 	echo EXPORTS >> $@
 
 	$(ADD_TO_DEF_FILE)
 
 $(IMPORT_LIBRARY): $(SHARED_LIBRARY)
+	$(REPORT_BUILD)
 	$(RM) $@
 	$(IMPLIB) $@ $^
 	$(RANLIB) $@
 endif # OS/2
 
 $(HOST_LIBRARY): $(HOST_OBJS) Makefile
+	$(REPORT_BUILD)
 	$(RM) $@
 	$(HOST_AR) $(HOST_AR_FLAGS) $(HOST_OBJS)
 	$(HOST_RANLIB) $@
 
 ifdef HAVE_DTRACE
 ifndef XP_MACOSX
 ifdef DTRACE_PROBE_OBJ
 ifndef DTRACE_LIB_DEPENDENT
@@ -1027,17 +1043,17 @@ endif
 endif
 
 # On Darwin (Mac OS X), dwarf2 debugging uses debug info left in .o files,
 # so instead of deleting .o files after repacking them into a dylib, we make
 # symlinks back to the originals. The symlinks are a no-op for stabs debugging,
 # so no need to conditionalize on OS version or debugging format.
 
 $(SHARED_LIBRARY): $(OBJS) $(LOBJS) $(DEF_FILE) $(RESFILE) $(LIBRARY) $(EXTRA_DEPS) $(GLOBAL_DEPS)
-	$(info $(notdir $@))
+	$(REPORT_BUILD)
 ifndef INCREMENTAL_LINKER
 	$(RM) $@
 endif
 ifdef DTRACE_LIB_DEPENDENT
 ifndef XP_MACOSX
 	dtrace -G -C -s $(MOZILLA_DTRACE_SRC) -o  $(DTRACE_PROBE_OBJ) $(shell $(EXPAND_LIBS) $(MOZILLA_PROBE_LIBS))
 endif
 	$(EXPAND_MKSHLIB) $(SHLIB_LDSTARTFILE) $(OBJS) $(LOBJS) $(SUB_SHLOBJS) $(DTRACE_PROBE_OBJ) $(MOZILLA_PROBE_LIBS) $(RESFILE) $(LDFLAGS) $(WRAP_LDFLAGS) $(SHARED_LIBRARY_LIBS) $(EXTRA_DSO_LDOPTS) $(MOZ_GLUE_LDFLAGS) $(OS_LIBS) $(EXTRA_LIBS) $(DEF_FILE) $(SHLIB_LDENDFILE) $(if $(LIB_IS_C_ONLY),,$(STLPORT_LIBS))
@@ -1125,32 +1141,37 @@ endef
 	$(REPORT_BUILD)
 	@$(MAKE_DEPS_AUTO_CC)
 	$(ELOG) $(CC) $(OUTOPTION)$@ -c $(COMPILE_CFLAGS) $(TARGET_LOCAL_INCLUDES) $(_VPATH_SRCS)
 
 # DEFINES and ACDEFINES are needed here to enable conditional compilation of Q_OBJECTs:
 # 'moc' only knows about #defines it gets on the command line (-D...), not in
 # included headers like mozilla-config.h
 moc_%.cpp: %.h
+	$(REPORT_BUILD)
 	$(ELOG) $(MOC) $(DEFINES) $(ACDEFINES) $< $(OUTOPTION)$@
 
 moc_%.cc: %.cc
+	$(REPORT_BUILD)
 	$(ELOG) $(MOC) $(DEFINES) $(ACDEFINES) $(_VPATH_SRCS:.cc=.h) $(OUTOPTION)$@
 
 qrc_%.cpp: %.qrc
+	$(REPORT_BUILD)
 	$(ELOG) $(RCC) -name $* $< $(OUTOPTION)$@
 
 ifdef ASFILES
 # The AS_DASH_C_FLAG is needed cause not all assemblers (Solaris) accept
 # a '-c' flag.
 $(ASOBJS):
+	$(REPORT_BUILD)
 	$(AS) $(ASOUTOPTION)$@ $(ASFLAGS) $(AS_DASH_C_FLAG) $(_VPATH_SRCS)
 endif
 
 $(SOBJS):
+	$(REPORT_BUILD)
 	$(AS) -o $@ $(ASFLAGS) $(LOCAL_INCLUDES) $(TARGET_LOCAL_INCLUDES) -c $<
 
 $(CPPOBJS):
 	$(REPORT_BUILD)
 	@$(MAKE_DEPS_AUTO_CXX)
 	$(ELOG) $(CCC) $(OUTOPTION)$@ -c $(COMPILE_CXXFLAGS) $(TARGET_LOCAL_INCLUDES) $(_VPATH_SRCS)
 
 $(CMMOBJS):
@@ -1159,37 +1180,45 @@ endif
 	$(ELOG) $(CCC) -o $@ -c $(COMPILE_CXXFLAGS) $(COMPILE_CMMFLAGS) $(TARGET_LOCAL_INCLUDES) $(_VPATH_SRCS)
 
 $(CMOBJS):
 	$(REPORT_BUILD)
 	@$(MAKE_DEPS_AUTO_CC)
 	$(ELOG) $(CC) -o $@ -c $(COMPILE_CFLAGS) $(COMPILE_CMFLAGS) $(TARGET_LOCAL_INCLUDES) $(_VPATH_SRCS)
 
 %.s: %.cpp $(call mkdir_deps,$(MDDEPDIR))
+	$(REPORT_BUILD)
 	$(CCC) -S $(COMPILE_CXXFLAGS) $(TARGET_LOCAL_INCLUDES) $(_VPATH_SRCS)
 
 %.s: %.cc $(call mkdir_deps,$(MDDEPDIR))
+	$(REPORT_BUILD)
 	$(CCC) -S $(COMPILE_CXXFLAGS) $(TARGET_LOCAL_INCLUDES) $(_VPATH_SRCS)
 
 %.s: %.c $(call mkdir_deps,$(MDDEPDIR))
+	$(REPORT_BUILD)
 	$(CC) -S $(COMPILE_CFLAGS) $(TARGET_LOCAL_INCLUDES) $(_VPATH_SRCS)
 
 %.i: %.cpp $(call mkdir_deps,$(MDDEPDIR))
+	$(REPORT_BUILD)
 	$(CCC) -C -E $(COMPILE_CXXFLAGS) $(TARGET_LOCAL_INCLUDES) $(_VPATH_SRCS) > $*.i
 
 %.i: %.cc $(call mkdir_deps,$(MDDEPDIR))
+	$(REPORT_BUILD)
 	$(CCC) -C -E $(COMPILE_CXXFLAGS) $(TARGET_LOCAL_INCLUDES) $(_VPATH_SRCS) > $*.i
 
 %.i: %.c $(call mkdir_deps,$(MDDEPDIR))
+	$(REPORT_BUILD)
 	$(CC) -C -E $(COMPILE_CFLAGS) $(TARGET_LOCAL_INCLUDES) $(_VPATH_SRCS) > $*.i
 
 %.i: %.mm $(call mkdir_deps,$(MDDEPDIR))
+	$(REPORT_BUILD)
 	$(CCC) -C -E $(COMPILE_CXXFLAGS) $(COMPILE_CMMFLAGS) $(TARGET_LOCAL_INCLUDES) $(_VPATH_SRCS) > $*.i
 
 %.res: %.rc
+	$(REPORT_BUILD)
 	@echo Creating Resource file: $@
 ifeq ($(OS_ARCH),OS2)
 	$(RC) $(RCFLAGS:-D%=-d %) -i $(subst /,\,$(srcdir)) -r $< $@
 else
 ifdef GNU_CC
 	$(RC) $(RCFLAGS) $(filter-out -U%,$(DEFINES)) $(INCLUDES:-I%=--include-dir %) $(OUTOPTION)$@ $(_VPATH_SRCS)
 else
 	$(RC) $(RCFLAGS) -r $(DEFINES) $(INCLUDES) $(OUTOPTION)$@ $(_VPATH_SRCS)
@@ -1254,20 +1283,22 @@ else
 _JAVA_CLASSPATH = .
 endif
 
 _JAVA_DIR = _java
 $(_JAVA_DIR)::
 	$(NSINSTALL) -D $@
 
 $(_JAVA_DIR)/%.class: %.java $(GLOBAL_DEPS) $(_JAVA_DIR)
+	$(REPORT_BUILD)
 	$(JAVAC) $(JAVAC_FLAGS) -classpath $(_JAVA_CLASSPATH) \
 			-sourcepath $(_JAVA_SOURCEPATH) -d $(_JAVA_DIR) $(_VPATH_SRCS)
 
 $(JAVA_LIBRARY): $(addprefix $(_JAVA_DIR)/,$(JAVA_SRCS:.java=.class)) $(GLOBAL_DEPS)
+	$(REPORT_BUILD)
 	$(JAR) cf $@ -C $(_JAVA_DIR) .
 
 GARBAGE_DIRS += $(_JAVA_DIR)
 
 ###############################################################################
 # Update Files Managed by Build Backend
 ###############################################################################
 
new file mode 100644
--- /dev/null
+++ b/js/src/ds/IdValuePair.h
@@ -0,0 +1,27 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*-
+ * vim: set ts=8 sts=4 et sw=4 tw=99:
+ * 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 ds_IdValuePair_h
+#define ds_IdValuePair_h
+
+#include "jsapi.h"
+
+namespace js {
+
+struct IdValuePair
+{
+    jsid id;
+    Value value;
+
+    IdValuePair() {}
+    IdValuePair(jsid idArg)
+      : id(idArg), value(UndefinedValue())
+    {}
+};
+
+} /* namespace js */
+
+#endif /* ds_IdValuePair_h */
--- a/js/src/frontend/BytecodeEmitter.h
+++ b/js/src/frontend/BytecodeEmitter.h
@@ -19,16 +19,19 @@
 #include "frontend/ParseMaps.h"
 #include "frontend/SharedContext.h"
 #include "frontend/SourceNotes.h"
 #include "vm/ScopeObject.h"
 
 namespace js {
 namespace frontend {
 
+template <typename ParseHandler>
+class Parser;
+
 struct CGTryNoteList {
     Vector<JSTryNote> list;
     CGTryNoteList(ExclusiveContext *cx) : list(cx) {}
 
     bool append(JSTryNoteKind kind, unsigned stackDepth, size_t start, size_t end);
     size_t length() const { return list.length(); }
     void finish(TryNoteArray *array);
 };
--- a/js/src/frontend/FoldConstants.h
+++ b/js/src/frontend/FoldConstants.h
@@ -2,18 +2,16 @@
  * vim: set ts=8 sts=4 et sw=4 tw=99:
  * 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 frontend_FoldConstants_h
 #define frontend_FoldConstants_h
 
-#include "jsprvtd.h"
-
 #include "frontend/SyntaxParseHandler.h"
 
 namespace js {
 namespace frontend {
 
 // Perform constant folding on the given AST. For example, the program
 // `print(2 + 2)` would become `print(4)`.
 //
--- a/js/src/frontend/ParseMaps.h
+++ b/js/src/frontend/ParseMaps.h
@@ -5,24 +5,29 @@
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #ifndef frontend_ParseMaps_h
 #define frontend_ParseMaps_h
 
 #include "mozilla/Attributes.h"
 #include "mozilla/TypeTraits.h"
 
-#include "jsprvtd.h"
-
 #include "ds/InlineMap.h"
 #include "gc/Barrier.h"
 #include "js/HashTable.h"
 #include "js/Vector.h"
 
+class JSAtom;
+
+typedef uintptr_t jsatomid;
+
 namespace js {
+
+class LifoAlloc;
+
 namespace frontend {
 
 class DefinitionSingle;
 class DefinitionList;
 
 typedef InlineMap<JSAtom *, jsatomid, 24> AtomIndexMap;
 typedef InlineMap<JSAtom *, DefinitionSingle, 24> AtomDefnMap;
 typedef InlineMap<JSAtom *, DefinitionList, 24> AtomDefnListMap;
--- a/js/src/frontend/ParseNode.h
+++ b/js/src/frontend/ParseNode.h
@@ -16,16 +16,18 @@
 
 namespace js {
 namespace frontend {
 
 template <typename ParseHandler>
 struct ParseContext;
 
 class FullParseHandler;
+class FunctionBox;
+class ObjectBox;
 
 /*
  * Indicates a location in the stack that an upvar value can be retrieved from
  * as a two tuple of (level, slot).
  *
  * Some existing client code uses the level value as a delta, or level "skip"
  * quantity. We could probably document that through use of more types at some
  * point in the future.
--- a/js/src/frontend/Parser.h
+++ b/js/src/frontend/Parser.h
@@ -6,17 +6,16 @@
 
 #ifndef frontend_Parser_h
 #define frontend_Parser_h
 
 /*
  * JS parser definitions.
  */
 
-#include "jsprvtd.h"
 #include "jspubtd.h"
 
 #include "frontend/BytecodeCompiler.h"
 #include "frontend/FullParseHandler.h"
 #include "frontend/ParseMaps.h"
 #include "frontend/ParseNode.h"
 #include "frontend/SharedContext.h"
 #include "frontend/SyntaxParseHandler.h"
--- a/js/src/frontend/SharedContext.h
+++ b/js/src/frontend/SharedContext.h
@@ -4,17 +4,16 @@
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #ifndef frontend_SharedContext_h
 #define frontend_SharedContext_h
 
 #include "jsatom.h"
 #include "jsopcode.h"
-#include "jsprvtd.h"
 #include "jspubtd.h"
 #include "jsscript.h"
 #include "jstypes.h"
 
 #include "builtin/Module.h"
 #include "frontend/ParseMaps.h"
 #include "frontend/ParseNode.h"
 #include "frontend/TokenStream.h"
--- a/js/src/frontend/SourceNotes.h
+++ b/js/src/frontend/SourceNotes.h
@@ -2,17 +2,17 @@
  * vim: set ts=8 sts=4 et sw=4 tw=99:
  * 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 frontend_SourceNotes_h
 #define frontend_SourceNotes_h
 
-#include "jsprvtd.h"
+typedef uint8_t jssrcnote;
 
 namespace js {
 
 /*
  * Source notes generated along with bytecode for decompiling and debugging.
  * A source note is a uint8_t with 5 bits of type and 3 of offset from the pc
  * of the previous note. If 3 bits of offset aren't enough, extended delta
  * notes (SRC_XDELTA) consisting of 2 set high order bits followed by 6 offset
--- a/js/src/frontend/SyntaxParseHandler.h
+++ b/js/src/frontend/SyntaxParseHandler.h
@@ -8,16 +8,19 @@
 #define frontend_SyntaxParseHandler_h
 
 #include "frontend/ParseNode.h"
 #include "frontend/TokenStream.h"
 
 namespace js {
 namespace frontend {
 
+template <typename ParseHandler>
+class Parser;
+
 // Parse handler used when processing the syntax in a block of code, to generate
 // the minimal information which is required to detect syntax errors and allow
 // bytecode to be emitted for outer functions.
 //
 // When parsing, we start at the top level with a full parse, and when possible
 // only check the syntax for inner functions, so that they can be lazily parsed
 // into bytecode when/if they first run. Checking the syntax of a function is
 // several times faster than doing a full parse/emit, and lazy parsing improves
--- a/js/src/frontend/TokenStream.cpp
+++ b/js/src/frontend/TokenStream.cpp
@@ -355,17 +355,16 @@ TokenStream::updateLineInfoForEOL()
     lineno++;
     srcCoords.add(lineno, linebase - userbuf.base());
 }
 
 JS_ALWAYS_INLINE void
 TokenStream::updateFlagsForEOL()
 {
     flags.isDirtyLine = false;
-    flags.sawEOL = true;
 }
 
 // This gets the next char, normalizing all EOL sequences to '\n' as it goes.
 int32_t
 TokenStream::getChar()
 {
     int32_t c;
     if (JS_LIKELY(userbuf.hasRawChars())) {
--- a/js/src/frontend/TokenStream.h
+++ b/js/src/frontend/TokenStream.h
@@ -13,21 +13,21 @@
 #include "mozilla/PodOperations.h"
 
 #include <stdarg.h>
 #include <stddef.h>
 #include <stdio.h>
 
 #include "jscntxt.h"
 #include "jsopcode.h"
-#include "jsprvtd.h"
 #include "jspubtd.h"
 #include "jsversion.h"
 
 #include "js/Vector.h"
+#include "vm/RegExpObject.h"
 
 namespace js {
 namespace frontend {
 
 // Values of this type are used to index into arrays such as isExprEnding[],
 // so the first value must be zero.
 enum TokenKind {
     TOK_ERROR = 0,                 // well-known as the only code < EOF
@@ -338,46 +338,47 @@ class StrictModeGetter {
 //
 // It takes a buffer of jschars and linearly scans it into |Token|s.
 // Internally the class uses a four element circular buffer |tokens| of
 // |Token|s. As an index for |tokens|, the member |cursor| points to the
 // current token.
 // Calls to getToken() increase |cursor| by one and return the new current
 // token. If a TokenStream was just created, the current token is initialized
 // with random data (i.e. not initialized). It is therefore important that
-// either of the first four member functions listed below is called first.
+// one of the first four member functions listed below is called first.
 // The circular buffer lets us go back up to two tokens from the last
 // scanned token. Internally, the relative number of backward steps that were
 // taken (via ungetToken()) after the last token was scanned is stored in
 // |lookahead|.
 //
 // The following table lists in which situations it is safe to call each listed
 // function. No checks are made by the functions in non-debug builds.
 //
 // Function Name     | Precondition; changes to |lookahead|
 // ------------------+---------------------------------------------------------
 // getToken          | none; if |lookahead > 0| then |lookahead--|
-// peekToken         | none; none
-// peekTokenSameLine | none; none
+// peekToken         | none; if |lookahead == 0| then |lookahead == 1|
+// peekTokenSameLine | none; if |lookahead == 0| then |lookahead == 1|
 // matchToken        | none; if |lookahead > 0| and the match succeeds then
 //                   |       |lookahead--|
 // consumeKnownToken | none; if |lookahead > 0| then |lookahead--|
 // ungetToken        | 0 <= |lookahead| <= |maxLookahead - 1|; |lookahead++|
 //
 // The behavior of the token scanning process (see getTokenInternal()) can be
 // modified by calling one of the first four above listed member functions with
 // an optional argument of type Modifier.  However, the modifier will be
 // ignored unless |lookahead == 0| holds.  Due to constraints of the grammar,
 // this turns out not to be a problem in practice. See the
 // mozilla.dev.tech.js-engine.internals thread entitled 'Bug in the scanner?'
 // for more details:
 // https://groups.google.com/forum/?fromgroups=#!topic/mozilla.dev.tech.js-engine.internals/2JLH5jRcr7E).
 //
 // The methods seek() and tell() allow to rescan from a previous visited
 // location of the buffer.
+//
 class MOZ_STACK_CLASS TokenStream
 {
     // Unicode separators that are treated as line terminators, in addition to \n, \r.
     enum {
         LINE_SEPARATOR = 0x2028,
         PARA_SEPARATOR = 0x2029
     };
 
@@ -390,17 +391,16 @@ class MOZ_STACK_CLASS TokenStream
     typedef Vector<jschar, 32> CharBuffer;
 
     TokenStream(ExclusiveContext *cx, const CompileOptions &options,
                 const jschar *base, size_t length, StrictModeGetter *smg);
 
     ~TokenStream();
 
     // Accessors.
-    bool onCurrentLine(const TokenPos &pos) const { return srcCoords.isOnThisLine(pos.end, lineno); }
     const Token &currentToken() const { return tokens[cursor]; }
     bool isCurrentTokenType(TokenKind type) const {
         return currentToken().type == type;
     }
     const CharBuffer &getTokenbuf() const { return tokenbuf; }
     const char *getFilename() const { return filename; }
     unsigned getLineno() const { return lineno; }
     unsigned getColumn() const { return userbuf.addressOfNextRawChar() - linebase - 1; }
@@ -442,23 +442,22 @@ class MOZ_STACK_CLASS TokenStream
 
     void onError();
     static JSAtom *atomize(ExclusiveContext *cx, CharBuffer &cb);
     bool putIdentInTokenbuf(const jschar *identStart);
 
     struct Flags
     {
         bool isEOF:1;           // Hit end of file.
-        bool sawEOL:1;          // An EOL was hit in whitespace or a multi-line comment.
         bool isDirtyLine:1;     // Non-whitespace since start of line.
         bool sawOctalEscape:1;  // Saw an octal character escape.
         bool hadError:1;        // Returned TOK_ERROR from getToken.
 
         Flags()
-          : isEOF(), sawEOL(), isDirtyLine(), sawOctalEscape(), hadError()
+          : isEOF(), isDirtyLine(), sawOctalEscape(), hadError()
         {}
     };
 
   public:
     // Sometimes the parser needs to modify how tokens are created.
     enum Modifier
     {
         None,           // Normal operation.
@@ -494,33 +493,45 @@ class MOZ_STACK_CLASS TokenStream
     TokenKind peekToken(Modifier modifier = None) {
         if (lookahead != 0)
             return tokens[(cursor + 1) & ntokensMask].type;
         TokenKind tt = getTokenInternal(modifier);
         ungetToken();
         return tt;
     }
 
-    TokenKind peekTokenSameLine(Modifier modifier = None) {
-        if (!onCurrentLine(currentToken().pos))
-            return TOK_EOL;
+    // This is like peekToken(), with one exception:  if there is an EOL
+    // between the end of the current token and the start of the next token, it
+    // returns TOK_EOL.  In that case, no token with TOK_EOL is actually
+    // created, just a TOK_EOL TokenKind is returned, and currentToken()
+    // shouldn't be consulted.  (This is the only place TOK_EOL is produced.)
+    JS_ALWAYS_INLINE TokenKind peekTokenSameLine(Modifier modifier = None) {
+       const Token &curr = currentToken();
 
-        if (lookahead != 0)
+        // If lookahead != 0, we have scanned ahead at least one token, and
+        // |lineno| is the line that the furthest-scanned token ends on.  If
+        // it's the same as the line that the current token ends on, that's a
+        // stronger condition than what we are looking for, and we don't need
+        // to return TOK_EOL.
+        if (lookahead != 0 && srcCoords.isOnThisLine(curr.pos.end, lineno))
             return tokens[(cursor + 1) & ntokensMask].type;
 
-        // This is the only place TOK_EOL is produced.  No token with TOK_EOL
-        // is created, just a TOK_EOL TokenKind is returned.
-        flags.sawEOL = false;
-        TokenKind tt = getToken(modifier);
-        if (flags.sawEOL) {
-            tt = TOK_EOL;
-            flags.sawEOL = false;
-        }
+        // The above check misses two cases where we don't have to return
+        // TOK_EOL.
+        // - The next token starts on the same line, but is a multi-line token.
+        // - The next token starts on the same line, but lookahead==2 and there
+        //   is a newline between the next token and the one after that.
+        // The following test is somewhat expensive but gets these cases (and
+        // all others) right.
+        (void)getToken(modifier);
+        const Token &next = currentToken();
         ungetToken();
-        return tt;
+        return srcCoords.lineNum(curr.pos.end) == srcCoords.lineNum(next.pos.begin)
+               ? next.type
+               : TOK_EOL;
     }
 
     // Get the next token from the stream if its kind is |tt|.
     bool matchToken(TokenKind tt, Modifier modifier = None) {
         if (getToken(modifier) == tt)
             return true;
         ungetToken();
         return false;
--- a/js/src/gc/Barrier.h
+++ b/js/src/gc/Barrier.h
@@ -111,16 +111,18 @@
  * newly allocated objects do not need a pre-barrier.  In these cases, we use
  * the "obj->field.init(value)" method instead of "obj->field = value". We use
  * the init naming idiom in many places to signify that a field is being
  * assigned for the first time.
  */
 
 namespace js {
 
+class PropertyName;
+
 template<class T, typename Unioned = uintptr_t>
 class EncapsulatedPtr
 {
   protected:
     union {
         T *value;
         Unioned other;
     };
new file mode 100644
--- /dev/null
+++ b/js/src/gc/Rooting.h
@@ -0,0 +1,38 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*-
+ * vim: set ts=8 sts=4 et sw=4 tw=99:
+ * 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 gc_Rooting_h
+#define gc_Rooting_h
+
+#include "js/RootingAPI.h"
+
+class JSAtom;
+
+namespace js {
+
+class PropertyName;
+class Shape;
+
+namespace types { struct TypeObject; }
+
+// These are internal counterparts to the public types such as HandleObject.
+
+typedef JS::Handle<Shape*>             HandleShape;
+typedef JS::Handle<types::TypeObject*> HandleTypeObject;
+typedef JS::Handle<JSAtom*>            HandleAtom;
+typedef JS::Handle<PropertyName*>      HandlePropertyName;
+
+typedef JS::MutableHandle<Shape*>      MutableHandleShape;
+typedef JS::MutableHandle<JSAtom*>     MutableHandleAtom;
+
+typedef JS::Rooted<Shape*>             RootedShape;
+typedef JS::Rooted<types::TypeObject*> RootedTypeObject;
+typedef JS::Rooted<JSAtom*>            RootedAtom;
+typedef JS::Rooted<PropertyName*>      RootedPropertyName;
+
+} /* namespace js */
+
+#endif /* gc_Rooting_h */
--- a/js/src/jit/AsmJS.cpp
+++ b/js/src/jit/AsmJS.cpp
@@ -1523,21 +1523,20 @@ class MOZ_STACK_CLASS ModuleCompiler
     void setEntryOffset(unsigned exportIndex) {
 #if defined(JS_CPU_ARM)
         masm_.flush();
 #endif
         module_->exportedFunction(exportIndex).initCodeOffset(masm_.size());
     }
 
     void buildCompilationTimeReport(ScopedJSFreePtr<char> *out) {
-        int msTotal = 0;
         ScopedJSFreePtr<char> slowFuns;
 #ifndef JS_MORE_DETERMINISTIC
         int64_t usecAfter = PRMJ_Now();
-        msTotal = (usecAfter - usecBefore_) / PRMJ_USEC_PER_MSEC;
+        int msTotal = (usecAfter - usecBefore_) / PRMJ_USEC_PER_MSEC;
         if (!slowFunctions_.empty()) {
             slowFuns.reset(JS_smprintf("; %d functions compiled slowly: ", slowFunctions_.length()));
             if (!slowFuns)
                 return;
             for (unsigned i = 0; i < slowFunctions_.length(); i++) {
                 SlowFunction &func = slowFunctions_[i];
                 JSAutoByteString name;
                 if (!AtomToPrintableString(cx_, func.name, &name))
--- a/js/src/jit/BaselineInspector.cpp
+++ b/js/src/jit/BaselineInspector.cpp
@@ -1,21 +1,25 @@
 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*-
  * vim: set ts=8 sts=4 et sw=4 tw=99:
  * This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #include "jit/BaselineInspector.h"
 
+#include "mozilla/DebugOnly.h"
+
 #include "jit/BaselineIC.h"
 
 using namespace js;
 using namespace js::ion;
 
+using mozilla::DebugOnly;
+
 bool
 SetElemICInspector::sawOOBDenseWrite() const
 {
     if (!icEntry_)
         return false;
 
     // Check for a SetElem_DenseAdd stub.
     for (ICStub *stub = icEntry_->firstStub(); stub; stub = stub->next()) {
@@ -223,17 +227,17 @@ BaselineInspector::expectedCompareType(j
     return MCompare::Compare_Unknown;
 }
 
 static bool
 TryToSpecializeBinaryArithOp(ICStub **stubs,
                              uint32_t nstubs,
                              MIRType *result)
 {
-    bool sawInt32 = false;
+    DebugOnly<bool> sawInt32 = false;
     bool sawDouble = false;
     bool sawOther = false;
 
     for (uint32_t i = 0; i < nstubs; i++) {
         switch (stubs[i]->kind()) {
           case ICStub::BinaryArith_Int32:
             sawInt32 = true;
             break;
--- a/js/src/jit/Ion.cpp
+++ b/js/src/jit/Ion.cpp
@@ -1383,18 +1383,20 @@ IonCompile(JSContext *cx, JSScript *scri
                         TraceLogging::ION_COMPILE_STOP,
                         script);
 #endif
 
     if (!script->ensureRanAnalysis(cx))
         return AbortReason_Alloc;
 
     // Try-finally is not yet supported.
-    if (script->analysis()->hasTryFinally())
+    if (script->analysis()->hasTryFinally()) {
+        IonSpew(IonSpew_Abort, "Has try-finally.");
         return AbortReason_Disable;
+    }
 
     LifoAlloc *alloc = cx->new_<LifoAlloc>(BUILDER_LIFO_ALLOC_PRIMARY_CHUNK_SIZE);
     if (!alloc)
         return AbortReason_Alloc;
 
     ScopedJSDeletePtr<LifoAlloc> autoDelete(alloc);
 
     TempAllocator *temp = alloc->new_<TempAllocator>(alloc);
--- a/js/src/jit/IonBuilder.cpp
+++ b/js/src/jit/IonBuilder.cpp
@@ -3224,17 +3224,17 @@ bool
 IonBuilder::jsop_try()
 {
     JS_ASSERT(JSOp(*pc) == JSOP_TRY);
 
     if (!js_IonOptions.compileTryCatch)
         return abort("Try-catch support disabled");
 
     // Try-finally is not yet supported.
-    JS_ASSERT(script()->analysis()->hasTryFinally());
+    JS_ASSERT(!script()->analysis()->hasTryFinally());
 
     graph().setHasTryBlock();
 
     jssrcnote *sn = info().getNote(cx, pc);
     JS_ASSERT(SN_TYPE(sn) == SRC_TRY);
 
     // Get the pc of the last instruction in the try block. It's a JSOP_GOTO to
     // jump over the catch block.
--- a/js/src/jit/IonCaches.cpp
+++ b/js/src/jit/IonCaches.cpp
@@ -1655,23 +1655,18 @@ GetPropertyParIC::attachTypedArrayLength
     return linkAndAttachStub(cx, masm, attacher, ion, "parallel typed array length");
 }
 
 ParallelResult
 GetPropertyParIC::update(ForkJoinSlice *slice, size_t cacheIndex,
                          HandleObject obj, MutableHandleValue vp)
 {
     AutoFlushCache afc("GetPropertyParCache");
-    PerThreadData *pt = slice->perThreadData;
-
-    const SafepointIndex *safepointIndex;
-    void *returnAddr;
-    RootedScript topScript(pt, GetTopIonJSScript(pt, &safepointIndex, &returnAddr));
-    IonScript *ion = topScript->parallelIonScript();
-
+
+    IonScript *ion = GetTopIonJSScript(slice)->parallelIonScript();
     GetPropertyParIC &cache = ion->getCache(cacheIndex).toGetPropertyPar();
 
     // Grab the property early, as the pure path is fast anyways and doesn't
     // need a lock. If we can't do it purely, bail out of parallel execution.
     if (!GetPropertyPure(slice, obj, NameToId(cache.name()), vp.address()))
         return TP_RETRY_SEQUENTIALLY;
 
     // Avoid unnecessary locking if cannot attach stubs.
@@ -2311,24 +2306,23 @@ GenerateTypedArrayElement(JSContext *cx,
 {
     JS_ASSERT(GetElementIC::canAttachTypedArrayElement(tarr, idval, output));
 
     Label failures;
 
     // The array type is the object within the table of typed array classes.
     int arrayType = tarr->type();
 
+    // Guard on the shape.
+    Shape *shape = tarr->lastProperty();
+    masm.branchTestObjShape(Assembler::NotEqual, object, shape, &failures);
+
+    // Decide to what type index the stub should be optimized
     Register tmpReg = output.scratchReg().gpr();
     JS_ASSERT(tmpReg != InvalidReg);
-
-    // Check that the typed array is of the same type as the current object
-    // because load size differ in function of the typed array data width.
-    masm.branchTestObjClass(Assembler::NotEqual, object, tmpReg, tarr->getClass(), &failures);
-
-    // Decide to what type index the stub should be optimized
     Register indexReg = tmpReg;
     JS_ASSERT(!index.constant());
     if (idval.isString()) {
         JS_ASSERT(GetIndexFromString(idval.toString()) != UINT32_MAX);
 
         // Part 1: Get the string into a register
         Register str;
         if (index.reg().hasValue()) {
@@ -2793,23 +2787,18 @@ GetElementParIC::attachTypedArrayElement
     return linkAndAttachStub(cx, masm, attacher, ion, "parallel typed array");
 }
 
 ParallelResult
 GetElementParIC::update(ForkJoinSlice *slice, size_t cacheIndex, HandleObject obj,
                         HandleValue idval, MutableHandleValue vp)
 {
     AutoFlushCache afc("GetElementParCache");
-    PerThreadData *pt = slice->perThreadData;
-
-    const SafepointIndex *safepointIndex;
-    void *returnAddr;
-    RootedScript topScript(pt, GetTopIonJSScript(pt, &safepointIndex, &returnAddr));
-    IonScript *ion = topScript->parallelIonScript();
-
+
+    IonScript *ion = GetTopIonJSScript(slice)->parallelIonScript();
     GetElementParIC &cache = ion->getCache(cacheIndex).toGetElementPar();
 
     // Try to get the element early, as the pure path doesn't need a lock. If
     // we can't do it purely, bail out of parallel execution.
     if (!GetObjectElementOperationPure(slice, obj, idval, vp.address()))
         return TP_RETRY_SEQUENTIALLY;
 
     // Avoid unnecessary locking if cannot attach stubs.
--- a/js/src/jit/IonFrames.h
+++ b/js/src/jit/IonFrames.h
@@ -312,40 +312,36 @@ GetTopIonJSScript(PerThreadData *pt, con
         JS_ASSERT(iter.isBaselineJS());
     }
 
     JS_ASSERT(iter.isScripted());
     return iter.script();
 }
 
 inline JSScript *
-GetTopIonJSScript(JSContext *cx, const SafepointIndex **safepointIndexOut, void **returnAddrOut)
+GetTopIonJSScript(ThreadSafeContext *cx, const SafepointIndex **safepointIndexOut = NULL,
+                  void **returnAddrOut = NULL)
 {
-    return GetTopIonJSScript(&cx->mainThread(), safepointIndexOut, returnAddrOut);
+    return GetTopIonJSScript(cx->perThreadData, safepointIndexOut, returnAddrOut);
 }
 
 } // namespace ion
 } // namespace js
 
 #if defined(JS_CPU_X86) || defined (JS_CPU_X64)
 # include "jit/shared/IonFrames-x86-shared.h"
 #elif defined (JS_CPU_ARM)
 # include "jit/arm/IonFrames-arm.h"
 #else
 # error "unsupported architecture"
 #endif
 
 namespace js {
 namespace ion {
 
-JSScript *
-GetTopIonJSScript(JSContext *cx,
-                  const SafepointIndex **safepointIndexOut = NULL,
-                  void **returnAddrOut = NULL);
-
 void
 GetPcScript(JSContext *cx, JSScript **scriptRes, jsbytecode **pcRes);
 
 // Given a slot index, returns the offset, in bytes, of that slot from an
 // IonJSFrameLayout. Slot distances are uniform across architectures, however,
 // the distance does depend on the size of the frame header.
 static inline int32_t
 OffsetOfFrameSlot(int32_t slot)
--- a/js/src/jit/MCallOptimize.cpp
+++ b/js/src/jit/MCallOptimize.cpp
@@ -1304,16 +1304,18 @@ IonBuilder::inlineNewDenseArrayForParall
     // Create the new parallel array object.  Parallel arrays have specially
     // constructed type objects, so we can only perform the inlining if we
     // already have one of these type objects.
     types::StackTypeSet *returnTypes = getInlineReturnTypeSet();
     if (returnTypes->getKnownTypeTag() != JSVAL_TYPE_OBJECT)
         return InliningStatus_NotInlined;
     if (returnTypes->unknownObject() || returnTypes->getObjectCount() != 1)
         return InliningStatus_NotInlined;
+    if (callInfo.getArg(0)->type() != MIRType_Int32)
+        return InliningStatus_NotInlined;
     types::TypeObject *typeObject = returnTypes->getTypeObject(0);
 
     RootedObject templateObject(cx, NewDenseAllocatedArray(cx, 0, NULL, TenuredObject));
     if (!templateObject)
         return InliningStatus_Error;
     templateObject->setType(typeObject);
 
     callInfo.unwrapArgs();
--- a/js/src/jit/arm/Assembler-arm.cpp
+++ b/js/src/jit/arm/Assembler-arm.cpp
@@ -1866,17 +1866,17 @@ Assembler::as_b(Label *l, Condition c, b
         // This will currently throw an assertion if we couldn't actually
         // encode the offset of the branch.
         ret = as_b(BOffImm(old), c, isPatchable);
     } else {
         old = LabelBase::INVALID_OFFSET;
         BOffImm inv;
         ret = as_b(inv, c, isPatchable);
     }
-    int32_t check = l->use(ret.getOffset());
+    DebugOnly<int32_t> check = l->use(ret.getOffset());
     JS_ASSERT(check == old);
     return ret;
 }
 BufferOffset
 Assembler::as_b(BOffImm off, Condition c, BufferOffset inst)
 {
     *editSrc(inst) = InstBImm(off, c);
     return inst;
@@ -1925,17 +1925,17 @@ Assembler::as_bl(Label *l, Condition c)
         // encode the offset of the branch.
         old = l->offset();
         ret = as_bl(BOffImm(old), c);
     } else {
         old = LabelBase::INVALID_OFFSET;
         BOffImm inv;
         ret = as_bl(inv, c);
     }
-    int32_t check = l->use(ret.getOffset());
+    DebugOnly<int32_t> check = l->use(ret.getOffset());
     JS_ASSERT(check == old);
     return ret;
 }
 BufferOffset
 Assembler::as_bl(BOffImm off, Condition c, BufferOffset inst)
 {
     *editSrc(inst) = InstBLImm(off, c);
     return inst;
@@ -2297,17 +2297,16 @@ void
 Assembler::retarget(Label *label, Label *target)
 {
     if (label->used()) {
         if (target->bound()) {
             bind(label, BufferOffset(target));
         } else if (target->used()) {
             // The target is not bound but used. Prepend label's branch list
             // onto target's.
-            bool more;
             BufferOffset labelBranchOffset(label);
             BufferOffset next;
 
             // Find the head of the use chain for label.
             while (nextLink(labelBranchOffset, &next))
                 labelBranchOffset = next;
 
             // Then patch the head of label's use chain to the tail of
@@ -2533,18 +2532,18 @@ Assembler::patchWrite_NearCall(CodeLocat
 }
 void
 Assembler::patchDataWithValueCheck(CodeLocationLabel label, ImmWord newValue, ImmWord expectedValue)
 {
     Instruction *ptr = (Instruction *) label.raw();
     InstructionIterator iter(ptr);
     Register dest;
     Assembler::RelocStyle rs;
-    const uint32_t *val = getPtr32Target(&iter, &dest, &rs);
-    JS_ASSERT((uint32_t)val == expectedValue.value);
+    DebugOnly<const uint32_t *> val = getPtr32Target(&iter, &dest, &rs);
+    JS_ASSERT((uint32_t)(const uint32_t *)val == expectedValue.value);
     reinterpret_cast<MacroAssemblerARM*>(dummy)->ma_movPatchable(Imm32(newValue.value), dest, Always, rs, ptr);
     // L_LDR won't cause any instructions to be updated.
     if (rs != L_LDR) {
         AutoFlushCache::updateTop(uintptr_t(ptr), 4);
         AutoFlushCache::updateTop(uintptr_t(ptr->next()), 4);
     }
 }
 
--- a/js/src/jit/arm/Trampoline-arm.cpp
+++ b/js/src/jit/arm/Trampoline-arm.cpp
@@ -98,26 +98,20 @@ struct EnterJITStack
  * signature:
  *   void enter(void *code, int argc, Value *argv, StackFrame *fp, CalleeToken
  *              calleeToken, JSObject *scopeChain, Value *vp)
  *   ...using standard EABI calling convention
  */
 IonCode *
 IonRuntime::generateEnterJIT(JSContext *cx, EnterJitType type)
 {
-
-    const Register reg_code  = r0;
-    const Register reg_argc  = r1;
-    const Register reg_argv  = r2;
-    const Register reg_frame = r3;
-
     const Address slot_token(sp, offsetof(EnterJITStack, token));
     const Address slot_vp(sp, offsetof(EnterJITStack, vp));
 
-    JS_ASSERT(OsrFrameReg == reg_frame);
+    JS_ASSERT(OsrFrameReg == r3);
 
     MacroAssembler masm(cx);
     AutoFlushCache afc("GenerateEnterJIT", cx->runtime()->ionRuntime());
     Assembler *aasm = &masm;
 
     // Save non-volatile registers. These must be saved by the trampoline,
     // rather than the JIT'd code, because they are scanned by the conservative
     // scanner.
--- a/js/src/jit/shared/IonAssemblerBuffer.h
+++ b/js/src/jit/shared/IonAssemblerBuffer.h
@@ -67,17 +67,17 @@ struct BufferSlice {
         this->next = next_;
         next_->prev = this;
     }
 
     uint8_t instructions [SliceSize];
     unsigned int size() {
         return nodeSize;
     }
-    BufferSlice() : next(NULL), prev(NULL), nodeSize(0) {}
+    BufferSlice() : prev(NULL), next(NULL), nodeSize(0) {}
     void putBlob(uint32_t instSize, uint8_t* inst) {
         if (inst != NULL)
             memcpy(&instructions[size()], inst, instSize);
         nodeSize += instSize;
     }
 };
 
 template<int SliceSize, class Inst>
@@ -198,43 +198,43 @@ struct AssemblerBuffer
             cur = head;
             cur_off = 0;
         } else {
             // it is closest to the end
             cur = tail;
             cur_off = bufferSize;
         }
         int count = 0;
-        char sigil;
         if (local_off < cur_off) {
             for (; cur != NULL; cur = cur->getPrev(), cur_off -= cur->size()) {
                 if (local_off >= cur_off) {
                     local_off -= cur_off;
                     break;
                 }
                 count++;
             }
             JS_ASSERT(cur != NULL);
         } else {
             for (; cur != NULL; cur = cur->getNext()) {
-                if (local_off < cur_off + cur->size()) {
+                int cur_size = cur->size();
+                if (local_off < cur_off + cur_size) {
                     local_off -= cur_off;
                     break;
                 }
-                cur_off += cur->size();
+                cur_off += cur_size;
                 count++;
             }
             JS_ASSERT(cur != NULL);
         }
         if (count > 2 || used_finger) {
             finger = cur;
             finger_offset = cur_off;
         }
         // the offset within this node should not be larger than the node itself.
-        JS_ASSERT(local_off < cur->size());
+        JS_ASSERT(local_off < (int)cur->size());
         return (Inst*)&cur->instructions[local_off];
     }
     BufferOffset nextOffset() const {
         if (tail != NULL)
             return BufferOffset(bufferSize + tail->size());
         else
             return BufferOffset(bufferSize);
     }
--- a/js/src/jit/shared/IonAssemblerBufferWithConstantPools.h
+++ b/js/src/jit/shared/IonAssemblerBufferWithConstantPools.h
@@ -2,16 +2,18 @@
  * vim: set ts=8 sts=4 et sw=4 tw=99:
  * 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 jit_shared_IonAssemblerBufferWithConstantPools_h
 #define jit_shared_IonAssemblerBufferWithConstantPools_h
 
+#include "mozilla/DebugOnly.h"
+
 #include "assembler/wtf/SegmentedVector.h"
 #include "jit/IonSpewer.h"
 #include "jit/shared/IonAssemblerBuffer.h"
 
 namespace js {
 namespace ion {
 typedef Vector<BufferOffset, 512, IonAllocPolicy> LoadOffsets;
 
@@ -399,17 +401,17 @@ struct AssemblerBufferWithConstantPool :
         if (this->oom())
             return;
         // TODO: only do this when the pool actually has a value in it
         flushPool();
         for (int idx = 0; idx < numPoolKinds; idx++) {
             JS_ASSERT(pools[idx].numEntries == 0 && pools[idx].other->numEntries == 0);
         }
         typedef uint8_t Chunk[InstBaseSize];
-        Chunk *start = (Chunk*)dest_;
+        mozilla::DebugOnly<Chunk *> start = (Chunk*)dest_;
         Chunk *dest = (Chunk*)(((uint32_t)dest_ + instBufferAlign - 1) & ~(instBufferAlign -1));
         int curIndex = 0;
         int curInstOffset = 0;
         JS_ASSERT(start == dest);
         for (BufferSlice * cur = *getHead(); cur != NULL; cur = cur->getNext()) {
             Chunk *src = (Chunk*)cur->instructions;
             for (unsigned int idx = 0; idx <cur->size()/InstBaseSize;
                  idx++, curInstOffset += InstBaseSize) {
@@ -877,17 +879,17 @@ struct AssemblerBufferWithConstantPool :
 
         // We have a perforation.  Time to cut the instruction stream, patch in the pool
         // and possibly re-arrange the pool to accomodate its new location.
         int poolOffset = perforation.getOffset();
         int magicAlign =  getInfo(numDumps-1).finalPos - getInfo(numDumps-1).offset;
         poolOffset += magicAlign;
         poolOffset += headerSize;
         for (int poolIdx = 0; poolIdx < numPoolKinds; poolIdx++) {
-            bool beforePool = true;
+            mozilla::DebugOnly<bool> beforePool = true;
             Pool *p = &pools[poolIdx];
             // Any entries that happened to be after the place we put our pool will need to be
             // switched from the forward-referenced pool to the backward-refrenced pool.
             int idx = 0;
             for (BufferOffset *iter = p->loadOffsets.begin();
                  iter != p->loadOffsets.end(); ++iter, ++idx)
             {
                 if (iter->getOffset() >= perforation.getOffset()) {
--- a/js/src/jsanalyze.h
+++ b/js/src/jsanalyze.h
@@ -17,16 +17,21 @@
 
 #include "vm/Runtime.h"
 
 class JSScript;
 
 namespace js {
 namespace analyze {
 
+class LoopAnalysis;
+class SlotValue;
+class SSAValue;
+class SSAUseChain;
+
 /*
  * There are three analyses we can perform on a JSScript, outlined below.
  * The results of all three are stored in ScriptAnalysis, but the analyses
  * themselves can be performed separately. Along with type inference results,
  * per-script analysis results are tied to the per-compartment analysis pool
  * and are freed on every garbage collection.
  *
  * - Basic bytecode analysis. For each bytecode, determine the stack depth at
--- a/js/src/jsapi-tests/tests.h
+++ b/js/src/jsapi-tests/tests.h
@@ -13,17 +13,16 @@
 #include <stdio.h>
 #include <stdlib.h>
 #include <string.h>
 
 #include "jsalloc.h"
 #include "jsapi.h"
 #include "jscntxt.h"
 #include "jsgc.h"
-#include "jsprvtd.h"
 
 #include "js/Vector.h"
 
 /* Note: Aborts on OOM. */
 class JSAPITestString {
     js::Vector<char, 0, js::SystemAllocPolicy> chars;
   public:
     JSAPITestString() {}
--- a/js/src/jsapi.cpp
+++ b/js/src/jsapi.cpp
@@ -1357,17 +1357,17 @@ JS_InitStandardClasses(JSContext *cx, JS
 #define OCLASP(name)                (&name##Object::class_)
 #define TYPED_ARRAY_CLASP(type)     (&TypedArrayObject::classes[TypedArrayObject::type])
 #define EAGER_ATOM(name)            NAME_OFFSET(name)
 #define EAGER_CLASS_ATOM(name)      NAME_OFFSET(name)
 #define EAGER_ATOM_AND_CLASP(name)  EAGER_CLASS_ATOM(name), CLASP(name)
 #define EAGER_ATOM_AND_OCLASP(name) EAGER_CLASS_ATOM(name), OCLASP(name)
 
 typedef struct JSStdName {
-    JSClassInitializerOp init;
+    ClassInitializerOp init;
     size_t      atomOffset;     /* offset of atom pointer in JSAtomState */
     Class       *clasp;
 } JSStdName;
 
 static Handle<PropertyName*>
 StdNameToPropertyName(JSContext *cx, const JSStdName *stdn)
 {
     return OFFSET_TO_NAME(cx->runtime(), stdn->atomOffset);
--- a/js/src/jsapi.h
+++ b/js/src/jsapi.h
@@ -943,16 +943,30 @@ typedef void
 
 /*
  * Callback that JSTraceOp implementation can provide to return a string
  * describing the reference traced with JS_CallTracer.
  */
 typedef void
 (* JSTraceNamePrinter)(JSTracer *trc, char *buf, size_t bufsize);
 
+/*
+ * A generic type for functions mapping an object to another object, or null
+ * if an error or exception was thrown on cx.
+ */
+typedef JSObject *
+(* JSObjectOp)(JSContext *cx, JS::Handle<JSObject*> obj);
+
+/*
+ * Hook that creates an iterator object for a given object. Returns the
+ * iterator object or null if an error or exception was thrown on cx.
+ */
+typedef JSObject *
+(* JSIteratorOp)(JSContext *cx, JS::HandleObject obj, bool keysonly);
+
 typedef JSObject *
 (* JSWeakmapKeyDelegateOp)(JSObject *obj);
 
 /* Callbacks and their arguments. */
 
 typedef enum JSContextOp {
     JSCONTEXT_NEW,
     JSCONTEXT_DESTROY
--- a/js/src/jsatom.h
+++ b/js/src/jsatom.h
@@ -8,20 +8,20 @@
 #define jsatom_h
 
 #include "mozilla/HashFunctions.h"
 
 #include <stddef.h>
 
 #include "jsalloc.h"
 #include "jsapi.h"
-#include "jsprvtd.h"
 #include "jspubtd.h"
 
 #include "gc/Barrier.h"
+#include "gc/Rooting.h"
 #include "js/HashTable.h"
 #include "vm/CommonPropertyNames.h"
 
 struct JSIdArray {
     int length;
     js::HeapId vector[1];    /* actually, length jsid words */
 };
 
@@ -213,15 +213,23 @@ AtomizeChars(ExclusiveContext *cx, const
 template <AllowGC allowGC>
 extern JSAtom *
 AtomizeString(ExclusiveContext *cx, JSString *str, js::InternBehavior ib = js::DoNotInternAtom);
 
 template <AllowGC allowGC>
 extern JSAtom *
 ToAtom(ExclusiveContext *cx, typename MaybeRooted<Value, allowGC>::HandleType v);
 
+enum XDRMode {
+    XDR_ENCODE,
+    XDR_DECODE
+};
+
+template <XDRMode mode>
+class XDRState;
+
 template<XDRMode mode>
 bool
 XDRAtom(XDRState<mode> *xdr, js::MutableHandleAtom atomp);
 
 } /* namespace js */
 
 #endif /* jsatom_h */
--- a/js/src/jsbool.cpp
+++ b/js/src/jsbool.cpp
@@ -193,13 +193,12 @@ js::ToBooleanSlow(const Value &v)
 
 /*
  * This slow path is only ever taken for proxies wrapping Boolean objects
  * The only caller of the fast path, JSON's PreprocessValue, ensures that.
  */
 bool
 js::BooleanGetPrimitiveValueSlow(HandleObject wrappedBool, JSContext *cx)
 {
-    JS_ASSERT(wrappedBool->is<ProxyObject>());
-    JSObject *obj = Wrapper::wrappedObject(wrappedBool);
+    JSObject *obj = wrappedBool->as<ProxyObject>().target();
     JS_ASSERT(obj);
     return obj->as<BooleanObject>().unbox();
 }
new file mode 100644
--- /dev/null
+++ b/js/src/jsbytecode.h
@@ -0,0 +1,14 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*-
+ * vim: set ts=8 sts=4 et sw=4 tw=99:
+ * 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 jsbytecode_h
+#define jsbytecode_h
+
+#include <stdint.h>
+
+typedef uint8_t jsbytecode;
+
+#endif /* jsbytecode_h */
--- a/js/src/jsclass.h
+++ b/js/src/jsclass.h
@@ -9,23 +9,25 @@
 /*
  * A JSClass acts as a vtable for JS objects that allows JSAPI clients to
  * control various aspects of the behavior of an object like property lookup.
  * js::Class is an engine-private extension that allows more control over
  * object behavior and, e.g., allows custom slow layout.
  */
 
 #include "jsapi.h"
-#include "jsprvtd.h"
 
 namespace js {
 
+class Class;
+class FreeOp;
+class PropertyId;
 class PropertyName;
+class Shape;
 class SpecialId;
-class PropertyId;
 
 // This is equal to JSFunction::class_.  Use it in places where you don't want
 // to #include jsfun.h.
 extern JS_FRIEND_DATA(js::Class* const) FunctionClassPtr;
 
 static JS_ALWAYS_INLINE jsid
 SPECIALID_TO_JSID(const SpecialId &sid);
 
@@ -130,66 +132,66 @@ JSID_TO_SPECIALID(jsid id)
 }
 
 typedef JS::Handle<SpecialId> HandleSpecialId;
 
 /* js::Class operation signatures. */
 
 typedef bool
 (* LookupGenericOp)(JSContext *cx, HandleObject obj, HandleId id,
-                    MutableHandleObject objp, MutableHandleShape propp);
+                    MutableHandleObject objp, JS::MutableHandle<Shape*> propp);
 typedef bool
-(* LookupPropOp)(JSContext *cx, HandleObject obj, HandlePropertyName name,
-                 MutableHandleObject objp, MutableHandleShape propp);
+(* LookupPropOp)(JSContext *cx, HandleObject obj, JS::Handle<PropertyName*> name,
+                 MutableHandleObject objp, JS::MutableHandle<Shape*> propp);
 typedef bool
 (* LookupElementOp)(JSContext *cx, HandleObject obj, uint32_t index,
-                    MutableHandleObject objp, MutableHandleShape propp);
+                    MutableHandleObject objp, JS::MutableHandle<Shape*> propp);
 typedef bool
 (* LookupSpecialOp)(JSContext *cx, HandleObject obj, HandleSpecialId sid,
-                    MutableHandleObject objp, MutableHandleShape propp);
+                    MutableHandleObject objp, JS::MutableHandle<Shape*> propp);
 typedef bool
 (* DefineGenericOp)(JSContext *cx, HandleObject obj, HandleId id, HandleValue value,
-                    PropertyOp getter, StrictPropertyOp setter, unsigned attrs);
+                    JSPropertyOp getter, JSStrictPropertyOp setter, unsigned attrs);
 typedef bool
-(* DefinePropOp)(JSContext *cx, HandleObject obj, HandlePropertyName name, HandleValue value,
-                 PropertyOp getter, StrictPropertyOp setter, unsigned attrs);
+(* DefinePropOp)(JSContext *cx, HandleObject obj, JS::Handle<PropertyName*> name, HandleValue value,
+                 JSPropertyOp getter, JSStrictPropertyOp setter, unsigned attrs);
 typedef bool
 (* DefineElementOp)(JSContext *cx, HandleObject obj, uint32_t index, HandleValue value,
-                    PropertyOp getter, StrictPropertyOp setter, unsigned attrs);
+                    JSPropertyOp getter, JSStrictPropertyOp setter, unsigned attrs);
 typedef bool
 (* DefineSpecialOp)(JSContext *cx, HandleObject obj, HandleSpecialId sid, HandleValue value,
-                    PropertyOp getter, StrictPropertyOp setter, unsigned attrs);
+                    JSPropertyOp getter, JSStrictPropertyOp setter, unsigned attrs);
 typedef bool
 (* GenericIdOp)(JSContext *cx, HandleObject obj, HandleObject receiver, HandleId id, MutableHandleValue vp);
 typedef bool
-(* PropertyIdOp)(JSContext *cx, HandleObject obj, HandleObject receiver, HandlePropertyName name, MutableHandleValue vp);
+(* PropertyIdOp)(JSContext *cx, HandleObject obj, HandleObject receiver, JS::Handle<PropertyName*> name, MutableHandleValue vp);
 typedef bool
 (* ElementIdOp)(JSContext *cx, HandleObject obj, HandleObject receiver, uint32_t index, MutableHandleValue vp);
 typedef bool
 (* ElementIfPresentOp)(JSContext *cx, HandleObject obj, HandleObject receiver, uint32_t index, MutableHandleValue vp, bool* present);
 typedef bool
 (* SpecialIdOp)(JSContext *cx, HandleObject obj, HandleObject receiver, HandleSpecialId sid, MutableHandleValue vp);
 typedef bool
 (* StrictGenericIdOp)(JSContext *cx, HandleObject obj, HandleId id, MutableHandleValue vp, bool strict);
 typedef bool
-(* StrictPropertyIdOp)(JSContext *cx, HandleObject obj, HandlePropertyName name, MutableHandleValue vp, bool strict);
+(* StrictPropertyIdOp)(JSContext *cx, HandleObject obj, JS::Handle<PropertyName*> name, MutableHandleValue vp, bool strict);
 typedef bool