Merge mozilla-central and mozilla-inbound
authorMarco Bonardo <mbonardo@mozilla.com>
Fri, 11 Nov 2011 11:09:58 +0100
changeset 80169 50c1bcb49c7678efed1d9592bbbc95cb9dc77c84
parent 80135 1374294a61191a19ba6f52be7ee980b1f5186532 (current diff)
parent 80168 71046de4fb6a7ee6fc0ffff9bf3b16a66ca426f1 (diff)
child 80170 13590cb94eab1ed7e632bbd457ef3f9cb09298b3
child 80172 0ad06b88a36b5e9344d825f1cafe2ecb148bae51
push id21467
push usermak77@bonardo.net
push dateFri, 11 Nov 2011 10:10:59 +0000
treeherdermozilla-central@50c1bcb49c76 [default view] [failures only]
perfherder[talos] [build metrics] [platform microbench] (compared to previous push)
milestone11.0a1
first release with
nightly win64
50c1bcb49c76 / 11.0a1 / 20111111031514 / files
nightly linux32
nightly linux64
nightly mac
nightly win32
last release without
nightly linux32
nightly linux64
nightly mac
nightly win32
nightly win64
releases
nightly win64
Merge mozilla-central and mozilla-inbound
gfx/cairo/cairo/src/Makefile.in
gfx/src/Makefile.in
js/src/configure.in
--- a/Makefile.in
+++ b/Makefile.in
@@ -60,17 +60,17 @@ TIERS += base
 #
 tier_base_dirs = \
 	config \
 	build \
 	probes \
 	$(NULL)
 
 ifndef LIBXUL_SDK
-ifeq ($(OS_TARGET),Android)
+ifeq (android,$(MOZ_WIDGET_TOOLKIT))
 tier_base_dirs += other-licenses/android
 endif
 
 tier_base_dirs += memory
 endif
 
 ifdef COMPILE_ENVIRONMENT
 include $(topsrcdir)/$(MOZ_BUILD_APP)/build.mk
--- a/accessible/src/base/nsAccDocManager.cpp
+++ b/accessible/src/base/nsAccDocManager.cpp
@@ -233,17 +233,18 @@ nsAccDocManager::OnProgressChange(nsIWeb
                                   PRInt32 aMaxTotalProgress)
 {
   NS_NOTREACHED("notification excluded in AddProgressListener(...)");
   return NS_OK;
 }
 
 NS_IMETHODIMP
 nsAccDocManager::OnLocationChange(nsIWebProgress *aWebProgress,
-                                  nsIRequest *aRequest, nsIURI *aLocation)
+                                  nsIRequest *aRequest, nsIURI *aLocation,
+                                  PRUint32 aFlags)
 {
   NS_NOTREACHED("notification excluded in AddProgressListener(...)");
   return NS_OK;
 }
 
 NS_IMETHODIMP
 nsAccDocManager::OnStatusChange(nsIWebProgress *aWebProgress,
                                 nsIRequest *aRequest, nsresult aStatus,
--- a/browser/base/content/browser.js
+++ b/browser/base/content/browser.js
@@ -4581,17 +4581,17 @@ var XULBrowserWindow = {
           this.throbberElement.removeAttribute("busy");
 
         this.stopCommand.setAttribute("disabled", "true");
         CombinedStopReload.switchToReload(aRequest instanceof Ci.nsIRequest);
       }
     }
   },
 
-  onLocationChange: function (aWebProgress, aRequest, aLocationURI) {
+  onLocationChange: function (aWebProgress, aRequest, aLocationURI, aFlags) {
     var location = aLocationURI ? aLocationURI.spec : "";
     this._hostChanged = true;
 
     // Hide the form invalid popup.
     if (gFormSubmitObserver.panelIsOpen()) {
       gFormSubmitObserver.panel.hidePopup();
     }
 
@@ -5047,17 +5047,18 @@ var TabsProgressListener = {
         aBrowser.removeEventListener("pagehide", arguments.callee, true);
       }, true);
 
       // We also want to make changes to page UI for unprivileged about pages.
       BrowserOnAboutPageLoad(aWebProgress.DOMWindow.document);
     }
   },
 
-  onLocationChange: function (aBrowser, aWebProgress, aRequest, aLocationURI) {
+  onLocationChange: function (aBrowser, aWebProgress, aRequest, aLocationURI,
+                              aFlags) {
     // Filter out any sub-frame loads
     if (aBrowser.contentWindow == aWebProgress.DOMWindow)
       FullZoom.onLocationChange(aLocationURI, false, aBrowser);
   },
 
   onRefreshAttempted: function (aBrowser, aWebProgress, aURI, aDelay, aSameURI) {
     if (gPrefService.getBoolPref("accessibility.blockautorefresh")) {
       let brandBundle = document.getElementById("bundle_brand");
--- a/browser/base/content/tabbrowser.xml
+++ b/browser/base/content/tabbrowser.xml
@@ -603,17 +603,18 @@
                 // reset cached temporary values at beginning and end
                 this.mMessage = "";
                 this.mTotalProgress = 0;
               }
               this.mStateFlags = aStateFlags;
               this.mStatus = aStatus;
             },
 
-            onLocationChange: function (aWebProgress, aRequest, aLocation) {
+            onLocationChange: function (aWebProgress, aRequest, aLocation,
+                                        aFlags) {
               // OnLocationChange is called for both the top-level content
               // and the subframes.
               let topLevel = aWebProgress.DOMWindow == this.mBrowser.contentWindow;
 
               if (topLevel) {
                 // The document loaded correctly, clear the value if we should
                 if (this.mBrowser.userTypedClear > 0)
                   this.mBrowser.userTypedValue = null;
@@ -636,17 +637,18 @@
                 if (aLocation.spec != "about:blank") {
                   autocomplete.registerOpenPage(aLocation);
                   this.mBrowser.registeredOpenURI = aLocation;
                 }
               }
 
               if (!this.mBlank) {
                 this._callProgressListeners("onLocationChange",
-                                            [aWebProgress, aRequest, aLocation]);
+                                            [aWebProgress, aRequest, aLocation,
+                                             aFlags]);
               }
 
               if (topLevel)
                 this.mBrowser.lastURI = aLocation;
             },
 
             onStatusChange: function (aWebProgress, aRequest, aStatus, aMessage) {
               if (this.mBlank)
@@ -885,17 +887,18 @@
 #ifdef MOZ_E10S_COMPAT
             // Bug 666801 - WebProgress support for e10s and
             // Bug 666809 - SecurityUI support for e10s
 #else
             var webProgress = this.mCurrentBrowser.webProgress;
             var securityUI = this.mCurrentBrowser.securityUI;
 
             this._callProgressListeners(null, "onLocationChange",
-                                        [webProgress, null, loc], true, false);
+                                        [webProgress, null, loc, 0], true,
+                                        false);
 
             if (securityUI) {
               this._callProgressListeners(null, "onSecurityChange",
                                           [webProgress, null, securityUI.state], true, false);
             }
 #endif
 
             var listener = this.mTabListeners[this.tabContainer.selectedIndex] || null;
--- a/browser/base/content/test/browser_alltabslistener.js
+++ b/browser/base/content/test/browser_alltabslistener.js
@@ -12,17 +12,17 @@ var gFrontProgressListener = {
   onStateChange: function (aWebProgress, aRequest, aStateFlags, aStatus) {
     var state = "onStateChange";
     info("FrontProgress: " + state + " 0x" + aStateFlags.toString(16));
     ok(gFrontNotificationsPos < gFrontNotifications.length, "Got an expected notification for the front notifications listener");
     is(state, gFrontNotifications[gFrontNotificationsPos], "Got a notification for the front notifications listener");
     gFrontNotificationsPos++;
   },
 
-  onLocationChange: function (aWebProgress, aRequest, aLocationURI) {
+  onLocationChange: function (aWebProgress, aRequest, aLocationURI, aFlags) {
     var state = "onLocationChange";
     info("FrontProgress: " + state + " " + aLocationURI.spec);
     ok(gFrontNotificationsPos < gFrontNotifications.length, "Got an expected notification for the front notifications listener");
     is(state, gFrontNotifications[gFrontNotificationsPos], "Got a notification for the front notifications listener");
     gFrontNotificationsPos++;
   },
   
   onStatusChange: function (aWebProgress, aRequest, aStatus, aMessage) {
@@ -48,17 +48,18 @@ var gAllProgressListener = {
 
     if ((aStateFlags & gCompleteState) == gCompleteState) {
       ok(gAllNotificationsPos == gAllNotifications.length, "Saw the expected number of notifications");
       ok(gFrontNotificationsPos == gFrontNotifications.length, "Saw the expected number of frontnotifications");
       executeSoon(gNextTest);
     }
   },
 
-  onLocationChange: function (aBrowser, aWebProgress, aRequest, aLocationURI) {
+  onLocationChange: function (aBrowser, aWebProgress, aRequest, aLocationURI,
+                              aFlags) {
     var state = "onLocationChange";
     info("AllProgress: " + state + " " + aLocationURI.spec);
     ok(aBrowser == gTestBrowser, state + " notification came from the correct browser");
     ok(gAllNotificationsPos < gAllNotifications.length, "Got an expected notification for the all notifications listener");
     is(state, gAllNotifications[gAllNotificationsPos], "Got a notification for the all notifications listener");
     gAllNotificationsPos++;
   },
   
--- a/browser/base/content/test/browser_urlbarTrimURLs.js
+++ b/browser/base/content/test/browser_urlbarTrimURLs.js
@@ -27,17 +27,23 @@ function test() {
   testVal("http://mozilla.imaginatory/", "mozilla.imaginatory");
   testVal("http://www.mozilla.org/", "www.mozilla.org");
   testVal("http://sub.mozilla.org/", "sub.mozilla.org");
   testVal("http://sub1.sub2.sub3.mozilla.org/", "sub1.sub2.sub3.mozilla.org");
   testVal("http://mozilla.org/file.ext", "mozilla.org/file.ext");
   testVal("http://mozilla.org/sub/", "mozilla.org/sub/");
 
   testVal("http://ftp.mozilla.org/", "http://ftp.mozilla.org");
+  testVal("http://ftp1.mozilla.org/", "http://ftp1.mozilla.org");
+  testVal("http://ftp42.mozilla.org/", "http://ftp42.mozilla.org");
+  testVal("http://ftpx.mozilla.org/", "ftpx.mozilla.org");
   testVal("ftp://ftp.mozilla.org/", "ftp://ftp.mozilla.org");
+  testVal("ftp://ftp1.mozilla.org/", "ftp://ftp1.mozilla.org");
+  testVal("ftp://ftp42.mozilla.org/", "ftp://ftp42.mozilla.org");
+  testVal("ftp://ftpx.mozilla.org/", "ftp://ftpx.mozilla.org");
 
   testVal("https://user:pass@mozilla.org/", "https://user:pass@mozilla.org");
   testVal("http://user:pass@mozilla.org/", "http://user:pass@mozilla.org");
   testVal("http://sub.mozilla.org:666/", "sub.mozilla.org:666");
 
   testVal("https://[fe80::222:19ff:fe11:8c76]/file.ext");
   testVal("http://[fe80::222:19ff:fe11:8c76]/", "[fe80::222:19ff:fe11:8c76]");
   testVal("https://user:pass@[fe80::222:19ff:fe11:8c76]:666/file.ext");
--- a/browser/base/content/utilityOverlay.js
+++ b/browser/base/content/utilityOverlay.js
@@ -630,13 +630,15 @@ function openPrefsHelp() {
   // since its probably behind the window.
   var instantApply = getBoolPref("browser.preferences.instantApply");
 
   var helpTopic = document.getElementsByTagName("prefwindow")[0].currentPane.helpTopic;
   openHelpLink(helpTopic, !instantApply);
 }
 
 function trimURL(aURL) {
+  // This function must not modify the given URL such that calling
+  // nsIURIFixup::createFixupURI with the result will produce a different URI.
   return aURL /* remove single trailing slash for http/https/ftp URLs */
              .replace(/^((?:http|https|ftp):\/\/[^/]+)\/$/, "$1")
-              /* remove http:// unless the host starts with "ftp." or contains "@" */
-             .replace(/^http:\/\/((?!ftp\.)[^\/@]+(?:\/|$))/, "$1");
+              /* remove http:// unless the host starts with "ftp\d*\." or contains "@" */
+             .replace(/^http:\/\/((?!ftp\d*\.)[^\/@]+(?:\/|$))/, "$1");
 }
--- a/browser/base/content/web-panels.js
+++ b/browser/base/content/web-panels.js
@@ -67,17 +67,17 @@ var panelProgressListener = {
         }
         else if (aStateFlags & Ci.nsIWebProgressListener.STATE_STOP &&
                 aStateFlags & Ci.nsIWebProgressListener.STATE_IS_NETWORK) {
             window.parent.document.getElementById('sidebar-throbber').removeAttribute("loading");
         }
     }
     ,
 
-    onLocationChange : function(aWebProgress, aRequest, aLocation) {
+    onLocationChange : function(aWebProgress, aRequest, aLocation, aFlags) {
         UpdateBackForwardCommands(getPanelBrowser().webNavigation);
     },
 
     onStatusChange : function(aWebProgress, aRequest, aStatus, aMessage) {
     },
 
     onSecurityChange : function(aWebProgress, aRequest, aState) { 
     },
--- a/browser/components/places/tests/browser/browser_library_middleclick.js
+++ b/browser/components/places/tests/browser/browser_library_middleclick.js
@@ -59,17 +59,18 @@ var gTabsListener = {
          "We have opened " + gCurrentTest.URIs.length + " new tab(s)");
     }
 
     var tab = aEvent.target;
     is(tab.ownerDocument.defaultView, window,
        "Tab has been opened in current browser window");
   },
 
-  onLocationChange: function(aBrowser, aWebProgress, aRequest, aLocationURI) {
+  onLocationChange: function(aBrowser, aWebProgress, aRequest, aLocationURI,
+                             aFlags) {
     var spec = aLocationURI.spec;
     ok(true, spec);
     // When a new tab is opened, location is first set to "about:blank", so
     // we can ignore those calls.
     // Ignore multiple notifications for the same URI too.
     if (spec == "about:blank" || this._loadedURIs.indexOf(spec) != -1)
       return;
 
--- a/browser/components/sessionstore/src/nsSessionStore.js
+++ b/browser/components/sessionstore/src/nsSessionStore.js
@@ -2300,17 +2300,17 @@ SessionStoreService.prototype = {
         scheme = uri.scheme;
         this._extractHostsForCookiesFromHostScheme(host, scheme, aHosts, aCheckPrivacy, aIsPinned);
       }
       catch(ex) { }
     }
 
     if (aEntry.children) {
       aEntry.children.forEach(function(entry) {
-        this._extractHostsForCookies(entry, aHosts, aCheckPrivacy, aIsPinned);
+        this._extractHostsForCookiesFromEntry(entry, aHosts, aCheckPrivacy, aIsPinned);
       }, this);
     }
   },
 
   /**
    * extract the base domain from a host & scheme
    * @param aHost
    *        the host of a uri (usually via nsIURI.host)
--- a/browser/components/shell/src/nsMacShellService.cpp
+++ b/browser/components/shell/src/nsMacShellService.cpp
@@ -230,17 +230,18 @@ nsMacShellService::OnProgressChange(nsIW
                                     PRInt32 aMaxTotalProgress)
 {
   return NS_OK;
 }
 
 NS_IMETHODIMP
 nsMacShellService::OnLocationChange(nsIWebProgress* aWebProgress,
                                     nsIRequest* aRequest,
-                                    nsIURI* aLocation)
+                                    nsIURI* aLocation,
+                                    PRUint32 aFlags)
 {
   return NS_OK;
 }
 
 NS_IMETHODIMP
 nsMacShellService::OnStatusChange(nsIWebProgress* aWebProgress,
                                   nsIRequest* aRequest,
                                   nsresult aStatus,
--- a/build/Makefile.in
+++ b/build/Makefile.in
@@ -51,17 +51,17 @@ endif
 
 ifeq (WINNT,$(OS_ARCH))
 DIRS = win32
 endif
 
 DIRS += pgo
 
 ifdef ENABLE_TESTS
-ifeq (Android,$(OS_TARGET))
+ifeq (android,$(MOZ_WIDGET_TOOLKIT))
   DIRS += mobile/sutagent/android \
           mobile/sutagent/android/watcher \
           mobile/sutagent/android/ffxcp \
           mobile/sutagent/android/fencp \
           $(NULL)
 endif
 endif
 
--- a/configure.in
+++ b/configure.in
@@ -284,16 +284,66 @@ i?86-*android*)
 arm-android-eabi)
     android_tool_prefix="arm-eabi"
     ;;
 *)
     android_tool_prefix="$target_os"
     ;;
 esac
 
+MOZ_ARG_WITH_STRING(gonk,
+[  --with-gonk=DIR
+               location of gonk dir],
+    gonkdir=$withval)
+
+if test -n "$gonkdir" ; then
+    kernel_name=`uname -s | tr "[[:upper:]]" "[[:lower:]]"`
+    gonk_toolchain="$gonkdir"/prebuilt/$kernel_name-x86/toolchain/arm-eabi-4.4.3
+
+    dnl set up compilers
+    AS="$gonk_toolchain"/bin/"$android_tool_prefix"-as
+    CC="$gonk_toolchain"/bin/"$android_tool_prefix"-gcc
+    CXX="$gonk_toolchain"/bin/"$android_tool_prefix"-g++
+    CPP="$gonk_toolchain"/bin/"$android_tool_prefix"-cpp
+    LD="$gonk_toolchain"/bin/"$android_tool_prefix"-ld
+    AR="$gonk_toolchain"/bin/"$android_tool_prefix"-ar
+    RANLIB="$gonk_toolchain"/bin/"$android_tool_prefix"-ranlib
+    STRIP="$gonk_toolchain"/bin/"$android_tool_prefix"-strip
+
+    STLPORT_CPPFLAGS="-I$gonkdir/ndk/sources/cxx-stl/stlport/stlport/"
+    STLPORT_LIBS="-lstlport"
+
+    CPPFLAGS="-DANDROID -I$gonkdir/bionic/libc/include/ -I$gonkdir/bionic/libc/kernel/common -I$gonkdir/bionic/libc/arch-arm/include -I$gonkdir/bionic/libc/kernel/arch-arm -I$gonkdir/bionic/libm/include -I$gonkdir/frameworks/base/opengl/include -I$gonkdir/frameworks/base/native/include -I$gonkdir/hardware/libhardware/include -I$gonkdir/system/core/include -I$gonkdir/bionic -I$gonkdir/frameworks/base/include $STLPORT_CPPFLAGS $CPPFLAGS"
+    CFLAGS="-mandroid -fno-short-enums -fno-exceptions $CFLAGS"
+    CXXFLAGS="-mandroid -fno-short-enums -fno-exceptions $CXXFLAGS"
+    LIBS="$LIBS $STLPORT_LIBS"
+
+    dnl Add -llog by default, since we use it all over the place.
+    LDFLAGS="-mandroid -L$gonkdir/out/target/product/$GONK_PRODUCT/obj/lib -Wl,-rpath-link=$gonkdir/out/target/product/$GONK_PRODUCT/obj/lib --sysroot=$gonkdir/out/target/product/$GONK_PRODUCT/obj/ -llog $LDFLAGS"
+
+    dnl prevent cross compile section from using these flags as host flags
+    if test -z "$HOST_CPPFLAGS" ; then
+        HOST_CPPFLAGS=" "
+    fi
+    if test -z "$HOST_CFLAGS" ; then
+        HOST_CFLAGS=" "
+    fi
+    if test -z "$HOST_CXXFLAGS" ; then
+        HOST_CXXFLAGS=" "
+    fi
+    if test -z "$HOST_LDFLAGS" ; then
+        HOST_LDFLAGS=" "
+    fi
+
+    AC_DEFINE(ANDROID)
+    CROSS_COMPILE=1
+    MOZ_CHROME_FILE_FORMAT=omni
+    ZLIB_DIR=yes
+    direct_nspr_config=1
+else
 case "$target" in
 *-android*|*-linuxandroid*)
     if test -z "$android_ndk" ; then
         AC_MSG_ERROR([You must specify --with-android-ndk=/path/to/ndk when targeting Android.])
     fi
 
     if test -z "$android_sdk" ; then
         AC_MSG_ERROR([You must specify --with-android-sdk=/path/to/sdk when targeting Android.])
@@ -414,16 +464,18 @@ case "$target" in
     MOZ_CHROME_FILE_FORMAT=omni
     ZLIB_DIR=yes
     ;;
 *-linux*)
     AC_PATH_PROG(OBJCOPY,objcopy)
     ;;
 esac
 
+fi
+
 AC_SUBST(ANDROID_NDK)
 AC_SUBST(ANDROID_TOOLCHAIN)
 AC_SUBST(ANDROID_PLATFORM)
 AC_SUBST(ANDROID_SDK)
 AC_SUBST(ANDROID_PLATFORM_TOOLS)
 AC_SUBST(ANDROID_PACKAGE_NAME)
 AC_SUBST(OBJCOPY)
 
@@ -1703,16 +1755,58 @@ if test "$CPU_ARCH" = "arm"; then
       AC_DEFINE(HAVE_ARM_NEON)
       HAVE_ARM_NEON=1
   fi
 fi # CPU_ARCH = arm
 
 AC_SUBST(HAVE_ARM_SIMD)
 AC_SUBST(HAVE_ARM_NEON)
 
+dnl =================================================================
+dnl Set up and test static assertion macros used to avoid AC_TRY_RUN,
+dnl which is bad when cross compiling.
+dnl =================================================================
+if test "$COMPILE_ENVIRONMENT"; then
+configure_static_assert_macros='
+#define CONFIGURE_STATIC_ASSERT(condition) CONFIGURE_STATIC_ASSERT_IMPL(condition, __LINE__)
+#define CONFIGURE_STATIC_ASSERT_IMPL(condition, line) CONFIGURE_STATIC_ASSERT_IMPL2(condition, line)
+#define CONFIGURE_STATIC_ASSERT_IMPL2(condition, line) typedef int static_assert_line_##line[(condition) ? 1 : -1]
+'
+
+dnl test that the macros actually work:
+AC_MSG_CHECKING(that static assertion macros used in autoconf tests work)
+AC_CACHE_VAL(ac_cv_static_assertion_macros_work,
+ [AC_LANG_SAVE
+  AC_LANG_C
+  ac_cv_static_assertion_macros_work="yes"
+  AC_TRY_COMPILE([$configure_static_assert_macros],
+                 [CONFIGURE_STATIC_ASSERT(1)],
+                 ,
+                 ac_cv_static_assertion_macros_work="no")
+  AC_TRY_COMPILE([$configure_static_assert_macros],
+                 [CONFIGURE_STATIC_ASSERT(0)],
+                 ac_cv_static_assertion_macros_work="no",
+                 )
+  AC_LANG_CPLUSPLUS
+  AC_TRY_COMPILE([$configure_static_assert_macros],
+                 [CONFIGURE_STATIC_ASSERT(1)],
+                 ,
+                 ac_cv_static_assertion_macros_work="no")
+  AC_TRY_COMPILE([$configure_static_assert_macros],
+                 [CONFIGURE_STATIC_ASSERT(0)],
+                 ac_cv_static_assertion_macros_work="no",
+                 )
+  AC_LANG_RESTORE
+ ])
+AC_MSG_RESULT("$ac_cv_static_assertion_macros_work")
+if test "$ac_cv_static_assertion_macros_work" = "no"; then
+    AC_MSG_ERROR([Compiler cannot compile macros used in autoconf tests.])
+fi
+fi # COMPILE_ENVIRONMENT
+
 dnl ========================================================
 dnl Android libstdc++, placed here so it can use MOZ_ARCH
 dnl computed above.
 dnl ========================================================
 
 if test "$OS_TARGET" = "Android"; then
     case "${CPU_ARCH}-${MOZ_ARCH}" in
     arm-armv7*)
@@ -1849,16 +1943,37 @@ if test "$GNU_CXX"; then
     # versions).  We can't use -std=c++0x yet, so gcc's support must remain
     # unused.  But clang's warning can be disabled, so when compiling with clang
     # we use it to opt out of the warning, enabling (macro-encapsulated) use of
     # deleted function syntax.
     if test "$CLANG_CXX"; then
         _WARNINGS_CXXFLAGS="${_WARNINGS_CXXFLAGS} -Wno-c++0x-extensions"
     fi
 
+    AC_CACHE_CHECK(whether the compiler supports -Wno-extended-offsetof,
+                   ac_has_wno_extended_offsetof,
+        [
+            AC_LANG_SAVE
+            AC_LANG_CPLUSPLUS
+            _SAVE_CXXFLAGS="$CXXFLAGS"
+            CXXFLAGS="$CXXFLAGS ${_COMPILER_PREFIX}-Wno-extended-offsetof"
+            AC_TRY_COMPILE([$configure_static_assert_macros
+                            #ifndef __has_warning
+                            #define __has_warning(x) 0
+                            #endif],
+                           [CONFIGURE_STATIC_ASSERT(__has_warning("-Wextended-offsetof"))],
+                           ac_has_wno_extended_offsetof="yes",
+                           ac_has_wno_extended_offsetof="no")
+            CXXFLAGS="$_SAVE_CXXFLAGS"
+            AC_LANG_RESTORE
+        ])
+    if test "$ac_has_wno_extended_offsetof" = "yes"; then
+        _WARNINGS_CXXFLAGS="${_WARNINGS_CXXFLAGS} ${_COMPILER_PREFIX}-Wno-extended-offsetof"
+    fi
+
     AC_CACHE_CHECK(whether the compiler supports -Wno-invalid-offsetof,
                    ac_has_wno_invalid_offsetof,
         [
             AC_LANG_SAVE
             AC_LANG_CPLUSPLUS
             _SAVE_CXXFLAGS="$CXXFLAGS"
             CXXFLAGS="$CXXFLAGS ${_COMPILER_PREFIX}-Wno-invalid-offsetof"
             AC_TRY_COMPILE([],
@@ -1947,58 +2062,16 @@ LOOP_INPUT
     AC_MSG_RESULT(yes)
     eval $ac_cv_mkshlib_force_and_unforce
     MKSHLIB_FORCE_ALL=$force
     MKSHLIB_UNFORCE_ALL=$unforce
   fi
 fi # GNU_CC
 fi # COMPILE_ENVIRONMENT
 
-dnl =================================================================
-dnl Set up and test static assertion macros used to avoid AC_TRY_RUN,
-dnl which is bad when cross compiling.
-dnl =================================================================
-if test "$COMPILE_ENVIRONMENT"; then
-configure_static_assert_macros='
-#define CONFIGURE_STATIC_ASSERT(condition) CONFIGURE_STATIC_ASSERT_IMPL(condition, __LINE__)
-#define CONFIGURE_STATIC_ASSERT_IMPL(condition, line) CONFIGURE_STATIC_ASSERT_IMPL2(condition, line)
-#define CONFIGURE_STATIC_ASSERT_IMPL2(condition, line) typedef int static_assert_line_##line[(condition) ? 1 : -1]
-'
-
-dnl test that the macros actually work:
-AC_MSG_CHECKING(that static assertion macros used in autoconf tests work)
-AC_CACHE_VAL(ac_cv_static_assertion_macros_work,
- [AC_LANG_SAVE
-  AC_LANG_C
-  ac_cv_static_assertion_macros_work="yes"
-  AC_TRY_COMPILE([$configure_static_assert_macros],
-                 [CONFIGURE_STATIC_ASSERT(1)],
-                 ,
-                 ac_cv_static_assertion_macros_work="no")
-  AC_TRY_COMPILE([$configure_static_assert_macros],
-                 [CONFIGURE_STATIC_ASSERT(0)],
-                 ac_cv_static_assertion_macros_work="no",
-                 )
-  AC_LANG_CPLUSPLUS
-  AC_TRY_COMPILE([$configure_static_assert_macros],
-                 [CONFIGURE_STATIC_ASSERT(1)],
-                 ,
-                 ac_cv_static_assertion_macros_work="no")
-  AC_TRY_COMPILE([$configure_static_assert_macros],
-                 [CONFIGURE_STATIC_ASSERT(0)],
-                 ac_cv_static_assertion_macros_work="no",
-                 )
-  AC_LANG_RESTORE
- ])
-AC_MSG_RESULT("$ac_cv_static_assertion_macros_work")
-if test "$ac_cv_static_assertion_macros_work" = "no"; then
-    AC_MSG_ERROR([Compiler cannot compile macros used in autoconf tests.])
-fi
-fi # COMPILE_ENVIRONMENT
-
 dnl ========================================================
 dnl Checking for 64-bit OS
 dnl ========================================================
 if test "$COMPILE_ENVIRONMENT"; then
 AC_LANG_SAVE
 AC_LANG_C
 AC_MSG_CHECKING(for 64-bit OS)
 AC_TRY_COMPILE([$configure_static_assert_macros],
@@ -2381,17 +2454,21 @@ ia64*-hpux*)
     fi
     MOZ_POST_PROGRAM_COMMAND='chatr +s enable'
     AC_DEFINE(NSCAP_DISABLE_DEBUG_PTR_TYPES)
     ;;
 
 *-android*|*-linuxandroid*)
     AC_DEFINE(NO_PW_GECOS)
     no_x=yes
-    _PLATFORM_DEFAULT_TOOLKIT=cairo-android
+    if test -n "$gonkdir"; then
+        _PLATFORM_DEFAULT_TOOLKIT=cairo-gonk
+    else
+        _PLATFORM_DEFAULT_TOOLKIT=cairo-android
+    fi
     TARGET_NSPR_MDCPUCFG='\"md/_linux.cfg\"'
 
     MOZ_GFX_OPTIMIZE_MOBILE=1
     MOZ_OPTIMIZE_FLAGS="-Os -freorder-blocks -fno-reorder-functions"
     ;;
 
 *-*linux*)
     # Note: both GNU_CC and INTEL_CC are set when using Intel's C compiler.
@@ -4767,17 +4844,18 @@ MOZ_ARG_HEADER(Toolkit Options)
     if test "$_DEFAULT_TOOLKIT" = "cairo-windows" \
         -o "$_DEFAULT_TOOLKIT" = "cairo-gtk2" \
         -o "$_DEFAULT_TOOLKIT" = "cairo-gtk2-dfb" \
         -o "$_DEFAULT_TOOLKIT" = "cairo-gtk2-x11" \
         -o "$_DEFAULT_TOOLKIT" = "cairo-qt" \
         -o "$_DEFAULT_TOOLKIT" = "cairo-os2" \
         -o "$_DEFAULT_TOOLKIT" = "cairo-cocoa" \
         -o "$_DEFAULT_TOOLKIT" = "cairo-uikit" \
-        -o "$_DEFAULT_TOOLKIT" = "cairo-android"
+        -o "$_DEFAULT_TOOLKIT" = "cairo-android" \
+        -o "$_DEFAULT_TOOLKIT" = "cairo-gonk"
     then
         dnl nglayout only supports building with one toolkit,
         dnl so ignore everything after the first comma (",").
         MOZ_WIDGET_TOOLKIT=`echo "$_DEFAULT_TOOLKIT" | sed -e "s/,.*$//"`
     else
         AC_MSG_ERROR([You must specify a default toolkit (perhaps $_PLATFORM_DEFAULT_TOOLKIT).])
     fi
 
@@ -4890,16 +4968,25 @@ cairo-android)
     MOZ_WIDGET_TOOLKIT=android
     TK_CFLAGS='$(MOZ_CAIRO_CFLAGS)'
     TK_LIBS='$(MOZ_CAIRO_LIBS)'
     MOZ_WEBGL=1
     MOZ_PDF_PRINTING=1
     MOZ_INSTRUMENT_EVENT_LOOP=1
     ;;
 
+cairo-gonk)
+    AC_DEFINE(MOZ_WIDGET_GONK)
+    MOZ_WIDGET_TOOLKIT=gonk
+    TK_CFLAGS='$(MOZ_CAIRO_CFLAGS)'
+    TK_LIBS='$(MOZ_CAIRO_LIBS)'
+    MOZ_WEBGL=1
+    MOZ_PDF_PRINTING=1
+    ;;
+
 esac
 
 AC_SUBST(MOZ_PDF_PRINTING)
 if test "$MOZ_PDF_PRINTING"; then
    PDF_SURFACE_FEATURE="#define CAIRO_HAS_PDF_SURFACE 1"
    AC_DEFINE(MOZ_PDF_PRINTING)
 fi
 
@@ -7170,17 +7257,19 @@ AC_SUBST(MOZ_UTILS_PROGRAM_LDFLAGS)
 AC_SUBST(WIN32_CRT_LIBS)
 dnl Need to set this for make because NSS doesn't have configure
 AC_SUBST(DLLFLAGS)
 
 dnl We need to wrap dlopen and related functions on Android because we use
 dnl our own linker.
 if test "$OS_TARGET" = Android; then
     WRAP_LDFLAGS="${WRAP_LDFLAGS} -L$_objdir/dist/lib -lmozutils"
-    WRAP_LDFLAGS="${WRAP_LDFLAGS} -Wl,--wrap=dlopen,--wrap=dlclose,--wrap=dlerror,--wrap=dlsym,--wrap=dladdr"
+    if test "$MOZ_WIDGET_TOOLKIT" = android; then
+        WRAP_LDFLAGS="${WRAP_LDFLAGS} -Wl,--wrap=dlopen,--wrap=dlclose,--wrap=dlerror,--wrap=dlsym,--wrap=dladdr"
+    fi
 fi
 
 dnl ========================================================
 dnl = Use malloc wrapper lib
 dnl ========================================================
 MOZ_ARG_ENABLE_BOOL(wrap-malloc,
 [  --enable-wrap-malloc    Wrap malloc calls (gnu linker only)],
     _WRAP_MALLOC=1,
@@ -7223,16 +7312,27 @@ MOZ_ARG_ENABLE_BOOL(tracevis,
 [  --enable-tracevis       Enable TraceVis tracing tool (default=no)],
     MOZ_TRACEVIS=1,
     MOZ_TRACEVIS= )
 if test -n "$MOZ_TRACEVIS"; then
     AC_DEFINE(MOZ_TRACEVIS)
 fi
 
 dnl ========================================================
+dnl = Use incremental GC
+dnl ========================================================
+JSGC_INCREMENTAL=1
+MOZ_ARG_DISABLE_BOOL(gcincremental,
+[  --disable-gcincremental Disable incremental GC],
+    JSGC_INCREMENTAL= )
+if test -n "$JSGC_INCREMENTAL"; then
+    AC_DEFINE(JSGC_INCREMENTAL)
+fi
+
+dnl ========================================================
 dnl ETW - Event Tracing for Windows
 dnl ========================================================
 MOZ_ARG_ENABLE_BOOL(ETW,
 [  --enable-ETW            Enable ETW (Event Tracing for Windows) event reporting
                           (needs Windows Vista+ SDK)],
     MOZ_ETW=1,
     MOZ_ETW= )
 if test -n "$MOZ_ETW"; then
@@ -7710,28 +7810,28 @@ AC_LANG_CPLUSPLUS
 dnl ========================================================
 dnl Test for -pedantic bustage
 dnl ========================================================
 MOZ_ARG_DISABLE_BOOL(pedantic,
 [  --disable-pedantic      Issue all warnings demanded by strict ANSI C ],
 _PEDANTIC= )
 if test "$_PEDANTIC"; then
     _SAVE_CXXFLAGS=$CXXFLAGS
-    CXXFLAGS="$CXXFLAGS ${_WARNINGS_CXXFLAGS} ${_COMPILER_PREFIX}-pedantic ${_COMPILER_PREFIX}-Wno-long-long"
+    CXXFLAGS="$CXXFLAGS ${_COMPILER_PREFIX}-pedantic ${_WARNINGS_CXXFLAGS} ${_COMPILER_PREFIX}-Wno-long-long"
     AC_MSG_CHECKING([whether C++ compiler has -pedantic long long bug])
     AC_TRY_COMPILE([$configure_static_assert_macros],
                    [CONFIGURE_STATIC_ASSERT(sizeof(long long) == 8)],
                    result="no", result="yes" )
     AC_MSG_RESULT([$result])
     CXXFLAGS="$_SAVE_CXXFLAGS"
 
     case "$result" in
     no)
-        _WARNINGS_CFLAGS="${_WARNINGS_CFLAGS} ${_COMPILER_PREFIX}-pedantic ${_COMPILER_PREFIX}-Wno-long-long"
-        _WARNINGS_CXXFLAGS="${_WARNINGS_CXXFLAGS} ${_COMPILER_PREFIX}-pedantic ${_COMPILER_PREFIX}-Wno-long-long"
+        _WARNINGS_CFLAGS="${_COMPILER_PREFIX}-pedantic ${_WARNINGS_CFLAGS} ${_COMPILER_PREFIX}-Wno-long-long"
+        _WARNINGS_CXXFLAGS="${_COMPILER_PREFIX}-pedantic ${_WARNINGS_CXXFLAGS} ${_COMPILER_PREFIX}-Wno-long-long"
         ;;
     yes)
         AC_MSG_ERROR([Your compiler appears to have a known bug where long long is miscompiled when using -pedantic.  Reconfigure using --disable-pedantic. ])
         ;;
     esac
 fi
 
 dnl ========================================================
@@ -8840,30 +8940,32 @@ if test "$MOZ_TREE_FREETYPE"; then
    export CPPFLAGS="$CPPFLAGS"
    export CXXFLAGS="$CXXFLAGS"
    export LDFLAGS="$LDFLAGS"
    export CONFIG_FILES="unix-cc.mk:unix-cc.in unix-def.mk:unix-def.in freetype-config freetype2.pc:freetype2.in"
    ac_configure_args="$ac_configure_args --host=$target --disable-shared --with-pic=yes"
    AC_OUTPUT_SUBDIRS(modules/freetype2)
 fi
 
-dnl ========================================================
-dnl = Setup a nice relatively clean build environment for
-dnl = sub-configures.
-dnl ========================================================
-CC="$_SUBDIR_CC"
-CXX="$_SUBDIR_CXX"
-CFLAGS="$_SUBDIR_CFLAGS"
-CPPFLAGS="$_SUBDIR_CPPFLAGS"
-CXXFLAGS="$_SUBDIR_CXXFLAGS"
-LDFLAGS="$_SUBDIR_LDFLAGS"
-HOST_CC="$_SUBDIR_HOST_CC"
-HOST_CFLAGS="$_SUBDIR_HOST_CFLAGS"
-HOST_LDFLAGS="$_SUBDIR_HOST_LDFLAGS"
-RC=
+if test -z "$direct_nspr_config"; then
+    dnl ========================================================
+    dnl = Setup a nice relatively clean build environment for
+    dnl = sub-configures.
+    dnl ========================================================
+    CC="$_SUBDIR_CC"
+    CXX="$_SUBDIR_CXX"
+    CFLAGS="$_SUBDIR_CFLAGS"
+    CPPFLAGS="$_SUBDIR_CPPFLAGS"
+    CXXFLAGS="$_SUBDIR_CXXFLAGS"
+    LDFLAGS="$_SUBDIR_LDFLAGS"
+    HOST_CC="$_SUBDIR_HOST_CC"
+    HOST_CFLAGS="$_SUBDIR_HOST_CFLAGS"
+    HOST_LDFLAGS="$_SUBDIR_HOST_LDFLAGS"
+    RC=
+fi
 
 unset MAKEFILES
 unset CONFIG_FILES
 
 # No need to run subconfigures when building with LIBXUL_SDK_DIR
 if test "$COMPILE_ENVIRONMENT" -a -z "$LIBXUL_SDK_DIR"; then
 
 export WRAP_LDFLAGS
@@ -8902,16 +9004,33 @@ if test -z "$MOZ_NATIVE_NSPR"; then
        NSPR_LIBS=`./nsprpub/config/nspr-config --prefix=$LIBXUL_DIST --exec-prefix=$MOZ_BUILD_ROOT/dist --libdir=$LIBXUL_DIST/lib --libs`
        $PERL -pi.bak -e "s '^NSPR_LIBS\\s*=.*'NSPR_LIBS = $NSPR_LIBS'" config/autoconf.mk
        NSPR_CFLAGS=`./nsprpub/config/nspr-config --prefix=$LIBXUL_DIST --exec-prefix=$MOZ_BUILD_ROOT/dist --includedir=$LIBXUL_DIST/include/nspr --cflags`
        $PERL -pi.bak -e "s '^NSPR_CFLAGS\\s*=.*'NSPR_CFLAGS = $NSPR_CFLAGS'" config/autoconf.mk
     fi
     rm -f config/autoconf.mk.bak
 fi
 
+if test -n "$direct_nspr_config"; then
+    dnl ========================================================
+    dnl = Setup a nice relatively clean build environment for
+    dnl = sub-configures.
+    dnl ========================================================
+    CC="$_SUBDIR_CC"
+    CXX="$_SUBDIR_CXX"
+    CFLAGS="$_SUBDIR_CFLAGS"
+    CPPFLAGS="$_SUBDIR_CPPFLAGS"
+    CXXFLAGS="$_SUBDIR_CXXFLAGS"
+    LDFLAGS="$_SUBDIR_LDFLAGS"
+    HOST_CC="$_SUBDIR_HOST_CC"
+    HOST_CFLAGS="$_SUBDIR_HOST_CFLAGS"
+    HOST_LDFLAGS="$_SUBDIR_HOST_LDFLAGS"
+    RC=
+fi
+
 # Run the SpiderMonkey 'configure' script.
 dist=$MOZ_BUILD_ROOT/dist
 ac_configure_args="$_SUBDIR_CONFIG_ARGS"
 ac_configure_args="$ac_configure_args --enable-threadsafe"
 if test "$BUILD_CTYPES"; then
     # Build js-ctypes on the platforms we can.
     ac_configure_args="$ac_configure_args --enable-ctypes"
 fi
--- a/content/base/public/nsIDocumentEncoder.idl
+++ b/content/base/public/nsIDocumentEncoder.idl
@@ -46,17 +46,17 @@ interface nsIOutputStream;
 
 %{ C++
 class nsINode;
 class nsIDocument;
 %}
 [ptr] native nsINodePtr(nsINode);
 [ptr] native nsIDocumentPtr(nsIDocument);
 
-[scriptable, uuid(c0da5b87-0ba7-4d7c-8cb3-fcb02af4253d)]
+[scriptable, uuid(82adaeca-63ee-44eb-830a-e1678bb8745e)]
 interface nsIDocumentEncoderNodeFixup : nsISupports
 {
   /**
    * Create a fixed up version of a node. This method is called before
    * each node in a document is about to be persisted. The implementor
    * may return a new node with fixed up attributes or null. If null is
    * returned the node should be used as-is.
    * @param aNode Node to fixup.
@@ -267,16 +267,17 @@ interface nsIDocumentEncoder : nsISuppor
 
   /**
    *  If the node is set to a non-null value, then the
    *  node is used for encoding, otherwise the entire
    *  document or range or selection is encoded.
    * @param aNode The node to encode.
    */
   void setNode(in nsIDOMNode aNode);
+  [noscript] void setNativeNode(in nsINodePtr aNode);
 
   /**
    *  If the container is set to a non-null value, then its
    *  child nodes are used for encoding, otherwise the entire
    *  document or range or selection or node is encoded.
    *  @param aContainer The node which child nodes will be encoded.
    */
   void setContainerNode(in nsIDOMNode aContainer);
--- a/content/base/src/nsDocumentEncoder.cpp
+++ b/content/base/src/nsDocumentEncoder.cpp
@@ -297,16 +297,24 @@ NS_IMETHODIMP
 nsDocumentEncoder::SetNode(nsIDOMNode* aNode)
 {
   mNodeIsContainer = false;
   mNode = do_QueryInterface(aNode);
   return NS_OK;
 }
 
 NS_IMETHODIMP
+nsDocumentEncoder::SetNativeNode(nsINode* aNode)
+{
+  mNodeIsContainer = false;
+  mNode = aNode;
+  return NS_OK;
+}
+
+NS_IMETHODIMP
 nsDocumentEncoder::SetContainerNode(nsIDOMNode *aContainer)
 {
   mNodeIsContainer = true;
   mNode = do_QueryInterface(aContainer);
   return NS_OK;
 }
 
 NS_IMETHODIMP
--- a/content/html/content/src/nsGenericHTMLElement.cpp
+++ b/content/html/content/src/nsGenericHTMLElement.cpp
@@ -115,16 +115,17 @@
 #include "nsHtml5Module.h"
 #include "nsITextControlElement.h"
 #include "mozilla/dom/Element.h"
 #include "nsHTMLFieldSetElement.h"
 #include "nsHTMLMenuElement.h"
 #include "nsPLDOMEvent.h"
 
 #include "mozilla/Preferences.h"
+#include "mozilla/dom/FromParser.h"
 
 using namespace mozilla;
 using namespace mozilla::dom;
 
 #include "nsThreadUtils.h"
 
 class nsINodeInfo;
 class nsIDOMNodeList;
@@ -660,25 +661,23 @@ nsGenericHTMLElement::GetOffsetParent(ns
     CallQueryInterface(parent, aOffsetParent);
   } else {
     *aOffsetParent = nsnull;
   }
 
   return NS_OK;
 }
 
-NS_IMETHODIMP
-nsGenericHTMLElement::GetInnerHTML(nsAString& aInnerHTML)
+nsresult
+nsGenericHTMLElement::GetMarkup(bool aIncludeSelf, nsAString& aMarkup)
 {
-  aInnerHTML.Truncate();
+  aMarkup.Truncate();
 
   nsIDocument* doc = OwnerDoc();
 
-  nsresult rv = NS_OK;
-
   nsAutoString contentType;
   if (IsInHTMLDocument()) {
     contentType.AssignLiteral("text/html");
   } else {
     doc->GetContentType(contentType);
   }
 
   nsCOMPtr<nsIDocumentEncoder> docEncoder = doc->GetCachedEncoder();
@@ -693,31 +692,47 @@ nsGenericHTMLElement::GetInnerHTML(nsASt
     // This could be some type for which we create a synthetic document.  Try
     // again as XML
     contentType.AssignLiteral("application/xml");
     docEncoder = do_CreateInstance(NS_DOC_ENCODER_CONTRACTID_BASE "application/xml");
   }
 
   NS_ENSURE_TRUE(docEncoder, NS_ERROR_FAILURE);
 
-  rv = docEncoder->NativeInit(doc, contentType,
-                              nsIDocumentEncoder::OutputEncodeBasicEntities |
-                              // Output DOM-standard newlines
-                              nsIDocumentEncoder::OutputLFLineBreak |
-                              // Don't do linebreaking that's not present in
-                              // the source
-                              nsIDocumentEncoder::OutputRaw);
+  nsresult rv = docEncoder->NativeInit(doc, contentType,
+                                       nsIDocumentEncoder::OutputEncodeBasicEntities |
+                                       // Output DOM-standard newlines
+                                       nsIDocumentEncoder::OutputLFLineBreak |
+                                       // Don't do linebreaking that's not present in
+                                       // the source
+                                       nsIDocumentEncoder::OutputRaw);
   NS_ENSURE_SUCCESS(rv, rv);
 
-  docEncoder->SetNativeContainerNode(this);
-  rv = docEncoder->EncodeToString(aInnerHTML);
-  doc->SetCachedEncoder(docEncoder.forget());
+  if (aIncludeSelf) {
+    docEncoder->SetNativeNode(this);
+  } else {
+    docEncoder->SetNativeContainerNode(this);
+  }
+  rv = docEncoder->EncodeToString(aMarkup);
+  if (!aIncludeSelf) {
+    doc->SetCachedEncoder(docEncoder.forget());
+  }
   return rv;
 }
 
+nsresult
+nsGenericHTMLElement::GetInnerHTML(nsAString& aInnerHTML) {
+  return GetMarkup(false, aInnerHTML);
+}
+
+NS_IMETHODIMP
+nsGenericHTMLElement::GetOuterHTML(nsAString& aOuterHTML) {
+  return GetMarkup(true, aOuterHTML);
+}
+
 void
 nsGenericHTMLElement::FireMutationEventsForDirectParsing(nsIDocument* aDoc,
                                                          nsIContent* aDest,
                                                          PRInt32 aOldChildCount)
 {
   // Fire mutation events. Optimize for the case when there are no listeners
   PRInt32 newChildCount = aDest->GetChildCount();
   if (newChildCount && nsContentUtils::
@@ -735,48 +750,46 @@ nsGenericHTMLElement::FireMutationEvents
   }
 }
 
 NS_IMETHODIMP
 nsGenericHTMLElement::SetInnerHTML(const nsAString& aInnerHTML)
 {
   nsIDocument* doc = OwnerDoc();
 
-  nsresult rv = NS_OK;
-
   // Batch possible DOMSubtreeModified events.
   mozAutoSubtreeModified subtree(doc, nsnull);
 
   FireNodeRemovedForChildren();
 
   // Needed when innerHTML is used in combination with contenteditable
   mozAutoDocUpdate updateBatch(doc, UPDATE_CONTENT_MODEL, true);
 
   // Remove childnodes.
   PRUint32 childCount = GetChildCount();
   for (PRUint32 i = 0; i < childCount; ++i) {
     RemoveChildAt(0, true);
   }
 
   nsAutoScriptLoaderDisabler sld(doc);
   
-  nsCOMPtr<nsIDOMDocumentFragment> df;
-
+  nsresult rv = NS_OK;
   if (doc->IsHTML()) {
     PRInt32 oldChildCount = GetChildCount();
     rv = nsContentUtils::ParseFragmentHTML(aInnerHTML,
                                            this,
                                            Tag(),
                                            GetNameSpaceID(),
                                            doc->GetCompatibilityMode() ==
                                              eCompatibility_NavQuirks,
                                            true);
     // HTML5 parser has notified, but not fired mutation events.
     FireMutationEventsForDirectParsing(doc, this, oldChildCount);
   } else {
+    nsCOMPtr<nsIDOMDocumentFragment> df;
     rv = nsContentUtils::CreateContextualFragment(this, aInnerHTML,
                                                   true,
                                                   getter_AddRefs(df));
     nsCOMPtr<nsINode> fragment = do_QueryInterface(df);
     if (NS_SUCCEEDED(rv)) {
       // Suppress assertion about node removal mutation events that can't have
       // listeners anyway, because no one has had the chance to register mutation
       // listeners on the fragment that comes from the parser.
@@ -784,16 +797,81 @@ nsGenericHTMLElement::SetInnerHTML(const
 
       static_cast<nsINode*>(this)->AppendChild(fragment, &rv);
     }
   }
 
   return rv;
 }
 
+NS_IMETHODIMP
+nsGenericHTMLElement::SetOuterHTML(const nsAString& aOuterHTML)
+{
+  nsINode* parent = GetNodeParent();
+  if (!parent) {
+    return NS_OK;
+  }
+
+  if (parent->NodeType() == nsIDOMNode::DOCUMENT_NODE) {
+    return NS_ERROR_DOM_NO_MODIFICATION_ALLOWED_ERR;
+  }
+
+  if (OwnerDoc()->IsHTML()) {
+    nsIAtom* localName;
+    PRInt32 namespaceID;
+    if (parent->IsElement()) {
+      localName = static_cast<nsIContent*>(parent)->Tag();
+      namespaceID = static_cast<nsIContent*>(parent)->GetNameSpaceID();
+    } else {
+      NS_ASSERTION(parent->NodeType() == nsIDOMNode::DOCUMENT_FRAGMENT_NODE,
+        "How come the parent isn't a document, a fragment or an element?");
+      localName = nsGkAtoms::body;
+      namespaceID = kNameSpaceID_XHTML;
+    }
+    nsCOMPtr<nsIDOMDocumentFragment> df;
+    nsresult rv = NS_NewDocumentFragment(getter_AddRefs(df),
+                                         OwnerDoc()->NodeInfoManager());
+    NS_ENSURE_SUCCESS(rv, rv);
+    nsCOMPtr<nsIContent> fragment = do_QueryInterface(df);
+    nsContentUtils::ParseFragmentHTML(aOuterHTML,
+                                      fragment,
+                                      localName,
+                                      namespaceID,
+                                      OwnerDoc()->GetCompatibilityMode() ==
+                                        eCompatibility_NavQuirks,
+                                      PR_TRUE);
+    parent->ReplaceChild(fragment, this, &rv);
+    return rv;
+  }
+
+  nsCOMPtr<nsINode> context;
+  if (parent->IsElement()) {
+    context = parent;
+  } else {
+    NS_ASSERTION(parent->NodeType() == nsIDOMNode::DOCUMENT_FRAGMENT_NODE,
+      "How come the parent isn't a document, a fragment or an element?");
+    nsCOMPtr<nsINodeInfo> info =
+      OwnerDoc()->NodeInfoManager()->GetNodeInfo(nsGkAtoms::body,
+                                                 nsnull,
+                                                 kNameSpaceID_XHTML,
+                                                 nsIDOMNode::ELEMENT_NODE);
+    context = NS_NewHTMLBodyElement(info.forget(), FROM_PARSER_FRAGMENT);
+  }
+
+  nsCOMPtr<nsIDOMDocumentFragment> df;
+  nsresult rv = nsContentUtils::CreateContextualFragment(context,
+                                                         aOuterHTML,
+                                                         PR_TRUE,
+                                                         getter_AddRefs(df));
+  NS_ENSURE_SUCCESS(rv, rv);
+  nsCOMPtr<nsINode> fragment = do_QueryInterface(df);
+  parent->ReplaceChild(fragment, this, &rv);
+  return rv;
+}
+
 enum nsAdjacentPosition {
   eBeforeBegin,
   eAfterBegin,
   eBeforeEnd,
   eAfterEnd
 };
 
 NS_IMETHODIMP
--- a/content/html/content/src/nsGenericHTMLElement.h
+++ b/content/html/content/src/nsGenericHTMLElement.h
@@ -127,16 +127,18 @@ public:
   nsresult SetClassName(const nsAString& aClassName);
   nsresult GetOffsetTop(PRInt32* aOffsetTop);
   nsresult GetOffsetLeft(PRInt32* aOffsetLeft);
   nsresult GetOffsetWidth(PRInt32* aOffsetWidth);
   nsresult GetOffsetHeight(PRInt32* aOffsetHeight);
   nsresult GetOffsetParent(nsIDOMElement** aOffsetParent);
   NS_IMETHOD GetInnerHTML(nsAString& aInnerHTML);
   NS_IMETHOD SetInnerHTML(const nsAString& aInnerHTML);
+  NS_IMETHOD GetOuterHTML(nsAString& aOuterHTML);
+  NS_IMETHOD SetOuterHTML(const nsAString& aOuterHTML);
   NS_IMETHOD InsertAdjacentHTML(const nsAString& aPosition,
                                 const nsAString& aText);
   nsresult ScrollIntoView(bool aTop, PRUint8 optional_argc);
   nsresult MozRequestFullScreen();
   // Declare Focus(), Blur(), GetTabIndex(), SetTabIndex(), GetHidden(),
   // SetHidden(), GetSpellcheck(), SetSpellcheck(), and GetDraggable() such that
   // classes that inherit interfaces with those methods properly override them.
   NS_IMETHOD Focus();
@@ -156,16 +158,20 @@ public:
   nsresult GetContentEditable(nsAString& aContentEditable);
   nsresult GetIsContentEditable(bool* aContentEditable);
   nsresult SetContentEditable(const nsAString &aContentEditable);
   nsresult GetDataset(nsIDOMDOMStringMap** aDataset);
   // Callback for destructor of of dataset to ensure to null out weak pointer.
   nsresult ClearDataset();
   nsresult GetContextMenu(nsIDOMHTMLMenuElement** aContextMenu);
 
+protected:
+  nsresult GetMarkup(bool aIncludeSelf, nsAString& aMarkup);
+
+public:
   // Implementation for nsIContent
   virtual nsresult BindToTree(nsIDocument* aDocument, nsIContent* aParent,
                               nsIContent* aBindingParent,
                               bool aCompileEventHandlers);
   virtual void UnbindFromTree(bool aDeep = true,
                               bool aNullParent = true);
   nsresult SetAttr(PRInt32 aNameSpaceID, nsIAtom* aName,
                    const nsAString& aValue, bool aNotify)
@@ -1566,16 +1572,22 @@ protected:
     return _to GetContextMenu(aContextMenu); \
   } \
   NS_SCRIPTABLE NS_IMETHOD GetSpellcheck(bool* aSpellcheck) { \
     return _to GetSpellcheck(aSpellcheck); \
   } \
   NS_SCRIPTABLE NS_IMETHOD SetSpellcheck(bool aSpellcheck) { \
     return _to SetSpellcheck(aSpellcheck); \
   } \
+  NS_SCRIPTABLE NS_IMETHOD GetOuterHTML(nsAString& aOuterHTML) { \
+    return _to GetOuterHTML(aOuterHTML); \
+  } \
+  NS_SCRIPTABLE NS_IMETHOD SetOuterHTML(const nsAString& aOuterHTML) { \
+    return _to SetOuterHTML(aOuterHTML); \
+  } \
   NS_SCRIPTABLE NS_IMETHOD InsertAdjacentHTML(const nsAString& position, const nsAString& text) { \
     return _to InsertAdjacentHTML(position, text); \
   } \
   NS_SCRIPTABLE NS_IMETHOD ScrollIntoView(bool top, PRUint8 _argc) { \
     return _to ScrollIntoView(top, _argc); \
   } \
   NS_SCRIPTABLE NS_IMETHOD GetOffsetParent(nsIDOMElement** aOffsetParent) { \
     return _to GetOffsetParent(aOffsetParent); \
--- a/content/html/content/src/nsHTMLCanvasElement.cpp
+++ b/content/html/content/src/nsHTMLCanvasElement.cpp
@@ -496,18 +496,18 @@ nsHTMLCanvasElement::GetContext(const ns
       // note: if any contexts end up supporting something other
       // than objects, e.g. plain strings, then we'll need to expand
       // this to know how to create nsISupportsStrings etc.
       if (JSVAL_IS_OBJECT(aContextOptions)) {
         contextProps = do_CreateInstance("@mozilla.org/hash-property-bag;1");
 
         JSObject *opts = JSVAL_TO_OBJECT(aContextOptions);
         JSIdArray *props = JS_Enumerate(cx, opts);
-        for (int i = 0; props && i < props->length; ++i) {
-          jsid propid = props->vector[i];
+        for (int i = 0; props && i < JS_IdArrayLength(cx, props); ++i) {
+          jsid propid = JS_IdArrayGet(cx, props, i);
           jsval propname, propval;
           if (!JS_IdToValue(cx, propid, &propname) ||
               !JS_GetPropertyById(cx, opts, propid, &propval))
           {
             continue;
           }
 
           JSString *propnameString = JS_ValueToString(cx, propname);
--- a/content/html/content/src/nsHTMLDNSPrefetch.cpp
+++ b/content/html/content/src/nsHTMLDNSPrefetch.cpp
@@ -390,17 +390,18 @@ nsHTMLDNSPrefetch::nsDeferrals::OnProgre
                                                  PRInt32 maxTotalProgress)
 {
   return NS_OK;
 }
 
 NS_IMETHODIMP
 nsHTMLDNSPrefetch::nsDeferrals::OnLocationChange(nsIWebProgress* aWebProgress,
                                                  nsIRequest* aRequest,
-                                                 nsIURI *location)
+                                                 nsIURI *location,
+                                                 PRUint32 aFlags)
 {
   return NS_OK;
 }
 
 NS_IMETHODIMP 
 nsHTMLDNSPrefetch::nsDeferrals::OnStatusChange(nsIWebProgress* aWebProgress,
                                                nsIRequest* aRequest,
                                                nsresult aStatus,
--- a/content/html/content/src/nsHTMLFormElement.cpp
+++ b/content/html/content/src/nsHTMLFormElement.cpp
@@ -1838,17 +1838,18 @@ nsHTMLFormElement::OnProgressChange(nsIW
 {
   NS_NOTREACHED("notification excluded in AddProgressListener(...)");
   return NS_OK;
 }
 
 NS_IMETHODIMP
 nsHTMLFormElement::OnLocationChange(nsIWebProgress* aWebProgress,
                                     nsIRequest* aRequest,
-                                    nsIURI* location)
+                                    nsIURI* location,
+                                    PRUint32 aFlags)
 {
   NS_NOTREACHED("notification excluded in AddProgressListener(...)");
   return NS_OK;
 }
 
 NS_IMETHODIMP
 nsHTMLFormElement::OnStatusChange(nsIWebProgress* aWebProgress,
                                   nsIRequest* aRequest,
--- a/content/xslt/src/base/txCore.h
+++ b/content/xslt/src/base/txCore.h
@@ -104,15 +104,12 @@ public:
      * represent a double, NaN will be returned.
      */
     static double toDouble(const nsAString& aStr);
 };
 
 // XXX These should go away eventually.
 #define TxObject txObject
 typedef txDouble Double;
-typedef bool MBool;
 
-#define MB_TRUE  true
-#define MB_FALSE false
 // XXX
 
 #endif
--- a/content/xslt/src/base/txDouble.cpp
+++ b/content/xslt/src/base/txDouble.cpp
@@ -58,34 +58,34 @@ const dpun Double::NEGATIVE_INFINITY = {
 const dpun Double::POSITIVE_INFINITY = {{0, DOUBLE_HI32_EXPMASK}};
 const dpun Double::NEGATIVE_INFINITY = {{0, DOUBLE_HI32_EXPMASK | DOUBLE_HI32_SIGNBIT}};
 #endif
 
 /*
  * Determines whether the given double represents positive or negative
  * inifinity
  */
-MBool Double::isInfinite(double aDbl)
+bool Double::isInfinite(double aDbl)
 {
     return ((DOUBLE_HI32(aDbl) & ~DOUBLE_HI32_SIGNBIT) == DOUBLE_HI32_EXPMASK &&
             !DOUBLE_LO32(aDbl));
 }
 
 /*
  * Determines whether the given double is NaN
  */
-MBool Double::isNaN(double aDbl)
+bool Double::isNaN(double aDbl)
 {
     return DOUBLE_IS_NaN(aDbl);
 }
 
 /*
  * Determines whether the given double is negative
  */
-MBool Double::isNeg(double aDbl)
+bool Double::isNeg(double aDbl)
 {
     return (DOUBLE_HI32(aDbl) & DOUBLE_HI32_SIGNBIT) != 0;
 }
 
 /*
  * Converts the given String to a double, if the String value does not
  * represent a double, NaN will be returned
  */
--- a/content/xslt/src/base/txExpandedNameMap.h
+++ b/content/xslt/src/base/txExpandedNameMap.h
@@ -90,17 +90,17 @@ protected:
     class iterator_base {
     public:
         iterator_base(txExpandedNameMap_base& aMap)
             : mMap(aMap),
               mCurrentPos(PRUint32(-1))
         {
         }
 
-        MBool next()
+        bool next()
         {
             return ++mCurrentPos < mMap.mItems.Length();
         }
 
         const txExpandedName key()
         {
             NS_ASSERTION(mCurrentPos >= 0 &&
                          mCurrentPos < mMap.mItems.Length(),
--- a/content/xslt/src/base/txList.cpp
+++ b/content/xslt/src/base/txList.cpp
@@ -238,17 +238,17 @@ void txList::clear()
 
 /**
  * Creates a new txListIterator for the given txList
  * @param list, the txList to create an Iterator for
 **/
 txListIterator::txListIterator(txList* list) {
    this->list   = list;
    currentItem  = 0;
-   atEndOfList  = MB_FALSE;
+   atEndOfList  = false;
 } //-- txListIterator
 
 /**
  * Adds the Object pointer to the txList pointed to by this txListIterator.
  * The Object pointer is inserted as the next item in the txList
  * based on the current position within the txList
  * @param objPtr the Object pointer to add to the list
 **/
@@ -271,36 +271,36 @@ nsresult txListIterator::addBefore(void*
     if (currentItem || atEndOfList)
         return list->insertBefore(objPtr, currentItem);
     return list->insertAfter(objPtr, 0);
 
 } //-- addBefore
 
 /**
  * Returns true if a successful call to the next() method can be made
- * @return MB_TRUE if a successful call to the next() method can be made,
- * otherwise MB_FALSE
+ * @return true if a successful call to the next() method can be made,
+ * otherwise false
 **/
-MBool txListIterator::hasNext() {
-    MBool hasNext = MB_FALSE;
+bool txListIterator::hasNext() {
+    bool hasNext = false;
     if (currentItem)
         hasNext = (currentItem->nextItem != 0);
     else if (!atEndOfList)
         hasNext = (list->firstItem != 0);
 
     return hasNext;
 } //-- hasNext
 
 /**
  * Returns true if a successful call to the previous() method can be made
- * @return MB_TRUE if a successful call to the previous() method can be made,
- * otherwise MB_FALSE
+ * @return true if a successful call to the previous() method can be made,
+ * otherwise false
 **/
-MBool txListIterator::hasPrevious() {
-    MBool hasPrevious = MB_FALSE;
+bool txListIterator::hasPrevious() {
+    bool hasPrevious = false;
     if (currentItem)
         hasPrevious = (currentItem->prevItem != 0);
     else if (atEndOfList)
         hasPrevious = (list->lastItem != 0);
 
     return hasPrevious;
 } //-- hasPrevious
 
@@ -313,17 +313,17 @@ void* txListIterator::next() {
     if (currentItem)
         currentItem = currentItem->nextItem;
     else if (!atEndOfList)
         currentItem = list->firstItem;
 
     if (currentItem)
         obj = currentItem->objPtr;
     else
-        atEndOfList = MB_TRUE;
+        atEndOfList = true;
 
     return obj;
 } //-- next
 
 /**
  * Returns the previous Object in the list
 **/
 void* txListIterator::previous() {
@@ -333,17 +333,17 @@ void* txListIterator::previous() {
     if (currentItem)
         currentItem = currentItem->prevItem;
     else if (atEndOfList)
         currentItem = list->lastItem;
     
     if (currentItem)
         obj = currentItem->objPtr;
 
-    atEndOfList = MB_FALSE;
+    atEndOfList = false;
 
     return obj;
 } //-- previous
 
 /**
  * Returns the current Object
 **/
 void* txListIterator::current() {
@@ -374,17 +374,17 @@ void* txListIterator::advance(int i) {
     else if (i < 0) {
         if (!currentItem && atEndOfList) {
             currentItem = list->lastItem;
             ++i;
         }
         for (; currentItem && i < 0; i++)
             currentItem = currentItem->prevItem;
 
-        atEndOfList = MB_FALSE;
+        atEndOfList = false;
     }
 
     if (currentItem)
         obj = currentItem->objPtr;
 
     return obj;
 } //-- advance
 
@@ -404,19 +404,19 @@ void* txListIterator::remove() {
     }
     return obj;
 } //-- remove
 
 /**
  * Resets the current location within the txList to the beginning of the txList
 **/
 void txListIterator::reset() {
-   atEndOfList = MB_FALSE;
+   atEndOfList = false;
    currentItem = 0;
 } //-- reset
 
 /**
  * Move the iterator to right after the last element
 **/
 void txListIterator::resetToEnd() {
-   atEndOfList = MB_TRUE;
+   atEndOfList = true;
    currentItem = 0;
 } //-- moveToEnd
--- a/content/xslt/src/base/txList.h
+++ b/content/xslt/src/base/txList.h
@@ -156,27 +156,27 @@ public:
      * The Object pointer is inserted as the previous item in the txList
      * based on the current position within the txList
      * @param objPtr the Object pointer to add to the list
     **/
     nsresult addBefore(void* objPtr);
 
     /**
      * Returns true if a successful call to the next() method can be made
-     * @return MB_TRUE if a successful call to the next() method can be made,
-     * otherwise MB_FALSE
+     * @return true if a successful call to the next() method can be made,
+     * otherwise false
     **/
-    MBool  hasNext();
+    bool  hasNext();
 
     /**
      * Returns true if a successful call to the previous() method can be made
-     * @return MB_TRUE if a successful call to the previous() method can be made,
-     * otherwise MB_FALSE
+     * @return true if a successful call to the previous() method can be made,
+     * otherwise false
     **/
-    MBool  hasPrevious();
+    bool  hasPrevious();
 
     /**
      * Returns the next Object pointer from the list
     **/
     void* next();
 
     /**
      * Returns the previous Object pointer from the list
@@ -213,14 +213,14 @@ private:
 
    //-- points to the current list item
    txList::ListItem* currentItem;
 
    //-- points to the list to iterator over
    txList* list;
 
    //-- we've moved off the end of the list
-   MBool atEndOfList;
+   bool atEndOfList;
 };
 
 typedef txList List;
 
 #endif
--- a/content/xslt/src/xml/txDOM.h
+++ b/content/xslt/src/xml/txDOM.h
@@ -111,26 +111,26 @@ class Node : public TxObject
     virtual Node* getLastChild() const = 0;
     virtual Node* getPreviousSibling() const = 0;
     virtual Node* getNextSibling() const = 0;
     virtual Document* getOwnerDocument() const = 0;
 
     //Node manipulation functions
     virtual Node* appendChild(Node* newChild) = 0;
 
-    virtual MBool hasChildNodes() const = 0;
+    virtual bool hasChildNodes() const = 0;
     
     //From DOM3 26-Jan-2001 WD
     virtual nsresult getBaseURI(nsAString& aURI) = 0;
 
     //Introduced in DOM2
     virtual nsresult getNamespaceURI(nsAString& aNSURI) = 0;
 
     //txXPathNode functions
-    virtual MBool getLocalName(nsIAtom** aLocalName) = 0;
+    virtual bool getLocalName(nsIAtom** aLocalName) = 0;
     virtual PRInt32 getNamespaceID() = 0;
     virtual Node* getXPathParent() = 0;
     virtual PRInt32 compareDocumentPosition(Node* aOther) = 0;
 };
 
 //
 // Definition and Implementation of Node and NodeList functionality.  This is
 // the central class, from which all other DOM classes (objects) are derrived.
@@ -151,26 +151,26 @@ class NodeDefinition : public Node
     Node* getLastChild() const;
     Node* getPreviousSibling() const;
     Node* getNextSibling() const;
     Document* getOwnerDocument() const;
 
     //Child node manipulation functions
     virtual Node* appendChild(Node* newChild);
 
-    MBool hasChildNodes() const;
+    bool hasChildNodes() const;
     
     //From DOM3 26-Jan-2001 WD
     virtual nsresult getBaseURI(nsAString& aURI);
 
     //Introduced in DOM2
     nsresult getNamespaceURI(nsAString& aNSURI);
 
     //txXPathNode functions
-    virtual MBool getLocalName(nsIAtom** aLocalName);
+    virtual bool getLocalName(nsIAtom** aLocalName);
     virtual PRInt32 getNamespaceID();
     virtual Node* getXPathParent();
     virtual PRInt32 compareDocumentPosition(Node* aOther);
 
     //Only to be used from XMLParser
     void appendData(const PRUnichar* aData, int aLength)
     {
       nodeValue.Append(aData, aLength);
@@ -294,20 +294,20 @@ class Element : public NodeDefinition
     nsresult appendAttributeNS(nsIAtom *aPrefix, nsIAtom *aLocalName,
                                PRInt32 aNamespaceID, const nsAString& aValue);
 
     // Node manipulation functions
     Node* appendChild(Node* newChild);
 
     //txXPathNode functions override
     nsresult getNodeName(nsAString& aName) const;
-    MBool getLocalName(nsIAtom** aLocalName);
+    bool getLocalName(nsIAtom** aLocalName);
     PRInt32 getNamespaceID();
-    MBool getAttr(nsIAtom* aLocalName, PRInt32 aNSID, nsAString& aValue);
-    MBool hasAttr(nsIAtom* aLocalName, PRInt32 aNSID);
+    bool getAttr(nsIAtom* aLocalName, PRInt32 aNSID, nsAString& aValue);
+    bool hasAttr(nsIAtom* aLocalName, PRInt32 aNSID);
 
     // ID getter
     bool getIDValue(nsAString& aValue);
 
     Attr *getFirstAttribute()
     {
       return mFirstAttribute;
     }
@@ -332,17 +332,17 @@ class Element : public NodeDefinition
 //
 class Attr : public NodeDefinition
 {
   public:
     Node* appendChild(Node* newChild);
 
     //txXPathNode functions override
     nsresult getNodeName(nsAString& aName) const;
-    MBool getLocalName(nsIAtom** aLocalName);
+    bool getLocalName(nsIAtom** aLocalName);
     PRInt32 getNamespaceID();
     Node* getXPathParent();
     bool equals(nsIAtom *aLocalName, PRInt32 aNamespaceID)
     {
       return mLocalName == aLocalName && aNamespaceID == mNamespaceID;
     }
     Attr *getNextAttribute()
     {
@@ -368,17 +368,17 @@ class Attr : public NodeDefinition
 //  inherrited from NodeDefinition.
 //  The Data of a processing instruction is stored in the nodeValue datamember
 //  inherrited from NodeDefinition
 //
 class ProcessingInstruction : public NodeDefinition
 {
   public:
     //txXPathNode functions override
-    MBool getLocalName(nsIAtom** aLocalName);
+    bool getLocalName(nsIAtom** aLocalName);
 
   private:
     friend class Document;
     ProcessingInstruction(nsIAtom *theTarget, const nsAString& theData,
                           Document* owner);
 };
 
 class txStandaloneNamespaceManager
@@ -410,40 +410,40 @@ public:
             aID > mNamespaces->Count()) {
             return NS_OK;
         }
 
         aNSURI = *mNamespaces->StringAt(aID - 1);
         return NS_OK;
     }
 
-    static MBool init()
+    static bool init()
     {
         NS_ASSERTION(!mNamespaces,
                      "called without matching shutdown()");
         if (mNamespaces)
-            return MB_TRUE;
+            return true;
         mNamespaces = new nsStringArray();
         if (!mNamespaces)
-            return MB_FALSE;
+            return false;
         /*
          * Hardwiring some Namespace IDs.
          * no Namespace is 0
          * xmlns prefix is 1, mapped to http://www.w3.org/2000/xmlns/
          * xml prefix is 2, mapped to http://www.w3.org/XML/1998/namespace
          */
         if (!mNamespaces->AppendString(NS_LITERAL_STRING("http://www.w3.org/2000/xmlns/")) ||
             !mNamespaces->AppendString(NS_LITERAL_STRING("http://www.w3.org/XML/1998/namespace")) ||
             !mNamespaces->AppendString(NS_LITERAL_STRING("http://www.w3.org/1999/XSL/Transform"))) {
             delete mNamespaces;
             mNamespaces = 0;
-            return MB_FALSE;
+            return false;
         }
 
-        return MB_TRUE;
+        return true;
     }
 
     static void shutdown()
     {
         NS_ASSERTION(mNamespaces, "called without matching init()");
         if (!mNamespaces)
             return;
         delete mNamespaces;
--- a/content/xslt/src/xml/txXMLUtils.cpp
+++ b/content/xslt/src/xml/txXMLUtils.cpp
@@ -46,17 +46,17 @@
 #include "nsReadableUtils.h"
 #include "nsGkAtoms.h"
 #include "txStringUtils.h"
 #include "txNamespaceMap.h"
 #include "txXPathTreeWalker.h"
 
 nsresult
 txExpandedName::init(const nsAString& aQName, txNamespaceMap* aResolver,
-                     MBool aUseDefault)
+                     bool aUseDefault)
 {
     const nsAFlatString& qName = PromiseFlatString(aQName);
     const PRUnichar* colon;
     bool valid = XMLUtils::isValidQName(qName, &colon);
     if (!valid) {
         return NS_ERROR_FAILURE;
     }
 
@@ -225,17 +225,17 @@ void XMLUtils::normalizePIValue(nsAStrin
         }
         piValue.Append(ch);
         prevCh = ch;
         ++conversionLoop;
     }
 }
 
 //static
-MBool XMLUtils::getXMLSpacePreserve(const txXPathNode& aNode)
+bool XMLUtils::getXMLSpacePreserve(const txXPathNode& aNode)
 {
     nsAutoString value;
     txXPathTreeWalker walker(aNode);
     do {
         if (walker.getAttr(nsGkAtoms::space, kNameSpaceID_XML, value)) {
             if (TX_StringEqualsAtom(value, nsGkAtoms::preserve)) {
                 return true;
             }
--- a/content/xslt/src/xml/txXMLUtils.h
+++ b/content/xslt/src/xml/txXMLUtils.h
@@ -70,17 +70,17 @@ public:
 
     txExpandedName(const txExpandedName& aOther) :
         mNamespaceID(aOther.mNamespaceID),
         mLocalName(aOther.mLocalName)
     {
     }
 
     nsresult init(const nsAString& aQName, txNamespaceMap* aResolver,
-                  MBool aUseDefault);
+                  bool aUseDefault);
 
     void reset()
     {
         mNamespaceID = kNameSpaceID_None;
         mLocalName = nsnull;
     }
 
     bool isNull()
@@ -90,23 +90,23 @@ public:
 
     txExpandedName& operator = (const txExpandedName& rhs)
     {
         mNamespaceID = rhs.mNamespaceID;
         mLocalName = rhs.mLocalName;
         return *this;
     }
 
-    MBool operator == (const txExpandedName& rhs) const
+    bool operator == (const txExpandedName& rhs) const
     {
         return ((mLocalName == rhs.mLocalName) &&
                 (mNamespaceID == rhs.mNamespaceID));
     }
 
-    MBool operator != (const txExpandedName& rhs) const
+    bool operator != (const txExpandedName& rhs) const
     {
         return ((mLocalName != rhs.mLocalName) ||
                 (mNamespaceID != rhs.mNamespaceID));
     }
 
     PRInt32 mNamespaceID;
     nsCOMPtr<nsIAtom> mLocalName;
 };
@@ -119,17 +119,17 @@ public:
                                    PRInt32* aNameSpaceID);
     static nsresult splitQName(const nsAString& aName, nsIAtom** aPrefix,
                                nsIAtom** aLocalName);
     static const nsDependentSubstring getLocalPart(const nsAString& src);
 
     /*
      * Returns true if the given character is whitespace.
      */
-    static MBool isWhitespace(const PRUnichar& aChar)
+    static bool isWhitespace(const PRUnichar& aChar)
     {
         return (aChar <= ' ' &&
                 (aChar == ' ' || aChar == '\r' ||
                  aChar == '\n'|| aChar == '\t'));
     }
 
     /**
      * Returns true if the given string has only whitespace characters
@@ -168,12 +168,12 @@ public:
         nsIParserService* ps = nsContentUtils::GetParserService();
         return ps && ps->IsXMLNCNameChar(aChar);
     }
 
     /*
      * Walks up the document tree and returns true if the closest xml:space
      * attribute is "preserve"
      */
-    static MBool getXMLSpacePreserve(const txXPathNode& aNode);
+    static bool getXMLSpacePreserve(const txXPathNode& aNode);
 };
 
 #endif
--- a/content/xslt/src/xpath/nsXPathExpression.cpp
+++ b/content/xslt/src/xpath/nsXPathExpression.cpp
@@ -191,19 +191,19 @@ nsresult
 nsXPathExpression::EvalContextImpl::getVariable(PRInt32 aNamespace,
                                                 nsIAtom* aLName,
                                                 txAExprResult*& aResult)
 {
     aResult = 0;
     return NS_ERROR_INVALID_ARG;
 }
 
-MBool nsXPathExpression::EvalContextImpl::isStripSpaceAllowed(const txXPathNode& aNode)
+bool nsXPathExpression::EvalContextImpl::isStripSpaceAllowed(const txXPathNode& aNode)
 {
-    return MB_FALSE;
+    return false;
 }
 
 void* nsXPathExpression::EvalContextImpl::getPrivateContext()
 {
     // we don't have a private context here.
     return nsnull;
 }
 
--- a/content/xslt/src/xpath/txBooleanResult.cpp
+++ b/content/xslt/src/xpath/txBooleanResult.cpp
@@ -38,18 +38,18 @@
 
 /*
  * Boolean Expression result
 */
 
 #include "txExprResult.h"
 
 /**
- * Creates a new BooleanResult with the value of the given MBool parameter
- * @param boolean the MBool to use for initialization of this BooleanResult's value
+ * Creates a new BooleanResult with the value of the given bool parameter
+ * @param boolean the bool to use for initialization of this BooleanResult's value
 **/
 BooleanResult::BooleanResult(bool boolean)
     : txAExprResult(nsnull)
 {
     this->value = boolean;
 } //-- BooleanResult
 
 /*
@@ -75,15 +75,15 @@ const nsString*
 BooleanResult::stringValuePointer()
 {
     // In theory we could set strings containing "true" and "false" somewhere,
     // but most stylesheets never get the stringvalue of a bool so that won't
     // really buy us anything.
     return nsnull;
 }
 
-MBool BooleanResult::booleanValue() {
+bool BooleanResult::booleanValue() {
    return this->value;
 } //-- toBoolean
 
 double BooleanResult::numberValue() {
     return ( value ) ? 1.0 : 0.0;
 } //-- toNumber
--- a/content/xslt/src/xpath/txCoreFunctionCall.cpp
+++ b/content/xslt/src/xpath/txCoreFunctionCall.cpp
@@ -298,33 +298,33 @@ txCoreFunctionCall::evaluate(txIEvalCont
                 txXPathNodeUtils::appendNodeValue(aContext->getContextNode(),
                                                   resultStr);
             }
 
             nsRefPtr<StringResult> strRes;
             rv = aContext->recycler()->getStringResult(getter_AddRefs(strRes));
             NS_ENSURE_SUCCESS(rv, rv);
 
-            MBool addSpace = MB_FALSE;
-            MBool first = MB_TRUE;
+            bool addSpace = false;
+            bool first = true;
             strRes->mValue.SetCapacity(resultStr.Length());
             PRUnichar c;
             PRUint32 src;
             for (src = 0; src < resultStr.Length(); src++) {
                 c = resultStr.CharAt(src);
                 if (XMLUtils::isWhitespace(c)) {
-                    addSpace = MB_TRUE;
+                    addSpace = true;
                 }
                 else {
                     if (addSpace && !first)
                         strRes->mValue.Append(PRUnichar(' '));
 
                     strRes->mValue.Append(c);
-                    addSpace = MB_FALSE;
-                    first = MB_FALSE;
+                    addSpace = false;
+                    first = false;
                 }
             }
             *aResult = strRes;
             NS_ADDREF(*aResult);
 
             return NS_OK;
         }
         case STARTS_WITH:
--- a/content/xslt/src/xpath/txExprParser.cpp
+++ b/content/xslt/src/xpath/txExprParser.cpp
@@ -297,17 +297,17 @@ txExprParser::createBinaryExpr(nsAutoPtr
 
 nsresult
 txExprParser::createExpr(txExprLexer& lexer, txIParseContext* aContext,
                          Expr** aResult)
 {
     *aResult = nsnull;
 
     nsresult rv = NS_OK;
-    MBool done = MB_FALSE;
+    bool done = false;
 
     nsAutoPtr<Expr> expr;
 
     txStack exprs;
     txStack ops;
 
     while (!done) {
 
--- a/content/xslt/src/xpath/txExprParser.h
+++ b/content/xslt/src/xpath/txExprParser.h
@@ -117,17 +117,17 @@ protected:
 
     /**
      * Resolve a QName, given the mContext parse context.
      * Returns prefix and localName as well as namespace ID
      */
     static nsresult resolveQName(const nsAString& aQName, nsIAtom** aPrefix,
                                  txIParseContext* aContext,
                                  nsIAtom** aLocalName, PRInt32& aNamespace,
-                                 bool aIsNameTest = MB_FALSE);
+                                 bool aIsNameTest = false);
 
     /**
      * Using the given lexer, parses the tokens if they represent a
      * predicate list
      * If an error occurs a non-zero String pointer will be returned
      * containing the error message.
      * @param predicateList, the PredicateList to add predicate expressions to
      * @param lexer the ExprLexer to use for parsing tokens
--- a/content/xslt/src/xpath/txExprResult.h
+++ b/content/xslt/src/xpath/txExprResult.h
@@ -99,20 +99,20 @@ public:
 
     /**
      * Returns a pointer to the stringvalue if possible. Otherwise null is
      * returned.
      */
     virtual const nsString* stringValuePointer() = 0;
 
     /**
-     * Converts this ExprResult to a Boolean (MBool) value
+     * Converts this ExprResult to a Boolean (bool) value
      * @return the Boolean value
     **/
-    virtual MBool booleanValue()          = 0;
+    virtual bool booleanValue()          = 0;
 
     /**
      * Converts this ExprResult to a Number (double) value
      * @return the Number value
     **/
     virtual double numberValue()          = 0;
 
 private:
@@ -126,22 +126,22 @@ private:
     virtual const nsString* stringValuePointer();                 \
     virtual bool booleanValue();                                \
     virtual double numberValue();                                 \
 
 
 class BooleanResult : public txAExprResult {
 
 public:
-    BooleanResult(MBool aValue);
+    BooleanResult(bool aValue);
 
     TX_DECL_EXPRRESULT
 
 private:
-    MBool value;
+    bool value;
 };
 
 class NumberResult : public txAExprResult {
 
 public:
     NumberResult(double aValue, txResultRecycler* aRecycler);
 
     TX_DECL_EXPRRESULT
--- a/content/xslt/src/xpath/txForwardContext.cpp
+++ b/content/xslt/src/xpath/txForwardContext.cpp
@@ -58,17 +58,17 @@ PRUint32 txForwardContext::position()
 
 nsresult txForwardContext::getVariable(PRInt32 aNamespace, nsIAtom* aLName,
                                        txAExprResult*& aResult)
 {
     NS_ASSERTION(mInner, "mInner is null!!!");
     return mInner->getVariable(aNamespace, aLName, aResult);
 }
 
-MBool txForwardContext::isStripSpaceAllowed(const txXPathNode& aNode)
+bool txForwardContext::isStripSpaceAllowed(const txXPathNode& aNode)
 {
     NS_ASSERTION(mInner, "mInner is null!!!");
     return mInner->isStripSpaceAllowed(aNode);
 }
 
 void* txForwardContext::getPrivateContext()
 {
     NS_ASSERTION(mInner, "mInner is null!!!");
--- a/content/xslt/src/xpath/txIXPathContext.h
+++ b/content/xslt/src/xpath/txIXPathContext.h
@@ -108,17 +108,17 @@ public:
      */
     virtual nsresult getVariable(PRInt32 aNamespace, nsIAtom* aLName,
                                  txAExprResult*& aResult) = 0;
 
     /*
      * Is whitespace stripping allowed for the given node?
      * See http://www.w3.org/TR/xslt#strip
      */
-    virtual MBool isStripSpaceAllowed(const txXPathNode& aNode) = 0;
+    virtual bool isStripSpaceAllowed(const txXPathNode& aNode) = 0;
 
     /**
      * Returns a pointer to the private context
      */
     virtual void* getPrivateContext() = 0;
 
     virtual txResultRecycler* recycler() = 0;
 
@@ -126,17 +126,17 @@ public:
      * Callback to be used by the expression/pattern if errors are detected.
      */
     virtual void receiveError(const nsAString& aMsg, nsresult aRes) = 0;
 };
 
 #define TX_DECL_MATCH_CONTEXT \
     nsresult getVariable(PRInt32 aNamespace, nsIAtom* aLName, \
                          txAExprResult*& aResult); \
-    MBool isStripSpaceAllowed(const txXPathNode& aNode); \
+    bool isStripSpaceAllowed(const txXPathNode& aNode); \
     void* getPrivateContext(); \
     txResultRecycler* recycler(); \
     void receiveError(const nsAString& aMsg, nsresult aRes)
 
 class txIEvalContext : public txIMatchContext
 {
 public:
     /*
--- a/content/xslt/src/xpath/txNameTest.cpp
+++ b/content/xslt/src/xpath/txNameTest.cpp
@@ -64,28 +64,28 @@ bool txNameTest::matches(const txXPathNo
          !txXPathNodeUtils::isAttribute(aNode)) ||
         (mNodeType == txXPathNodeType::DOCUMENT_NODE &&
          !txXPathNodeUtils::isRoot(aNode))) {
         return false;
     }
 
     // Totally wild?
     if (mLocalName == nsGkAtoms::_asterix && !mPrefix)
-        return MB_TRUE;
+        return true;
 
     // Compare namespaces
     if (mNamespace != txXPathNodeUtils::getNamespaceID(aNode) 
         && !(mNamespace == kNameSpaceID_None &&
              txXPathNodeUtils::isHTMLElementInHTMLDocument(aNode))
        )
-        return MB_FALSE;
+        return false;
 
     // Name wild?
     if (mLocalName == nsGkAtoms::_asterix)
-        return MB_TRUE;
+        return true;
 
     // Compare local-names
     return txXPathNodeUtils::localNameEquals(aNode, mLocalName);
 }
 
 /*
  * Returns the default priority of this txNodeTest
  */
--- a/content/xslt/src/xpath/txNodeSetContext.cpp
+++ b/content/xslt/src/xpath/txNodeSetContext.cpp
@@ -57,17 +57,17 @@ PRUint32 txNodeSetContext::position()
 
 nsresult txNodeSetContext::getVariable(PRInt32 aNamespace, nsIAtom* aLName,
                                        txAExprResult*& aResult)
 {
     NS_ASSERTION(mInner, "mInner is null!!!");
     return mInner->getVariable(aNamespace, aLName, aResult);
 }
 
-MBool txNodeSetContext::isStripSpaceAllowed(const txXPathNode& aNode)
+bool txNodeSetContext::isStripSpaceAllowed(const txXPathNode& aNode)
 {
     NS_ASSERTION(mInner, "mInner is null!!!");
     return mInner->isStripSpaceAllowed(aNode);
 }
 
 void* txNodeSetContext::getPrivateContext()
 {
     NS_ASSERTION(mInner, "mInner is null!!!");
--- a/content/xslt/src/xpath/txNodeSetContext.h
+++ b/content/xslt/src/xpath/txNodeSetContext.h
@@ -47,17 +47,17 @@ class txNodeSetContext : public txIEvalC
 {
 public:
     txNodeSetContext(txNodeSet* aContextNodeSet, txIMatchContext* aContext)
         : mContextSet(aContextNodeSet), mPosition(0), mInner(aContext)
     {
     }
 
     // Iteration over the given NodeSet
-    MBool hasNext()
+    bool hasNext()
     {
         return mPosition < size();
     }
     void next()
     {
         NS_ASSERTION(mPosition < size(), "Out of bounds.");
         mPosition++;
     }
--- a/content/xslt/src/xpath/txNumberResult.cpp
+++ b/content/xslt/src/xpath/txNumberResult.cpp
@@ -71,20 +71,20 @@ NumberResult::stringValue(nsString& aRes
 }
 
 const nsString*
 NumberResult::stringValuePointer()
 {
     return nsnull;
 }
 
-MBool NumberResult::booleanValue() {
+bool NumberResult::booleanValue() {
   // OG+
   // As per the XPath spec, the boolean value of a number is true if and only if
   // it is neither positive 0 nor negative 0 nor NaN
-  return (MBool)(value != 0.0 && !Double::isNaN(value));
+  return (bool)(value != 0.0 && !Double::isNaN(value));
   // OG-
 } //-- booleanValue
 
 double NumberResult::numberValue() {
     return this->value;
 } //-- numberValue
 
--- a/content/xslt/src/xpath/txPathExpr.cpp
+++ b/content/xslt/src/xpath/txPathExpr.cpp
@@ -188,17 +188,17 @@ PathExpr::evalDescendants(Expr* aStep, c
                                    (static_cast<txAExprResult*>(res));
     nsRefPtr<txNodeSet> newSet;
     rv = aContext->recycler()->getNonSharedNodeSet(oldSet,
                                                    getter_AddRefs(newSet));
     NS_ENSURE_SUCCESS(rv, rv);
 
     resNodes->addAndTransfer(newSet);
 
-    MBool filterWS = aContext->isStripSpaceAllowed(aNode);
+    bool filterWS = aContext->isStripSpaceAllowed(aNode);
 
     txXPathTreeWalker walker(aNode);
     if (!walker.moveToFirstChild()) {
         return NS_OK;
     }
 
     do {
         const txXPathNode& node = walker.getCurrentPosition();
--- a/content/xslt/src/xpath/txSingleNodeContext.h
+++ b/content/xslt/src/xpath/txSingleNodeContext.h
@@ -54,17 +54,17 @@ public:
 
     nsresult getVariable(PRInt32 aNamespace, nsIAtom* aLName,
                          txAExprResult*& aResult)
     {
         NS_ASSERTION(mInner, "mInner is null!!!");
         return mInner->getVariable(aNamespace, aLName, aResult);
     }
 
-    MBool isStripSpaceAllowed(const txXPathNode& aNode)
+    bool isStripSpaceAllowed(const txXPathNode& aNode)
     {
         NS_ASSERTION(mInner, "mInner is null!!!");
         return mInner->isStripSpaceAllowed(aNode);
     }
 
     void* getPrivateContext()
     {
         NS_ASSERTION(mInner, "mInner is null!!!");
--- a/content/xslt/src/xpath/txStringResult.cpp
+++ b/content/xslt/src/xpath/txStringResult.cpp
@@ -74,16 +74,16 @@ StringResult::stringValue(nsString& aRes
 }
 
 const nsString*
 StringResult::stringValuePointer()
 {
     return &mValue;
 }
 
-MBool StringResult::booleanValue() {
+bool StringResult::booleanValue() {
    return !mValue.IsEmpty();
 } //-- booleanValue
 
 double StringResult::numberValue() {
     return Double::toDouble(mValue);
 } //-- numberValue
 
--- a/content/xslt/src/xslt/txDocumentFunctionCall.cpp
+++ b/content/xslt/src/xslt/txDocumentFunctionCall.cpp
@@ -116,30 +116,30 @@ DocumentFunctionCall::evaluate(txIEvalCo
         return NS_ERROR_XPATH_BAD_ARGUMENT_COUNT;
     }
 
     nsRefPtr<txAExprResult> exprResult1;
     rv = mParams[0]->evaluate(aContext, getter_AddRefs(exprResult1));
     NS_ENSURE_SUCCESS(rv, rv);
 
     nsAutoString baseURI;
-    MBool baseURISet = MB_FALSE;
+    bool baseURISet = false;
 
     if (mParams.Length() == 2) {
         // We have 2 arguments, get baseURI from the first node
         // in the resulting nodeset
         nsRefPtr<txNodeSet> nodeSet2;
         rv = evaluateToNodeSet(mParams[1],
                                aContext, getter_AddRefs(nodeSet2));
         NS_ENSURE_SUCCESS(rv, rv);
 
         // Make this true, even if nodeSet2 is empty. For relative URLs,
         // we'll fail to load the document with an empty base URI, and for
         // absolute URLs, the base URI doesn't matter
-        baseURISet = MB_TRUE;
+        baseURISet = true;
 
         if (!nodeSet2->isEmpty()) {
             txXPathNodeUtils::getBaseURI(nodeSet2->get(0), baseURI);
         }
     }
 
     if (exprResult1->getResultType() == txAExprResult::NODESET) {
         // The first argument is a NodeSet, iterate on its nodes
--- a/content/xslt/src/xslt/txFormatNumberFunctionCall.cpp
+++ b/content/xslt/src/xslt/txFormatNumberFunctionCall.cpp
@@ -91,17 +91,17 @@ txFormatNumberFunctionCall::evaluate(txI
     rv = mParams[1]->evaluateToString(aContext, formatStr);
     NS_ENSURE_SUCCESS(rv, rv);
 
     if (mParams.Length() == 3) {
         nsAutoString formatQName;
         rv = mParams[2]->evaluateToString(aContext, formatQName);
         NS_ENSURE_SUCCESS(rv, rv);
 
-        rv = formatName.init(formatQName, mMappings, MB_FALSE);
+        rv = formatName.init(formatQName, mMappings, false);
         NS_ENSURE_SUCCESS(rv, rv);
     }
 
     txDecimalFormat* format = mStylesheet->getDecimalFormat(formatName);
     if (!format) {
         nsAutoString err(NS_LITERAL_STRING("unknown decimal format"));
 #ifdef TX_TO_STRING
         err.AppendLiteral(" for: ");
@@ -134,20 +134,20 @@ txFormatNumberFunctionCall::evaluate(txI
     int minIntegerSize=0;
     int minFractionSize=0;
     int maxFractionSize=0;
     int multiplier=1;
     int groupSize=-1;
 
     PRUint32 pos = 0;
     PRUint32 formatLen = formatStr.Length();
-    MBool inQuote;
+    bool inQuote;
 
     // Get right subexpression
-    inQuote = MB_FALSE;
+    inQuote = false;
     if (Double::isNeg(value)) {
         while (pos < formatLen &&
                (inQuote ||
                 formatStr.CharAt(pos) != format->mPatternSeparator)) {
             if (formatStr.CharAt(pos) == FORMAT_QUOTE)
                 inQuote = !inQuote;
             pos++;
         }
@@ -157,17 +157,17 @@ txFormatNumberFunctionCall::evaluate(txI
             prefix.Append(format->mMinusSign);
         }
         else
             pos++;
     }
 
     // Parse the format string
     FormatParseState pState = Prefix;
-    inQuote = MB_FALSE;
+    inQuote = false;
 
     PRUnichar c = 0;
     while (pos < formatLen && pState != Finished) {
         c=formatStr.CharAt(pos++);
 
         switch (pState) {
 
         case Prefix:
@@ -322,18 +322,18 @@ txFormatNumberFunctionCall::evaluate(txI
     // XXX We shouldn't use SetLength.
     res.SetLength(res.Length() +
                   intDigits +               // integer digits
                   1 +                       // decimal separator
                   maxFractionSize +         // fractions
                   (intDigits-1)/groupSize); // group separators
 
     PRInt32 i = bufIntDigits + maxFractionSize - 1;
-    MBool carry = (i+1 < buflen) && (buf[i+1] >= '5');
-    MBool hasFraction = MB_FALSE;
+    bool carry = (i+1 < buflen) && (buf[i+1] >= '5');
+    bool hasFraction = false;
 
     PRUint32 resPos = res.Length()-1;
 
     // Fractions
     for (; i >= bufIntDigits; --i) {
         int digit;
         if (i >= buflen || i < 0) {
             digit = 0;
@@ -343,17 +343,17 @@ txFormatNumberFunctionCall::evaluate(txI
         }
         
         if (carry) {
             digit = (digit + 1) % 10;
             carry = digit == 0;
         }
 
         if (hasFraction || digit != 0 || i < bufIntDigits+minFractionSize) {
-            hasFraction = MB_TRUE;
+            hasFraction = true;
             res.SetCharAt((PRUnichar)(digit + format->mZeroDigit),
                           resPos--);
         }
         else {
             res.Truncate(resPos--);
         }
     }
 
@@ -443,17 +443,17 @@ txDecimalFormat::txDecimalFormat() : mIn
     mMinusSign = '-';
     mPercent = '%';
     mPerMille = 0x2030;
     mZeroDigit = '0';
     mDigit = '#';
     mPatternSeparator = ';';
 }
 
-MBool txDecimalFormat::isEqual(txDecimalFormat* other)
+bool txDecimalFormat::isEqual(txDecimalFormat* other)
 {
     return mDecimalSeparator == other->mDecimalSeparator &&
            mGroupingSeparator == other->mGroupingSeparator &&
            mInfinity.Equals(other->mInfinity) &&
            mMinusSign == other->mMinusSign &&
            mNaN.Equals(other->mNaN) &&
            mPercent == other->mPercent &&
            mPerMille == other->mPerMille &&
--- a/content/xslt/src/xslt/txNodeSorter.cpp
+++ b/content/xslt/src/xslt/txNodeSorter.cpp
@@ -73,24 +73,24 @@ txNodeSorter::addSortElement(Expr* aSele
     nsAutoPtr<SortKey> key(new SortKey);
     NS_ENSURE_TRUE(key, NS_ERROR_OUT_OF_MEMORY);
     nsresult rv = NS_OK;
 
     // Select
     key->mExpr = aSelectExpr;
 
     // Order
-    MBool ascending = MB_TRUE;
+    bool ascending = true;
     if (aOrderExpr) {
         nsAutoString attrValue;
         rv = aOrderExpr->evaluateToString(aContext, attrValue);
         NS_ENSURE_SUCCESS(rv, rv);
 
         if (TX_StringEqualsAtom(attrValue, nsGkAtoms::descending)) {
-            ascending = MB_FALSE;
+            ascending = false;
         }
         else if (!TX_StringEqualsAtom(attrValue, nsGkAtoms::ascending)) {
             // XXX ErrorReport: unknown value for order attribute
             return NS_ERROR_XSLT_BAD_VALUE;
         }
     }
 
 
@@ -107,17 +107,17 @@ txNodeSorter::addSortElement(Expr* aSele
         // Language
         nsAutoString lang;
         if (aLangExpr) {
             rv = aLangExpr->evaluateToString(aContext, lang);
             NS_ENSURE_SUCCESS(rv, rv);
         }
 
         // Case-order 
-        MBool upperFirst = false;
+        bool upperFirst = false;
         if (aCaseOrderExpr) {
             nsAutoString attrValue;
 
             rv = aCaseOrderExpr->evaluateToString(aContext, attrValue);
             NS_ENSURE_SUCCESS(rv, rv);
 
             if (TX_StringEqualsAtom(attrValue, nsGkAtoms::upperFirst)) {
                 upperFirst = true;
--- a/content/xslt/src/xslt/txPatternParser.cpp
+++ b/content/xslt/src/xslt/txPatternParser.cpp
@@ -134,31 +134,31 @@ nsresult txPatternParser::createUnionPat
 }
 
 nsresult txPatternParser::createLocPathPattern(txExprLexer& aLexer,
                                                txIParseContext* aContext,
                                                txPattern*& aPattern)
 {
     nsresult rv = NS_OK;
 
-    MBool isChild = MB_TRUE;
-    MBool isAbsolute = MB_FALSE;
+    bool isChild = true;
+    bool isAbsolute = false;
     txPattern* stepPattern = 0;
     txLocPathPattern* pathPattern = 0;
 
     Token::Type type = aLexer.peek()->mType;
     switch (type) {
         case Token::ANCESTOR_OP:
-            isChild = MB_FALSE;
-            isAbsolute = MB_TRUE;
+            isChild = false;
+            isAbsolute = true;
             aLexer.nextToken();
             break;
         case Token::PARENT_OP:
             aLexer.nextToken();
-            isAbsolute = MB_TRUE;
+            isAbsolute = true;
             if (aLexer.peek()->mType == Token::END || 
                 aLexer.peek()->mType == Token::UNION_OP) {
                 aPattern = new txRootPattern();
 
                 return aPattern ? NS_OK : NS_ERROR_OUT_OF_MEMORY;
             }
             break;
         case Token::FUNCTION_NAME_AND_PAREN:
@@ -294,32 +294,32 @@ nsresult txPatternParser::createKeyPatte
     return aPattern ? NS_OK : NS_ERROR_OUT_OF_MEMORY;
 }
 
 nsresult txPatternParser::createStepPattern(txExprLexer& aLexer,
                                             txIParseContext* aContext,
                                             txPattern*& aPattern)
 {
     nsresult rv = NS_OK;
-    MBool isAttr = MB_FALSE;
+    bool isAttr = false;
     Token* tok = aLexer.peek();
     if (tok->mType == Token::AXIS_IDENTIFIER) {
         if (TX_StringEqualsAtom(tok->Value(), nsGkAtoms::attribute)) {
-            isAttr = MB_TRUE;
+            isAttr = true;
         }
         else if (!TX_StringEqualsAtom(tok->Value(), nsGkAtoms::child)) {
             // all done already for CHILD_AXIS, for all others
             // XXX report unexpected axis error
             return NS_ERROR_XPATH_PARSE_FAILURE;
         }
         aLexer.nextToken();
     }
     else if (tok->mType == Token::AT_SIGN) {
         aLexer.nextToken();
-        isAttr = MB_TRUE;
+        isAttr = true;
     }
     tok = aLexer.nextToken();
 
     txNodeTest* nodeTest;
     if (tok->mType == Token::CNAME) {
         // resolve QName
         nsCOMPtr<nsIAtom> prefix, lName;
         PRInt32 nspace;
--- a/content/xslt/src/xslt/txStylesheet.h
+++ b/content/xslt/src/xslt/txStylesheet.h
@@ -187,37 +187,37 @@ private:
 
 /**
  * txStripSpaceTest holds both an txNameTest and a bool for use in
  * whitespace stripping.
  */
 class txStripSpaceTest {
 public:
     txStripSpaceTest(nsIAtom* aPrefix, nsIAtom* aLocalName, PRInt32 aNSID,
-                     MBool stripSpace)
+                     bool stripSpace)
         : mNameTest(aPrefix, aLocalName, aNSID, txXPathNodeType::ELEMENT_NODE),
           mStrips(stripSpace)
     {
     }
 
-    MBool matches(const txXPathNode& aNode, txIMatchContext* aContext) {
+    bool matches(const txXPathNode& aNode, txIMatchContext* aContext) {
         return mNameTest.matches(aNode, aContext);
     }
 
-    MBool stripsSpace() {
+    bool stripsSpace() {
         return mStrips;
     }
 
     double getDefaultPriority() {
         return mNameTest.getDefaultPriority();
     }
 
 protected:
     txNameTest mNameTest;
-    MBool mStrips;
+    bool mStrips;
 };
 
 /**
  * Value of a global parameter
  */
 class txIGlobalParameter
 {
 public:
--- a/content/xslt/src/xslt/txStylesheetCompileHandlers.cpp
+++ b/content/xslt/src/xslt/txStylesheetCompileHandlers.cpp
@@ -1362,17 +1362,17 @@ txFnEndLRE(txStylesheetCompilerState& aS
 
   txText
 */
 static nsresult
 txFnText(const nsAString& aStr, txStylesheetCompilerState& aState)
 {
     TX_RETURN_IF_WHITESPACE(aStr, aState);
 
-    nsAutoPtr<txInstruction> instr(new txText(aStr, MB_FALSE));
+    nsAutoPtr<txInstruction> instr(new txText(aStr, false));
     NS_ENSURE_TRUE(instr, NS_ERROR_OUT_OF_MEMORY);
 
     nsresult rv = aState.addInstruction(instr);
     NS_ENSURE_SUCCESS(rv, rv);
 
     return NS_OK;
 }
 
@@ -2408,17 +2408,17 @@ txFnStartText(PRInt32 aNamespaceID,
     aState.mDOE = doe == eTrue;
 
     return aState.pushHandlerTable(gTxTextHandler);
 }
 
 static nsresult
 txFnEndText(txStylesheetCompilerState& aState)
 {
-    aState.mDOE = MB_FALSE;
+    aState.mDOE = false;
     aState.popHandlerTable();
     return NS_OK;
 }
 
 static nsresult
 txFnTextText(const nsAString& aStr, txStylesheetCompilerState& aState)
 {
     nsAutoPtr<txInstruction> instr(new txText(aStr, aState.mDOE));
@@ -3039,17 +3039,17 @@ txHandlerTable::find(PRInt32 aNamespaceI
     if (NS_FAILED(rv))                                               \
         return false
 
 #define SHUTDOWN_HANDLER(_name)                                      \
     delete gTx##_name##Handler;                                      \
     gTx##_name##Handler = nsnull
 
 // static
-MBool
+bool
 txHandlerTable::init()
 {
     nsresult rv = NS_OK;
 
     INIT_HANDLER_WITH_ELEMENT_HANDLERS(Root);
     INIT_HANDLER(Embed);
     INIT_HANDLER_WITH_ELEMENT_HANDLERS(Top);
     INIT_HANDLER(Ignore);
@@ -3061,17 +3061,17 @@ txHandlerTable::init()
     INIT_HANDLER_WITH_ELEMENT_HANDLERS(ForEach);
     INIT_HANDLER(TopVariable);
     INIT_HANDLER_WITH_ELEMENT_HANDLERS(Choose);
     INIT_HANDLER_WITH_ELEMENT_HANDLERS(Param);
     INIT_HANDLER_WITH_ELEMENT_HANDLERS(Import);
     INIT_HANDLER_WITH_ELEMENT_HANDLERS(AttributeSet);
     INIT_HANDLER_WITH_ELEMENT_HANDLERS(Fallback);
 
-    return MB_TRUE;
+    return true;
 }
 
 // static
 void
 txHandlerTable::shutdown()
 {
     SHUTDOWN_HANDLER(Root);
     SHUTDOWN_HANDLER(Embed);
--- a/content/xslt/src/xslt/txStylesheetCompileHandlers.h
+++ b/content/xslt/src/xslt/txStylesheetCompileHandlers.h
@@ -70,17 +70,17 @@ public:
                    const txElementHandler* aLREHandler,
                    const txElementHandler* aOtherHandler);
     nsresult init(const txElementHandler* aHandlers, PRUint32 aCount);
     const txElementHandler* find(PRInt32 aNamespaceID, nsIAtom* aLocalName);
     
     const HandleTextFn mTextHandler;
     const txElementHandler* const mLREHandler;
 
-    static MBool init();
+    static bool init();
     static void shutdown();
 
 private:
     const txElementHandler* const mOtherHandler;
     txExpandedNameMap<const txElementHandler> mHandlers;
 };
 
 extern txHandlerTable* gTxRootHandler;
--- a/content/xslt/src/xslt/txStylesheetCompiler.cpp
+++ b/content/xslt/src/xslt/txStylesheetCompiler.cpp
@@ -222,20 +222,20 @@ txStylesheetCompiler::startElementIntern
 
         // xml:space
         if (attr->mNamespaceID == kNameSpaceID_XML &&
             attr->mLocalName == nsGkAtoms::space) {
             rv = ensureNewElementContext();
             NS_ENSURE_SUCCESS(rv, rv);
 
             if (TX_StringEqualsAtom(attr->mValue, nsGkAtoms::preserve)) {
-                mElementContext->mPreserveWhitespace = MB_TRUE;
+                mElementContext->mPreserveWhitespace = true;
             }
             else if (TX_StringEqualsAtom(attr->mValue, nsGkAtoms::_default)) {
-                mElementContext->mPreserveWhitespace = MB_FALSE;
+                mElementContext->mPreserveWhitespace = false;
             }
             else {
                 return NS_ERROR_XSLT_PARSE_FAILURE;
             }
         }
 
         // xml:base
         if (attr->mNamespaceID == kNameSpaceID_XML &&
@@ -286,30 +286,30 @@ txStylesheetCompiler::startElementIntern
              attr->mLocalName == nsGkAtoms::version &&
              aNamespaceID == kNameSpaceID_XSLT &&
              (aLocalName == nsGkAtoms::stylesheet ||
               aLocalName == nsGkAtoms::transform))) {
             rv = ensureNewElementContext();
             NS_ENSURE_SUCCESS(rv, rv);
 
             if (attr->mValue.EqualsLiteral("1.0")) {
-                mElementContext->mForwardsCompatibleParsing = MB_FALSE;
+                mElementContext->mForwardsCompatibleParsing = false;
             }
             else {
-                mElementContext->mForwardsCompatibleParsing = MB_TRUE;
+                mElementContext->mForwardsCompatibleParsing = true;
             }
         }
     }
 
     // Find the right elementhandler and execute it
-    MBool isInstruction = MB_FALSE;
+    bool isInstruction = false;
     PRInt32 count = mElementContext->mInstructionNamespaces.Length();
     for (i = 0; i < count; ++i) {
         if (mElementContext->mInstructionNamespaces[i] == aNamespaceID) {
-            isInstruction = MB_TRUE;
+            isInstruction = true;
             break;
         }
     }
 
     if (mEmbedStatus == eNeedEmbed) {
         // handle embedded stylesheets
         if (aIDOffset >= 0 && aAttributes[aIDOffset].mValue.Equals(mTarget)) {
             // We found the right ID, signal to compile the 
--- a/content/xslt/src/xslt/txTextHandler.cpp
+++ b/content/xslt/src/xslt/txTextHandler.cpp
@@ -34,17 +34,17 @@
  * the provisions above, a recipient may use your version of this file under
  * the terms of any one of the MPL, the GPL or the LGPL.
  *
  * ***** END LICENSE BLOCK ***** */
 
 #include "txTextHandler.h"
 #include "nsAString.h"
 
-txTextHandler::txTextHandler(MBool aOnlyText) : mLevel(0),
+txTextHandler::txTextHandler(bool aOnlyText) : mLevel(0),
                                                 mOnlyText(aOnlyText)
 {
 }
 
 nsresult
 txTextHandler::attribute(nsIAtom* aPrefix, nsIAtom* aLocalName,
                          nsIAtom* aLowercaseLocalName, PRInt32 aNsID,
                          const nsString& aValue)
--- a/content/xslt/src/xslt/txTextHandler.h
+++ b/content/xslt/src/xslt/txTextHandler.h
@@ -40,20 +40,20 @@
 #define TRANSFRMX_TEXT_HANDLER_H
 
 #include "txXMLEventHandler.h"
 #include "nsString.h"
 
 class txTextHandler : public txAXMLEventHandler
 {
 public:
-    txTextHandler(MBool aOnlyText);
+    txTextHandler(bool aOnlyText);
 
     TX_DECL_TXAXMLEVENTHANDLER
 
     nsString mValue;
 
 private:
     PRUint32 mLevel;
-    MBool mOnlyText;
+    bool mOnlyText;
 };
 
 #endif
--- a/content/xslt/src/xslt/txXPathResultComparator.cpp
+++ b/content/xslt/src/xslt/txXPathResultComparator.cpp
@@ -45,18 +45,18 @@
 #include "nsILocaleService.h"
 #include "nsIServiceManager.h"
 #include "nsLocaleCID.h"
 #include "prmem.h"
 
 #define kAscending (1<<0)
 #define kUpperFirst (1<<1)
 
-txResultStringComparator::txResultStringComparator(MBool aAscending,
-                                                   MBool aUpperFirst,
+txResultStringComparator::txResultStringComparator(bool aAscending,
+                                                   bool aUpperFirst,
                                                    const nsAFlatString& aLanguage)
 {
     mSorting = 0;
     if (aAscending)
         mSorting |= kAscending;
     if (aUpperFirst)
         mSorting |= kUpperFirst;
     nsresult rv = init(aLanguage);
@@ -210,17 +210,17 @@ txResultStringComparator::StringValue::~
 {
     PR_Free(mKey);
     if (mCaseLength > 0)
         PR_Free((PRUint8*)mCaseKey);
     else
         delete (nsString*)mCaseKey;
 }
 
-txResultNumberComparator::txResultNumberComparator(MBool aAscending)
+txResultNumberComparator::txResultNumberComparator(bool aAscending)
 {
     mAscending = aAscending ? 1 : -1;
 }
 
 nsresult
 txResultNumberComparator::createSortableValue(Expr *aExpr,
                                               txIEvalContext *aContext,
                                               TxObject *&aResult)
--- a/content/xslt/src/xslt/txXPathResultComparator.h
+++ b/content/xslt/src/xslt/txXPathResultComparator.h
@@ -72,17 +72,17 @@ public:
 };
 
 /*
  * Compare results as stings (data-type="text")
  */
 class txResultStringComparator : public txXPathResultComparator
 {
 public:
-    txResultStringComparator(MBool aAscending, MBool aUpperFirst,
+    txResultStringComparator(bool aAscending, bool aUpperFirst,
                              const nsAFlatString& aLanguage);
 
     int compareValues(TxObject* aVal1, TxObject* aVal2);
     nsresult createSortableValue(Expr *aExpr, txIEvalContext *aContext,
                                  TxObject *&aResult);
 private:
     nsCOMPtr<nsICollation> mCollation;
     nsresult init(const nsAFlatString& aLanguage);
@@ -105,17 +105,17 @@ private:
 };
 
 /*
  * Compare results as numbers (data-type="number")
  */
 class txResultNumberComparator : public txXPathResultComparator
 {
 public:
-    txResultNumberComparator(MBool aAscending);
+    txResultNumberComparator(bool aAscending);
 
     int compareValues(TxObject* aVal1, TxObject* aVal2);
     nsresult createSortableValue(Expr *aExpr, txIEvalContext *aContext,
                                  TxObject *&aResult);
 
 private:
     int mAscending;
 
--- a/content/xslt/src/xslt/txXSLTFunctions.h
+++ b/content/xslt/src/xslt/txXSLTFunctions.h
@@ -122,17 +122,17 @@ private:
 class txDecimalFormat {
 
 public:
     /*
      * Creates a new decimal format and initilizes all properties with
      * default values
      */
     txDecimalFormat();
-    MBool isEqual(txDecimalFormat* other);
+    bool isEqual(txDecimalFormat* other);
     
     PRUnichar       mDecimalSeparator;
     PRUnichar       mGroupingSeparator;
     nsString        mInfinity;
     PRUnichar       mMinusSign;
     nsString        mNaN;
     PRUnichar       mPercent;
     PRUnichar       mPerMille;
--- a/content/xslt/src/xslt/txXSLTNumber.cpp
+++ b/content/xslt/src/xslt/txXSLTNumber.cpp
@@ -71,33 +71,33 @@ nsresult txXSLTNumber::createNumber(Expr
     if (!valueString.IsEmpty()) {
         aResult = valueString;
 
         return NS_OK;
     }
 
     // Create resulting string
     aResult = head;
-    MBool first = MB_TRUE;
+    bool first = true;
     txListIterator valueIter(&values);
     txListIterator counterIter(&counters);
     valueIter.resetToEnd();
     PRInt32 value;
     txFormattedCounter* counter = 0;
     while ((value = NS_PTR_TO_INT32(valueIter.previous()))) {
         if (counterIter.hasNext()) {
             counter = (txFormattedCounter*)counterIter.next();
         }
 
         if (!first) {
             aResult.Append(counter->mSeparator);
         }
 
         counter->appendNumber(value, aResult);
-        first = MB_FALSE;
+        first = false;
     }
     
     aResult.Append(tail);
     
     txListIterator iter(&counters);
     while (iter.hasNext()) {
         delete (txFormattedCounter*)iter.next();
     }
@@ -131,23 +131,23 @@ txXSLTNumber::getValueList(Expr* aValueE
         aValues.add(NS_INT32_TO_PTR((PRInt32)floor(value + 0.5)));
         return NS_OK;
     }
 
 
     // Otherwise use count/from/level
 
     txPattern* countPattern = aCountPattern;
-    MBool ownsCountPattern = MB_FALSE;
+    bool ownsCountPattern = false;
     const txXPathNode& currNode = aContext->getContextNode();
 
     // Parse count- and from-attributes
 
     if (!aCountPattern) {
-        ownsCountPattern = MB_TRUE;
+        ownsCountPattern = true;
         txNodeTest* nodeTest;
         PRUint16 nodeType = txXPathNodeUtils::getNodeType(currNode);
         switch (nodeType) {
             case txXPathNodeType::ELEMENT_NODE:
             {
                 nsCOMPtr<nsIAtom> localName =
                     txXPathNodeUtils::getLocalName(currNode);
                 PRInt32 namespaceID = txXPathNodeUtils::getNamespaceID(currNode);
@@ -186,17 +186,17 @@ txXSLTNumber::getValueList(Expr* aValueE
                 // but it's what the spec says to do
                 nodeTest = new txNameTest(0, nsGkAtoms::_asterix, 0,
                                           nodeType);
                 break;
             }
         }
         NS_ENSURE_TRUE(nodeTest, NS_ERROR_OUT_OF_MEMORY);
 
-        countPattern = new txStepPattern(nodeTest, MB_FALSE);
+        countPattern = new txStepPattern(nodeTest, false);
         if (!countPattern) {
             // XXX error reporting
             delete nodeTest;
             return NS_ERROR_OUT_OF_MEMORY;
         }
     }
 
 
@@ -234,22 +234,22 @@ txXSLTNumber::getValueList(Expr* aValueE
                 aValues.clear();
             }
         }
     }
     // level = "multiple"
     else if (aLevel == eLevelMultiple) {
         // find all ancestor-or-selfs that matches count until...
         txXPathTreeWalker walker(currNode);
-        MBool matchedFrom = MB_FALSE;
+        bool matchedFrom = false;
         do {
             if (aFromPattern && !walker.isOnNode(currNode) &&
                 aFromPattern->matches(walker.getCurrentPosition(), aContext)) {
                 //... we find one that matches from
-                matchedFrom = MB_TRUE;
+                matchedFrom = true;
                 break;
             }
 
             if (countPattern->matches(walker.getCurrentPosition(), aContext)) {
                 aValues.add(NS_INT32_TO_PTR(getSiblingCount(walker, countPattern,
                                                             aContext)));
             }
         } while (walker.moveToParent());
@@ -259,23 +259,23 @@ txXSLTNumber::getValueList(Expr* aValueE
         // we shouldn't search anything
         if (aFromPattern && !matchedFrom) {
             aValues.clear();
         }
     }
     // level = "any"
     else if (aLevel == eLevelAny) {
         PRInt32 value = 0;
-        MBool matchedFrom = MB_FALSE;
+        bool matchedFrom = false;
 
         txXPathTreeWalker walker(currNode);
         do {
             if (aFromPattern && !walker.isOnNode(currNode) &&
                 aFromPattern->matches(walker.getCurrentPosition(), aContext)) {
-                matchedFrom = MB_TRUE;
+                matchedFrom = true;
                 break;
             }
 
             if (countPattern->matches(walker.getCurrentPosition(), aContext)) {
                 ++value;
             }
 
         } while (getPrevInDocumentOrder(walker));
@@ -445,22 +445,22 @@ txXSLTNumber::getPrevInDocumentOrder(txX
         while (aWalker.moveToLastChild()) {
             // do nothing
         }
         return true;
     }
     return aWalker.moveToParent();
 }
 
-#define TX_CHAR_RANGE(ch, a, b) if (ch < a) return MB_FALSE; \
-    if (ch <= b) return MB_TRUE
-#define TX_MATCH_CHAR(ch, a) if (ch < a) return MB_FALSE; \
-    if (ch == a) return MB_TRUE
+#define TX_CHAR_RANGE(ch, a, b) if (ch < a) return false; \
+    if (ch <= b) return true
+#define TX_MATCH_CHAR(ch, a) if (ch < a) return false; \
+    if (ch == a) return true
 
-MBool txXSLTNumber::isAlphaNumeric(PRUnichar ch)
+bool txXSLTNumber::isAlphaNumeric(PRUnichar ch)
 {
     TX_CHAR_RANGE(ch, 0x0030, 0x0039);
     TX_CHAR_RANGE(ch, 0x0041, 0x005A);
     TX_CHAR_RANGE(ch, 0x0061, 0x007A);
     TX_MATCH_CHAR(ch, 0x00AA);
     TX_CHAR_RANGE(ch, 0x00B2, 0x00B3);
     TX_MATCH_CHAR(ch, 0x00B5);
     TX_CHAR_RANGE(ch, 0x00B9, 0x00BA);
@@ -742,10 +742,10 @@ MBool txXSLTNumber::isAlphaNumeric(PRUni
     TX_CHAR_RANGE(ch, 0xFE76, 0xFEFC);
     TX_CHAR_RANGE(ch, 0xFF10, 0xFF19);
     TX_CHAR_RANGE(ch, 0xFF21, 0xFF3A);
     TX_CHAR_RANGE(ch, 0xFF41, 0xFF5A);
     TX_CHAR_RANGE(ch, 0xFF66, 0xFFBE);
     TX_CHAR_RANGE(ch, 0xFFC2, 0xFFC7);
     TX_CHAR_RANGE(ch, 0xFFCA, 0xFFCF);
     TX_CHAR_RANGE(ch, 0xFFD2, 0xFFD7);
-    return MB_FALSE;
+    return false;
 }
--- a/content/xslt/src/xslt/txXSLTNumber.h
+++ b/content/xslt/src/xslt/txXSLTNumber.h
@@ -80,17 +80,17 @@ private:
      *
      */
     static PRInt32 getSiblingCount(txXPathTreeWalker& aWalker,
                                    txPattern* aCountPattern,
                                    txIMatchContext* aContext);
     
     static bool getPrevInDocumentOrder(txXPathTreeWalker& aWalker);
 
-    static MBool isAlphaNumeric(PRUnichar ch);
+    static bool isAlphaNumeric(PRUnichar ch);
 };
 
 class txFormattedCounter {
 public:
     virtual ~txFormattedCounter()
     {
     }
     
--- a/content/xslt/src/xslt/txXSLTNumberCounters.cpp
+++ b/content/xslt/src/xslt/txXSLTNumberCounters.cpp
@@ -66,17 +66,17 @@ public:
     virtual void appendNumber(PRInt32 aNumber, nsAString& aDest);
     
 private:
     PRUnichar mOffset;
 };
 
 class txRomanCounter : public txFormattedCounter {
 public:
-    txRomanCounter(MBool aUpper) : mTableOffset(aUpper ? 30 : 0)
+    txRomanCounter(bool aUpper) : mTableOffset(aUpper ? 30 : 0)
     {
     }
 
     void appendNumber(PRInt32 aNumber, nsAString& aDest);
 
 private:
     PRInt32 mTableOffset;
 };
--- a/content/xslt/src/xslt/txXSLTPatterns.cpp
+++ b/content/xslt/src/xslt/txXSLTPatterns.cpp
@@ -58,25 +58,25 @@ double txUnionPattern::getDefaultPriorit
 }
 
 /*
  * Determines whether this Pattern matches the given node within
  * the given context
  * This should be called on the simple patterns for xsl:template,
  * but is fine for xsl:key and xsl:number
  */
-MBool txUnionPattern::matches(const txXPathNode& aNode, txIMatchContext* aContext)
+bool txUnionPattern::matches(const txXPathNode& aNode, txIMatchContext* aContext)
 {
     PRUint32 i, len = mLocPathPatterns.Length();
     for (i = 0; i < len; ++i) {
         if (mLocPathPatterns[i]->matches(aNode, aContext)) {
-            return MB_TRUE;
+            return true;
         }
     }
-    return MB_FALSE;
+    return false;
 }
 
 txPattern::Type
 txUnionPattern::getType()
 {
   return UNION_PATTERN;
 }
 
@@ -129,17 +129,17 @@ nsresult txLocPathPattern::addStep(txPat
         return NS_ERROR_OUT_OF_MEMORY;
 
     step->pattern = aPattern;
     step->isChild = isChild;
 
     return NS_OK;
 }
 
-MBool txLocPathPattern::matches(const txXPathNode& aNode, txIMatchContext* aContext)
+bool txLocPathPattern::matches(const txXPathNode& aNode, txIMatchContext* aContext)
 {
     NS_ASSERTION(mSteps.Length() > 1, "Internal error");
 
     /*
      * The idea is to split up a path into blocks separated by descendant
      * operators. For example "foo/bar//baz/bop//ying/yang" is split up into
      * three blocks. The "ying/yang" block is handled by the first while-loop
      * and the "foo/bar" and "baz/bop" blocks are handled by the second
@@ -148,38 +148,38 @@ MBool txLocPathPattern::matches(const tx
      * match the block. If there are more than one list of ancestors that
      * match a block we only need to find the one furthermost down in the
      * tree.
      */
 
     PRUint32 pos = mSteps.Length();
     Step* step = &mSteps[--pos];
     if (!step->pattern->matches(aNode, aContext))
-        return MB_FALSE;
+        return false;
 
     txXPathTreeWalker walker(aNode);
     bool hasParent = walker.moveToParent();
 
     while (step->isChild) {
         if (!pos)
-            return MB_TRUE; // all steps matched
+            return true; // all steps matched
         step = &mSteps[--pos];
         if (!hasParent || !step->pattern->matches(walker.getCurrentPosition(), aContext))
-            return MB_FALSE; // no more ancestors or no match
+            return false; // no more ancestors or no match
 
         hasParent = walker.moveToParent();
     }
 
     // We have at least one // path separator
     txXPathTreeWalker blockWalker(walker);
     PRUint32 blockPos = pos;
 
     while (pos) {
         if (!hasParent)
-            return MB_FALSE; // There are more steps in the current block 
+            return false; // There are more steps in the current block 
                              // than ancestors of the tested node
 
         step = &mSteps[--pos];
         if (!step->pattern->matches(walker.getCurrentPosition(), aContext)) {
             // Didn't match. We restart at beginning of block using a new
             // start node
             pos = blockPos;
             hasParent = blockWalker.moveToParent();
@@ -190,17 +190,17 @@ MBool txLocPathPattern::matches(const tx
             if (!step->isChild) {
                 // We've matched an entire block. Set new start pos and start node
                 blockPos = pos;
                 blockWalker.moveTo(walker);
             }
         }
     }
 
-    return MB_TRUE;
+    return true;
 } // txLocPathPattern::matches
 
 double txLocPathPattern::getDefaultPriority()
 {
     NS_ASSERTION(mSteps.Length() > 1, "Internal error");
 
     return 0.5;
 }
@@ -244,17 +244,17 @@ txLocPathPattern::toString(nsAString& aD
 #endif
 
 /*
  * txRootPattern
  *
  * a txPattern matching the document node, or '/'
  */
 
-MBool txRootPattern::matches(const txXPathNode& aNode, txIMatchContext* aContext)
+bool txRootPattern::matches(const txXPathNode& aNode, txIMatchContext* aContext)
 {
     return txXPathNodeUtils::isRoot(aNode);
 }
 
 double txRootPattern::getDefaultPriority()
 {
     return 0.5;
 }
@@ -290,17 +290,17 @@ txIdPattern::txIdPattern(const nsSubstri
     nsWhitespaceTokenizer tokenizer(aString);
     while (tokenizer.hasMoreTokens()) {
         // this can fail, XXX move to a Init(aString) method
         nsCOMPtr<nsIAtom> atom = do_GetAtom(tokenizer.nextToken());
         mIds.AppendObject(atom);
     }
 }
 
-MBool txIdPattern::matches(const txXPathNode& aNode, txIMatchContext* aContext)
+bool txIdPattern::matches(const txXPathNode& aNode, txIMatchContext* aContext)
 {
     if (!txXPathNodeUtils::isElement(aNode)) {
         return false;
     }
 
     // Get a ID attribute, if there is
     nsIContent* content = txXPathNativeNode::getContent(aNode);
     NS_ASSERTION(content, "a Element without nsIContent");
@@ -346,17 +346,17 @@ txIdPattern::toString(nsAString& aDest)
  * txKeyPattern
  *
  * txKeyPattern matches if the given node is in the evalation of 
  * the key() function
  * This resembles the key() function, but may only have LITERALs as
  * argument.
  */
 
-MBool txKeyPattern::matches(const txXPathNode& aNode, txIMatchContext* aContext)
+bool txKeyPattern::matches(const txXPathNode& aNode, txIMatchContext* aContext)
 {
     txExecutionState* es = (txExecutionState*)aContext->getPrivateContext();
     nsAutoPtr<txXPathNode> contextDoc(txXPathNodeUtils::getOwnerDocument(aNode));
     NS_ENSURE_TRUE(contextDoc, false);
 
     nsRefPtr<txNodeSet> nodes;
     nsresult rv = es->getKeyNodes(mName, *contextDoc, mValue, true,
                                   getter_AddRefs(nodes));
@@ -399,108 +399,108 @@ txKeyPattern::toString(nsAString& aDest)
 #endif
 
 /*
  * txStepPattern
  *
  * a txPattern to hold the NodeTest and the Predicates of a StepPattern
  */
 
-MBool txStepPattern::matches(const txXPathNode& aNode, txIMatchContext* aContext)
+bool txStepPattern::matches(const txXPathNode& aNode, txIMatchContext* aContext)
 {
     NS_ASSERTION(mNodeTest, "Internal error");
 
     if (!mNodeTest->matches(aNode, aContext))
-        return MB_FALSE;
+        return false;
 
     txXPathTreeWalker walker(aNode);
     if ((!mIsAttr &&
          txXPathNodeUtils::isAttribute(walker.getCurrentPosition())) ||
         !walker.moveToParent()) {
-        return MB_FALSE;
+        return false;
     }
     if (isEmpty()) {
-        return MB_TRUE;
+        return true;
     }
 
     /*
      * Evaluate Predicates
      *
      * Copy all siblings/attributes matching mNodeTest to nodes
      * Up to the last Predicate do
      *  Foreach node in nodes
      *   evaluate Predicate with node as context node
      *   if the result is a number, check the context position,
      *    otherwise convert to bool
      *   if result is true, copy node to newNodes
-     *  if aNode is not member of newNodes, return MB_FALSE
+     *  if aNode is not member of newNodes, return false
      *  nodes = newNodes
      *
      * For the last Predicate, evaluate Predicate with aNode as
      *  context node, if the result is a number, check the position,
      *  otherwise return the result converted to boolean
      */
 
     // Create the context node set for evaluating the predicates
     nsRefPtr<txNodeSet> nodes;
     nsresult rv = aContext->recycler()->getNodeSet(getter_AddRefs(nodes));
-    NS_ENSURE_SUCCESS(rv, MB_FALSE);
+    NS_ENSURE_SUCCESS(rv, false);
 
     bool hasNext = mIsAttr ? walker.moveToFirstAttribute() :
                                walker.moveToFirstChild();
     while (hasNext) {
         if (mNodeTest->matches(walker.getCurrentPosition(), aContext)) {
             nodes->append(walker.getCurrentPosition());
         }
         hasNext = mIsAttr ? walker.moveToNextAttribute() :
                             walker.moveToNextSibling();
     }
 
     Expr* predicate = mPredicates[0];
     nsRefPtr<txNodeSet> newNodes;
     rv = aContext->recycler()->getNodeSet(getter_AddRefs(newNodes));
-    NS_ENSURE_SUCCESS(rv, MB_FALSE);
+    NS_ENSURE_SUCCESS(rv, false);
 
     PRUint32 i, predLen = mPredicates.Length();
     for (i = 1; i < predLen; ++i) {
         newNodes->clear();
-        MBool contextIsInPredicate = MB_FALSE;
+        bool contextIsInPredicate = false;
         txNodeSetContext predContext(nodes, aContext);
         while (predContext.hasNext()) {
             predContext.next();
             nsRefPtr<txAExprResult> exprResult;
             rv = predicate->evaluate(&predContext, getter_AddRefs(exprResult));
             NS_ENSURE_SUCCESS(rv, false);
 
             switch(exprResult->getResultType()) {
                 case txAExprResult::NUMBER:
                     // handle default, [position() == numberValue()]
                     if ((double)predContext.position() ==
                         exprResult->numberValue()) {
                         const txXPathNode& tmp = predContext.getContextNode();
                         if (tmp == aNode)
-                            contextIsInPredicate = MB_TRUE;
+                            contextIsInPredicate = true;
                         newNodes->append(tmp);
                     }
                     break;
                 default:
                     if (exprResult->booleanValue()) {
                         const txXPathNode& tmp = predContext.getContextNode();
                         if (tmp == aNode)
-                            contextIsInPredicate = MB_TRUE;
+                            contextIsInPredicate = true;
                         newNodes->append(tmp);
                     }
                     break;
             }
         }
         // Move new NodeSet to the current one
         nodes->clear();
         nodes->append(*newNodes);
         if (!contextIsInPredicate) {
-            return MB_FALSE;
+            return false;
         }
         predicate = mPredicates[i];
     }
     txForwardContext evalContext(aContext, aNode, nodes);
     nsRefPtr<txAExprResult> exprResult;
     rv = predicate->evaluate(&evalContext, getter_AddRefs(exprResult));
     NS_ENSURE_SUCCESS(rv, false);
 
--- a/content/xslt/src/xslt/txXSLTPatterns.h
+++ b/content/xslt/src/xslt/txXSLTPatterns.h
@@ -54,17 +54,17 @@ public:
     virtual ~txPattern()
     {
         MOZ_COUNT_DTOR(txPattern);
     }
 
     /*
      * Determines whether this Pattern matches the given node.
      */
-    virtual MBool matches(const txXPathNode& aNode,
+    virtual bool matches(const txXPathNode& aNode,
                           txIMatchContext* aContext) = 0;
 
     /*
      * Returns the default priority of this Pattern.
      *
      * Simple Patterns return the values as specified in XPath 5.5.
      * Returns -Inf for union patterns, as it shouldn't be called on them.
      */
@@ -114,17 +114,17 @@ public:
      * other #toString() methods for Patterns.
      * @return the String representation of this Pattern.
      */
     virtual void toString(nsAString& aDest) = 0;
 #endif
 };
 
 #define TX_DECL_PATTERN_BASE \
-    MBool matches(const txXPathNode& aNode, txIMatchContext* aContext); \
+    bool matches(const txXPathNode& aNode, txIMatchContext* aContext); \
     double getDefaultPriority(); \
     virtual Expr* getSubExprAt(PRUint32 aPos); \
     virtual void setSubExprAt(PRUint32 aPos, Expr* aExpr); \
     virtual txPattern* getSubPatternAt(PRUint32 aPos); \
     virtual void setSubPatternAt(PRUint32 aPos, txPattern* aPattern)
 
 #ifndef TX_TO_STRING
 #define TX_DECL_PATTERN TX_DECL_PATTERN_BASE
--- a/content/xslt/src/xslt/txXSLTProcessor.cpp
+++ b/content/xslt/src/xslt/txXSLTProcessor.cpp
@@ -43,29 +43,29 @@
 #include "txStylesheetCompileHandlers.h"
 #include "txStylesheetCompiler.h"
 #include "txExecutionState.h"
 #include "txExprResult.h"
 
 TX_LG_IMPL
 
 /* static */
-MBool
+bool
 txXSLTProcessor::init()
 {
     TX_LG_CREATE;
 
     if (!txHandlerTable::init())
-        return MB_FALSE;
+        return false;
 
     extern bool TX_InitEXSLTFunction();
     if (!TX_InitEXSLTFunction())
-        return MB_FALSE;
+        return false;
 
-    return MB_TRUE;
+    return true;
 }
 
 /* static */
 void
 txXSLTProcessor::shutdown()
 {
     txStylesheetCompilerState::shutdown();
     txHandlerTable::shutdown();
--- a/content/xslt/src/xslt/txXSLTProcessor.h
+++ b/content/xslt/src/xslt/txXSLTProcessor.h
@@ -43,17 +43,17 @@
 
 class txXSLTProcessor
 {
 public:
     /**
      * Initialisation and shutdown routines. Initilizes and cleansup all
      * dependant classes
      */
-    static MBool init();
+    static bool init();
     static void shutdown();
 
 
     static nsresult execute(txExecutionState& aEs);
 
     // once we want to have interuption we should probably have functions for
     // running X number of steps or running until a condition is true.
 };
--- a/content/xslt/tests/buster/buster-test.js
+++ b/content/xslt/tests/buster/buster-test.js
@@ -216,17 +216,17 @@ runItem.prototype =
             aProg.removeProgressListener(this);
             this.mRefDoc = document.getElementById('hiddenHtml').contentDocument;
             this.fileLoaded(4);
         }
     },
     onProgressChange: function(aProg, b,c,d,e,f)
     {
     },
-    onLocationChange: function(aProg, aRequest, aURI)
+    onLocationChange: function(aProg, aRequest, aURI, aFlags)
     {
     },
     onStatusChange: function(aProg, aRequest, aStatus, aMessage)
     {
     },
     onSecurityChange: function(aWebProgress, aRequest, aState)
     {
     },
--- a/docshell/base/nsDocShell.cpp
+++ b/docshell/base/nsDocShell.cpp
@@ -1765,27 +1765,29 @@ NS_IMETHODIMP
 nsDocShell::GetChromeEventHandler(nsIDOMEventTarget** aChromeEventHandler)
 {
     NS_ENSURE_ARG_POINTER(aChromeEventHandler);
     nsCOMPtr<nsIDOMEventTarget> target = do_QueryInterface(mChromeEventHandler);
     target.swap(*aChromeEventHandler);
     return NS_OK;
 }
 
-/* [noscript] void setCurrentURI (in nsIURI uri); */
+/* void setCurrentURI (in nsIURI uri); */
 NS_IMETHODIMP
 nsDocShell::SetCurrentURI(nsIURI *aURI)
 {
-    SetCurrentURI(aURI, nsnull, true);
+    // Note that securityUI will set STATE_IS_INSECURE, even if
+    // the scheme of |aURI| is "https".
+    SetCurrentURI(aURI, nsnull, true, 0);
     return NS_OK;
 }
 
 bool
 nsDocShell::SetCurrentURI(nsIURI *aURI, nsIRequest *aRequest,
-                          bool aFireOnLocationChange)
+                          bool aFireOnLocationChange, PRUint32 aLocationFlags)
 {
 #ifdef PR_LOGGING
     if (gDocShellLeakLog && PR_LOG_TEST(gDocShellLeakLog, PR_LOG_DEBUG)) {
         nsCAutoString spec;
         if (aURI)
             aURI->GetSpec(spec);
         PR_LogPrint("DOCSHELL %p SetCurrentURI %s\n", this, spec.get());
     }
@@ -1819,17 +1821,17 @@ nsDocShell::SetCurrentURI(nsIURI *aURI, 
        * We don't want to send OnLocationChange notifications when
        * a subframe is being loaded for the first time, while
        * visiting a frameset page
        */
       return false; 
     }
 
     if (aFireOnLocationChange) {
-        FireOnLocationChange(this, aRequest, aURI);
+        FireOnLocationChange(this, aRequest, aURI, aLocationFlags);
     }
     return !aFireOnLocationChange;
 }
 
 NS_IMETHODIMP
 nsDocShell::GetCharset(char** aCharset)
 {
     NS_ENSURE_ARG_POINTER(aCharset);
@@ -5923,17 +5925,17 @@ nsDocShell::OnStateChange(nsIWebProgress
                 }
 
                 // This is a document.write(). Get the made-up url
                 // from the channel and store it in session history.
                 // Pass false for aCloneChildren, since we're creating
                 // a new DOM here.
                 rv = AddToSessionHistory(uri, wcwgChannel, nsnull, false,
                                          getter_AddRefs(mLSHE));
-                SetCurrentURI(uri, aRequest, true);
+                SetCurrentURI(uri, aRequest, true, 0);
                 // Save history state of the previous page
                 rv = PersistLayoutHistoryState();
                 // We'll never get an Embed() for this load, so just go ahead
                 // and SetHistoryEntry now.
                 SetHistoryEntry(&mOSHE, mLSHE);
             }
         
         }
@@ -5979,18 +5981,18 @@ nsDocShell::OnStateChange(nsIWebProgress
     }
     // note that redirect state changes will go through here as well, but it
     // is better to handle those in OnRedirectStateChange where more
     // information is available.
     return NS_OK;
 }
 
 NS_IMETHODIMP
-nsDocShell::OnLocationChange(nsIWebProgress * aProgress,
-                             nsIRequest * aRequest, nsIURI * aURI)
+nsDocShell::OnLocationChange(nsIWebProgress * aProgress, nsIRequest * aRequest,
+                             nsIURI * aURI, PRUint32 aFlags)
 {
     NS_NOTREACHED("notification excluded in AddProgressListener(...)");
     return NS_OK;
 }
 
 void
 nsDocShell::OnRedirectStateChange(nsIChannel* aOldChannel,
                                   nsIChannel* aNewChannel,
@@ -6510,17 +6512,17 @@ nsDocShell::CreateAboutBlankContentViewe
       docFactory->CreateInstanceForDocument(NS_ISUPPORTS_CAST(nsIDocShell *, this),
                     blankDoc, "view", getter_AddRefs(viewer));
 
       // hook 'em up
       if (viewer) {
         viewer->SetContainer(static_cast<nsIContentViewerContainer *>(this));
         Embed(viewer, "", 0);
 
-        SetCurrentURI(blankDoc->GetDocumentURI(), nsnull, true);
+        SetCurrentURI(blankDoc->GetDocumentURI(), nsnull, true, 0);
         rv = mIsBeingDestroyed ? NS_ERROR_NOT_AVAILABLE : NS_OK;
       }
     }
   }
   mCreatingDocument = false;
 
   // The transient about:blank viewer doesn't have a session history entry.
   SetHistoryEntry(&mOSHE, nsnull);
@@ -7161,17 +7163,17 @@ nsDocShell::RestoreFromHistory()
 
         // Use the uri from the mLSHE we had when we entered this function
         // (which need not match the document's URI if anchors are involved),
         // since that's the history entry we're loading.  Note that if we use
         // origLSHE we don't have to worry about whether the entry in question
         // is still mLSHE or whether it's now mOSHE.
         nsCOMPtr<nsIURI> uri;
         origLSHE->GetURI(getter_AddRefs(uri));
-        SetCurrentURI(uri, document->GetChannel(), true);
+        SetCurrentURI(uri, document->GetChannel(), true, 0);
     }
 
     // This is the end of our CreateContentViewer() replacement.
     // Now we simulate a load.  First, we restore the state of the javascript
     // window object.
     nsCOMPtr<nsPIDOMWindow> privWin =
         do_GetInterface(static_cast<nsIInterfaceRequestor*>(this));
     NS_ASSERTION(privWin, "could not get nsPIDOMWindow interface");
@@ -7500,17 +7502,17 @@ nsDocShell::CreateContentViewer(const ch
     if (++gNumberOfDocumentsLoading == 1) {
       // Hint to favor performance for the plevent notification mechanism.
       // We want the pages to load as fast as possible even if its means 
       // native messages might be starved.
       FavorPerformanceHint(true, NS_EVENT_STARVATION_DELAY_HINT);
     }
 
     if (onLocationChangeNeeded) {
-      FireOnLocationChange(this, request, mCurrentURI);
+      FireOnLocationChange(this, request, mCurrentURI, 0);
     }
   
     return NS_OK;
 }
 
 nsresult
 nsDocShell::NewContentViewerObj(const char *aContentType,
                                 nsIRequest * request, nsILoadGroup * aLoadGroup,
@@ -8360,16 +8362,21 @@ nsDocShell::InternalLoad(nsIURI * aURI,
              */
             nsCOMPtr<nsISupports> owner;
             if (mOSHE) {
                 mOSHE->GetOwner(getter_AddRefs(owner));
             }
             // Pass true for aCloneSHChildren, since we're not
             // changing documents here, so all of our subframes are
             // still relevant to the new session history entry.
+            //
+            // It also makes OnNewURI(...) set LOCATION_CHANGE_SAME_DOCUMENT
+            // flag on firing onLocationChange(...).
+            // Anyway, aCloneSHChildren param is simply reflecting
+            // doShortCircuitedLoad in this scope.
             OnNewURI(aURI, nsnull, owner, mLoadType, true, true, true);
 
             nsCOMPtr<nsIInputStream> postData;
             nsCOMPtr<nsISupports> cacheKey;
 
             if (mOSHE) {
                 /* save current position of scroller(s) (bug 59774) */
                 mOSHE->SetScrollPosition(cx, cy);
@@ -9413,18 +9420,24 @@ nsDocShell::OnNewURI(nsIURI * aURI, nsIC
             shInternal->UpdateIndex();
             rootSH->GetIndex(&mLoadedTransIndex);
 #ifdef DEBUG_PAGE_CACHE
             printf("Previous index: %d, Loaded index: %d\n\n",
                    mPreviousTransIndex, mLoadedTransIndex);
 #endif
         }
     }
+
+    // aCloneSHChildren exactly means "we are not loading a new document".
+    PRUint32 locationFlags = aCloneSHChildren?
+                                 PRUint32(LOCATION_CHANGE_SAME_DOCUMENT) : 0;
+
     bool onLocationChangeNeeded = SetCurrentURI(aURI, aChannel,
-                                                  aFireOnLocationChange);
+                                                aFireOnLocationChange,
+                                                locationFlags);
     // Make sure to store the referrer from the channel, if any
     SetupReferrerFromChannel(aChannel);
     return onLocationChangeNeeded;
 }
 
 bool
 nsDocShell::OnLoadingSite(nsIChannel * aChannel, bool aFireOnLocationChange,
                           bool aAddToGlobalHistory)
@@ -9722,18 +9735,24 @@ nsDocShell::AddState(nsIVariant *aData, 
 
     // Step 6: If the document's URI changed, update document's URI and update
     // global history.
     //
     // We need to call FireOnLocationChange so that the browser's address bar
     // gets updated and the back button is enabled, but we only need to
     // explicitly call FireOnLocationChange if we're not calling SetCurrentURI,
     // since SetCurrentURI will call FireOnLocationChange for us.
+    //
+    // Both SetCurrentURI(...) and FireDummyOnLocationChange() pass
+    // nsnull for aRequest param to FireOnLocationChange(...). Such an update
+    // notification is allowed only when we know docshell is not loading a new
+    // document and it requires LOCATION_CHANGE_SAME_DOCUMENT flag. Otherwise,
+    // FireOnLocationChange(...) breaks security UI.
     if (!equalURIs) {
-        SetCurrentURI(newURI, nsnull, true);
+        SetCurrentURI(newURI, nsnull, true, LOCATION_CHANGE_SAME_DOCUMENT);
         document->SetDocumentURI(newURI);
 
         AddURIVisit(newURI, oldURI, oldURI, 0);
 
         // AddURIVisit doesn't set the title for the new URI in global history,
         // so do that here.
         if (mUseGlobalHistory) {
             nsCOMPtr<IHistory> history = services::GetHistoryService();
--- a/docshell/base/nsDocShell.h
+++ b/docshell/base/nsDocShell.h
@@ -264,20 +264,22 @@ public:
     // ForceRefreshURI method on nsIRefreshURI, but makes sure to take
     // the timer involved out of mRefreshURIList if it's there.
     // aTimer must not be null.
     nsresult ForceRefreshURIFromTimer(nsIURI * aURI, PRInt32 aDelay,
                                       bool aMetaRefresh, nsITimer* aTimer);
 
     friend class OnLinkClickEvent;
 
-    // We need dummy OnLocationChange in some cases to update the UI.
+    // We need dummy OnLocationChange in some cases to update the UI without
+    // updating security info.
     void FireDummyOnLocationChange()
     {
-      FireOnLocationChange(this, nsnull, mCurrentURI);
+        FireOnLocationChange(this, nsnull, mCurrentURI,
+                             LOCATION_CHANGE_SAME_DOCUMENT);
     }
 
     nsresult HistoryTransactionRemoved(PRInt32 aIndex);
 protected:
     // Object Management
     virtual ~nsDocShell();
     virtual void DestroyChildren();
 
@@ -588,17 +590,18 @@ protected:
                                  nsIDocShellTreeItem* aTargetTreeItem);
 
     // Returns true if would have called FireOnLocationChange,
     // but did not because aFireOnLocationChange was false on entry.
     // In this case it is the caller's responsibility to ensure
     // FireOnLocationChange is called.
     // In all other cases false is returned.
     bool SetCurrentURI(nsIURI *aURI, nsIRequest *aRequest,
-                         bool aFireOnLocationChange);
+                       bool aFireOnLocationChange,
+                       PRUint32 aLocationFlags);
 
     // The following methods deal with saving and restoring content viewers
     // in session history.
 
     // mContentViewer points to the current content viewer associated with
     // this docshell.  When loading a new document, the content viewer is
     // either destroyed or stored into a session history entry.  To make sure
     // that destruction happens in a controlled fashion, a given content viewer
--- a/docshell/build/nsDocShellModule.cpp
+++ b/docshell/build/nsDocShellModule.cpp
@@ -52,20 +52,20 @@
 #include "nsOSHelperAppService.h"
 #include "nsExternalProtocolHandler.h"
 #include "nsPrefetchService.h"
 #include "nsOfflineCacheUpdate.h"
 #include "nsLocalHandlerApp.h"
 #ifdef MOZ_ENABLE_DBUS
 #include "nsDBusHandlerApp.h"
 #endif 
-#if defined(ANDROID) || defined(MOZ_ENABLE_MEEGOTOUCHSHARE)
+#if defined(MOZ_WIDGET_ANDROID) || defined(MOZ_ENABLE_MEEGOTOUCHSHARE)
 #include "nsExternalSharingAppService.h"
 #endif
-#if defined(ANDROID)
+#if defined(MOZ_WIDGET_ANDROID)
 #include "nsExternalURLHandlerService.h"
 #endif
 
 // session history
 #include "nsSHEntry.h"
 #include "nsSHEntryShared.h"
 #include "nsSHistory.h"
 #include "nsSHTransaction.h"
@@ -113,20 +113,20 @@ NS_GENERIC_FACTORY_CONSTRUCTOR(nsExterna
 NS_GENERIC_FACTORY_CONSTRUCTOR_INIT(nsPrefetchService, Init)
 NS_GENERIC_FACTORY_SINGLETON_CONSTRUCTOR(nsOfflineCacheUpdateService,
                                          nsOfflineCacheUpdateService::GetInstance)
 NS_GENERIC_FACTORY_CONSTRUCTOR(nsOfflineCacheUpdate)
 NS_GENERIC_FACTORY_CONSTRUCTOR(PlatformLocalHandlerApp_t)
 #ifdef MOZ_ENABLE_DBUS
 NS_GENERIC_FACTORY_CONSTRUCTOR(nsDBusHandlerApp)
 #endif 
-#if defined(ANDROID) || defined(MOZ_ENABLE_MEEGOTOUCHSHARE)
+#if defined(MOZ_WIDGET_ANDROID) || defined(MOZ_ENABLE_MEEGOTOUCHSHARE)
 NS_GENERIC_FACTORY_CONSTRUCTOR(nsExternalSharingAppService)
 #endif
-#if defined(ANDROID)
+#if defined(MOZ_WIDGET_ANDROID)
 NS_GENERIC_FACTORY_CONSTRUCTOR(nsExternalURLHandlerService)
 #endif
 
 // session history
 NS_GENERIC_FACTORY_CONSTRUCTOR(nsSHEntry)
 NS_GENERIC_FACTORY_CONSTRUCTOR(nsSHTransaction)
 NS_GENERIC_FACTORY_CONSTRUCTOR(nsSHistory)
 
@@ -143,20 +143,20 @@ NS_DEFINE_NAMED_CID(NS_EXTERNALHELPERAPP
 NS_DEFINE_NAMED_CID(NS_EXTERNALPROTOCOLHANDLER_CID);
 NS_DEFINE_NAMED_CID(NS_PREFETCHSERVICE_CID);
 NS_DEFINE_NAMED_CID(NS_OFFLINECACHEUPDATESERVICE_CID);
 NS_DEFINE_NAMED_CID(NS_OFFLINECACHEUPDATE_CID);
 NS_DEFINE_NAMED_CID(NS_LOCALHANDLERAPP_CID);
 #ifdef MOZ_ENABLE_DBUS
 NS_DEFINE_NAMED_CID(NS_DBUSHANDLERAPP_CID);
 #endif
-#if defined(ANDROID) || defined(MOZ_ENABLE_MEEGOTOUCHSHARE)
+#if defined(MOZ_WIDGET_ANDROID) || defined(MOZ_ENABLE_MEEGOTOUCHSHARE)
 NS_DEFINE_NAMED_CID(NS_EXTERNALSHARINGAPPSERVICE_CID);
 #endif
-#if defined(ANDROID)
+#if defined(MOZ_WIDGET_ANDROID)
 NS_DEFINE_NAMED_CID(NS_EXTERNALURLHANDLERSERVICE_CID);
 #endif
 NS_DEFINE_NAMED_CID(NS_SHENTRY_CID);
 NS_DEFINE_NAMED_CID(NS_HISTORYENTRY_CID);
 NS_DEFINE_NAMED_CID(NS_SHTRANSACTION_CID);
 NS_DEFINE_NAMED_CID(NS_SHISTORY_CID);
 NS_DEFINE_NAMED_CID(NS_SHISTORY_INTERNAL_CID);
 NS_DEFINE_NAMED_CID(NS_DOWNLOADHISTORY_CID);
@@ -173,20 +173,20 @@ const mozilla::Module::CIDEntry kDocShel
   { &kNS_EXTERNALPROTOCOLHANDLER_CID, false, NULL, nsExternalProtocolHandlerConstructor },
   { &kNS_PREFETCHSERVICE_CID, false, NULL, nsPrefetchServiceConstructor },
   { &kNS_OFFLINECACHEUPDATESERVICE_CID, false, NULL, nsOfflineCacheUpdateServiceConstructor },
   { &kNS_OFFLINECACHEUPDATE_CID, false, NULL, nsOfflineCacheUpdateConstructor },
   { &kNS_LOCALHANDLERAPP_CID, false, NULL, PlatformLocalHandlerApp_tConstructor },
 #ifdef MOZ_ENABLE_DBUS
   { &kNS_DBUSHANDLERAPP_CID, false, NULL, nsDBusHandlerAppConstructor },
 #endif
-#if defined(ANDROID) || defined(MOZ_ENABLE_MEEGOTOUCHSHARE)
+#if defined(MOZ_WIDGET_ANDROID) || defined(MOZ_ENABLE_MEEGOTOUCHSHARE)
   { &kNS_EXTERNALSHARINGAPPSERVICE_CID, false, NULL, nsExternalSharingAppServiceConstructor },
 #endif
-#if defined(ANDROID)
+#if defined(MOZ_WIDGET_ANDROID)
   { &kNS_EXTERNALURLHANDLERSERVICE_CID, false, NULL, nsExternalURLHandlerServiceConstructor },
 #endif
   { &kNS_SHENTRY_CID, false, NULL, nsSHEntryConstructor },
   { &kNS_HISTORYENTRY_CID, false, NULL, nsSHEntryConstructor },
   { &kNS_SHTRANSACTION_CID, false, NULL, nsSHTransactionConstructor },
   { &kNS_SHISTORY_CID, false, NULL, nsSHistoryConstructor },
   { &kNS_SHISTORY_INTERNAL_CID, false, NULL, nsSHistoryConstructor },
   { &kNS_DOWNLOADHISTORY_CID, false, NULL, nsDownloadHistoryConstructor },
@@ -222,20 +222,20 @@ const mozilla::Module::ContractIDEntry k
   { NS_NETWORK_PROTOCOL_CONTRACTID_PREFIX"default", &kNS_EXTERNALPROTOCOLHANDLER_CID },
   { NS_PREFETCHSERVICE_CONTRACTID, &kNS_PREFETCHSERVICE_CID },
   { NS_OFFLINECACHEUPDATESERVICE_CONTRACTID, &kNS_OFFLINECACHEUPDATESERVICE_CID },
   { NS_OFFLINECACHEUPDATE_CONTRACTID, &kNS_OFFLINECACHEUPDATE_CID },
   { NS_LOCALHANDLERAPP_CONTRACTID, &kNS_LOCALHANDLERAPP_CID },
 #ifdef MOZ_ENABLE_DBUS
   { NS_DBUSHANDLERAPP_CONTRACTID, &kNS_DBUSHANDLERAPP_CID },
 #endif
-#if defined(ANDROID) || defined(MOZ_ENABLE_MEEGOTOUCHSHARE)
+#if defined(MOZ_WIDGET_ANDROID) || defined(MOZ_ENABLE_MEEGOTOUCHSHARE)
   { NS_EXTERNALSHARINGAPPSERVICE_CONTRACTID, &kNS_EXTERNALSHARINGAPPSERVICE_CID },
 #endif
-#if defined(ANDROID)
+#if defined(MOZ_WIDGET_ANDROID)
   { NS_EXTERNALURLHANDLERSERVICE_CONTRACTID, &kNS_EXTERNALURLHANDLERSERVICE_CID },
 #endif
   { NS_SHENTRY_CONTRACTID, &kNS_SHENTRY_CID },
   { NS_HISTORYENTRY_CONTRACTID, &kNS_HISTORYENTRY_CID },
   { NS_SHTRANSACTION_CONTRACTID, &kNS_SHTRANSACTION_CID },
   { NS_SHISTORY_CONTRACTID, &kNS_SHISTORY_CID },
   { NS_SHISTORY_INTERNAL_CONTRACTID, &kNS_SHISTORY_INTERNAL_CID },
   { NS_DOWNLOADHISTORY_CONTRACTID, &kNS_DOWNLOADHISTORY_CID },
--- a/docshell/test/chrome/Makefile.in
+++ b/docshell/test/chrome/Makefile.in
@@ -117,16 +117,18 @@ include $(topsrcdir)/config/rules.mk
 		test_bug456980.xul \
 		test_bug662200.xul \
 		bug662200_window.xul \
 		662200a.html \
 		662200b.html \
 		662200c.html \
 		test_bug690056.xul \
 		bug690056_window.xul \
+		test_bug311007.xul \
+		bug311007_window.xul \
 		$(NULL)
 
 _DOCSHELL_SUBHARNESS = \
     docshell_helpers.js \
     generic.html \
     $(NULL)
 
 libs:: $(_HTTP_FILES)
new file mode 100644
--- /dev/null
+++ b/docshell/test/chrome/bug311007_window.xul
@@ -0,0 +1,186 @@
+<?xml version="1.0"?>
+<?xml-stylesheet href="chrome://global/skin" type="text/css"?>
+
+<window id="311007Test"
+        xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"
+        width="600"
+        height="600"
+        onload="startup();"
+        title="bug 311007 test">
+
+  <script type="application/javascript" src="docshell_helpers.js"></script>
+  <script type="application/javascript"><![CDATA[
+/*
+   Regression test for bug 283733 and bug 307027.
+
+   Bug 283733
+     "accessing a relative anchor in a secure page removes the
+      locked icon and yellow background UI"
+
+   Bug 307027
+     "Going back from secure page to error page does not clear yellow bar"
+
+ */
+
+const kDNSErrorURI = "https://example/err.html";
+const kSecureURI =
+  "https://example.com/tests/docshell/test/navigation/blank.html";
+
+/*
+  Step 1: load a network error page.   <err.html>       Not Secure
+  Step 2: load a secure page.          <blank.html>     Secure
+  Step 3: a secure page + hashchange.  <blank.html#foo> Secure     (bug 283733)
+  Step 4: go back to the error page.   <err.html>       Not Secure (bug 307027)
+ */
+
+var gListener = null;
+
+function WebProgressListener() {
+  this._callback = null;
+}
+
+WebProgressListener.prototype = {
+  QueryInterface: function(aIID) {
+    if (aIID.equals(Components.interfaces.nsIWebProgressListener) ||
+        aIID.equals(Components.interfaces.nsISupportsWeakReference) ||
+        aIID.equals(Components.interfaces.nsISupports))
+      return this;
+    throw Components.results.NS_NOINTERFACE;
+  },
+
+  onLocationChange: function(aWebProgress, aRequest, aLocation, aFlags) {
+    setTimeout(this._callback, 0, aWebProgress, aRequest, aLocation, aFlags);
+  },
+
+  set callback(aVal) {
+    this._callback = aVal;
+  }
+};
+
+function startup() {
+  gListener = new WebProgressListener();
+
+  document.getElementById("content")
+          .webProgress
+          .addProgressListener(gListener,
+                               Components.interfaces.nsIWebProgress
+                                         .NOTIFY_LOCATION);
+
+  setTimeout(step1A, 0);
+}
+
+/******************************************************************************
+ * Step 1: Load an error page, and confirm UA knows it's insecure.
+ ******************************************************************************/
+
+function step1A() {
+  gListener.callback = step1B;
+  content.location = kDNSErrorURI;
+}
+
+function step1B(aWebProgress, aRequest, aLocation, aFlags) {
+  /* XXX Here we receive 2 notifications, due to bug 673752. */
+  if (!aRequest) {
+    return;
+  }
+
+  is(aLocation.spec, kDNSErrorURI, "Error page's URI (1)");
+
+  ok(!(aFlags & Components.interfaces.nsIWebProgressListener
+                          .LOCATION_CHANGE_SAME_DOCUMENT),
+     "DocShell loaded a document (1)");
+
+  ok(!(aWebProgress.QueryInterface(Components.interfaces.nsIDocShell)
+                   .securityUI.state &
+       Components.interfaces.nsIWebProgressListener.STATE_IS_SECURE),
+     "This is not a secure page (1)");
+
+  /* Go to step 2. */
+  setTimeout(step2A, 0);
+}
+
+/******************************************************************************
+ * Step 2: Load a HTTPS page, and confirm it's secure. 
+ ******************************************************************************/
+
+function step2A() {
+  gListener.callback = step2B;
+  content.location = kSecureURI;
+}
+
+function step2B(aWebProgress, aRequest, aLocation, aFlags) {
+  is(aLocation.spec, kSecureURI, "A URI on HTTPS (2)");
+
+  ok(!(aFlags & Components.interfaces.nsIWebProgressListener
+                          .LOCATION_CHANGE_SAME_DOCUMENT),
+     "DocShell loaded a document (2)");
+
+  ok((aWebProgress.QueryInterface(Components.interfaces.nsIDocShell)
+                  .securityUI.state &
+      Components.interfaces.nsIWebProgressListener.STATE_IS_SECURE),
+     "This is a secure page (2)");
+
+  /* Go to step 3. */
+  setTimeout(step3A, 0);
+}
+
+/*****************************************************************************
+ * Step 3: Trigger hashchange within a secure page, and confirm UA knows
+ *         it's secure. (Bug 283733)
+ *****************************************************************************/
+
+function step3A() {
+  gListener.callback = step3B;
+  content.location += "#foo";
+}
+
+function step3B(aWebProgress, aRequest, aLocation, aFlags) {
+  is(aLocation.spec, kSecureURI + "#foo", "hashchange on HTTPS (3)");
+
+  ok((aFlags & Components.interfaces.nsIWebProgressListener
+                         .LOCATION_CHANGE_SAME_DOCUMENT),
+     "We are in the same document as before (3)");
+
+  ok((aWebProgress.QueryInterface(Components.interfaces.nsIDocShell)
+                  .securityUI.state &
+      Components.interfaces.nsIWebProgressListener.STATE_IS_SECURE),
+     "This is a secure page (3)");
+
+  /* Go to step 4. */
+  setTimeout(step4A, 0);
+}
+
+/*****************************************************************************
+ * Step 4: Go back from a secure page to an error page, and confirm UA knows
+ *         it's not secure. (Bug 307027)
+ *****************************************************************************/
+
+function step4A() {
+  gListener.callback = step4B;
+  content.history.go(-2);
+}
+
+function step4B(aWebProgress, aRequest, aLocation, aFlags) {
+  if (!aRequest) // See step1B(...) and bug 673752.
+    return;
+
+  is(aLocation.spec, kDNSErrorURI, "Go back to the error URI (4)");
+
+  ok(!(aFlags & Components.interfaces.nsIWebProgressListener
+                          .LOCATION_CHANGE_SAME_DOCUMENT),
+       "DocShell loaded a document (4)");
+
+  ok(!(aWebProgress.QueryInterface(Components.interfaces.nsIDocShell)
+                   .securityUI.state &
+       Components.interfaces.nsIWebProgressListener.STATE_IS_SECURE),
+     "This is not a secure page (4)");
+
+  /* End. */
+  aWebProgress.removeProgressListener(gListener);
+  delete(gListener);
+  finish();
+}
+  ]]></script>
+
+  <browser type="content-primary" flex="1" id="content" src="about:blank"/>
+</window>
new file mode 100644
--- /dev/null
+++ b/docshell/test/chrome/test_bug311007.xul
@@ -0,0 +1,43 @@
+<?xml version="1.0"?>
+<?xml-stylesheet href="chrome://global/skin" type="text/css"?>
+<?xml-stylesheet
+  href="chrome://mochikit/content/tests/SimpleTest/test.css"
+  type="text/css"?>
+<!--
+https://bugzilla.mozilla.org/show_bug.cgi?id=311007.xul
+-->
+<window title="Mozilla Bug 311007"
+  xmlns:html="http://www.w3.org/1999/xhtml"
+  xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul">
+
+  <title>Test for Bug 311007</title>
+  <script type="application/javascript"
+    src="chrome://mochikit/content/MochiKit/packed.js"></script>
+  <script type="application/javascript"
+    src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"></script>
+
+<body  xmlns="http://www.w3.org/1999/xhtml">
+<a target="_blank"
+   href="https://bugzilla.mozilla.org/show_bug.cgi?id=311007">
+   Mozilla Bug 311007</a>
+<p id="display"></p>
+<div id="content" style="display: none">
+
+</div>
+<pre id="test">
+</pre>
+</body>
+
+<script class="testbody" type="application/javascript">
+<![CDATA[
+
+/** Test for Bug 311007 **/
+
+SimpleTest.waitForExplicitFinish();
+window.open("bug311007_window.xul", "bug311007",
+            "chrome,width=600,height=600");
+
+]]>
+</script>
+
+</window>
--- a/docshell/test/chrome/window.template.txt
+++ b/docshell/test/chrome/window.template.txt
@@ -1,12 +1,12 @@
 <?xml version="1.0"?>
 <?xml-stylesheet href="chrome://global/skin" type="text/css"?>
 
-<window id="303267Test"
+<window id="{BUGNUMBER}Test"
         xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"
         width="600"
         height="600"
         onload="setTimeout(nextTest,0);"
         title="bug {BUGNUMBER} test">
 
   <script type="application/javascript"
   src="docshell_helpers.js">
--- a/dom/base/nsFocusManager.cpp
+++ b/dom/base/nsFocusManager.cpp
@@ -461,16 +461,29 @@ nsFocusManager::SetFocus(nsIDOMElement* 
   NS_ENSURE_ARG(newFocus);
 
   SetFocusInner(newFocus, aFlags, true, true);
 
   return NS_OK;
 }
 
 NS_IMETHODIMP
+nsFocusManager::ElementIsFocusable(nsIDOMElement* aElement, PRUint32 aFlags,
+                                   bool* aIsFocusable)
+{
+  NS_ENSURE_TRUE(aElement, NS_ERROR_INVALID_ARG);
+
+  nsCOMPtr<nsIContent> aContent = do_QueryInterface(aElement);
+
+  *aIsFocusable = CheckIfFocusable(aContent, aFlags) != nsnull;
+
+  return NS_OK;
+}
+
+NS_IMETHODIMP
 nsFocusManager::MoveFocus(nsIDOMWindow* aWindow, nsIDOMElement* aStartElement,
                           PRUint32 aType, PRUint32 aFlags, nsIDOMElement** aElement)
 {
   *aElement = nsnull;
 
 #ifdef DEBUG_FOCUS
   printf("<<MoveFocus Type: %d Flags: %x>>\n<<", aType, aFlags);
 
--- a/dom/interfaces/base/nsIFocusManager.idl
+++ b/dom/interfaces/base/nsIFocusManager.idl
@@ -161,16 +161,21 @@ interface nsIFocusManager : nsISupports
   nsIDOMElement getFocusedElementForWindow(in nsIDOMWindow aWindow, in boolean aDeep,
                                            out nsIDOMWindow aFocusedWindow);
 
   /**
    * Moves the selection caret within aWindow to the current focus.
    */
   void moveCaretToFocus(in nsIDOMWindow aWindow);
 
+  /***
+   * Check if given element is focusable.
+   */
+  boolean elementIsFocusable(in nsIDOMElement aElement, in unsigned long aFlags);
+
   /*
    * Raise the window when switching focus
    */
   const unsigned long FLAG_RAISE = 1;
 
   /**
    * Do not scroll the element to focus into view
    */
--- a/dom/interfaces/html/nsIDOMHTMLAnchorElement.idl
+++ b/dom/interfaces/html/nsIDOMHTMLAnchorElement.idl
@@ -45,17 +45,17 @@
  *
  * This interface is trying to follow the DOM Level 2 HTML specification:
  * http://www.w3.org/TR/DOM-Level-2-HTML/
  *
  * with changes from the work-in-progress WHATWG HTML specification:
  * http://www.whatwg.org/specs/web-apps/current-work/
  */
 
-[scriptable, uuid(2da904fa-83da-426d-a320-a6868192583e)]
+[scriptable, uuid(bcb54394-d9f8-4bcb-bbbb-eca9826cdbca)]
 interface nsIDOMHTMLAnchorElement : nsIDOMHTMLElement
 {
            attribute DOMString        href;
            attribute DOMString        target;
 
            attribute DOMString        ping;
 
            attribute DOMString        rel;
--- a/dom/interfaces/html/nsIDOMHTMLAppletElement.idl
+++ b/dom/interfaces/html/nsIDOMHTMLAppletElement.idl
@@ -45,17 +45,17 @@
  *
  * This interface is trying to follow the DOM Level 2 HTML specification:
  * http://www.w3.org/TR/DOM-Level-2-HTML/
  *
  * with changes from the work-in-progress WHATWG HTML specification:
  * http://www.whatwg.org/specs/web-apps/current-work/
  */
 
-[scriptable, uuid(c874e500-a185-4d69-96dd-474d1137e21f)]
+[scriptable, uuid(a06bca18-791f-474e-a031-bf6c2bd14994)]
 interface nsIDOMHTMLAppletElement : nsIDOMHTMLElement
 {
            attribute DOMString        align;
            attribute DOMString        alt;
            attribute DOMString        archive;
            attribute DOMString        code;
            attribute DOMString        codeBase;
            attribute DOMString        height;
--- a/dom/interfaces/html/nsIDOMHTMLAreaElement.idl
+++ b/dom/interfaces/html/nsIDOMHTMLAreaElement.idl
@@ -45,17 +45,17 @@
  *
  * This interface is trying to follow the DOM Level 2 HTML specification:
  * http://www.w3.org/TR/DOM-Level-2-HTML/
  *
  * with changes from the work-in-progress WHATWG HTML specification:
  * http://www.whatwg.org/specs/web-apps/current-work/
  */
 
-[scriptable, uuid(d88c8515-5a27-4955-8ca5-18c908433cfd)]
+[scriptable, uuid(7e607c36-aecc-4dee-a93a-95e22a374bfb)]
 interface nsIDOMHTMLAreaElement : nsIDOMHTMLElement
 {
            attribute DOMString        alt;
            attribute DOMString        coords;
            attribute DOMString        shape;
            attribute DOMString        href;
            attribute DOMString        target;
 
--- a/dom/interfaces/html/nsIDOMHTMLAudioElement.idl
+++ b/dom/interfaces/html/nsIDOMHTMLAudioElement.idl
@@ -47,17 +47,17 @@
  * <audio> element.
  *
  * For more information on this interface, please see
  * http://www.whatwg.org/specs/web-apps/current-work/#audio
  *
  * @status UNDER_DEVELOPMENT
  */
 
-[scriptable, uuid(f4115c13-bc51-4c3b-a5c0-9106af9f7368)]
+[scriptable, uuid(756e2792-b937-4a70-bd1f-9d6820473e7e)]
 interface nsIDOMHTMLAudioElement : nsIDOMHTMLMediaElement
 {
   // Setup the audio stream for writing
   void mozSetup(in PRUint32 channels, in PRUint32 rate);
 
   // Write audio to the audio stream
   [implicit_jscontext]
   unsigned long mozWriteAudio(in jsval data);
--- a/dom/interfaces/html/nsIDOMHTMLBRElement.idl
+++ b/dom/interfaces/html/nsIDOMHTMLBRElement.idl
@@ -45,13 +45,13 @@
  *
  * This interface is trying to follow the DOM Level 2 HTML specification:
  * http://www.w3.org/TR/DOM-Level-2-HTML/
  *
  * with changes from the work-in-progress WHATWG HTML specification:
  * http://www.whatwg.org/specs/web-apps/current-work/
  */
 
-[scriptable, uuid(a4f319d7-442d-4154-8c60-b9acdca87523)]
+[scriptable, uuid(7eefd466-7c4d-499a-a076-e33204e69dc3)]
 interface nsIDOMHTMLBRElement : nsIDOMHTMLElement
 {
            attribute DOMString        clear;
 };
--- a/dom/interfaces/html/nsIDOMHTMLBaseElement.idl
+++ b/dom/interfaces/html/nsIDOMHTMLBaseElement.idl
@@ -45,14 +45,14 @@
  *
  * This interface is trying to follow the DOM Level 2 HTML specification:
  * http://www.w3.org/TR/DOM-Level-2-HTML/
  *
  * with changes from the work-in-progress WHATWG HTML specification:
  * http://www.whatwg.org/specs/web-apps/current-work/
  */
 
-[scriptable, uuid(1ba4957f-629e-4410-b5fd-64f2b7eeb32c)]
+[scriptable, uuid(e55cd224-b603-4976-892a-20b11d469394)]
 interface nsIDOMHTMLBaseElement : nsIDOMHTMLElement
 {
            attribute DOMString        href;
            attribute DOMString        target;
 };
--- a/dom/interfaces/html/nsIDOMHTMLBodyElement.idl
+++ b/dom/interfaces/html/nsIDOMHTMLBodyElement.idl
@@ -49,17 +49,17 @@
  *
  * This interface is trying to follow the DOM Level 2 HTML specification:
  * http://www.w3.org/TR/DOM-Level-2-HTML/
  *
  * with changes from the work-in-progress WHATWG HTML specification:
  * http://www.whatwg.org/specs/web-apps/current-work/
  */
 
-[scriptable, uuid(dcf343a9-fa7f-4e16-b122-0ece0d8bdea9)]
+[scriptable, uuid(6c377d44-a5d1-4f0f-860a-9858d2cb5679)]
 interface nsIDOMHTMLBodyElement : nsIDOMHTMLElement
 {
            attribute DOMString        aLink;
            attribute DOMString        background;
            attribute DOMString        bgColor;
            attribute DOMString        link;
            attribute DOMString        text;
            attribute DOMString        vLink;
--- a/dom/interfaces/html/nsIDOMHTMLButtonElement.idl
+++ b/dom/interfaces/html/nsIDOMHTMLButtonElement.idl
@@ -47,17 +47,17 @@
  * http://www.w3.org/TR/DOM-Level-2-HTML/
  *
  * with changes from the work-in-progress WHATWG HTML specification:
  * http://www.whatwg.org/specs/web-apps/current-work/
  */
 
 interface nsIDOMValidityState;
 
-[scriptable, uuid(4b48e075-a05b-480f-9e37-fcd88e7aebdd)]
+[scriptable, uuid(79f034f0-5c13-4101-9598-412e1eac1986)]
 interface nsIDOMHTMLButtonElement : nsIDOMHTMLElement
 {
            attribute boolean               autofocus;
            attribute boolean               disabled;
   readonly attribute nsIDOMHTMLFormElement form;
            attribute DOMString             formAction;
            attribute DOMString             formEnctype;
            attribute DOMString             formMethod;
--- a/dom/interfaces/html/nsIDOMHTMLCanvasElement.idl
+++ b/dom/interfaces/html/nsIDOMHTMLCanvasElement.idl
@@ -50,17 +50,17 @@
  * http://www.whatwg.org/specs/web-apps/current-work/#graphics
  *
  * @status UNDER_DEVELOPMENT
  */
 
 interface nsIDOMFile;
 interface nsIVariant;
 
-[scriptable, uuid(e1ea26e6-4141-487f-a9cf-d7e9344b571c)]
+[scriptable, uuid(dbbeeba1-3c20-4d9d-ac82-98b69fd819a9)]
 interface nsIDOMHTMLCanvasElement : nsIDOMHTMLElement
 {
   attribute unsigned long width;
   attribute unsigned long height;
   attribute boolean mozOpaque;
 
   nsISupports getContext(in DOMString contextId,
                          [optional] in jsval contextOptions);
--- a/dom/interfaces/html/nsIDOMHTMLCommandElement.idl
+++ b/dom/interfaces/html/nsIDOMHTMLCommandElement.idl
@@ -41,17 +41,17 @@
  * <command> element.
  *
  * For more information on this interface, please see
  * http://www.whatwg.org/specs/web-apps/current-work/#the-command-element
  *
  * @status UNDER_DEVELOPMENT
  */
 
-[scriptable, uuid(4c466da8-5c6d-427f-95f5-bba96ab99c96)]
+[scriptable, uuid(13032f74-4150-4768-ab5e-51f4de39a300)]
 interface nsIDOMHTMLCommandElement : nsIDOMHTMLElement
 {
            attribute DOMString        type;
            attribute DOMString        label;
            attribute DOMString        icon;
            attribute boolean          disabled;
            attribute boolean          defaultChecked;
            attribute boolean          checked;
--- a/dom/interfaces/html/nsIDOMHTMLDListElement.idl
+++ b/dom/interfaces/html/nsIDOMHTMLDListElement.idl
@@ -45,13 +45,13 @@
  *
  * This interface is trying to follow the DOM Level 2 HTML specification:
  * http://www.w3.org/TR/DOM-Level-2-HTML/
  *
  * with changes from the work-in-progress WHATWG HTML specification:
  * http://www.whatwg.org/specs/web-apps/current-work/
  */
 
-[scriptable, uuid(f3e65e2b-e079-4970-bb5d-f96ac9cd18c5)]
+[scriptable, uuid(50e9ff30-0982-4074-bc65-313f41be8624)]
 interface nsIDOMHTMLDListElement : nsIDOMHTMLElement
 {
            attribute boolean          compact;
 };
--- a/dom/interfaces/html/nsIDOMHTMLDataListElement.idl
+++ b/dom/interfaces/html/nsIDOMHTMLDataListElement.idl
@@ -44,14 +44,14 @@
  * For more information on this interface, please see
  * http://www.whatwg.org/specs/web-apps/current-work/#the-datalist-element
  *
  * @status UNDER_DEVELOPMENT
  */
 
 interface nsIDOMHTMLCollection;
 
-[scriptable, uuid(312ed7c1-8c62-4d80-bbd9-99d7ea4377e6)]
+[scriptable, uuid(3bace78b-9eca-4990-a5d6-9c2b8c32cc8a)]
 interface nsIDOMHTMLDataListElement : nsIDOMHTMLElement
 {
   readonly attribute nsIDOMHTMLCollection options;
 };
 
--- a/dom/interfaces/html/nsIDOMHTMLDirectoryElement.idl
+++ b/dom/interfaces/html/nsIDOMHTMLDirectoryElement.idl
@@ -45,13 +45,13 @@
  *
  * This interface is trying to follow the DOM Level 2 HTML specification:
  * http://www.w3.org/TR/DOM-Level-2-HTML/
  *
  * with changes from the work-in-progress WHATWG HTML specification:
  * http://www.whatwg.org/specs/web-apps/current-work/
  */
 
-[scriptable, uuid(1e04cd43-edc0-4658-bd77-d67661af6c9c)]
+[scriptable, uuid(a99e86ae-7761-4145-b8a4-5a91186051f1)]
 interface nsIDOMHTMLDirectoryElement : nsIDOMHTMLElement
 {
            attribute boolean          compact;
 };
--- a/dom/interfaces/html/nsIDOMHTMLDivElement.idl
+++ b/dom/interfaces/html/nsIDOMHTMLDivElement.idl
@@ -45,13 +45,13 @@
  *
  * This interface is trying to follow the DOM Level 2 HTML specification:
  * http://www.w3.org/TR/DOM-Level-2-HTML/
  *
  * with changes from the work-in-progress WHATWG HTML specification:
  * http://www.whatwg.org/specs/web-apps/current-work/
  */
 
-[scriptable, uuid(771be9ee-b883-4556-bf90-2d7c904fe94d)]
+[scriptable, uuid(6815b902-8e04-49dd-977b-0a8785e5ffaf)]
 interface nsIDOMHTMLDivElement : nsIDOMHTMLElement
 {
            attribute DOMString        align;
 };
--- a/dom/interfaces/html/nsIDOMHTMLElement.idl
+++ b/dom/interfaces/html/nsIDOMHTMLElement.idl
@@ -48,17 +48,17 @@ interface nsIDOMHTMLMenuElement;
  * tree.
  *
  * This interface is trying to follow the DOM Level 2 HTML specification:
  * http://www.w3.org/TR/DOM-Level-2-HTML/
  *
  * with changes from the work-in-progress WHATWG HTML specification:
  * http://www.whatwg.org/specs/web-apps/current-work/
  */
-[scriptable, uuid(0a21bb68-d8bd-4b2a-a3db-048a02e81c62)]
+[scriptable, uuid(4eccf8a3-8bf5-43f3-a728-f5b632f7db3a)]
 interface nsIDOMHTMLElement : nsIDOMElement
 {
   // metadata attributes
            attribute DOMString        id;
            attribute DOMString        title;
            attribute DOMString        lang;
            attribute DOMString        dir;
            attribute DOMString        className;
@@ -81,16 +81,17 @@ interface nsIDOMHTMLElement : nsIDOMElem
            attribute DOMString        contentEditable;
   readonly attribute boolean          isContentEditable;
   readonly attribute nsIDOMHTMLMenuElement contextMenu;
            attribute boolean          spellcheck;
 
 
   // DOM Parsing and Serialization
            attribute DOMString        innerHTML;
+           attribute DOMString        outerHTML;
   void insertAdjacentHTML(in DOMString position,
                           in DOMString text);
 
 
   // CSSOM View
   [optional_argc] void scrollIntoView([optional] in boolean top);
   readonly attribute nsIDOMElement    offsetParent;
   readonly attribute long             offsetTop;
--- a/dom/interfaces/html/nsIDOMHTMLEmbedElement.idl
+++ b/dom/interfaces/html/nsIDOMHTMLEmbedElement.idl
@@ -42,17 +42,17 @@
 /**
  * The nsIDOMHTMLEmbedElement interface is the interface to a [X]HTML
  * embed element.
  *
  * For more information on this interface, please see
  * http://www.whatwg.org/specs/web-apps/current-work/#the-embed-element
  */
 
-[scriptable, uuid(d6309fc7-e9d2-4087-b452-490ed84f2dc2)]
+[scriptable, uuid(940a15c2-0d48-4186-b4d8-067fa1ce5675)]
 interface nsIDOMHTMLEmbedElement : nsIDOMHTMLElement
 {
            attribute DOMString        align;
            attribute DOMString        height;
            attribute DOMString        name;
            attribute DOMString        src;
            attribute DOMString        type;
            attribute DOMString        width;
--- a/dom/interfaces/html/nsIDOMHTMLFieldSetElement.idl
+++ b/dom/interfaces/html/nsIDOMHTMLFieldSetElement.idl
@@ -47,17 +47,17 @@
  * http://www.w3.org/TR/DOM-Level-2-HTML/
  *
  * with changes from the work-in-progress WHATWG HTML specification:
  * http://www.whatwg.org/specs/web-apps/current-work/
  */
 
 interface nsIDOMValidityState;
 
-[scriptable, uuid(e153c20e-7a3d-4184-865c-ee7c6d9b65df)]
+[scriptable, uuid(781ae103-b030-4aad-b2d5-96e5c2317dec)]
 interface nsIDOMHTMLFieldSetElement : nsIDOMHTMLElement
 {
            attribute boolean                disabled;
   readonly attribute nsIDOMHTMLFormElement  form;
            attribute DOMString              name;
 
   readonly attribute DOMString              type;
 
--- a/dom/interfaces/html/nsIDOMHTMLFontElement.idl
+++ b/dom/interfaces/html/nsIDOMHTMLFontElement.idl
@@ -45,15 +45,15 @@
  *
  * This interface is trying to follow the DOM Level 2 HTML specification:
  * http://www.w3.org/TR/DOM-Level-2-HTML/
  *
  * with changes from the work-in-progress WHATWG HTML specification:
  * http://www.whatwg.org/specs/web-apps/current-work/
  */
 
-[scriptable, uuid(8a205975-86cb-44db-b20e-df7f2d200580)]
+[scriptable, uuid(1c9778ee-a49c-40ee-9b93-c0ff15630431)]
 interface nsIDOMHTMLFontElement : nsIDOMHTMLElement
 {
            attribute DOMString        color;
            attribute DOMString        face;
            attribute DOMString        size;
 };
--- a/dom/interfaces/html/nsIDOMHTMLFormElement.idl
+++ b/dom/interfaces/html/nsIDOMHTMLFormElement.idl
@@ -45,17 +45,17 @@
  *
  * This interface is trying to follow the DOM Level 2 HTML specification:
  * http://www.w3.org/TR/DOM-Level-2-HTML/
  *
  * with changes from the work-in-progress WHATWG HTML specification:
  * http://www.whatwg.org/specs/web-apps/current-work/
  */
 
-[scriptable, uuid(8fe67952-6f7b-4d6e-b17b-79a454687e5f)]
+[scriptable, uuid(d873b251-6f96-4e70-baf5-aaa935aabe59)]
 interface nsIDOMHTMLFormElement : nsIDOMHTMLElement
 {
            attribute DOMString            acceptCharset;
            attribute DOMString            action;
            attribute DOMString            autocomplete;
            attribute DOMString            enctype;
            attribute DOMString            encoding;
            attribute DOMString            method;
--- a/dom/interfaces/html/nsIDOMHTMLFrameElement.idl
+++ b/dom/interfaces/html/nsIDOMHTMLFrameElement.idl
@@ -45,17 +45,17 @@
  *
  * This interface is trying to follow the DOM Level 2 HTML specification:
  * http://www.w3.org/TR/DOM-Level-2-HTML/
  *
  * with changes from the work-in-progress WHATWG HTML specification:
  * http://www.whatwg.org/specs/web-apps/current-work/
  */
 
-[scriptable, uuid(6de9d59d-42fd-44df-bb41-22cd64a85d4f)]
+[scriptable, uuid(318fdc4a-3fca-4099-94aa-c9a1c30ca2b9)]
 interface nsIDOMHTMLFrameElement : nsIDOMHTMLElement
 {
            attribute DOMString        frameBorder;
            attribute DOMString        longDesc;
            attribute DOMString        marginHeight;
            attribute DOMString        marginWidth;
            attribute DOMString        name;
            attribute boolean          noResize;
--- a/dom/interfaces/html/nsIDOMHTMLFrameSetElement.idl
+++ b/dom/interfaces/html/nsIDOMHTMLFrameSetElement.idl
@@ -49,17 +49,17 @@
  *
  * This interface is trying to follow the DOM Level 2 HTML specification:
  * http://www.w3.org/TR/DOM-Level-2-HTML/
  *
  * with changes from the work-in-progress WHATWG HTML specification:
  * http://www.whatwg.org/specs/web-apps/current-work/
  */
 
-[scriptable, uuid(a9423392-0f92-4b25-8700-49d28752c092)]
+[scriptable, uuid(6eefbe6d-182c-42e9-9850-af1892b6f2e4)]
 interface nsIDOMHTMLFrameSetElement : nsIDOMHTMLElement
 {
            attribute DOMString        cols;
            attribute DOMString        rows;
 
            [implicit_jscontext] attribute jsval            onafterprint;
            [implicit_jscontext] attribute jsval            onbeforeprint;
            [implicit_jscontext] attribute jsval            onbeforeunload;
--- a/dom/interfaces/html/nsIDOMHTMLHRElement.idl
+++ b/dom/interfaces/html/nsIDOMHTMLHRElement.idl
@@ -46,17 +46,17 @@
  *
  * This interface is trying to follow the DOM Level 2 HTML specification:
  * http://www.w3.org/TR/DOM-Level-2-HTML/
  *
  * with changes from the work-in-progress WHATWG HTML specification:
  * http://www.whatwg.org/specs/web-apps/current-work/
  */
 
-[scriptable, uuid(a6950d69-a376-4ad5-a911-8f91abb2b15d)]
+[scriptable, uuid(b94bff8f-dfa7-4dd8-8d97-c301dd9de729)]
 interface nsIDOMHTMLHRElement : nsIDOMHTMLElement
 {
            attribute DOMString        align;
            attribute boolean          noShade;
            attribute DOMString        size;
            attribute DOMString        width;
            attribute DOMString        color;
 };
--- a/dom/interfaces/html/nsIDOMHTMLHeadElement.idl
+++ b/dom/interfaces/html/nsIDOMHTMLHeadElement.idl
@@ -45,12 +45,12 @@
  *
  * This interface is trying to follow the DOM Level 2 HTML specification:
  * http://www.w3.org/TR/DOM-Level-2-HTML/
  *
  * with changes from the work-in-progress WHATWG HTML specification:
  * http://www.whatwg.org/specs/web-apps/current-work/
  */
 
-[scriptable, uuid(6d049c37-2cee-4c04-816c-270973e58ccf)]
+[scriptable, uuid(628fe597-6408-4387-9fcb-75381e2b2dd0)]
 interface nsIDOMHTMLHeadElement : nsIDOMHTMLElement
 {
 };
--- a/dom/interfaces/html/nsIDOMHTMLHeadingElement.idl
+++ b/dom/interfaces/html/nsIDOMHTMLHeadingElement.idl
@@ -45,13 +45,13 @@
  *
  * This interface is trying to follow the DOM Level 2 HTML specification:
  * http://www.w3.org/TR/DOM-Level-2-HTML/
  *
  * with changes from the work-in-progress WHATWG HTML specification:
  * http://www.whatwg.org/specs/web-apps/current-work/
  */
 
-[scriptable, uuid(c3c30a05-1dc0-413a-85f6-3c4d5af5f2b6)]
+[scriptable, uuid(964c94b0-5571-44e7-9b29-f81c6ea7828a)]
 interface nsIDOMHTMLHeadingElement : nsIDOMHTMLElement
 {
            attribute DOMString        align;
 };
--- a/dom/interfaces/html/nsIDOMHTMLHtmlElement.idl
+++ b/dom/interfaces/html/nsIDOMHTMLHtmlElement.idl
@@ -45,13 +45,13 @@
  *
  * This interface is trying to follow the DOM Level 2 HTML specification:
  * http://www.w3.org/TR/DOM-Level-2-HTML/
  *
  * with changes from the work-in-progress WHATWG HTML specification:
  * http://www.whatwg.org/specs/web-apps/current-work/
  */
 
-[scriptable, uuid(84825a7d-d5c7-4b1a-9d2a-b3e5df055824)]
+[scriptable, uuid(4bafbc15-aa88-4021-9ad6-e14189b7227b)]
 interface nsIDOMHTMLHtmlElement : nsIDOMHTMLElement
 {
            attribute DOMString        version;
 };
--- a/dom/interfaces/html/nsIDOMHTMLIFrameElement.idl
+++ b/dom/interfaces/html/nsIDOMHTMLIFrameElement.idl
@@ -45,17 +45,17 @@
  *
  * This interface is trying to follow the DOM Level 2 HTML specification:
  * http://www.w3.org/TR/DOM-Level-2-HTML/
  *
  * with changes from the work-in-progress WHATWG HTML specification:
  * http://www.whatwg.org/specs/web-apps/current-work/
  */
 
-[scriptable, uuid(166c1cdb-9af5-4217-9a2f-f9dae0923e85)]
+[scriptable, uuid(5ef30718-fe45-43a2-a478-a9e3cbf3a118)]
 interface nsIDOMHTMLIFrameElement : nsIDOMHTMLElement
 {
            attribute DOMString        align;
            attribute DOMString        frameBorder;
            attribute DOMString        height;
            attribute DOMString        longDesc;
            attribute DOMString        marginHeight;
            attribute DOMString        marginWidth;
--- a/dom/interfaces/html/nsIDOMHTMLImageElement.idl
+++ b/dom/interfaces/html/nsIDOMHTMLImageElement.idl
@@ -45,17 +45,17 @@
  *
  * This interface is trying to follow the DOM Level 2 HTML specification:
  * http://www.w3.org/TR/DOM-Level-2-HTML/
  *
  * with changes from the work-in-progress WHATWG HTML specification:
  * http://www.whatwg.org/specs/web-apps/current-work/
  */
 
-[scriptable, uuid(02dbe3c7-e75e-4a35-989c-b6f6d7a3108f)]
+[scriptable, uuid(56d9191f-5a94-432f-af70-6fccdeaf614b)]
 interface nsIDOMHTMLImageElement : nsIDOMHTMLElement
 {
            attribute DOMString        alt;
            attribute DOMString        src;
            attribute DOMString        crossOrigin;
            attribute DOMString        useMap;
            attribute boolean          isMap;
            attribute unsigned long    width;
--- a/dom/interfaces/html/nsIDOMHTMLInputElement.idl
+++ b/dom/interfaces/html/nsIDOMHTMLInputElement.idl
@@ -49,17 +49,17 @@ interface nsIDOMValidityState;
   *
   * This interface is trying to follow the DOM Level 2 HTML specification:
   * http://www.w3.org/TR/DOM-Level-2-HTML/
   *
   * with changes from the work-in-progress WHATWG HTML specification:
   * http://www.whatwg.org/specs/web-apps/current-work/
   */
 
-[scriptable, uuid(81cc1b30-02e1-4779-ac9e-0091933478a4)]
+[scriptable, uuid(7330cd35-c930-4f45-ae61-f5380c30222d)]
 interface nsIDOMHTMLInputElement : nsIDOMHTMLElement
 {
            attribute DOMString             accept;
            attribute DOMString             alt;
 
            attribute DOMString             autocomplete;
            attribute boolean               autofocus;
            attribute boolean               defaultChecked;
--- a/dom/interfaces/html/nsIDOMHTMLLIElement.idl
+++ b/dom/interfaces/html/nsIDOMHTMLLIElement.idl
@@ -45,14 +45,14 @@
  *
  * This interface is trying to follow the DOM Level 2 HTML specification:
  * http://www.w3.org/TR/DOM-Level-2-HTML/
  *
  * with changes from the work-in-progress WHATWG HTML specification:
  * http://www.whatwg.org/specs/web-apps/current-work/
  */
 
-[scriptable, uuid(cb9bbac6-3198-4159-9ee9-262eef35f265)]
+[scriptable, uuid(85b15d13-be6d-4653-9c70-22a13d510247)]
 interface nsIDOMHTMLLIElement : nsIDOMHTMLElement
 {
            attribute DOMString           type;
            attribute long                value;
 };
--- a/dom/interfaces/html/nsIDOMHTMLLabelElement.idl
+++ b/dom/interfaces/html/nsIDOMHTMLLabelElement.idl
@@ -45,15 +45,15 @@
  *
  * This interface is trying to follow the DOM Level 2 HTML specification:
  * http://www.w3.org/TR/DOM-Level-2-HTML/
  *
  * with changes from the work-in-progress WHATWG HTML specification:
  * http://www.whatwg.org/specs/web-apps/current-work/
  */
 
-[scriptable, uuid(0c36c887-04e3-4926-a916-8e3596130f9a)]
+[scriptable, uuid(ddbca449-625d-467c-a22d-7887474f9eb9)]
 interface nsIDOMHTMLLabelElement : nsIDOMHTMLElement
 {
   readonly attribute nsIDOMHTMLFormElement form;
            attribute DOMString             htmlFor;
   readonly attribute nsIDOMHTMLElement     control;
 };
--- a/dom/interfaces/html/nsIDOMHTMLLegendElement.idl
+++ b/dom/interfaces/html/nsIDOMHTMLLegendElement.idl
@@ -45,14 +45,14 @@
  *
  * This interface is trying to follow the DOM Level 2 HTML specification:
  * http://www.w3.org/TR/DOM-Level-2-HTML/
  *
  * with changes from the work-in-progress WHATWG HTML specification:
  * http://www.whatwg.org/specs/web-apps/current-work/
  */
 
-[scriptable, uuid(cabacc5f-5179-4c97-be60-0af8feafb4c9)]
+[scriptable, uuid(dac72753-6919-414b-b771-9e1e86e7749c)]
 interface nsIDOMHTMLLegendElement : nsIDOMHTMLElement
 {
   readonly attribute nsIDOMHTMLFormElement form;
            attribute DOMString             align;
 };
--- a/dom/interfaces/html/nsIDOMHTMLLinkElement.idl
+++ b/dom/interfaces/html/nsIDOMHTMLLinkElement.idl
@@ -45,17 +45,17 @@
  *
  * This interface is trying to follow the DOM Level 2 HTML specification:
  * http://www.w3.org/TR/DOM-Level-2-HTML/
  *
  * with changes from the work-in-progress WHATWG HTML specification:
  * http://www.whatwg.org/specs/web-apps/current-work/
  */
 
-[scriptable, uuid(2f238f84-1b45-4ef9-9cda-bd1430ce9304)]
+[scriptable, uuid(2ece79f4-83d7-499c-946f-ae9ab93147b7)]
 interface nsIDOMHTMLLinkElement : nsIDOMHTMLElement
 {
            attribute boolean          disabled;
            attribute DOMString        charset;
            attribute DOMString        href;
            attribute DOMString        hreflang;
            attribute DOMString        media;
            attribute DOMString        rel;
--- a/dom/interfaces/html/nsIDOMHTMLMapElement.idl
+++ b/dom/interfaces/html/nsIDOMHTMLMapElement.idl
@@ -45,14 +45,14 @@
  *
  * This interface is trying to follow the DOM Level 2 HTML specification:
  * http://www.w3.org/TR/DOM-Level-2-HTML/
  *
  * with changes from the work-in-progress WHATWG HTML specification:
  * http://www.whatwg.org/specs/web-apps/current-work/
  */
 
-[scriptable, uuid(3fb8ec10-8778-418d-9c83-556e46f115a9)]
+[scriptable, uuid(c919bc49-bd49-4b89-ba70-5c74c4ef504a)]
 interface nsIDOMHTMLMapElement : nsIDOMHTMLElement
 {
   readonly attribute nsIDOMHTMLCollection areas;
            attribute DOMString            name;
 };
--- a/dom/interfaces/html/nsIDOMHTMLMediaElement.idl
+++ b/dom/interfaces/html/nsIDOMHTMLMediaElement.idl
@@ -52,17 +52,17 @@
 
 // undef the GetCurrentTime macro defined in WinBase.h from the MS Platform SDK
 %{C++
 #ifdef GetCurrentTime
 #undef GetCurrentTime
 #endif
 %}
 
-[scriptable, uuid(85baaa10-73ab-4a48-a57a-b3951b67e494)]
+[scriptable, uuid(642a3b85-4edb-4c01-a162-06b5d88171e7)]
 interface nsIDOMHTMLMediaElement : nsIDOMHTMLElement
 {
   // error state
   readonly attribute nsIDOMMediaError error;
 
   // network state
            attribute DOMString src;
   readonly attribute DOMString currentSrc;
--- a/dom/interfaces/html/nsIDOMHTMLMenuElement.idl
+++ b/dom/interfaces/html/nsIDOMHTMLMenuElement.idl
@@ -45,16 +45,16 @@
  *
  * This interface is trying to follow the DOM Level 2 HTML specification:
  * http://www.w3.org/TR/DOM-Level-2-HTML/
  *
  * with changes from the work-in-progress WHATWG HTML specification:
  * http://www.whatwg.org/specs/web-apps/current-work/
  */
 
-[scriptable, uuid(12de9196-b164-43e0-9347-f23e1bffbede)]
+[scriptable, uuid(06d48250-45e0-4f26-9a07-d9b5a3f08bb6)]
 interface nsIDOMHTMLMenuElement : nsIDOMHTMLElement
 {
            attribute boolean          compact;
 
            attribute DOMString        type;
            attribute DOMString        label;
 };
--- a/dom/interfaces/html/nsIDOMHTMLMenuItemElement.idl
+++ b/dom/interfaces/html/nsIDOMHTMLMenuItemElement.idl
@@ -38,12 +38,12 @@
 
 /**
  * The nsIDOMHTMLMenuItemElement interface is the interface to a HTML
  * <menuitem> element.
  *
  * @status UNDER_DEVELOPMENT
  */
 
-[scriptable, uuid(e0469d92-a137-4329-9d4b-9f2ba5ce8e77)]
+[scriptable, uuid(4680ec24-94f0-4eb7-9413-98f9a857de72)]
 interface nsIDOMHTMLMenuItemElement : nsIDOMHTMLCommandElement
 {
 };
--- a/dom/interfaces/html/nsIDOMHTMLMetaElement.idl
+++ b/dom/interfaces/html/nsIDOMHTMLMetaElement.idl
@@ -45,16 +45,16 @@
  *
  * This interface is trying to follow the DOM Level 2 HTML specification:
  * http://www.w3.org/TR/DOM-Level-2-HTML/
  *
  * with changes from the work-in-progress WHATWG HTML specification:
  * http://www.whatwg.org/specs/web-apps/current-work/
  */
 
-[scriptable, uuid(c883b92b-5ae0-4563-894a-fa7f0e9aacda)]
+[scriptable, uuid(db476657-5f59-4e29-84a6-50afe6f85ac7)]
 interface nsIDOMHTMLMetaElement : nsIDOMHTMLElement
 {
            attribute DOMString        content;
            attribute DOMString        httpEquiv;
            attribute DOMString        name;
            attribute DOMString        scheme;
 };
--- a/dom/interfaces/html/nsIDOMHTMLModElement.idl
+++ b/dom/interfaces/html/nsIDOMHTMLModElement.idl
@@ -45,14 +45,14 @@
  *
  * This interface is trying to follow the DOM Level 2 HTML specification:
  * http://www.w3.org/TR/DOM-Level-2-HTML/
  *
  * with changes from the work-in-progress WHATWG HTML specification:
  * http://www.whatwg.org/specs/web-apps/current-work/
  */
 
-[scriptable, uuid(417626fa-191c-41e5-aed5-f6157b408e72)]
+[scriptable, uuid(170733d4-aad5-4f6e-86c0-94845ea6116d)]
 interface nsIDOMHTMLModElement : nsIDOMHTMLElement
 {
            attribute DOMString        cite;
            attribute DOMString        dateTime;
 };
--- a/dom/interfaces/html/nsIDOMHTMLOListElement.idl
+++ b/dom/interfaces/html/nsIDOMHTMLOListElement.idl
@@ -45,15 +45,15 @@
  *
  * This interface is trying to follow the DOM Level 2 HTML specification:
  * http://www.w3.org/TR/DOM-Level-2-HTML/
  *
  * with changes from the work-in-progress WHATWG HTML specification:
  * http://www.whatwg.org/specs/web-apps/current-work/
  */
 
-[scriptable, uuid(11e66686-b1ef-47be-9025-ffc20b875e4a)]
+[scriptable, uuid(31a5f083-59a6-41c3-8a0b-e58e484c6516)]
 interface nsIDOMHTMLOListElement : nsIDOMHTMLElement
 {
            attribute boolean          compact;
            attribute long             start;
            attribute DOMString        type;
 };
--- a/dom/interfaces/html/nsIDOMHTMLObjectElement.idl
+++ b/dom/interfaces/html/nsIDOMHTMLObjectElement.idl
@@ -47,17 +47,17 @@
  * http://www.w3.org/TR/DOM-Level-2-HTML/
  *
  * with changes from the work-in-progress WHATWG HTML specification:
  * http://www.whatwg.org/specs/web-apps/current-work/
  */
 
 interface nsIDOMValidityState;
 
-[scriptable, uuid(5d873128-d4e3-4e89-8900-599155167105)]
+[scriptable, uuid(40037f4a-5bae-476f-977b-bbd8e78aaefe)]
 interface nsIDOMHTMLObjectElement : nsIDOMHTMLElement
 {
   readonly attribute nsIDOMHTMLFormElement form;
            attribute DOMString             code;
            attribute DOMString             align;
            attribute DOMString             archive;
            attribute DOMString             border;
            attribute DOMString             codeBase;
--- a/dom/interfaces/html/nsIDOMHTMLOptGroupElement.idl
+++ b/dom/interfaces/html/nsIDOMHTMLOptGroupElement.idl
@@ -45,14 +45,14 @@
  *
  * This interface is trying to follow the DOM Level 2 HTML specification:
  * http://www.w3.org/TR/DOM-Level-2-HTML/
  *
  * with changes from the work-in-progress WHATWG HTML specification:
  * http://www.whatwg.org/specs/web-apps/current-work/
  */
 
-[scriptable, uuid(7b585d49-1da3-4fc6-a50c-b661063c2edc)]
+[scriptable, uuid(ab55d67a-aabb-4441-b182-8ff2bd7d157e)]
 interface nsIDOMHTMLOptGroupElement : nsIDOMHTMLElement
 {
            attribute boolean          disabled;
            attribute DOMString        label;
 };
--- a/dom/interfaces/html/nsIDOMHTMLOptionElement.idl
+++ b/dom/interfaces/html/nsIDOMHTMLOptionElement.idl
@@ -45,17 +45,17 @@
  *
  * This interface is trying to follow the DOM Level 2 HTML specification:
  * http://www.w3.org/TR/DOM-Level-2-HTML/
  *
  * with changes from the work-in-progress WHATWG HTML specification:
  * http://www.whatwg.org/specs/web-apps/current-work/
  */
 
-[scriptable, uuid(c20ead8a-cb89-43b1-89ed-8f4713bf8452)]
+[scriptable, uuid(7c5bf0ac-6230-4ee0-8b82-e7ebf211af03)]
 interface nsIDOMHTMLOptionElement : nsIDOMHTMLElement
 {
            attribute boolean               disabled;
   readonly attribute nsIDOMHTMLFormElement form;
            attribute DOMString             label;
            attribute boolean               defaultSelected;
            attribute boolean               selected;
            attribute DOMString             value;
--- a/dom/interfaces/html/nsIDOMHTMLOutputElement.idl
+++ b/dom/interfaces/html/nsIDOMHTMLOutputElement.idl
@@ -45,17 +45,17 @@
  * http://www.whatwg.org/specs/web-apps/current-work/#the-output-element
  *
  * @status UNDER_DEVELOPMENT
  */
 
 interface nsIDOMDOMSettableTokenList;
 interface nsIDOMValidityState;
 
-[scriptable, uuid(7d1fb2a9-7678-409e-8eb5-9216c47c233b)]
+[scriptable, uuid(f2074cdb-19cb-447a-935c-9f4402dc1b5e)]
 interface nsIDOMHTMLOutputElement : nsIDOMHTMLElement
 {
   readonly attribute nsIDOMDOMSettableTokenList htmlFor;
   readonly attribute nsIDOMHTMLFormElement      form;
            attribute DOMString                  name;
 
   readonly attribute DOMString                  type;
            attribute DOMString                  defaultValue;
--- a/dom/interfaces/html/nsIDOMHTMLParagraphElement.idl
+++ b/dom/interfaces/html/nsIDOMHTMLParagraphElement.idl
@@ -45,13 +45,13 @@
  *
  * This interface is trying to follow the DOM Level 2 HTML specification:
  * http://www.w3.org/TR/DOM-Level-2-HTML/
  *
  * with changes from the work-in-progress WHATWG HTML specification:
  * http://www.whatwg.org/specs/web-apps/current-work/
  */
 
-[scriptable, uuid(d5d3eb33-0925-4555-be2f-4078dec49f59)]
+[scriptable, uuid(e4f498f4-e3c5-46fe-92d0-c9957ccab530)]
 interface nsIDOMHTMLParagraphElement : nsIDOMHTMLElement
 {
            attribute DOMString        align;
 };
--- a/dom/interfaces/html/nsIDOMHTMLParamElement.idl
+++ b/dom/interfaces/html/nsIDOMHTMLParamElement.idl
@@ -45,16 +45,16 @@
  *
  * This interface is trying to follow the DOM Level 2 HTML specification:
  * http://www.w3.org/TR/DOM-Level-2-HTML/
  *
  * with changes from the work-in-progress WHATWG HTML specification:
  * http://www.whatwg.org/specs/web-apps/current-work/
  */
 
-[scriptable, uuid(ccffedb8-f234-474e-9af4-576eba766023)]
+[scriptable, uuid(d832b1ac-9bb6-4df0-9d9e-f7c040759672)]
 interface nsIDOMHTMLParamElement : nsIDOMHTMLElement
 {
            attribute DOMString        name;
            attribute DOMString        type;
            attribute DOMString        value;
            attribute DOMString        valueType;
 };
--- a/dom/interfaces/html/nsIDOMHTMLPreElement.idl
+++ b/dom/interfaces/html/nsIDOMHTMLPreElement.idl
@@ -45,13 +45,13 @@
  *
  * This interface is trying to follow the DOM Level 2 HTML specification:
  * http://www.w3.org/TR/DOM-Level-2-HTML/
  *
  * with changes from the work-in-progress WHATWG HTML specification:
  * http://www.whatwg.org/specs/web-apps/current-work/
  */
 
-[scriptable, uuid(c9d9b45a-e7d9-4dfb-abae-f3b9e6addbaa)]
+[scriptable, uuid(f4088dff-649c-4eff-a3a4-dbd6333cdc44)]
 interface nsIDOMHTMLPreElement : nsIDOMHTMLElement
 {
            attribute long             width;
 };
--- a/dom/interfaces/html/nsIDOMHTMLProgressElement.idl
+++ b/dom/interfaces/html/nsIDOMHTMLProgressElement.idl
@@ -42,17 +42,17 @@
  * <progress> element.
  *
  * For more information on this interface, please see
  * http://www.whatwg.org/specs/web-apps/current-work/#the-progress-element
  *
  * @status UNDER_DEVELOPMENT
  */
 
-[scriptable, uuid(aa830aa2-a4ea-455e-8285-8344cadb4c6d)]
+[scriptable, uuid(9b1d2263-b60f-4d18-b4d1-66e8c3867c79)]
 interface nsIDOMHTMLProgressElement : nsIDOMHTMLElement
 {
            attribute double value;
            attribute double max;
   readonly attribute double position;
   readonly attribute nsIDOMHTMLFormElement form;
   /**
    * The labels attribute will be done with bug 567740.
--- a/dom/interfaces/html/nsIDOMHTMLQuoteElement.idl
+++ b/dom/interfaces/html/nsIDOMHTMLQuoteElement.idl
@@ -45,13 +45,13 @@
  *
  * This interface is trying to follow the DOM Level 2 HTML specification:
  * http://www.w3.org/TR/DOM-Level-2-HTML/
  *
  * with changes from the work-in-progress WHATWG HTML specification:
  * http://www.whatwg.org/specs/web-apps/current-work/
  */
 
-[scriptable, uuid(820ccd14-2479-4e4a-99d3-76d138caf7ec)]
+[scriptable, uuid(55643647-2eda-4a45-af55-b2ba6c40c5f5)]
 interface nsIDOMHTMLQuoteElement : nsIDOMHTMLElement
 {
            attribute DOMString        cite;
 };
--- a/dom/interfaces/html/nsIDOMHTMLScriptElement.idl
+++ b/dom/interfaces/html/nsIDOMHTMLScriptElement.idl
@@ -45,17 +45,17 @@
  *
  * This interface is trying to follow the DOM Level 2 HTML specification:
  * http://www.w3.org/TR/DOM-Level-2-HTML/
  *
  * with changes from the work-in-progress WHATWG HTML specification:
  * http://www.whatwg.org/specs/web-apps/current-work/
  */
 
-[scriptable, uuid(e6252d3b-521a-4f79-9d57-2721a81e7cc2)]
+[scriptable, uuid(4b6a0957-5466-4134-8a0a-dd7e4675c106)]
 interface nsIDOMHTMLScriptElement : nsIDOMHTMLElement
 {
            attribute DOMString        src;
            attribute boolean          async;
            attribute boolean          defer;
            attribute DOMString        type;
            attribute DOMString        charset;
            attribute DOMString        text;
--- a/dom/interfaces/html/nsIDOMHTMLSelectElement.idl
+++ b/dom/interfaces/html/nsIDOMHTMLSelectElement.idl
@@ -48,17 +48,17 @@
  * http://www.w3.org/TR/DOM-Level-2-HTML/
  *
  * with changes from the work-in-progress WHATWG HTML specification:
  * http://www.whatwg.org/specs/web-apps/current-work/
  */
 
 interface nsIDOMValidityState;
 
-[scriptable, uuid(30a948a3-61a0-453c-a1e4-de67a1664746)]
+[scriptable, uuid(98f111e0-2b7e-4abd-984b-2cc1d174fe44)]
 interface nsIDOMHTMLSelectElement : nsIDOMHTMLElement
 {
            attribute boolean                     autofocus;
            attribute boolean                     disabled;
   readonly attribute nsIDOMHTMLFormElement       form;
            attribute boolean                     multiple;
            attribute DOMString                   name;
            attribute long                        size;
--- a/dom/interfaces/html/nsIDOMHTMLSourceElement.idl
+++ b/dom/interfaces/html/nsIDOMHTMLSourceElement.idl
@@ -43,14 +43,14 @@
  * <source> element.
  *
  * For more information on this interface, please see
  * http://www.whatwg.org/specs/web-apps/current-work/#source
  *
  * @status UNDER_DEVELOPMENT
  */
 
-[scriptable, uuid(dcac4414-37e2-409f-b0a6-8231007e585b)]
+[scriptable, uuid(c49d9a78-fa02-49c9-b239-9cd51e99f866)]
 interface nsIDOMHTMLSourceElement : nsIDOMHTMLElement
 {
            attribute DOMString src;
            attribute DOMString type;
 };
--- a/dom/interfaces/html/nsIDOMHTMLStyleElement.idl
+++ b/dom/interfaces/html/nsIDOMHTMLStyleElement.idl
@@ -45,15 +45,15 @@
  *
  * This interface is trying to follow the DOM Level 2 HTML specification:
  * http://www.w3.org/TR/DOM-Level-2-HTML/
  *
  * with changes from the work-in-progress WHATWG HTML specification:
  * http://www.whatwg.org/specs/web-apps/current-work/
  */
 
-[scriptable, uuid(e72a6069-4987-480b-a349-ffd5fbebd59f)]
+[scriptable, uuid(247fc8c4-92f3-427b-af6f-41b13f28287d)]
 interface nsIDOMHTMLStyleElement : nsIDOMHTMLElement
 {
            attribute boolean          disabled;
            attribute DOMString        media;
            attribute DOMString        type;
 };
--- a/dom/interfaces/html/nsIDOMHTMLTableCaptionElem.idl
+++ b/dom/interfaces/html/nsIDOMHTMLTableCaptionElem.idl
@@ -45,13 +45,13 @@
  *
  * This interface is trying to follow the DOM Level 2 HTML specification:
  * http://www.w3.org/TR/DOM-Level-2-HTML/
  *
  * with changes from the work-in-progress WHATWG HTML specification:
  * http://www.whatwg.org/specs/web-apps/current-work/
  */
 
-[scriptable, uuid(cbd44d29-3120-470d-a7fb-fac4730c8b4b)]
+[scriptable, uuid(db0e641f-ba2b-4c67-8da1-4e418cc5fbf7)]
 interface nsIDOMHTMLTableCaptionElement : nsIDOMHTMLElement
 {
            attribute DOMString        align;
 };
--- a/dom/interfaces/html/nsIDOMHTMLTableCellElement.idl
+++ b/dom/interfaces/html/nsIDOMHTMLTableCellElement.idl
@@ -45,17 +45,17 @@
  *
  * This interface is trying to follow the DOM Level 2 HTML specification:
  * http://www.w3.org/TR/DOM-Level-2-HTML/
  *
  * with changes from the work-in-progress WHATWG HTML specification:
  * http://www.whatwg.org/specs/web-apps/current-work/
  */
 
-[scriptable, uuid(03dd5118-7eaf-4bd3-a4a7-77f3f7eb8539)]
+[scriptable, uuid(4caa7af0-fec4-44c1-9a81-e1f14166e60c)]
 interface nsIDOMHTMLTableCellElement : nsIDOMHTMLElement
 {
   readonly attribute long             cellIndex;
            attribute DOMString        abbr;
            attribute DOMString        align;
            attribute DOMString        axis;
            attribute DOMString        bgColor;
            attribute DOMString        ch;
--- a/dom/interfaces/html/nsIDOMHTMLTableColElement.idl
+++ b/dom/interfaces/html/nsIDOMHTMLTableColElement.idl
@@ -45,17 +45,17 @@
  *
  * This interface is trying to follow the DOM Level 2 HTML specification:
  * http://www.w3.org/TR/DOM-Level-2-HTML/
  *
  * with changes from the work-in-progress WHATWG HTML specification:
  * http://www.whatwg.org/specs/web-apps/current-work/
  */
 
-[scriptable, uuid(d221534a-d13c-43b2-9ba0-7e0dd7452856)]
+[scriptable, uuid(9a4d1f6a-fb19-4886-b0d8-dcd201566580)]
 interface nsIDOMHTMLTableColElement : nsIDOMHTMLElement
 {
            attribute DOMString        align;
            attribute DOMString        ch;
            attribute DOMString        chOff;
            attribute long             span;
            attribute DOMString        vAlign;
            attribute DOMString        width;
--- a/dom/interfaces/html/nsIDOMHTMLTableElement.idl
+++ b/dom/interfaces/html/nsIDOMHTMLTableElement.idl
@@ -45,17 +45,17 @@
  *
  * This interface is trying to follow the DOM Level 2 HTML specification:
  * http://www.w3.org/TR/DOM-Level-2-HTML/
  *
  * with changes from the work-in-progress WHATWG HTML specification:
  * http://www.whatwg.org/specs/web-apps/current-work/
  */
 
-[scriptable, uuid(bba4b8b2-d01c-4c9b-abc8-3df28d048e68)]
+[scriptable, uuid(0f809b97-9311-45c4-a44e-7145f354438b)]
 interface nsIDOMHTMLTableElement : nsIDOMHTMLElement
 {
   // Modified in DOM Level 2:
            attribute nsIDOMHTMLTableCaptionElement caption;
                                              // raises(DOMException) on setting
 
   // Modified in DOM Level 2:
            attribute nsIDOMHTMLTableSectionElement tHead;
--- a/dom/interfaces/html/nsIDOMHTMLTableRowElement.idl
+++ b/dom/interfaces/html/nsIDOMHTMLTableRowElement.idl
@@ -45,17 +45,17 @@
  *
  * This interface is trying to follow the DOM Level 2 HTML specification:
  * http://www.w3.org/TR/DOM-Level-2-HTML/
  *
  * with changes from the work-in-progress WHATWG HTML specification:
  * http://www.whatwg.org/specs/web-apps/current-work/
  */
 
-[scriptable, uuid(b0199f36-9e76-4ec6-867f-850e388d6244)]
+[scriptable, uuid(d24a80d4-491d-4e36-9349-afd3c6999b3e)]
 interface nsIDOMHTMLTableRowElement : nsIDOMHTMLElement
 {
   // Modified in DOM Level 2:
   readonly attribute long                 rowIndex;
   // Modified in DOM Level 2:
   readonly attribute long                 sectionRowIndex;
   // Modified in DOM Level 2:
   readonly attribute nsIDOMHTMLCollection cells;
--- a/dom/interfaces/html/nsIDOMHTMLTableSectionElem.idl
+++ b/dom/interfaces/html/nsIDOMHTMLTableSectionElem.idl
@@ -45,17 +45,17 @@
  *
  * This interface is trying to follow the DOM Level 2 HTML specification:
  * http://www.w3.org/TR/DOM-Level-2-HTML/
  *
  * with changes from the work-in-progress WHATWG HTML specification:
  * http://www.whatwg.org/specs/web-apps/current-work/
  */
 
-[scriptable, uuid(ac2e2719-71f1-4485-ac1e-694e7e49bd2a)]
+[scriptable, uuid(6acc106e-96a2-4519-8f3a-142ebbdc1bb1)]
 interface nsIDOMHTMLTableSectionElement : nsIDOMHTMLElement
 {
            attribute DOMString            align;
            attribute DOMString            ch;
            attribute DOMString            chOff;
            attribute DOMString            vAlign;
   readonly attribute nsIDOMHTMLCollection rows;
   // Modified in DOM Level 2:
--- a/dom/interfaces/html/nsIDOMHTMLTextAreaElement.idl
+++ b/dom/interfaces/html/nsIDOMHTMLTextAreaElement.idl
@@ -48,17 +48,17 @@ interface nsIDOMValidityState;
  *
  * This interface is trying to follow the DOM Level 2 HTML specification:
  * http://www.w3.org/TR/DOM-Level-2-HTML/
  *
  * with changes from the work-in-progress WHATWG HTML specification:
  * http://www.whatwg.org/specs/web-apps/current-work/
  */
 
-[scriptable, uuid(88d09917-d2da-4737-a887-277a2f9750c7)]
+[scriptable, uuid(16db703d-4816-440c-bcb3-c1ae0cae6532)]
 interface nsIDOMHTMLTextAreaElement : nsIDOMHTMLElement
 {
            attribute boolean               autofocus;
            attribute unsigned long         cols;
            attribute boolean               disabled;
   readonly attribute nsIDOMHTMLFormElement form;
            attribute long                  maxLength;
            attribute DOMString             name;
--- a/dom/interfaces/html/nsIDOMHTMLTitleElement.idl
+++ b/dom/interfaces/html/nsIDOMHTMLTitleElement.idl
@@ -45,13 +45,13 @@
  *
  * This interface is trying to follow the DOM Level 2 HTML specification:
  * http://www.w3.org/TR/DOM-Level-2-HTML/
  *
  * with changes from the work-in-progress WHATWG HTML specification:
  * http://www.whatwg.org/specs/web-apps/current-work/
  */
 
-[scriptable, uuid(5cb8cfaf-7551-422b-9b03-58d756e54339)]
+[scriptable, uuid(e20fd651-6240-4f20-b8f0-6cc25cb699b7)]
 interface nsIDOMHTMLTitleElement : nsIDOMHTMLElement
 {
            attribute DOMString        text;
 };
--- a/dom/interfaces/html/nsIDOMHTMLUListElement.idl
+++ b/dom/interfaces/html/nsIDOMHTMLUListElement.idl
@@ -45,14 +45,14 @@
  *
  * This interface is trying to follow the DOM Level 2 HTML specification:
  * http://www.w3.org/TR/DOM-Level-2-HTML/
  *
  * with changes from the work-in-progress WHATWG HTML specification:
  * http://www.whatwg.org/specs/web-apps/current-work/
  */
 
-[scriptable, uuid(1f409357-8cea-4f69-9f0c-4149886b63a1)]
+[scriptable, uuid(2467d39c-2c30-407e-9b67-ea5f231b7809)]
 interface nsIDOMHTMLUListElement : nsIDOMHTMLElement
 {
            attribute boolean          compact;
            attribute DOMString        type;
 };
--- a/dom/interfaces/html/nsIDOMHTMLUnknownElement.idl
+++ b/dom/interfaces/html/nsIDOMHTMLUnknownElement.idl
@@ -38,12 +38,12 @@
 #include "nsIDOMHTMLElement.idl"
 
 /**
  * The nsIDOMHTMLUnknownElement interface is the interface to an unknown HTML
  * element.
  *
  * @see <http://www.whatwg.org/html/#htmlunknownelement>
  */
-[scriptable, uuid(0d69049f-8181-47f1-a7f7-e5417dd54136)]
+[scriptable, uuid(5f922c13-c2c1-4c49-b7c2-0e4e5c8e6860)]
 interface nsIDOMHTMLUnknownElement : nsIDOMHTMLElement
 {
 };
--- a/dom/interfaces/html/nsIDOMHTMLVideoElement.idl
+++ b/dom/interfaces/html/nsIDOMHTMLVideoElement.idl
@@ -43,17 +43,17 @@
  * <video> element.
  *
  * For more information on this interface, please see
  * http://www.whatwg.org/specs/web-apps/current-work/#video
  *
  * @status UNDER_DEVELOPMENT
  */
 
-[scriptable, uuid(5e1e4453-96fe-4cc0-9c32-7e9355b4f917)]
+[scriptable, uuid(390b974b-1c3a-4700-8001-5ef832c4b4bf)]
 interface nsIDOMHTMLVideoElement : nsIDOMHTMLMediaElement
 {
            attribute long width; 
            attribute long height;
   readonly attribute unsigned long videoWidth;
   readonly attribute unsigned long videoHeight;
            attribute DOMString poster;
            
--- a/dom/ipc/ContentChild.cpp
+++ b/dom/ipc/ContentChild.cpp
@@ -93,17 +93,17 @@
 
 #ifdef MOZ_PERMISSIONS
 #include "nsPermission.h"
 #include "nsPermissionManager.h"
 #endif
 
 #include "nsDeviceMotion.h"
 
-#if defined(ANDROID)
+#if defined(MOZ_WIDGET_ANDROID)
 #include "APKOpen.h"
 #endif
 
 #ifdef XP_WIN
 #include <process.h>
 #define getpid _getpid
 #endif
 
@@ -267,17 +267,17 @@ ContentChild::Init(MessageLoop* aIOLoop,
     NS_ASSERTION(!sSingleton, "only one ContentChild per child");
 
     Open(aChannel, aParentHandle, aIOLoop);
     sSingleton = this;
 
 #ifdef MOZ_CRASHREPORTER
     SendPCrashReporterConstructor(CrashReporter::CurrentThreadId(),
                                   XRE_GetProcessType());
-#if defined(ANDROID)
+#if defined(MOZ_WIDGET_ANDROID)
     PCrashReporterChild* crashreporter = ManagedPCrashReporterChild()[0];
 
     InfallibleTArray<Mapping> mappings;
     const struct mapping_info *info = getLibraryMapping();
     while (info && info->name) {
         mappings.AppendElement(Mapping(nsDependentCString(info->name),
                                        nsDependentCString(info->file_id),
                                        info->base,
--- a/dom/ipc/ContentParent.cpp
+++ b/dom/ipc/ContentParent.cpp
@@ -101,16 +101,18 @@
 #include "mozilla/Util.h"
 
 #include "nsIMemoryReporter.h"
 #include "nsMemoryReporterManager.h"
 #include "mozilla/dom/PMemoryReportRequestParent.h"
 
 #ifdef ANDROID
 #include "gfxAndroidPlatform.h"
+#endif
+#ifdef MOZ_WIDGET_ANDROID
 #include "AndroidBridge.h"
 #endif
 
 #include "nsIClipboard.h"
 #include "nsWidgetsCID.h"
 #include "nsISupportsPrimitives.h"
 static NS_DEFINE_CID(kCClipboardCID, NS_CLIPBOARD_CID);
 static const char* sClipboardTextFlavors[] = { kUnicodeMime };
@@ -631,17 +633,17 @@ ContentParent::RecvClipboardHasText(bool
     clipboard->HasDataMatchingFlavors(sClipboardTextFlavors, 1, 
                                       nsIClipboard::kGlobalClipboard, hasText);
     return true;
 }
 
 bool
 ContentParent::RecvGetSystemColors(const PRUint32& colorsCount, InfallibleTArray<PRUint32>* colors)
 {
-#ifdef ANDROID
+#ifdef MOZ_WIDGET_ANDROID
     NS_ASSERTION(AndroidBridge::Bridge() != nsnull, "AndroidBridge is not available");
     if (AndroidBridge::Bridge() == nsnull) {
         // Do not fail - the colors won't be right, but it's not critical
         return true;
     }
 
     colors->AppendElements(colorsCount);
 
@@ -650,17 +652,17 @@ ContentParent::RecvGetSystemColors(const
     AndroidBridge::Bridge()->GetSystemColors((AndroidSystemColors*)colors->Elements());
 #endif
     return true;
 }
 
 bool
 ContentParent::RecvGetIconForExtension(const nsCString& aFileExt, const PRUint32& aIconSize, InfallibleTArray<PRUint8>* bits)
 {
-#ifdef ANDROID
+#ifdef MOZ_WIDGET_ANDROID
     NS_ASSERTION(AndroidBridge::Bridge() != nsnull, "AndroidBridge is not available");
     if (AndroidBridge::Bridge() == nsnull) {
         // Do not fail - just no icon will be shown
         return true;
     }
 
     bits->AppendElements(aIconSize * aIconSize * 4);
 
@@ -669,17 +671,17 @@ ContentParent::RecvGetIconForExtension(c
     return true;
 }
 
 bool
 ContentParent::RecvGetShowPasswordSetting(bool* showPassword)
 {
     // default behavior is to show the last password character
     *showPassword = true;
-#ifdef ANDROID
+#ifdef MOZ_WIDGET_ANDROID
     NS_ASSERTION(AndroidBridge::Bridge() != nsnull, "AndroidBridge is not available");
     if (AndroidBridge::Bridge() != nsnull)
         *showPassword = AndroidBridge::Bridge()->GetShowPasswordSetting();
 #endif
     return true;
 }
 
 NS_IMPL_THREADSAFE_ISUPPORTS4(ContentParent,
--- a/dom/plugins/base/PluginPRLibrary.cpp
+++ b/dom/plugins/base/PluginPRLibrary.cpp
@@ -46,25 +46,25 @@
 // gNotOptimized exists so that the compiler will not optimize the alloca
 // below.
 static int gNotOptimized;
 #define CALLING_CONVENTION_HACK void* foo = _alloca(gNotOptimized);
 #else
 #define CALLING_CONVENTION_HACK
 #endif
 
-#ifdef ANDROID
+#ifdef MOZ_WIDGET_ANDROID
 #include "AndroidBridge.h"
 #include "android_npapi.h"
 #include <android/log.h>
 #define ALOG(args...) __android_log_print(ANDROID_LOG_INFO, "GeckoJavaEnv", ## args)
 #endif
 
 namespace mozilla {
-#ifdef ANDROID
+#ifdef MOZ_WIDGET_ANDROID
 nsresult
 PluginPRLibrary::NP_Initialize(NPNetscapeFuncs* bFuncs,
 			       NPPluginFuncs* pFuncs, NPError* error)
 {
   if (mNP_Initialize) {
     *error = mNP_Initialize(bFuncs, pFuncs, GetJNIForThread());
   } else {
     NP_InitializeFunc pfNP_Initialize = (NP_InitializeFunc)
@@ -77,20 +77,26 @@ PluginPRLibrary::NP_Initialize(NPNetscap
 
   // Save pointers to functions that get called through PluginLibrary itself.
   mNPP_New = pFuncs->newp;
   mNPP_GetValue = pFuncs->getvalue;
   mNPP_ClearSiteData = pFuncs->clearsitedata;
   mNPP_GetSitesWithData = pFuncs->getsiteswithdata;
   return NS_OK;
 }
+#elif defined(MOZ_WIDGET_GONK)
+nsresult
+PluginPRLibrary::NP_Initialize(NPNetscapeFuncs* bFuncs, NPError* error)
+{
+  return NS_OK;
+}
 #elif defined(XP_UNIX) && !defined(XP_MACOSX)
 nsresult
 PluginPRLibrary::NP_Initialize(NPNetscapeFuncs* bFuncs,
-			       NPPluginFuncs* pFuncs, NPError* error)
+                               NPPluginFuncs* pFuncs, NPError* error)
 {
   if (mNP_Initialize) {
     *error = mNP_Initialize(bFuncs, pFuncs);
   } else {
     NP_InitializeFunc pfNP_Initialize = (NP_InitializeFunc)
       PR_FindFunctionSymbol(mLibrary, "NP_Initialize");
     if (!pfNP_Initialize)
       return NS_ERROR_FAILURE;
--- a/dom/plugins/base/PluginPRLibrary.h
+++ b/dom/plugins/base/PluginPRLibrary.h
@@ -109,17 +109,17 @@ public:
         mNP_GetEntryPoints = (NP_GetEntryPointsFunc)
             PR_FindFunctionSymbol(mLibrary, "NP_GetEntryPoints");
         if (!mNP_GetEntryPoints)
             return false;
 #endif
         return true;
     }
 
-#if defined(XP_UNIX) && !defined(XP_MACOSX)
+#if defined(XP_UNIX) && !defined(XP_MACOSX) && !defined(MOZ_WIDGET_GONK)
     virtual nsresult NP_Initialize(NPNetscapeFuncs* bFuncs,
                                    NPPluginFuncs* pFuncs, NPError* error);
 #else
     virtual nsresult NP_Initialize(NPNetscapeFuncs* bFuncs,
                                    NPError* error);
 #endif
 
     virtual nsresult NP_Shutdown(NPError* error);
--- a/dom/plugins/base/npfunctions.h
+++ b/dom/plugins/base/npfunctions.h
@@ -43,17 +43,17 @@
 #define NP_LOADDS _System
 #else
 #define NP_LOADDS
 #endif
 
 #include "npapi.h"
 #include "npruntime.h"
 
-#ifdef ANDROID
+#ifdef MOZ_WIDGET_ANDROID
 #include <jni.h>
 #endif
 
 typedef NPError      (* NP_LOADDS NPP_NewProcPtr)(NPMIMEType pluginType, NPP instance, uint16_t mode, int16_t argc, char* argn[], char* argv[], NPSavedData* saved);
 typedef NPError      (* NP_LOADDS NPP_DestroyProcPtr)(NPP instance, NPSavedData** save);
 typedef NPError      (* NP_LOADDS NPP_SetWindowProcPtr)(NPP instance, NPWindow* window);
 typedef NPError      (* NP_LOADDS NPP_NewStreamProcPtr)(NPP instance, NPMIMEType type, NPStream* stream, NPBool seekable, uint16_t* stype);
 typedef NPError      (* NP_LOADDS NPP_DestroyStreamProcPtr)(NPP instance, NPStream* stream, NPReason reason);
@@ -306,17 +306,17 @@ NP_EXPORT(char*)       NP_GetPluginVersi
 typedef const char*    (*NP_GetMIMEDescriptionFunc)(void);
 NP_EXPORT(const char*) NP_GetMIMEDescription(void);
 #ifdef XP_MACOSX
 typedef NPError        (*NP_InitializeFunc)(NPNetscapeFuncs*);
 NP_EXPORT(NPError)     NP_Initialize(NPNetscapeFuncs* bFuncs);
 typedef NPError        (*NP_GetEntryPointsFunc)(NPPluginFuncs*);
 NP_EXPORT(NPError)     NP_GetEntryPoints(NPPluginFuncs* pFuncs);
 #else
-#ifdef ANDROID
+#ifdef MOZ_WIDGET_ANDROID
 typedef NPError    (*NP_InitializeFunc)(NPNetscapeFuncs*, NPPluginFuncs*, JNIEnv* pEnv);
 NP_EXPORT(NPError) NP_Initialize(NPNetscapeFuncs* bFuncs, NPPluginFuncs* pFuncs, JNIEnv* pEnv);
 #else
 typedef NPError    (*NP_InitializeFunc)(NPNetscapeFuncs*, NPPluginFuncs*);
 NP_EXPORT(NPError) NP_Initialize(NPNetscapeFuncs* bFuncs, NPPluginFuncs* pFuncs);
 #endif
 #endif
 typedef NPError        (*NP_ShutdownFunc)(void);
--- a/dom/plugins/base/nsNPAPIPlugin.cpp
+++ b/dom/plugins/base/nsNPAPIPlugin.cpp
@@ -126,17 +126,17 @@ using mozilla::plugins::PluginModulePare
 #ifdef MOZ_X11
 #include "mozilla/X11Util.h"
 #endif
 
 #ifdef XP_WIN
 #include <windows.h>
 #endif
 
-#ifdef ANDROID
+#ifdef MOZ_WIDGET_ANDROID
 #include "ANPBase.h"
 #include "AndroidBridge.h"
 #include <android/log.h>
 #define LOG(args...)  __android_log_print(ANDROID_LOG_INFO, "GeckoPlugins" , ## args)
 #endif
 
 using namespace mozilla;
 using namespace mozilla::plugins::parent;
@@ -483,17 +483,17 @@ nsNPAPIPlugin::CreatePlugin(nsPluginTag 
   if (!plugin)
     return NS_ERROR_OUT_OF_MEMORY;
 
   PluginLibrary* pluginLib = GetNewPluginLibrary(aPluginTag);
   if (!pluginLib) {
     return NS_ERROR_FAILURE;
   }
 
-#if defined(XP_MACOSX) || defined(ANDROID)
+#if defined(XP_MACOSX) || defined(MOZ_WIDGET_ANDROID)
   if (!pluginLib->HasRequiredFunctions()) {
     NS_WARNING("Not all necessary functions exposed by plugin, it will not load.");
     return NS_ERROR_FAILURE;
   }
 #endif
 
   plugin->mLibrary = pluginLib;
   pluginLib->SetPlugin(plugin);
@@ -521,16 +521,17 @@ nsNPAPIPlugin::CreatePlugin(nsPluginTag 
   if (rv != NS_OK || pluginCallError != NPERR_NO_ERROR) {
     return NS_ERROR_FAILURE;
   }
 
   rv = pluginLib->NP_GetEntryPoints(&plugin->mPluginFuncs, &pluginCallError);
   if (rv != NS_OK || pluginCallError != NPERR_NO_ERROR) {
     return NS_ERROR_FAILURE;
   }
+#elif defined(MOZ_WIDGET_GONK)
 #else
   rv = pluginLib->NP_Initialize(&sBrowserFuncs, &plugin->mPluginFuncs, &pluginCallError);
   if (rv != NS_OK || pluginCallError != NPERR_NO_ERROR) {
     return NS_ERROR_FAILURE;
   }
 #endif
 
   *aResult = plugin.forget().get();
@@ -2293,17 +2294,17 @@ NPError NP_CALLBACK
   }
 
   case NPNVsupportsUpdatedCocoaTextInputBool: {
     *(NPBool*)result = true;
     return NPERR_NO_ERROR;
   }
 #endif
 
-#ifdef ANDROID
+#ifdef MOZ_WIDGET_ANDROID
     case kLogInterfaceV0_ANPGetValue: {
       LOG("get log interface");
       ANPLogInterfaceV0 *i = (ANPLogInterfaceV0 *) result;
       InitLogInterface(i);
       return NPERR_NO_ERROR;
     }
 
     case kBitmapInterfaceV0_ANPGetValue: {
@@ -2510,17 +2511,17 @@ NPError NP_CALLBACK
         inst->SetEventModel((NPEventModel)NS_PTR_TO_INT32(result));
         return NPERR_NO_ERROR;
       }
       else {
         return NPERR_GENERIC_ERROR;
       }
     }
 #endif
-#ifdef ANDROID
+#ifdef MOZ_WIDGET_ANDROID
   case kRequestDrawingModel_ANPSetValue:
     if (inst)
       inst->SetDrawingModel(NS_PTR_TO_INT32(result));
     return NPERR_NO_ERROR;
   case kAcceptEvents_ANPSetValue:
     return NPERR_NO_ERROR;
 #endif
     default:
--- a/dom/plugins/base/nsNPAPIPluginInstance.cpp
+++ b/dom/plugins/base/nsNPAPIPluginInstance.cpp
@@ -56,28 +56,28 @@
 #include "nsIScriptContext.h"
 #include "nsDirectoryServiceDefs.h"
 #include "nsJSNPRuntime.h"
 #include "nsPluginStreamListenerPeer.h"
 #include "nsSize.h"
 #include "nsNetCID.h"
 #include "nsIContent.h"
 
-#ifdef ANDROID
+#ifdef MOZ_WIDGET_ANDROID
 #include "ANPBase.h"
 #include <android/log.h>
 #include "android_npapi.h"
 #include "mozilla/CondVar.h"
 #include "AndroidBridge.h"
 #endif
 
 using namespace mozilla;
 using namespace mozilla::plugins::parent;
 
-#ifdef ANDROID
+#ifdef MOZ_WIDGET_ANDROID
 #include <map>
 static std::map<void*, nsNPAPIPluginInstance*> sSurfaceMap;
 #endif
 
 static NS_DEFINE_IID(kIOutputStreamIID, NS_IOUTPUTSTREAM_IID);
 static NS_DEFINE_IID(kIPluginStreamListenerIID, NS_IPLUGINSTREAMLISTENER_IID);
 
 NS_IMPL_THREADSAFE_ISUPPORTS0(nsNPAPIPluginInstance)
@@ -86,17 +86,17 @@ nsNPAPIPluginInstance::nsNPAPIPluginInst
   :
 #ifdef XP_MACOSX
 #ifdef NP_NO_QUICKDRAW
     mDrawingModel(NPDrawingModelCoreGraphics),
 #else
     mDrawingModel(NPDrawingModelQuickDraw),
 #endif
 #endif
-#ifdef ANDROID
+#ifdef MOZ_WIDGET_ANDROID
     mSurface(nsnull),
     mTargetSurface(nsnull),
     mDrawingModel(0),
 #endif
     mRunning(NOT_STARTED),
     mWindowless(false),
     mWindowlessLocal(false),
     mTransparent(false),
@@ -122,33 +122,33 @@ nsNPAPIPluginInstance::nsNPAPIPluginInst
   nsCOMPtr<nsIPrefBranch> prefs(do_GetService(NS_PREFSERVICE_CONTRACTID));
   if (prefs) {
     bool useLayersPref;
     nsresult rv = prefs->GetBoolPref("plugins.use_layers", &useLayersPref);
     if (NS_SUCCEEDED(rv))
       mUsePluginLayersPref = useLayersPref;
   }
 
-#ifdef ANDROID
+#ifdef MOZ_WIDGET_ANDROID
   mTargetSurfaceLock = new Mutex("nsNPAPIPluginInstance::SurfaceLock");
 #endif
 
   PLUGIN_LOG(PLUGIN_LOG_BASIC, ("nsNPAPIPluginInstance ctor: this=%p\n",this));
 }
 
 nsNPAPIPluginInstance::~nsNPAPIPluginInstance()
 {
   PLUGIN_LOG(PLUGIN_LOG_BASIC, ("nsNPAPIPluginInstance dtor: this=%p\n",this));
 
   if (mMIMEType) {
     PR_Free((void *)mMIMEType);
     mMIMEType = nsnull;
   }
 
-#ifdef ANDROID
+#ifdef MOZ_WIDGET_ANDROID
   if (mSurface) {
     sSurfaceMap.erase(mSurface);
   }
 
   if (mTargetSurface) {
     delete mTargetSurface;
     mTargetSurface = nsnull;
   }
@@ -359,17 +359,17 @@ nsNPAPIPluginInstance::InitializePlugin(
     // with a null entry as a separator. This is for 4.x backwards compatibility!
     // see bug 111008 for details
     if (tagtype != nsPluginTagType_Embed) {
       PRUint16 pcount = 0;
       const char* const* pnames = nsnull;
       const char* const* pvalues = nsnull;    
       if (NS_SUCCEEDED(GetParameters(pcount, pnames, pvalues))) {
         // Android expects an empty string as the separator instead of null
-#ifdef ANDROID
+#ifdef MOZ_WIDGET_ANDROID
         NS_ASSERTION(PL_strcmp(values[count], "") == 0, "attribute/parameter array not setup correctly for Android NPAPI plugins");
 #else
         NS_ASSERTION(!values[count], "attribute/parameter array not setup correctly for NPAPI plugins");
 #endif
         if (pcount)
           count += ++pcount; // if it's all setup correctly, then all we need is to
                              // change the count (attrs + PARAM/blank + params)
       }
@@ -742,17 +742,17 @@ void nsNPAPIPluginInstance::SetEventMode
     NS_WARNING("Trying to set event model without a plugin instance owner!");
     return;
   }
 
   owner->SetEventModel(aModel);
 }
 #endif
 
-#if defined(ANDROID)
+#if defined(MOZ_WIDGET_ANDROID)
 void nsNPAPIPluginInstance::SetDrawingModel(PRUint32 aModel)
 {
   mDrawingModel = aModel;
 }
 
 class SurfaceGetter : public nsRunnable {
 public:
   SurfaceGetter(NPPluginFuncs* aPluginFunctions, NPP_t aNPP) : 
@@ -854,17 +854,17 @@ nsNPAPIPluginInstance::FindByJavaSurface
 {
   return sSurfaceMap[aJavaSurface];
 }
 
 #endif
 
 nsresult nsNPAPIPluginInstance::GetDrawingModel(PRInt32* aModel)
 {
-#if defined(XP_MACOSX) || defined(ANDROID)
+#if defined(XP_MACOSX) || defined(MOZ_WIDGET_ANDROID)
   *aModel = (PRInt32)mDrawingModel;
   return NS_OK;
 #else
   return NS_ERROR_FAILURE;
 #endif
 }
 
 nsresult nsNPAPIPluginInstance::IsRemoteDrawingCoreAnimation(bool* aDrawing)
@@ -953,17 +953,17 @@ nsNPAPIPluginInstance::DefineJavaPropert
     return NS_ERROR_FAILURE;
 
   return NS_OK;
 }
 
 nsresult
 nsNPAPIPluginInstance::IsWindowless(bool* isWindowless)
 {
-#ifdef ANDROID
+#ifdef MOZ_WIDGET_ANDROID
   // On android, pre-honeycomb, all plugins are treated as windowless.
   *isWindowless = true;
 #else
   *isWindowless = mWindowless;
 #endif
   return NS_OK;
 }
 
--- a/dom/plugins/base/nsNPAPIPluginInstance.h
+++ b/dom/plugins/base/nsNPAPIPluginInstance.h
@@ -88,17 +88,17 @@ public:
 
   nsresult Initialize(nsIPluginInstanceOwner* aOwner, const char* aMIMEType);
   nsresult Start();
   nsresult Stop();
   nsresult SetWindow(NPWindow* window);
   nsresult NewStreamToPlugin(nsIPluginStreamListener** listener);
   nsresult NewStreamFromPlugin(const char* type, const char* target, nsIOutputStream* *result);
   nsresult Print(NPPrint* platformPrint);
-#ifdef ANDROID
+#ifdef MOZ_WIDGET_ANDROID
   nsresult PostEvent(void* event) { return 0; };
 #endif
   nsresult HandleEvent(void* event, PRInt16* result);
   nsresult GetValueFromPlugin(NPPVariable variable, void* value);
   nsresult GetDrawingModel(PRInt32* aModel);
   nsresult IsRemoteDrawingCoreAnimation(bool* aDrawing);
   nsresult GetJSObject(JSContext *cx, JSObject** outObject);
   nsresult DefineJavaProperties();
@@ -147,17 +147,17 @@ public:
   NPError SetUsesDOMForCursor(bool aUsesDOMForCursor);
   bool UsesDOMForCursor();
 
 #ifdef XP_MACOSX
   void SetDrawingModel(NPDrawingModel aModel);
   void SetEventModel(NPEventModel aModel);
 #endif
 
-#ifdef ANDROID
+#ifdef MOZ_WIDGET_ANDROID
   void SetDrawingModel(PRUint32 aModel);
   void* GetJavaSurface();
 
   gfxImageSurface* LockTargetSurface();
   gfxImageSurface* LockTargetSurface(PRUint32 aWidth, PRUint32 aHeight, gfxASurface::gfxImageFormat aFormat,
                                      NPRect* aRect);
   void UnlockTargetSurface(bool aInvalidate);
 
@@ -225,17 +225,17 @@ protected:
   // The structure used to communicate between the plugin instance and
   // the browser.
   NPP_t mNPP;
 
 #ifdef XP_MACOSX
   NPDrawingModel mDrawingModel;
 #endif
 
-#ifdef ANDROID
+#ifdef MOZ_WIDGET_ANDROID
   PRUint32 mDrawingModel;
 #endif
 
   enum {
     NOT_STARTED,
     RUNNING,
     DESTROYING,
     DESTROYED
@@ -272,17 +272,17 @@ private:
   nsTArray<nsNPAPITimer*> mTimers;
 
   // non-null during a HandleEvent call
   void* mCurrentPluginEvent;
 
   nsCOMPtr<nsIURI> mURI;
 
   bool mUsePluginLayersPref;
-#ifdef ANDROID
+#ifdef MOZ_WIDGET_ANDROID
   void InvalidateTargetRect();
   
   void* mSurface;
   gfxImageSurface *mTargetSurface;
   mozilla::Mutex* mTargetSurfaceLock;
   NPRect mTargetLockRect;
 #endif
 };
--- a/dom/plugins/base/nsPluginInstanceOwner.cpp
+++ b/dom/plugins/base/nsPluginInstanceOwner.cpp
@@ -113,17 +113,17 @@ static NS_DEFINE_CID(kAppShellCID, NS_AP
 
 #ifdef MOZ_WIDGET_GTK2
 #include <gdk/gdk.h>
 #include <gdk/gdkx.h>
 #include <gtk/gtk.h>
 #include "gfxXlibNativeRenderer.h"
 #endif
 
-#ifdef ANDROID
+#ifdef MOZ_WIDGET_ANDROID
 #include "ANPBase.h"
 #include "android_npapi.h"
 #include "AndroidBridge.h"
 using namespace mozilla::dom;
 
 #include <android/log.h>
 #define LOG(args...)  __android_log_print(ANDROID_LOG_INFO, "GeckoPlugins" , ## args)
 #endif
@@ -1275,17 +1275,17 @@ nsresult nsPluginInstanceOwner::EnsureCa
   if (!data.IsEmpty()) {
     mCachedAttrParamNames [nextAttrParamIndex] = ToNewUTF8String(NS_LITERAL_STRING("SRC"));
     mCachedAttrParamValues[nextAttrParamIndex] = ToNewUTF8String(data);
     nextAttrParamIndex++;
   }
 
   // Add PARAM and null separator.
   mCachedAttrParamNames [nextAttrParamIndex] = ToNewUTF8String(NS_LITERAL_STRING("PARAM"));
-#ifdef ANDROID
+#ifdef MOZ_WIDGET_ANDROID
   // Flash expects an empty string on android
   mCachedAttrParamValues[nextAttrParamIndex] = ToNewUTF8String(NS_LITERAL_STRING(""));
 #else
   mCachedAttrParamValues[nextAttrParamIndex] = nsnull;
 #endif
   nextAttrParamIndex++;
 
   // Add PARAM name/value pairs.
@@ -1667,17 +1667,17 @@ void nsPluginInstanceOwner::ScrollPositi
         mInstance->HandleEvent(&scrollEvent, nsnull);
       }
       pluginWidget->EndDrawPlugin();
     }
   }
 #endif
 }
 
-#ifdef ANDROID
+#ifdef MOZ_WIDGET_ANDROID
 void nsPluginInstanceOwner::AddPluginView(const gfxRect& aRect)
 {
   void* javaSurface = mInstance->GetJavaSurface();
 
   if (!javaSurface)
     return;
 
   JNIEnv* env = GetJNIForThread();
@@ -1709,17 +1709,17 @@ void nsPluginInstanceOwner::RemovePlugin
       }
     }
   }
 }
 #endif
 
 nsresult nsPluginInstanceOwner::DispatchFocusToPlugin(nsIDOMEvent* aFocusEvent)
 {
-#ifdef ANDROID
+#ifdef MOZ_WIDGET_ANDROID
   {
     ANPEvent event;
     event.inSize = sizeof(ANPEvent);
     event.eventType = kLifecycle_ANPEventType;
 
     nsAutoString eventType;
     aFocusEvent->GetType(eventType);
     if (eventType.EqualsLiteral("focus")) {
@@ -2522,17 +2522,17 @@ nsEventStatus nsPluginInstanceOwner::Pro
   event.send_event = False;
 
   PRInt16 response = kNPEventNotHandled;
   mInstance->HandleEvent(&pluginEvent, &response);
   if (response == kNPEventHandled)
     rv = nsEventStatus_eConsumeNoDefault;
 #endif
 
-#ifdef ANDROID
+#ifdef MOZ_WIDGET_ANDROID
   // this code supports windowless plugins
   {
     // The plugin needs focus to receive keyboard and touch events
     nsIFocusManager* fm = nsFocusManager::GetFocusManager();
     if (fm) {
       nsCOMPtr<nsIDOMElement> elem = do_QueryInterface(mContent);
       fm->SetFocus(elem, 0);
     }
@@ -2728,17 +2728,17 @@ nsPluginInstanceOwner::PrepareToStop(boo
     // and plugin et al not holding any other references to its
     // parent.
     mWidget->SetParent(nsnull);
 
     mDestroyWidget = true;
   }
 #endif
 
-#ifdef ANDROID
+#ifdef MOZ_WIDGET_ANDROID
   RemovePluginView();
 #endif
 
   // Unregister scroll position listeners
   for (nsIFrame* f = mObjectFrame; f; f = nsLayoutUtils::GetCrossDocParentFrame(f)) {
     nsIScrollableFrame* sf = do_QueryFrame(f);
     if (sf) {
       sf->RemoveScrollPositionListener(this);
@@ -2828,17 +2828,17 @@ void nsPluginInstanceOwner::Paint(const 
   NPEvent pluginEvent;
   pluginEvent.event = WM_PAINT;
   pluginEvent.wParam = (uint32)aHPS;
   pluginEvent.lParam = (uint32)&rectl;
   mInstance->HandleEvent(&pluginEvent, nsnull);
 }
 #endif
 
-#ifdef ANDROID
+#ifdef MOZ_WIDGET_ANDROID
 
 void nsPluginInstanceOwner::Paint(gfxContext* aContext,
                                   const gfxRect& aFrameRect,
                                   const gfxRect& aDirtyRect)
 {
   if (!mInstance || !mObjectFrame)
     return;
 
@@ -3551,29 +3551,29 @@ void nsPluginInstanceOwner::UpdateWindow
   mPluginWindow->y = origin.y;
 
   mPluginWindow->clipRect.left = 0;
   mPluginWindow->clipRect.top = 0;
 
   if (mPluginWindowVisible && mPluginDocumentActiveState) {
     mPluginWindow->clipRect.right = mPluginWindow->width;
     mPluginWindow->clipRect.bottom = mPluginWindow->height;
-#ifdef ANDROID
+#ifdef MOZ_WIDGET_ANDROID
     if (mInstance) {
       ANPEvent event;
       event.inSize = sizeof(ANPEvent);
       event.eventType = kLifecycle_ANPEventType;
       event.data.lifecycle.action = kOnScreen_ANPLifecycleAction;
       mInstance->HandleEvent(&event, nsnull);
     }
 #endif
   } else {
     mPluginWindow->clipRect.right = 0;
     mPluginWindow->clipRect.bottom = 0;
-#ifdef ANDROID
+#ifdef MOZ_WIDGET_ANDROID
     if (mInstance) {
       ANPEvent event;
       event.inSize = sizeof(ANPEvent);
       event.eventType = kLifecycle_ANPEventType;
       event.data.lifecycle.action = kOffScreen_ANPLifecycleAction;
       mInstance->HandleEvent(&event, nsnull);
     }
     RemovePluginView();
--- a/dom/plugins/ipc/PluginLibrary.h
+++ b/dom/plugins/ipc/PluginLibrary.h
@@ -73,17 +73,17 @@ public:
   /**
    * Inform this library about the nsNPAPIPlugin which owns it. This
    * object will hold a weak pointer to the plugin.
    */
   virtual void SetPlugin(nsNPAPIPlugin* plugin) = 0;
 
   virtual bool HasRequiredFunctions() = 0;
 
-#if defined(XP_UNIX) && !defined(XP_MACOSX)
+#if defined(XP_UNIX) && !defined(XP_MACOSX) && !defined(MOZ_WIDGET_GONK)
   virtual nsresult NP_Initialize(NPNetscapeFuncs* bFuncs, NPPluginFuncs* pFuncs, NPError* error) = 0;
 #else
   virtual nsresult NP_Initialize(NPNetscapeFuncs* bFuncs, NPError* error) = 0;
 #endif
   virtual nsresult NP_Shutdown(NPError* error) = 0;
   virtual nsresult NP_GetMIMEDescription(const char** mimeDesc) = 0;
   virtual nsresult NP_GetValue(void *future, NPPVariable aVariable,
                                void *aValue, NPError* error) = 0;
--- a/dom/plugins/ipc/PluginModuleParent.cpp
+++ b/dom/plugins/ipc/PluginModuleParent.cpp
@@ -730,17 +730,17 @@ PluginModuleParent::EndUpdateBackground(
 {
     PluginInstanceParent* i = InstCast(instance);
     if (!i)
         return NS_ERROR_FAILURE;
 
     return i->EndUpdateBackground(aCtx, aRect);
 }
 
-#if defined(XP_UNIX) && !defined(XP_MACOSX)
+#if defined(XP_UNIX) && !defined(XP_MACOSX) && !defined(MOZ_WIDGET_GONK)
 nsresult
 PluginModuleParent::NP_Initialize(NPNetscapeFuncs* bFuncs, NPPluginFuncs* pFuncs, NPError* error)
 {
     PLUGIN_LOG_DEBUG_METHOD;
 
     mNPNIface = bFuncs;
 
     if (mShutdown) {
--- a/dom/plugins/ipc/PluginModuleParent.h
+++ b/dom/plugins/ipc/PluginModuleParent.h
@@ -271,17 +271,17 @@ private:
     virtual nsresult BeginUpdateBackground(NPP instance,
                                            const nsIntRect& aRect,
                                            gfxContext** aCtx);
     NS_OVERRIDE
     virtual nsresult EndUpdateBackground(NPP instance,
                                          gfxContext* aCtx,
                                          const nsIntRect& aRect);
 
-#if defined(XP_UNIX) && !defined(XP_MACOSX)
+#if defined(XP_UNIX) && !defined(XP_MACOSX) && !defined(MOZ_WIDGET_GONK)
     virtual nsresult NP_Initialize(NPNetscapeFuncs* bFuncs, NPPluginFuncs* pFuncs, NPError* error);
 #else
     virtual nsresult NP_Initialize(NPNetscapeFuncs* bFuncs, NPError* error);
 #endif
     virtual nsresult NP_Shutdown(NPError* error);
     virtual nsresult NP_GetMIMEDescription(const char** mimeDesc);
     virtual nsresult NP_GetValue(void *future, NPPVariable aVariable,
                                  void *aValue, NPError* error);
--- a/dom/src/geolocation/nsGeolocation.cpp
+++ b/dom/src/geolocation/nsGeolocation.cpp
@@ -79,17 +79,17 @@
 #ifdef MOZ_MAEMO_LIBLOCATION
 #include "MaemoLocationProvider.h"
 #endif
 
 #ifdef MOZ_ENABLE_QTMOBILITY
 #include "QTMLocationProvider.h"
 #endif
 
-#ifdef ANDROID
+#ifdef MOZ_WIDGET_ANDROID
 #include "AndroidLocationProvider.h"
 #endif
 
 #include "nsIDOMDocument.h"
 #include "nsIDocument.h"
 
 // Some limit to the number of get or watch geolocation requests
 // that a window can make.
@@ -590,17 +590,17 @@ nsresult nsGeolocationService::Init()
 #endif
 
 #ifdef MOZ_ENABLE_QTMOBILITY
   provider = new QTMLocationProvider();
   if (provider)
     mProviders.AppendObject(provider);
 #endif
 
-#ifdef ANDROID
+#ifdef MOZ_WIDGET_ANDROID
   provider = new AndroidLocationProvider();
   if (provider)
     mProviders.AppendObject(provider);
 #endif
   return NS_OK;
 }
 
 nsGeolocationService::~nsGeolocationService()
--- a/dom/tests/mochitest/general/Makefile.in
+++ b/dom/tests/mochitest/general/Makefile.in
@@ -40,16 +40,18 @@ topsrcdir	= @top_srcdir@
 srcdir		= @srcdir@
 VPATH		= @srcdir@
 relativesrcdir  = dom/tests/mochitest/general
 
 include $(DEPTH)/config/autoconf.mk
 include $(topsrcdir)/config/rules.mk
 
 _TEST_FILES = \
+		test_outerHTML.html \
+		test_outerHTML.xhtml \
 		497633.html \
 		489127.html \
 		historyframes.html \
 		test_497898.html \
 		test_bug504220.html \
 		test_bug628069_1.html \
 		test_bug628069_2.html \
 		file_bug628069.html \
new file mode 100644
--- /dev/null
+++ b/dom/tests/mochitest/general/test_outerHTML.html
@@ -0,0 +1,73 @@
+<!DOCTYPE HTML>
+<html>
+<!--
+https://bugzilla.mozilla.org/show_bug.cgi?id=92264
+-->
+<head>
+  <title>Test for Bug 92264</title>
+  <script type="application/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
+  <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css"/>
+</head>
+<body onload="runTest();">
+<a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=92264">Mozilla Bug 92264</a>
+<p id="display"></p>
+<div id="content" style="display: none">
+<div id="wrap"><dl></dl><p id="thep">foo<span>bar</span></p><ol></ol></div>
+<table id="thetable"><tbody><tr><td>1</td></tr><tr id="thetr"><td>2</td></tr><tr><td>3</td></tr></tbody></table>
+<iframe></iframe>
+<div id="fragmentwrap"></div>
+</div>
+<pre id="test">
+<script type="application/javascript">
+
+/** Test for Bug 92264 **/
+
+SimpleTest.waitForExplicitFinish();
+
+function runTest() {
+
+  var thep = document.getElementById("thep");
+  var wrap = document.getElementById("wrap");
+  is(thep.outerHTML, '<p id="thep">foo<span>bar</span></p>', "Unexpected thep outerHTML");
+  thep.outerHTML = "<ul></ul><tr></tr><p></p>";
+  is(wrap.innerHTML, "<dl></dl><ul></ul><p></p><ol></ol>", "Bad outerHTML parsing inside wrap");
+
+  var thetr = document.getElementById("thetr");
+  thetr.outerHTML = "<tr><td>a</td></tr><div></div><tr><td>b</td></tr>";
+  var thetable = document.getElementById("thetable");
+  is(thetable.innerHTML, "<tbody><tr><td>1</td></tr><tr><td>a</td></tr><div></div><tr><td>b</td></tr><tr><td>3</td></tr></tbody>", "Wrong outerHTML parsing inside table");
+
+  var iframe = document.getElementsByTagName("iframe")[0];
+  var oldbody = iframe.contentDocument.body;
+  iframe.contentDocument.body.outerHTML = "<body></body>";
+  isnot(oldbody, iframe.contentDocument.body, "Failed to replace body");
+  is(iframe.contentDocument.getElementsByTagName("body").length, 1, "Should have gotten one body");
+  // Yes, two heads per spec. Also Ragnarök and Chrome produce two heads.
+  is(iframe.contentDocument.getElementsByTagName("head").length, 2, "Should have gotten two heads");
+
+  try {
+    document.documentElement.outerHTML = "<html></html>";
+    ok(false, "Should have thrown an exception");
+  } catch(e) {
+    is(e.code, 7, "outerHTML should throw NO_MODIFICATION_ALLOWED_ERR");
+  }
+
+  var f = document.createDocumentFragment();
+  var dl = document.createElement("dl");
+  var p = document.createElement("p");
+  var ol = document.createElement("ol");
+  f.appendChild(dl);
+  f.appendChild(p);
+  f.appendChild(ol);
+  p.outerHTML = "<ul></ul><tr></tr><body></body><p></p>";
+  var fragmentwrap = document.getElementById("fragmentwrap");
+  fragmentwrap.appendChild(f);
+  is(fragmentwrap.innerHTML, "<dl></dl><ul></ul><p></p><ol></ol>", "Bad outerHTML parsing in fragment");
+
+  SimpleTest.finish();
+}
+
+</script>
+</pre>
+</body>
+</html>
new file mode 100644
--- /dev/null
+++ b/dom/tests/mochitest/general/test_outerHTML.xhtml
@@ -0,0 +1,74 @@
+<!DOCTYPE HTML>
+<html xmlns="http://www.w3.org/1999/xhtml">
+<!--
+https://bugzilla.mozilla.org/show_bug.cgi?id=92264
+-->
+<head>
+  <title>Test for Bug 92264</title>
+  <script type="application/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
+  <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css"/>
+</head>
+<body onload="runTest();">
+<a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=92264">Mozilla Bug 92264</a>
+<p id="display"></p>
+<div id="content" style="display: none">
+<div id="wrap"><dl></dl><p id="thep">foo<span>bar</span></p><ol></ol></div>
+<table id="thetable"><tbody><tr><td>1</td></tr><tr id="thetr"><td>2</td></tr><tr><td>3</td></tr></tbody></table>
+<iframe></iframe>
+<div id="fragmentwrap"></div>
+</div>
+<pre id="test">
+<script type="application/javascript">
+<![CDATA[
+
+/** Test for Bug 92264 **/
+
+SimpleTest.waitForExplicitFinish();
+
+function runTest() {
+
+  var thep = document.getElementById("thep");
+  var wrap = document.getElementById("wrap");
+  is(thep.outerHTML, '<p xmlns="http://www.w3.org/1999/xhtml" id="thep">foo<span>bar</span></p>', "Unexpected thep outerHTML");
+  thep.outerHTML = "<ul></ul><tr></tr><p></p>";
+  is(wrap.innerHTML, '<dl xmlns="http://www.w3.org/1999/xhtml"></dl><ul xmlns="http://www.w3.org/1999/xhtml"></ul><tr xmlns="http://www.w3.org/1999/xhtml"></tr><p xmlns="http://www.w3.org/1999/xhtml"></p><ol xmlns="http://www.w3.org/1999/xhtml"></ol>', "Bad outerHTML parsing inside wrap");
+
+  var thetr = document.getElementById("thetr");
+  thetr.outerHTML = "<tr><td>a</td></tr><div></div><tr><td>b</td></tr>";
+  var thetable = document.getElementById("thetable");
+  is(thetable.innerHTML, '<tbody xmlns="http://www.w3.org/1999/xhtml"><tr><td>1</td></tr><tr><td>a</td></tr><div></div><tr><td>b</td></tr><tr><td>3</td></tr></tbody>', "Wrong outerHTML parsing inside table");
+
+  var iframe = document.getElementsByTagName("iframe")[0];
+  var oldbody = iframe.contentDocument.body;
+  iframe.contentDocument.body.outerHTML = "<body></body>";
+  isnot(oldbody, iframe.contentDocument.body, "Failed to replace body");
+  is(iframe.contentDocument.getElementsByTagName("body").length, 1, "Should have gotten one body");
+  // Yes, two heads per spec. Also Ragnarök and Chrome produce two heads.
+  is(iframe.contentDocument.getElementsByTagName("head").length, 2, "Should have gotten two heads");
+
+  try {
+    document.documentElement.outerHTML = "<html></html>";
+    ok(false, "Should have thrown an exception");
+  } catch(e) {
+    is(e.code, 7, "outerHTML should throw NO_MODIFICATION_ALLOWED_ERR");
+  }
+
+  var f = document.createDocumentFragment();
+  var dl = document.createElement("dl");
+  var p = document.createElement("p");
+  var ol = document.createElement("ol");
+  f.appendChild(dl);
+  f.appendChild(p);
+  f.appendChild(ol);
+  p.outerHTML = "<ul></ul><tr></tr><body></body><p></p>";
+  var fragmentwrap = document.getElementById("fragmentwrap");
+  fragmentwrap.appendChild(f);
+  is(fragmentwrap.innerHTML, '<dl xmlns="http://www.w3.org/1999/xhtml"></dl><ul xmlns="http://www.w3.org/1999/xhtml"></ul><tr xmlns="http://www.w3.org/1999/xhtml"></tr><body xmlns="http://www.w3.org/1999/xhtml"></body><p xmlns="http://www.w3.org/1999/xhtml"></p><ol xmlns="http://www.w3.org/1999/xhtml"></ol>', "Bad outerHTML parsing in fragment");
+
+  SimpleTest.finish();
+}
+]]>
+</script>
+</pre>
+</body>
+</html>
--- a/dom/workers/WorkerScope.cpp
+++ b/dom/workers/WorkerScope.cpp
@@ -827,16 +827,21 @@ CreateDedicatedWorkerGlobalScope(JSConte
 
   JSObject* global =
     JS_NewCompartmentAndGlobalObject(aCx, DedicatedWorkerGlobalScope::Class(),
                                      GetWorkerPrincipal());
   if (!global) {
     return NULL;
   }
 
+  JSAutoEnterCompartment ac;
+  if (!ac.enter(aCx, global)) {
+    return NULL;
+  }
+
   // Make the private slots now so that all our instance checks succeed.
   if (!DedicatedWorkerGlobalScope::InitPrivate(aCx, global, worker)) {
     return NULL;
   }
 
   // Proto chain should be:
   //   global -> DedicatedWorkerGlobalScope
   //          -> WorkerGlobalScope
--- a/editor/composer/src/nsEditingSession.cpp
+++ b/editor/composer/src/nsEditingSession.cpp
@@ -832,17 +832,18 @@ nsEditingSession::OnProgressChange(nsIWe
 
 /*---------------------------------------------------------------------------
 
   OnLocationChange
 
 ----------------------------------------------------------------------------*/
 NS_IMETHODIMP
 nsEditingSession::OnLocationChange(nsIWebProgress *aWebProgress, 
-                                   nsIRequest *aRequest, nsIURI *aURI)
+                                   nsIRequest *aRequest, nsIURI *aURI,
+                                   PRUint32 aFlags)
 {
   nsCOMPtr<nsIDOMWindow> domWindow;
   nsresult rv = aWebProgress->GetDOMWindow(getter_AddRefs(domWindow));
   NS_ENSURE_SUCCESS(rv, rv);
 
   nsCOMPtr<nsIDOMDocument> domDoc;
   rv = domWindow->GetDocument(getter_AddRefs(domDoc));
   NS_ENSURE_SUCCESS(rv, rv);
--- a/editor/composer/test/test_bug434998.xul
+++ b/editor/composer/test/test_bug434998.xul
@@ -73,17 +73,17 @@ https://bugzilla.mozilla.org/show_bug.cg
 
 
     onProgressChange : function(aWebProgress, aRequest,
                                 aCurSelfProgress, aMaxSelfProgress,
                                 aCurTotalProgress, aMaxTotalProgress)
     {
     },
 
-    onLocationChange : function(aWebProgress, aRequest, aLocation)
+    onLocationChange : function(aWebProgress, aRequest, aLocation, aFlags)
     {
     },
 
     onStatusChange : function(aWebProgress, aRequest, aStatus, aMessage)
     {
     },
 
     onSecurityChange : function(aWebProgress, aRequest, aState)
--- a/editor/libeditor/html/tests/test_bug607584.xul
+++ b/editor/libeditor/html/tests/test_bug607584.xul
@@ -78,17 +78,17 @@ https://bugzilla.mozilla.org/show_bug.cg
   
   
     onProgressChange : function(aWebProgress, aRequest,
                                 aCurSelfProgress, aMaxSelfProgress,
                                 aCurTotalProgress, aMaxTotalProgress)
       {
       },
   
-    onLocationChange : function(aWebProgress, aRequest, aLocation)
+    onLocationChange : function(aWebProgress, aRequest, aLocation, aFlags)
       {
       },
   
     onStatusChange : function(aWebProgress, aRequest, aStatus, aMessage)
       {
       },
   
     onSecurityChange : function(aWebProgress, aRequest, aState)
--- a/editor/libeditor/html/tests/test_bug616590.xul
+++ b/editor/libeditor/html/tests/test_bug616590.xul
@@ -68,17 +68,17 @@ https://bugzilla.mozilla.org/show_bug.cg
 
 
     onProgressChange : function(aWebProgress, aRequest,
                                 aCurSelfProgress, aMaxSelfProgress,
                                 aCurTotalProgress, aMaxTotalProgress)
     {
     },
 
-    onLocationChange : function(aWebProgress, aRequest, aLocation)
+    onLocationChange : function(aWebProgress, aRequest, aLocation, aFlags)
     {
     },
 
     onStatusChange : function(aWebProgress, aRequest, aStatus, aMessage)
     {
     },
 
     onSecurityChange : function(aWebProgress, aRequest, aState)
--- a/embedding/Makefile.in
+++ b/embedding/Makefile.in
@@ -48,13 +48,13 @@ MODULE       = embed
 
 DIRS = base components browser
 
 ifdef ENABLE_TESTS
 XPCSHELL_TESTS = tests/unit
 DIRS += test
 endif
 
-ifeq ($(OS_TARGET),Android)
+ifeq ($(MOZ_WIDGET_TOOLKIT),android)
 DIRS += android
 endif
 
 include $(topsrcdir)/config/rules.mk
--- a/embedding/browser/webBrowser/nsDocShellTreeOwner.cpp
+++ b/embedding/browser/webBrowser/nsDocShellTreeOwner.cpp
@@ -718,17 +718,18 @@ nsDocShellTreeOwner::OnStateChange(nsIWe
                                    nsresult aStatus)
 {
     return NS_OK;
 }
 
 NS_IMETHODIMP
 nsDocShellTreeOwner::OnLocationChange(nsIWebProgress* aWebProgress,
                                       nsIRequest* aRequest,
-                                      nsIURI* aURI)
+                                      nsIURI* aURI,
+                                      PRUint32 aFlags)
 {
     return NS_OK;
 }
 
 NS_IMETHODIMP 
 nsDocShellTreeOwner::OnStatusChange(nsIWebProgress* aWebProgress,
                                     nsIRequest* aRequest,
                                     nsresult aStatus,
--- a/embedding/browser/webBrowser/nsWebBrowser.cpp
+++ b/embedding/browser/webBrowser/nsWebBrowser.cpp
@@ -847,22 +847,22 @@ NS_IMETHODIMP nsWebBrowser::OnProgressCh
     }
     if (mProgressListener)
     {
         return mProgressListener->OnProgressChange(aWebProgress, aRequest, aCurSelfProgress, aMaxSelfProgress, aCurTotalProgress, aMaxTotalProgress);
     }
     return NS_OK;
 }
 
-/* void onLocationChange (in nsIWebProgress aWebProgress, in nsIRequest aRequest, in nsIURI location); */
-NS_IMETHODIMP nsWebBrowser::OnLocationChange(nsIWebProgress *aWebProgress, nsIRequest *aRequest, nsIURI *location)
+/* void onLocationChange (in nsIWebProgress aWebProgress, in nsIRequest aRequest, in nsIURI location, in unsigned long aFlags); */
+NS_IMETHODIMP nsWebBrowser::OnLocationChange(nsIWebProgress *aWebProgress, nsIRequest *aRequest, nsIURI *location, PRUint32 aFlags)
 {
     if (mProgressListener)
     {
-        return mProgressListener->OnLocationChange(aWebProgress, aRequest, location);
+        return mProgressListener->OnLocationChange(aWebProgress, aRequest, location, aFlags);
     }
     return NS_OK;
 }
 
 /* void onStatusChange (in nsIWebProgress aWebProgress, in nsIRequest aRequest, in nsresult aStatus, in wstring aMessage); */
 NS_IMETHODIMP nsWebBrowser::OnStatusChange(nsIWebProgress *aWebProgress, nsIRequest *aRequest, nsresult aStatus, const PRUnichar *aMessage)
 {
     if (mProgressListener)
--- a/embedding/components/printingui/src/mac/nsPrintProgress.cpp
+++ b/embedding/components/printingui/src/mac/nsPrintProgress.cpp
@@ -252,18 +252,18 @@ NS_IMETHODIMP nsPrintProgress::OnProgres
       if (aProgressListener)
         aProgressListener->OnProgressChange(aWebProgress, aRequest, aCurSelfProgress, aMaxSelfProgress, aCurTotalProgress, aMaxTotalProgress);
     }
   }
   
   return rv;
 }
 
-/* void onLocationChange (in nsIWebProgress aWebProgress, in nsIRequest aRequest, in nsIURI location); */
-NS_IMETHODIMP nsPrintProgress::OnLocationChange(nsIWebProgress *aWebProgress, nsIRequest *aRequest, nsIURI *location)
+/* void onLocationChange (in nsIWebProgress aWebProgress, in nsIRequest aRequest, in nsIURI location, in unsigned long aFlags); */
+NS_IMETHODIMP nsPrintProgress::OnLocationChange(nsIWebProgress *aWebProgress, nsIRequest *aRequest, nsIURI *location, PRUint32 aFlags)
 {
     return NS_OK;
 }
 
 /* void onStatusChange (in nsIWebProgress aWebProgress, in nsIRequest aRequest, in nsresult aStatus, in wstring aMessage); */
 NS_IMETHODIMP nsPrintProgress::OnStatusChange(nsIWebProgress *aWebProgress, nsIRequest *aRequest, nsresult aStatus, const PRUnichar *aMessage)
 {
   nsresult rv = NS_OK;
--- a/embedding/components/printingui/src/mac/nsPrintingPromptServiceX.mm
+++ b/embedding/components/printingui/src/mac/nsPrintingPromptServiceX.mm
@@ -131,19 +131,19 @@ nsPrintingPromptService::OnStateChange(n
 
 /* void onProgressChange (in nsIWebProgress aWebProgress, in nsIRequest aRequest, in long aCurSelfProgress, in long aMaxSelfProgress, in long aCurTotalProgress, in long aMaxTotalProgress); */
 NS_IMETHODIMP 
 nsPrintingPromptService::OnProgressChange(nsIWebProgress *aWebProgress, nsIRequest *aRequest, PRInt32 aCurSelfProgress, PRInt32 aMaxSelfProgress, PRInt32 aCurTotalProgress, PRInt32 aMaxTotalProgress)
 {
     return NS_OK;
 }
 
-/* void onLocationChange (in nsIWebProgress aWebProgress, in nsIRequest aRequest, in nsIURI location); */
+/* void onLocationChange (in nsIWebProgress aWebProgress, in nsIRequest aRequest, in nsIURI location, in unsigned long aFlags); */
 NS_IMETHODIMP 
-nsPrintingPromptService::OnLocationChange(nsIWebProgress *aWebProgress, nsIRequest *aRequest, nsIURI *location)
+nsPrintingPromptService::OnLocationChange(nsIWebProgress *aWebProgress, nsIRequest *aRequest, nsIURI *location, PRUint32 aFlags)
 {
     return NS_OK;
 }
 
 /* void onStatusChange (in nsIWebProgress aWebProgress, in nsIRequest aRequest, in nsresult aStatus, in wstring aMessage); */
 NS_IMETHODIMP 
 nsPrintingPromptService::OnStatusChange(nsIWebProgress *aWebProgress, nsIRequest *aRequest, nsresult aStatus, const PRUnichar *aMessage)
 {
--- a/embedding/components/printingui/src/os2/nsPrintProgress.cpp
+++ b/embedding/components/printingui/src/os2/nsPrintProgress.cpp
@@ -249,18 +249,18 @@ NS_IMETHODIMP nsPrintProgress::OnProgres
       if (aProgressListener)
         aProgressListener->OnProgressChange(aWebProgress, aRequest, aCurSelfProgress, aMaxSelfProgress, aCurTotalProgress, aMaxTotalProgress);
     }
   }
   
   return rv;
 }
 
-/* void onLocationChange (in nsIWebProgress aWebProgress, in nsIRequest aRequest, in nsIURI location); */
-NS_IMETHODIMP nsPrintProgress::OnLocationChange(nsIWebProgress *aWebProgress, nsIRequest *aRequest, nsIURI *location)
+/* void onLocationChange (in nsIWebProgress aWebProgress, in nsIRequest aRequest, in nsIURI location, in unsigned long aFlags); */
+NS_IMETHODIMP nsPrintProgress::OnLocationChange(nsIWebProgress *aWebProgress, nsIRequest *aRequest, nsIURI *location, PRUint32 aFlags)
 {
     return NS_OK;
 }
 
 /* void onStatusChange (in nsIWebProgress aWebProgress, in nsIRequest aRequest, in nsresult aStatus, in wstring aMessage); */
 NS_IMETHODIMP nsPrintProgress::OnStatusChange(nsIWebProgress *aWebProgress, nsIRequest *aRequest, nsresult aStatus, const PRUnichar *aMessage)
 {
   nsresult rv = NS_OK;
--- a/embedding/components/printingui/src/os2/nsPrintingPromptService.cpp
+++ b/embedding/components/printingui/src/os2/nsPrintingPromptService.cpp
@@ -284,22 +284,22 @@ NS_IMETHODIMP
 nsPrintingPromptService::OnProgressChange(nsIWebProgress *aWebProgress, nsIRequest *aRequest, PRInt32 aCurSelfProgress, PRInt32 aMaxSelfProgress, PRInt32 aCurTotalProgress, PRInt32 aMaxTotalProgress)
 {
   if (mWebProgressListener) {
     return mWebProgressListener->OnProgressChange(aWebProgress, aRequest, aCurSelfProgress, aMaxSelfProgress, aCurTotalProgress, aMaxTotalProgress);
   }
   return NS_OK;
 }
 
-/* void onLocationChange (in nsIWebProgress aWebProgress, in nsIRequest aRequest, in nsIURI location); */
+/* void onLocationChange (in nsIWebProgress aWebProgress, in nsIRequest aRequest, in nsIURI location, in unsigned long aFlags); */
 NS_IMETHODIMP 
-nsPrintingPromptService::OnLocationChange(nsIWebProgress *aWebProgress, nsIRequest *aRequest, nsIURI *location)
+nsPrintingPromptService::OnLocationChange(nsIWebProgress *aWebProgress, nsIRequest *aRequest, nsIURI *location, PRUint32 aFlags)
 {
   if (mWebProgressListener) {
-    return mWebProgressListener->OnLocationChange(aWebProgress, aRequest, location);
+    return mWebProgressListener->OnLocationChange(aWebProgress, aRequest, location, aFlags);
   }
   return NS_OK;
 }
 
 /* void onStatusChange (in nsIWebProgress aWebProgress, in nsIRequest aRequest, in nsresult aStatus, in wstring aMessage); */
 NS_IMETHODIMP 
 nsPrintingPromptService::OnStatusChange(nsIWebProgress *aWebProgress, nsIRequest *aRequest, nsresult aStatus, const PRUnichar *aMessage)
 {
--- a/embedding/components/printingui/src/unixshared/nsPrintProgress.cpp
+++ b/embedding/components/printingui/src/unixshared/nsPrintProgress.cpp
@@ -252,18 +252,18 @@ NS_IMETHODIMP nsPrintProgress::OnProgres
       if (aProgressListener)
         aProgressListener->OnProgressChange(aWebProgress, aRequest, aCurSelfProgress, aMaxSelfProgress, aCurTotalProgress, aMaxTotalProgress);
     }
   }
   
   return rv;
 }
 
-/* void onLocationChange (in nsIWebProgress aWebProgress, in nsIRequest aRequest, in nsIURI location); */
-NS_IMETHODIMP nsPrintProgress::OnLocationChange(nsIWebProgress *aWebProgress, nsIRequest *aRequest, nsIURI *location)
+/* void onLocationChange (in nsIWebProgress aWebProgress, in nsIRequest aRequest, in nsIURI location, in unsigned long aFlags); */
+NS_IMETHODIMP nsPrintProgress::OnLocationChange(nsIWebProgress *aWebProgress, nsIRequest *aRequest, nsIURI *location, PRUint32 aFlags)
 {
     return NS_ERROR_NOT_IMPLEMENTED;
 }
 
 /* void onStatusChange (in nsIWebProgress aWebProgress, in nsIRequest aRequest, in nsresult aStatus, in wstring aMessage); */
 NS_IMETHODIMP nsPrintProgress::OnStatusChange(nsIWebProgress *aWebProgress, nsIRequest *aRequest, nsresult aStatus, const PRUnichar *aMessage)
 {
   nsresult rv = NS_OK;
--- a/embedding/components/printingui/src/unixshared/nsPrintingPromptService.cpp
+++ b/embedding/components/printingui/src/unixshared/nsPrintingPromptService.cpp
@@ -303,22 +303,22 @@ NS_IMETHODIMP
 nsPrintingPromptService::OnProgressChange(nsIWebProgress *aWebProgress, nsIRequest *aRequest, PRInt32 aCurSelfProgress, PRInt32 aMaxSelfProgress, PRInt32 aCurTotalProgress, PRInt32 aMaxTotalProgress)
 {
   if (mWebProgressListener) {
     return mWebProgressListener->OnProgressChange(aWebProgress, aRequest, aCurSelfProgress, aMaxSelfProgress, aCurTotalProgress, aMaxTotalProgress);
   }
   return NS_OK;
 }
 
-/* void onLocationChange (in nsIWebProgress aWebProgress, in nsIRequest aRequest, in nsIURI location); */
+/* void onLocationChange (in nsIWebProgress aWebProgress, in nsIRequest aRequest, in nsIURI location, in unsigned long aFlags); */
 NS_IMETHODIMP 
-nsPrintingPromptService::OnLocationChange(nsIWebProgress *aWebProgress, nsIRequest *aRequest, nsIURI *location)
+nsPrintingPromptService::OnLocationChange(nsIWebProgress *aWebProgress, nsIRequest *aRequest, nsIURI *location, PRUint32 aFlags)
 {
   if (mWebProgressListener) {
-    return mWebProgressListener->OnLocationChange(aWebProgress, aRequest, location);
+    return mWebProgressListener->OnLocationChange(aWebProgress, aRequest, location, aFlags);
   }
   return NS_OK;
 }
 
 /* void onStatusChange (in nsIWebProgress aWebProgress, in nsIRequest aRequest, in nsresult aStatus, in wstring aMessage); */
 NS_IMETHODIMP 
 nsPrintingPromptService::OnStatusChange(nsIWebProgress *aWebProgress, nsIRequest *aRequest, nsresult aStatus, const PRUnichar *aMessage)
 {
--- a/embedding/components/printingui/src/win/nsPrintProgress.cpp
+++ b/embedding/components/printingui/src/win/nsPrintProgress.cpp
@@ -280,18 +280,18 @@ NS_IMETHODIMP nsPrintProgress::OnProgres
       if (aProgressListener)
         aProgressListener->OnProgressChange(aWebProgress, aRequest, aCurSelfProgress, aMaxSelfProgress, aCurTotalProgress, aMaxTotalProgress);
     }
   }
   
   return rv;
 }
 
-/* void onLocationChange (in nsIWebProgress aWebProgress, in nsIRequest aRequest, in nsIURI location); */
-NS_IMETHODIMP nsPrintProgress::OnLocationChange(nsIWebProgress *aWebProgress, nsIRequest *aRequest, nsIURI *location)
+/* void onLocationChange (in nsIWebProgress aWebProgress, in nsIRequest aRequest, in nsIURI location, in unsigned long aFlags); */
+NS_IMETHODIMP nsPrintProgress::OnLocationChange(nsIWebProgress *aWebProgress, nsIRequest *aRequest, nsIURI *location, PRUint32 aFlags)
 {
     return NS_OK;
 }
 
 /* void onStatusChange (in nsIWebProgress aWebProgress, in nsIRequest aRequest, in nsresult aStatus, in wstring aMessage); */
 NS_IMETHODIMP nsPrintProgress::OnStatusChange(nsIWebProgress *aWebProgress, nsIRequest *aRequest, nsresult aStatus, const PRUnichar *aMessage)
 {
   nsresult rv = NS_OK;
--- a/embedding/components/printingui/src/win/nsPrintingPromptService.cpp
+++ b/embedding/components/printingui/src/win/nsPrintingPromptService.cpp
@@ -352,23 +352,23 @@ nsPrintingPromptService::OnProgressChang
 {
   if (mWebProgressListener) 
   {
       return mWebProgressListener->OnProgressChange(aWebProgress, aRequest, aCurSelfProgress, aMaxSelfProgress, aCurTotalProgress, aMaxTotalProgress);
   }
   return NS_ERROR_FAILURE;
 }
 
-/* void onLocationChange (in nsIWebProgress aWebProgress, in nsIRequest aRequest, in nsIURI location); */
+/* void onLocationChange (in nsIWebProgress aWebProgress, in nsIRequest aRequest, in nsIURI location, in unsigned long aFlags); */
 NS_IMETHODIMP 
-nsPrintingPromptService::OnLocationChange(nsIWebProgress *aWebProgress, nsIRequest *aRequest, nsIURI *location)
+nsPrintingPromptService::OnLocationChange(nsIWebProgress *aWebProgress, nsIRequest *aRequest, nsIURI *location, PRUint32 aFlags)
 {
   if (mWebProgressListener) 
   {
-      return mWebProgressListener->OnLocationChange(aWebProgress, aRequest, location);
+      return mWebProgressListener->OnLocationChange(aWebProgress, aRequest, location, aFlags);
   }
   return NS_ERROR_FAILURE;
 }
 
 /* void onStatusChange (in nsIWebProgress aWebProgress, in nsIRequest aRequest, in nsresult aStatus, in wstring aMessage); */
 NS_IMETHODIMP 
 nsPrintingPromptService::OnStatusChange(nsIWebProgress *aWebProgress, nsIRequest *aRequest, nsresult aStatus, const PRUnichar *aMessage)
 {
--- a/embedding/tests/winEmbed/WebBrowserChrome.cpp
+++ b/embedding/tests/winEmbed/WebBrowserChrome.cpp
@@ -271,17 +271,18 @@ NS_IMETHODIMP WebBrowserChrome::OnStateC
     }
 
     return NS_OK;
 }
 
 
 NS_IMETHODIMP WebBrowserChrome::OnLocationChange(nsIWebProgress* aWebProgress,
                                                  nsIRequest* aRequest,
-                                                 nsIURI *location)
+                                                 nsIURI *location,
+                                                 PRUint32 aFlags)
 {
   bool isSubFrameLoad = false; // Is this a subframe load
   if (aWebProgress) {
     nsCOMPtr<nsIDOMWindow>  domWindow;
     nsCOMPtr<nsIDOMWindow>  topDomWindow;
     aWebProgress->GetDOMWindow(getter_AddRefs(domWindow));
     if (domWindow) { // Get root domWindow
       domWindow->GetTop(getter_AddRefs(topDomWindow));
--- a/gfx/cairo/cairo/src/Makefile.in
+++ b/gfx/cairo/cairo/src/Makefile.in
@@ -200,17 +200,17 @@ CPPSRCS += cairo-beos-surface.cpp
 EXPORTS_cairo += cairo-beos.h
 endif
 
 ifeq ($(MOZ_WIDGET_TOOLKIT),gtk2)
 CSRCS   += $(PSPDF_BASE_CSRCS) $(PDF_CSRCS) $(PS_CSRCS)
 EXPORTS_cairo += $(PDF_EXPORTS) $(PS_EXPORTS)
 endif
 
-ifeq ($(MOZ_WIDGET_TOOLKIT),android)
+ifneq (,$(filter android gonk,$(MOZ_WIDGET_TOOLKIT)))
 CSRCS   += $(PSPDF_BASE_CSRCS) $(PDF_CSRCS)
 EXPORTS_cairo += $(PDF_EXPORTS)
 endif
 
 ifeq ($(MOZ_WIDGET_TOOLKIT),qt)
 CPPSRCS += cairo-qt-surface.cpp
 CSRCS   += $(PSPDF_BASE_CSRCS) $(PDF_CSRCS) 
 EXPORTS_cairo += cairo-qt.h
--- a/gfx/src/Makefile.in
+++ b/gfx/src/Makefile.in
@@ -102,16 +102,20 @@ CPPSRCS = \
 ifdef MOZ_X11
 CPPSRCS += X11Util.cpp
 endif
 
 ifeq ($(MOZ_WIDGET_TOOLKIT),android)
 CPPSRCS += nsSystemFontsAndroid.cpp
 endif
 
+ifeq ($(MOZ_WIDGET_TOOLKIT),gonk)
+CPPSRCS += nsSystemFontsAndroid.cpp
+endif
+
 ifeq ($(MOZ_WIDGET_TOOLKIT),cocoa)
 CMMSRCS = nsSystemFontsMac.mm
 endif
 
 ifeq ($(MOZ_WIDGET_TOOLKIT),gtk2)
 CPPSRCS += nsSystemFontsGTK2.cpp
 endif
 
--- a/gfx/src/nsDeviceContext.cpp
+++ b/gfx/src/nsDeviceContext.cpp
@@ -71,17 +71,21 @@ static nsSystemFontsOS2 *gSystemFonts = 
 #elif XP_MACOSX
 #include "nsSystemFontsMac.h"
 #include "gfxQuartzSurface.h"
 static nsSystemFontsMac *gSystemFonts = nsnull;
 #elif defined(MOZ_WIDGET_QT)
 #include "nsSystemFontsQt.h"
 #include "gfxPDFSurface.h"
 static nsSystemFontsQt *gSystemFonts = nsnull;
-#elif defined(ANDROID)
+#elif defined(MOZ_WIDGET_ANDROID)
+#include "nsSystemFontsAndroid.h"
+#include "gfxPDFSurface.h"
+static nsSystemFontsAndroid *gSystemFonts = nsnull;
+#elif defined(MOZ_WIDGET_GONK)
 #include "nsSystemFontsAndroid.h"
 #include "gfxPDFSurface.h"
 static nsSystemFontsAndroid *gSystemFonts = nsnull;
 #else
 #error Need to declare gSystemFonts!
 #endif
 
 using namespace mozilla;
--- a/gfx/thebes/GLContextProviderEGL.cpp
+++ b/gfx/thebes/GLContextProviderEGL.cpp
@@ -47,28 +47,33 @@
 #include <gdk/gdkx.h>
 // we're using default display for now
 #define GET_NATIVE_WINDOW(aWidget) (EGLNativeWindowType)GDK_WINDOW_XID((GdkWindow *) aWidget->GetNativeData(NS_NATIVE_WINDOW))
 #elif defined(MOZ_WIDGET_QT)
 #include <QtOpenGL/QGLContext>
 #define GLdouble_defined 1
 // we're using default display for now
 #define GET_NATIVE_WINDOW(aWidget) (EGLNativeWindowType)static_cast<QWidget*>(aWidget->GetNativeData(NS_NATIVE_SHELLWIDGET))->winId()
+#elif defined(MOZ_WIDGET_GONK)
+#define GET_NATIVE_WINDOW(aWidget) ((EGLNativeWindowType)aWidget->GetNativeData(NS_NATIVE_WINDOW))
 #endif
 
 #if defined(MOZ_X11)
 #include <X11/Xlib.h>
 #include <X11/Xutil.h>
 #include "mozilla/X11Util.h"
 #include "gfxXlibSurface.h"
 #endif
 
 #if defined(ANDROID)
 /* from widget */
+#if defined(MOZ_WIDGET_ANDROID)
 #include "AndroidBridge.h"
+#endif
+#include <android/log.h>
 #define EGL_LIB "/system/lib/libEGL.so"
 #define GLES2_LIB "/system/lib/libGLESv2.so"
 #else
 #define EGL_LIB "/usr/lib/libEGL.so"
 #define GLES2_LIB "/usr/lib/libGLESv2.so"
 #endif
 
 typedef void *EGLNativeDisplayType;
@@ -151,16 +156,20 @@ public:
 #include "gfxCrashReporterUtils.h"
 
 #ifdef MOZ_PLATFORM_MAEMO
 static bool gUseBackingSurface = true;
 #else
 static bool gUseBackingSurface = false;
 #endif
 
+#ifdef MOZ_WIDGET_GONK
+extern nsIntRect gScreenBounds;
+#endif
+
 namespace mozilla {
 namespace gl {
 
 typedef int EGLint;
 typedef unsigned int EGLBoolean;
 typedef unsigned int EGLenum;
 typedef void *EGLConfig;
 typedef void *EGLContext;
@@ -295,16 +304,20 @@ public:
     typedef EGLBoolean (GLAPIENTRY * pfnBindTexImage)(EGLDisplay, EGLSurface surface, EGLint buffer);
     pfnBindTexImage fBindTexImage;
     typedef EGLBoolean (GLAPIENTRY * pfnReleaseTexImage)(EGLDisplay, EGLSurface surface, EGLint buffer);
     pfnReleaseTexImage fReleaseTexImage;
     typedef EGLImageKHR (GLAPIENTRY * pfnCreateImageKHR)(EGLDisplay dpy, EGLContext ctx, EGLenum target, EGLClientBuffer buffer, const EGLint *attrib_list);
     pfnCreateImageKHR fCreateImageKHR;
     typedef EGLBoolean (GLAPIENTRY * pfnDestroyImageKHR)(EGLDisplay dpy, EGLImageKHR image);
     pfnDestroyImageKHR fDestroyImageKHR;
+#ifdef MOZ_WIDGET_GONK
+    typedef EGLBoolean (GLAPIENTRY * pfnSetSwapRectangleANDROID)(EGLDisplay dpy, EGLSurface surface, EGLint left, EGLint top, EGLint width, EGLint height);
+    pfnSetSwapRectangleANDROID fSetSwapRectangleANDROID;
+#endif
 
     // New extension which allow us to lock texture and get raw image pointer
     typedef EGLBoolean (GLAPIENTRY * pfnLockSurfaceKHR)(EGLDisplay dpy, EGLSurface surface, const EGLint *attrib_list);
     pfnLockSurfaceKHR fLockSurfaceKHR;
     typedef EGLBoolean (GLAPIENTRY * pfnUnlockSurfaceKHR)(EGLDisplay dpy, EGLSurface surface);
     pfnUnlockSurfaceKHR fUnlockSurfaceKHR;
     typedef EGLBoolean (GLAPIENTRY * pfnQuerySurface)(EGLDisplay dpy, EGLSurface surface, EGLint attribute, EGLint *value);
     pfnQuerySurface fQuerySurface;
@@ -391,16 +404,19 @@ public:
             SYMBOL(GetProcAddress),
             SYMBOL(SwapBuffers),
             SYMBOL(CopyBuffers),
             SYMBOL(QueryString),
             SYMBOL(QueryContext),
             SYMBOL(BindTexImage),
             SYMBOL(ReleaseTexImage),
             SYMBOL(QuerySurface),
+#ifdef MOZ_WIDGET_GONK
+            SYMBOL(SetSwapRectangleANDROID),
+#endif
             { NULL, { NULL } }
         };
 
         if (!LibrarySymbolLoader::LoadSymbols(mEGLLibrary, &earlySymbols[0])) {
             NS_WARNING("Couldn't find required entry points in EGL library (early init)");
             return false;
         }
 
@@ -591,17 +607,17 @@ public:
 
     void DumpEGLConfigs() {
         int nc = 0;
         fGetConfigs(mEGLDisplay, NULL, 0, &nc);
         EGLConfig *ec = new EGLConfig[nc];
         fGetConfigs(mEGLDisplay, ec, nc, &nc);
 
         for (int i = 0; i < nc; ++i) {
-            printf_stderr ("========= EGL Config %d ========\n");
+            printf_stderr ("========= EGL Config %d ========\n", i);
             DumpEGLConfig(ec[i]);
         }
 
         delete [] ec;
     }
 
 private:
     bool mInitialized;
@@ -864,16 +880,17 @@ public:
         default:
             return nsnull;
         }
     }
 
     bool SwapBuffers()
     {
         if (mSurface && !mPlatformContext) {
+            //sEGLLibrary.fSetSwapRectangleANDROID(EGL_DISPLAY(), mSurface, 0, 0, gScreenBounds.width, gScreenBounds.height);
             return sEGLLibrary.fSwapBuffers(EGL_DISPLAY(), mSurface);
         } else {
             return false;
         }
     }
     // GLContext interface - returns Tiled Texture Image in our case
     virtual already_AddRefed<TextureImage>
     CreateTextureImage(const nsIntSize& aSize,
@@ -1869,31 +1886,38 @@ CreateSurfaceForWindow(nsIWidget *aWidge
 {
     EGLSurface surface;
 
 
 #ifdef DEBUG
     sEGLLibrary.DumpEGLConfig(config);
 #endif
 
-#ifdef ANDROID
+#ifdef MOZ_WIDGET_ANDROID
     // On Android, we have to ask Java to make the eglCreateWindowSurface
     // call for us.  See GLHelpers.java for a description of why.
     //
     // We also only have one true "window", so we just use it directly and ignore
     // what was passed in.
     printf_stderr("... requesting window surface from bridge\n");
     surface = mozilla::AndroidBridge::Bridge()->
         CallEglCreateWindowSurface(EGL_DISPLAY(), config,
                                    mozilla::AndroidBridge::Bridge()->SurfaceView());
     printf_stderr("got surface %p\n", surface);
 #else
     surface = sEGLLibrary.fCreateWindowSurface(EGL_DISPLAY(), config, GET_NATIVE_WINDOW(aWidget), 0);
 #endif
 
+#ifdef MOZ_WIDGET_GONK
+    gScreenBounds.x = 0;
+    gScreenBounds.y = 0;
+    sEGLLibrary.fQuerySurface(EGL_DISPLAY(), surface, LOCAL_EGL_WIDTH, &gScreenBounds.width);
+    sEGLLibrary.fQuerySurface(EGL_DISPLAY(), surface, LOCAL_EGL_HEIGHT, &gScreenBounds.height);
+#endif
+
     return surface;
 }
 
 const char*
 GetVendor()
 {
     if (!sEGLLibrary.EnsureInitialized()) {
         return nsnull;
--- a/gfx/thebes/Makefile.in
+++ b/gfx/thebes/Makefile.in
@@ -59,16 +59,24 @@ EXPORTS	= \
 ifeq ($(MOZ_WIDGET_TOOLKIT),android)
 EXPORTS += \
 	gfxAndroidPlatform.h \
 	gfxFT2Fonts.h \
 	gfxFT2FontBase.h \
 	$(NULL)
 endif
 
+ifeq ($(MOZ_WIDGET_TOOLKIT),gonk)
+EXPORTS += \
+	gfxAndroidPlatform.h \
+	gfxFT2Fonts.h \
+	gfxFT2FontBase.h \
+	$(NULL)
+endif
+
 ifeq ($(MOZ_WIDGET_TOOLKIT),cocoa)
 EXPORTS += \
 	gfxPlatformMac.h \
 	gfxQuartzSurface.h \
 	gfxQuartzImageSurface.h \
 	gfxQuartzPDFSurface.h \
 	gfxQuartzNativeDrawing.h \
 	$(NULL)
@@ -237,16 +245,31 @@ CPPSRCS += \
 	gfxFT2FontBase.cpp \
 	gfxFT2Utils.cpp \
 	gfxFT2FontList.cpp \
 	gfxPDFSurface.cpp \
 	nsUnicodeRange.cpp \
 	$(NULL)
 endif
 
+ifeq ($(MOZ_WIDGET_TOOLKIT),gonk)
+EXPORTS	+= \
+	gfxPDFSurface.h \
+	$(NULL)
+CPPSRCS += \
+	gfxAndroidPlatform.cpp \
+	gfxFT2Fonts.cpp \
+	gfxFT2FontBase.cpp \
+	gfxFT2Utils.cpp \
+	gfxFT2FontList.cpp \
+	gfxPDFSurface.cpp \
+	nsUnicodeRange.cpp \
+	$(NULL)
+endif
+
 ifeq ($(MOZ_WIDGET_TOOLKIT),os2)
 CPPSRCS	+=	gfxOS2Fonts.cpp \
 		gfxOS2Platform.cpp \
 		gfxOS2Surface.cpp \
 		nsUnicodeRange.cpp \
 		gfxFontconfigUtils.cpp \
 		$(NULL)
 CPPSRCS +=	gfxPDFSurface.cpp
@@ -349,16 +372,20 @@ else
 GL_PROVIDER = GLX
 endif
 endif
 
 ifeq ($(MOZ_WIDGET_TOOLKIT),android)
 GL_PROVIDER = EGL
 endif
 
+ifeq ($(MOZ_WIDGET_TOOLKIT),gonk)
+GL_PROVIDER = EGL
+endif
+
 # Mac is a special snowflake
 ifeq ($(GL_PROVIDER),CGL)
 CMMSRCS += GLContextProvider$(GL_PROVIDER).mm
 else
 CPPSRCS += GLContextProvider$(GL_PROVIDER).cpp
 endif
 
 # Win32 is a special snowflake, for ANGLE
@@ -375,16 +402,20 @@ DEFINES := $(filter-out -DUNICODE,$(DEFI
 
 CXXFLAGS += $(MOZ_CAIRO_CFLAGS) $(TK_CFLAGS)
 CFLAGS += $(MOZ_CAIRO_CFLAGS) $(TK_CFLAGS)
 
 ifeq ($(MOZ_WIDGET_TOOLKIT),android)
 CXXFLAGS += $(CAIRO_FT_CFLAGS)
 endif
 
+ifeq ($(MOZ_WIDGET_TOOLKIT),gonk)
+CXXFLAGS += $(CAIRO_FT_CFLAGS)
+endif
+
 ifeq ($(MOZ_WIDGET_TOOLKIT),gtk2)
 CXXFLAGS += $(MOZ_PANGO_CFLAGS)
 endif
 
 ifeq ($(MOZ_WIDGET_TOOLKIT),os2)
 CXXFLAGS += $(CAIRO_FT_CFLAGS)
 endif
 
--- a/image/decoders/Makefile.in
+++ b/image/decoders/Makefile.in
@@ -77,15 +77,15 @@ ifeq ($(OS_ARCH),WINNT)
 DIRS = icon/win icon
 endif
 ifeq ($(OS_ARCH),OS2)
 DIRS = icon/os2 icon
 endif
 ifeq (cocoa,$(MOZ_WIDGET_TOOLKIT))
 DIRS = icon/mac icon
 endif
-ifeq ($(OS_TARGET),Android)
+ifeq (android,$(MOZ_WIDGET_TOOLKIT))
 DIRS = icon/android icon
 endif
 
 
 include $(topsrcdir)/config/rules.mk
 
--- a/ipc/chromium/src/base/message_loop.cc
+++ b/ipc/chromium/src/base/message_loop.cc
@@ -22,17 +22,17 @@
 #if defined(OS_LINUX)
 #ifdef MOZ_WIDGET_GTK2
 #include "base/message_pump_glib.h"
 #endif
 #ifdef MOZ_WIDGET_QT
 #include "base/message_pump_qt.h"
 #endif
 #endif
-#ifdef MOZ_WIDGET_ANDROID
+#ifdef ANDROID
 #include "base/message_pump_android.h"
 #endif
 
 #include "MessagePump.h"
 
 using base::Time;
 using base::TimeDelta;
 
--- a/ipc/glue/GeckoChildProcessHost.cpp
+++ b/ipc/glue/GeckoChildProcessHost.cpp
@@ -65,24 +65,24 @@
 #include "mozilla/Omnijar.h"
 #include <sys/stat.h>
 
 #ifdef XP_WIN
 #include "nsIWinTaskbar.h"
 #define NS_TASKBAR_CONTRACTID "@mozilla.org/windows-taskbar;1"
 #endif
 
-#ifdef ANDROID
+#ifdef MOZ_WIDGET_ANDROID
 #include "APKOpen.h"
 #endif
 
 using mozilla::MonitorAutoLock;
 using mozilla::ipc::GeckoChildProcessHost;
 
-#ifdef ANDROID
+#ifdef MOZ_WIDGET_ANDROID
 // Like its predecessor in nsExceptionHandler.cpp, this is
 // the magic number of a file descriptor remapping we must
 // preserve for the child process.
 static const int kMagicAndroidSystemPropFd = 5;
 #endif
 
 static bool
 ShouldHaveDirectoryService()
@@ -441,19 +441,19 @@ GeckoChildProcessHost::PerformAsyncLaunc
     NS_ASSERTION(directoryService, "Expected XPCOM to be available");
     if (directoryService) {
       nsCOMPtr<nsIFile> greDir;
       nsresult rv = directoryService->Get(NS_GRE_DIR, NS_GET_IID(nsIFile), getter_AddRefs(greDir));
       if (NS_SUCCEEDED(rv)) {
         nsCString path;
         greDir->GetNativePath(path);
 # ifdef OS_LINUX
-#  ifdef ANDROID
+#  ifdef MOZ_WIDGET_ANDROID
         path += "/lib";
-#  endif  // ANDROID
+#  endif  // MOZ_WIDGET_ANDROID
         const char *ld_library_path = PR_GetEnv("LD_LIBRARY_PATH");
         nsCString new_ld_lib_path;
         if (ld_library_path && *ld_library_path) {
             new_ld_lib_path.Assign(ld_library_path);
             new_ld_lib_path.AppendLiteral(":");
             new_ld_lib_path.Append(path.get());
             newEnvVars["LD_LIBRARY_PATH"] = new_ld_lib_path.get();
         } else {
@@ -484,17 +484,17 @@ GeckoChildProcessHost::PerformAsyncLaunc
       }
     }
   }
 #endif  // OS_LINUX || OS_MACOSX
 
   FilePath exePath;
   GetPathToBinary(exePath);
 
-#ifdef ANDROID
+#ifdef MOZ_WIDGET_ANDROID
   // The java wrapper unpacks this for us but can't make it executable
   chmod(exePath.value().c_str(), 0700);
   int cacheCount = 0;
   const struct lib_cache_info * cache = getLibraryCache();
   nsCString cacheStr;
   while (cache &&
          cacheCount++ < MAX_LIB_CACHE_ENTRIES &&
          strlen(cache->name)) {
@@ -516,17 +516,17 @@ GeckoChildProcessHost::PerformAsyncLaunc
     mFileMap.push_back(std::pair<int, int>(fd, kMagicAndroidSystemPropFd));
 
     char buf[32];
     char *szptr = strchr(apws, ',');
 
     snprintf(buf, sizeof(buf), "%d%s", kMagicAndroidSystemPropFd, szptr);
     newEnvVars["ANDROID_PROPERTY_WORKSPACE"] = buf;
   }
-#endif  // ANDROID
+#endif  // MOZ_WIDGET_ANDROID
 
   // remap the IPC socket fd to a well-known int, as the OS does for
   // STDOUT_FILENO, for example
   int srcChannelFd, dstChannelFd;
   channel().GetClientFileDescriptorMapping(&srcChannelFd, &dstChannelFd);
   mFileMap.push_back(std::pair<int,int>(srcChannelFd, dstChannelFd));
 
   // no need for kProcessChannelID, the child process inherits the
@@ -584,17 +584,17 @@ GeckoChildProcessHost::PerformAsyncLaunc
   // can't pretend being the child that's forked off.
   std::string mach_connection_name = StringPrintf("org.mozilla.machname.%d",
                                                   base::RandInt(0, std::numeric_limits<int>::max()));
   childArgv.push_back(mach_connection_name.c_str());
 #endif
 
   childArgv.push_back(childProcessType);
 
-#ifdef ANDROID
+#ifdef MOZ_WIDGET_ANDROID
   childArgv.push_back(cacheStr.get());
 #endif
 
   base::LaunchApp(childArgv, mFileMap,
 #if defined(OS_LINUX) || defined(OS_MACOSX)
                   newEnvVars,
 #endif
                   false, &process, arch);
--- a/js/public/HashTable.h
+++ b/js/public/HashTable.h
@@ -907,17 +907,20 @@ class HashMapEntry
     template <class> friend class detail::HashTableEntry;
     void operator=(const HashMapEntry &rhs) {
         const_cast<Key &>(key) = rhs.key;
         value = rhs.value;
     }
 
   public:
     HashMapEntry() : key(), value() {}
-    HashMapEntry(const Key &k, const Value &v) : key(k), value(v) {}
+
+    template<typename KeyInput, typename ValueInput>
+    HashMapEntry(const KeyInput &k, const ValueInput &v) : key(k), value(v) {}
+
     HashMapEntry(MoveRef<HashMapEntry> rhs) 
       : key(Move(rhs->key)), value(Move(rhs->value)) { }
     void operator=(MoveRef<HashMapEntry> rhs) {
         const_cast<Key &>(key) = Move(rhs->key);
         value = Move(rhs->value);
     }
 
     const Key key;
@@ -1043,17 +1046,18 @@ class HashMap
      *    assert(p->key == 3);
      *    char val = p->value;
      */
     typedef typename Impl::AddPtr AddPtr;
     AddPtr lookupForAdd(const Lookup &l) const {
         return impl.lookupForAdd(l);
     }
 
-    bool add(AddPtr &p, const Key &k, const Value &v) {
+    template<typename KeyInput, typename ValueInput>
+    bool add(AddPtr &p, const KeyInput &k, const ValueInput &v) {
         Entry *pentry;
         if (!impl.add(p, &pentry))
             return false;
         const_cast<Key &>(pentry->key) = k;
         pentry->value = v;
         return true;
     }
 
@@ -1069,17 +1073,18 @@ class HashMap
     bool add(AddPtr &p, const Key &k) {
         Entry *pentry;
         if (!impl.add(p, &pentry))
             return false;
         const_cast<Key &>(pentry->key) = k;
         return true;
     }
 
-    bool relookupOrAdd(AddPtr &p, const Key &k, const Value &v) {
+    template<typename KeyInput, typename ValueInput>
+    bool relookupOrAdd(AddPtr &p, const KeyInput &k, const ValueInput &v) {
         return impl.relookupOrAdd(p, k, Entry(k, v));
     }
 
     /*
      * |all()| returns a Range containing |count()| elements. E.g.:
      *
      *   typedef HashMap<int,char> HM;
      *   HM h;
@@ -1132,17 +1137,18 @@ class HashMap
 
     /* Shorthand operations: */
 
     bool has(const Lookup &l) const {
         return impl.lookup(l) != NULL;
     }
 
     /* Overwrite existing value with v. Return NULL on oom. */
-    Entry *put(const Key &k, const Value &v) {
+    template<typename KeyInput, typename ValueInput>
+    Entry *put(const KeyInput &k, const ValueInput &v) {
         AddPtr p = lookupForAdd(k);
         if (p) {
             p->value = v;
             return &*p;
         }
         return add(p, k, v) ? &*p : NULL;
     }
 
--- a/js/src/Makefile.in
+++ b/js/src/Makefile.in
@@ -245,16 +245,17 @@ EXPORTS_vm = \
 
 EXPORTS_ds = \
 		LifoAlloc.h \
 		BitArray.h \
 		$(NULL)
 
 EXPORTS_gc = \
 		Statistics.h \
+		Barrier.h \
 		$(NULL)
 
 ######################################################
 # BEGIN include exported headers from the JS engine
 #
 #       Ultimately, after cleansing INSTALLED_HEADERS,
 #       these will be the ONLY headers exported by
 #       the js engine
--- a/js/src/builtin/RegExp.cpp
+++ b/js/src/builtin/RegExp.cpp
@@ -154,21 +154,21 @@ ExecuteRegExpImpl(JSContext *cx, RegExpS
         *rval = BooleanValue(true);
         return true;
     }
 
     return CreateRegExpMatchResult(cx, input, chars, length, matchPairs, rval);
 }
 
 bool
-js::ExecuteRegExp(JSContext *cx, RegExpStatics *res, RegExpPrivate *rep, JSLinearString *input,
+js::ExecuteRegExp(JSContext *cx, RegExpStatics *res, RegExpMatcher &matcher, JSLinearString *input,
                   const jschar *chars, size_t length,
                   size_t *lastIndex, RegExpExecType type, Value *rval)
 {
-    return ExecuteRegExpImpl(cx, res, rep, input, chars, length, lastIndex, type, rval);
+    return ExecuteRegExpImpl(cx, res, &matcher, input, chars, length, lastIndex, type, rval);
 }
 
 bool
 js::ExecuteRegExp(JSContext *cx, RegExpStatics *res, RegExpObject *reobj, JSLinearString *input,
                   const jschar *chars, size_t length,
                   size_t *lastIndex, RegExpExecType type, Value *rval)
 {
     return ExecuteRegExpImpl(cx, res, reobj, input, chars, length, lastIndex, type, rval);
@@ -273,17 +273,17 @@ CompileRegExpObject(JSContext *cx, RegEx
         if (!ParseRegExpFlags(cx, flagStr, &flags))
             return false;
     }
 
     JSLinearString *escapedSourceStr = EscapeNakedForwardSlashes(cx, sourceStr);
     if (!escapedSourceStr)
         return false;
 
-    if (!RegExpPrivateCode::checkSyntax(cx, NULL, escapedSourceStr))
+    if (!CheckRegExpSyntax(cx, escapedSourceStr))
         return false;
 
     RegExpStatics *res = cx->regExpStatics();
     RegExpObject *reobj = builder.build(escapedSourceStr, RegExpFlag(flags | res->getFlags()));
     if (!reobj)
         return NULL;
 
     *rval = ObjectValue(*reobj);
@@ -510,25 +510,20 @@ ExecuteRegExp(JSContext *cx, Native nati
 
     /* Step 1. */
     bool ok;
     JSObject *obj = NonGenericMethodGuard(cx, args, native, &RegExpClass, &ok);
     if (!obj)
         return ok;
 
     RegExpObject *reobj = obj->asRegExp();
-    RegExpPrivate *rep = reobj->getOrCreatePrivate(cx);
-    if (!rep)
-        return true;
 
-    /*
-     * Code execution under this call could swap out the guts of |reobj|, so we
-     * have to take a defensive refcount here.
-     */
-    AutoRefCount<RegExpPrivate> arc(cx, NeedsIncRef<RegExpPrivate>(rep));
+    RegExpMatcher matcher(cx);
+    if (!matcher.reset(reobj))
+        return false;
 
     RegExpStatics *res = cx->regExpStatics();
 
     /* Step 2. */
     JSString *input = js_ValueToString(cx, (args.length() > 0) ? args[0] : UndefinedValue());
     if (!input)
         return false;
 
@@ -543,36 +538,36 @@ ExecuteRegExp(JSContext *cx, Native nati
     const Value &lastIndex = reobj->getLastIndex();
 
     /* Step 5. */
     jsdouble i;
     if (!ToInteger(cx, lastIndex, &i))
         return false;
 
     /* Steps 6-7 (with sticky extension). */
-    if (!rep->global() && !rep->sticky())
+    if (!matcher.global() && !matcher.sticky())
         i = 0;
 
     /* Step 9a. */
     if (i < 0 || i > length) {
         reobj->zeroLastIndex();
         args.rval() = NullValue();
         return true;
     }
 
     /* Steps 8-21. */
     RegExpExecType execType = (native == regexp_test) ? RegExpTest : RegExpExec;
     size_t lastIndexInt(i);
-    if (!ExecuteRegExp(cx, res, rep, linearInput, chars, length, &lastIndexInt, execType,
+    if (!ExecuteRegExp(cx, res, matcher, linearInput, chars, length, &lastIndexInt, execType,
                        &args.rval())) {
         return false;
     }
 
     /* Step 11 (with sticky extension). */
-    if (rep->global() || (!args.rval().isNull() && rep->sticky())) {
+    if (matcher.global() || (!args.rval().isNull() && matcher.sticky())) {
         if (args.rval().isNull())
             reobj->zeroLastIndex();
         else
             reobj->setLastIndex(lastIndexInt);
     }
 
     return true;
 }
--- a/js/src/builtin/RegExp.h
+++ b/js/src/builtin/RegExp.h
@@ -59,17 +59,17 @@ namespace js {
  * |chars| and |length|.
  */
 bool
 ExecuteRegExp(JSContext *cx, RegExpStatics *res, RegExpObject *reobj, JSLinearString *input,
               const jschar *chars, size_t length,
               size_t *lastIndex, RegExpExecType type, Value *rval);
 
 bool
-ExecuteRegExp(JSContext *cx, RegExpStatics *res, RegExpPrivate *rep, JSLinearString *input,
+ExecuteRegExp(JSContext *cx, RegExpStatics *res, RegExpMatcher &matcher, JSLinearString *input,
               const jschar *chars, size_t length,
               size_t *lastIndex, RegExpExecType type, Value *rval);
 
 extern JSBool
 regexp_exec(JSContext *cx, uintN argc, Value *vp);
 
 extern JSBool
 regexp_test(JSContext *cx, uintN argc, Value *vp);
--- a/js/src/configure.in
+++ b/js/src/configure.in
@@ -276,16 +276,70 @@ arm-android-eabi)
 i?86-*android*)
     android_tool_prefix="i686-android-linux"
     ;;
 *)
     android_tool_prefix="$target_os"
     ;;
 esac
 
+MOZ_ARG_WITH_STRING(gonk,
+[  --with-gonk=DIR
+               location of gonk dir],
+    gonkdir=$withval)
+
+if test -n "$gonkdir" ; then
+    kernel_name=`uname -s | tr "[[:upper:]]" "[[:lower:]]"`
+    gonk_toolchain="$gonkdir"/prebuilt/$kernel_name-x86/toolchain/arm-eabi-4.4.3
+
+    dnl set up compilers
+    AS="$gonk_toolchain"/bin/"$android_tool_prefix"-as
+    CC="$gonk_toolchain"/bin/"$android_tool_prefix"-gcc
+    CXX="$gonk_toolchain"/bin/"$android_tool_prefix"-g++
+    CPP="$gonk_toolchain"/bin/"$android_tool_prefix"-cpp
+    LD="$gonk_toolchain"/bin/"$android_tool_prefix"-ld
+    AR="$gonk_toolchain"/bin/"$android_tool_prefix"-ar
+    RANLIB="$gonk_toolchain"/bin/"$android_tool_prefix"-ranlib
+    STRIP="$gonk_toolchain"/bin/"$android_tool_prefix"-strip
+
+    STLPORT_CPPFLAGS="-I$gonkdir/external/stlport/stlport"
+    STLPORT_LIBS="-lstlport"
+
+    CPPFLAGS="-DANDROID -I$gonkdir/bionic/libc/include/ -I$gonkdir/bionic/libc/kernel/common -I$gonkdir/bionic/libc/arch-arm/include -I$gonkdir/bionic/libc/kernel/arch-arm -I$gonkdir/bionic/libm/include -I$gonkdir/frameworks/base/native/include -I$gonkdir/system/core/include -I$gonkdir/bionic $STLPORT_CPPFLAGS $CPPFLAGS"
+    CFLAGS="-mandroid -fno-short-enums -fno-exceptions $CFLAGS"
+    CXXFLAGS="-mandroid -fno-short-enums -fno-exceptions $CXXFLAGS"
+    LIBS="$LIBS $STLPORT_LIBS"
+
+    dnl Add -llog by default, since we use it all over the place.
+    LDFLAGS="-mandroid -L$gonkdir/out/target/product/$GONK_PRODUCT/obj/lib -Wl,-rpath-link=$gonkdir/out/target/product/$GONK_PRODUCT/obj/lib --sysroot=$gonkdir/out/target/product/$GONK_PRODUCT/obj/ -llog $LDFLAGS"
+
+    dnl prevent cross compile section from using these flags as host flags
+    if test -z "$HOST_CPPFLAGS" ; then
+        HOST_CPPFLAGS=" "
+    fi
+    if test -z "$HOST_CFLAGS" ; then
+        HOST_CFLAGS=" "
+    fi
+    if test -z "$HOST_CXXFLAGS" ; then
+        HOST_CXXFLAGS=" "
+    fi
+    if test -z "$HOST_LDFLAGS" ; then
+        HOST_LDFLAGS=" "
+    fi
+
+    # save these for libffi's subconfigure,
+    # which doesn't know how to figure this stuff out on its own
+    ANDROID_CFLAGS="$CFLAGS"
+    ANDROID_CPPFLAGS="$CPPFLAGS"
+    ANDROID_LDFLAGS="$LDFLAGS"
+
+    AC_DEFINE(ANDROID)
+    AC_DEFINE(GONK)
+    CROSS_COMPILE=1
+else
 case "$target" in
 *-android*|*-linuxandroid*)
     if test -z "$android_ndk" ; then
         AC_MSG_ERROR([You must specify --with-android-ndk=/path/to/ndk when targeting Android.])
     fi
 
     if test -z "$android_sdk" ; then
         AC_MSG_ERROR([You must specify --with-android-sdk=/path/to/sdk when targeting Android.])
@@ -398,16 +452,18 @@ case "$target" in
     AC_DEFINE(ANDROID)
     AC_DEFINE_UNQUOTED(ANDROID_VERSION, $android_version)
     AC_SUBST(ANDROID_VERSION)
     CROSS_COMPILE=1
     MOZ_CHROME_FILE_FORMAT=omni
     ;;
 esac
 
+fi
+
 AC_SUBST(ANDROID_NDK)
 AC_SUBST(ANDROID_TOOLCHAIN)
 AC_SUBST(ANDROID_PLATFORM)
 AC_SUBST(ANDROID_SDK)
 AC_SUBST(ANDROID_PLATFORM_TOOLS)
 
 dnl ========================================================
 dnl Checks for compilers.
@@ -1633,16 +1689,58 @@ if test "$CPU_ARCH" = "arm"; then
       AC_DEFINE(HAVE_ARM_NEON)
       HAVE_ARM_NEON=1
   fi
 fi # CPU_ARCH = arm
 
 AC_SUBST(HAVE_ARM_SIMD)
 AC_SUBST(HAVE_ARM_NEON)
 
+dnl =================================================================
+dnl Set up and test static assertion macros used to avoid AC_TRY_RUN,
+dnl which is bad when cross compiling.
+dnl =================================================================
+if test "$COMPILE_ENVIRONMENT"; then
+configure_static_assert_macros='
+#define CONFIGURE_STATIC_ASSERT(condition) CONFIGURE_STATIC_ASSERT_IMPL(condition, __LINE__)
+#define CONFIGURE_STATIC_ASSERT_IMPL(condition, line) CONFIGURE_STATIC_ASSERT_IMPL2(condition, line)
+#define CONFIGURE_STATIC_ASSERT_IMPL2(condition, line) typedef int static_assert_line_##line[(condition) ? 1 : -1]
+'
+
+dnl test that the macros actually work:
+AC_MSG_CHECKING(that static assertion macros used in autoconf tests work)
+AC_CACHE_VAL(ac_cv_static_assertion_macros_work,
+ [AC_LANG_SAVE
+  AC_LANG_C
+  ac_cv_static_assertion_macros_work="yes"
+  AC_TRY_COMPILE([$configure_static_assert_macros],
+                 [CONFIGURE_STATIC_ASSERT(1)],
+                 ,
+                 ac_cv_static_assertion_macros_work="no")
+  AC_TRY_COMPILE([$configure_static_assert_macros],
+                 [CONFIGURE_STATIC_ASSERT(0)],
+                 ac_cv_static_assertion_macros_work="no",
+                 )
+  AC_LANG_CPLUSPLUS
+  AC_TRY_COMPILE([$configure_static_assert_macros],
+                 [CONFIGURE_STATIC_ASSERT(1)],
+                 ,
+                 ac_cv_static_assertion_macros_work="no")
+  AC_TRY_COMPILE([$configure_static_assert_macros],
+                 [CONFIGURE_STATIC_ASSERT(0)],
+                 ac_cv_static_assertion_macros_work="no",
+                 )
+  AC_LANG_RESTORE
+ ])
+AC_MSG_RESULT("$ac_cv_static_assertion_macros_work")
+if test "$ac_cv_static_assertion_macros_work" = "no"; then
+    AC_MSG_ERROR([Compiler cannot compile macros used in autoconf tests.])
+fi
+fi # COMPILE_ENVIRONMENT
+
 dnl ========================================================
 dnl Android libstdc++, placed here so it can use MOZ_ARCH
 dnl computed above.
 dnl ========================================================
 
 if test "$OS_TARGET" = "Android"; then
     case "${CPU_ARCH}-${MOZ_ARCH}" in
     arm-armv7*)
@@ -1780,16 +1878,37 @@ if test "$GNU_CXX"; then
     # versions).  We can't use -std=c++0x yet, so gcc's support must remain
     # unused.  But clang's warning can be disabled, so when compiling with clang
     # we use it to opt out of the warning, enabling (macro-encapsulated) use of
     # deleted function syntax.
     if test "$CLANG_CXX"; then
         _WARNINGS_CXXFLAGS="${_WARNINGS_CXXFLAGS} -Wno-c++0x-extensions"
     fi
 
+    AC_CACHE_CHECK(whether the compiler supports -Wno-extended-offsetof,
+                   ac_has_wno_extended_offsetof,
+        [
+            AC_LANG_SAVE
+            AC_LANG_CPLUSPLUS
+            _SAVE_CXXFLAGS="$CXXFLAGS"
+            CXXFLAGS="$CXXFLAGS ${_COMPILER_PREFIX}-Wno-extended-offsetof"
+            AC_TRY_COMPILE([$configure_static_assert_macros
+                            #ifndef __has_warning
+                            #define __has_warning(x) 0
+                            #endif],
+                           [CONFIGURE_STATIC_ASSERT(__has_warning("-Wextended-offsetof"))],
+                           ac_has_wno_extended_offsetof="yes",
+                           ac_has_wno_extended_offsetof="no")
+            CXXFLAGS="$_SAVE_CXXFLAGS"
+            AC_LANG_RESTORE
+        ])
+    if test "$ac_has_wno_extended_offsetof" = "yes"; then
+        _WARNINGS_CXXFLAGS="${_WARNINGS_CXXFLAGS} ${_COMPILER_PREFIX}-Wno-extended-offsetof"
+    fi
+
     AC_CACHE_CHECK(whether the compiler supports -Wno-invalid-offsetof,
                    ac_has_wno_invalid_offsetof,
         [
             AC_LANG_SAVE
             AC_LANG_CPLUSPLUS
             _SAVE_CXXFLAGS="$CXXFLAGS"
             CXXFLAGS="$CXXFLAGS ${_COMPILER_PREFIX}-Wno-invalid-offsetof"
             AC_TRY_COMPILE([],
@@ -1878,58 +1997,16 @@ LOOP_INPUT
     AC_MSG_RESULT(yes)
     eval $ac_cv_mkshlib_force_and_unforce
     MKSHLIB_FORCE_ALL=$force
     MKSHLIB_UNFORCE_ALL=$unforce
   fi
 fi # GNU_CC
 fi # COMPILE_ENVIRONMENT
 
-dnl =================================================================
-dnl Set up and test static assertion macros used to avoid AC_TRY_RUN,
-dnl which is bad when cross compiling.
-dnl =================================================================
-if test "$COMPILE_ENVIRONMENT"; then
-configure_static_assert_macros='
-#define CONFIGURE_STATIC_ASSERT(condition) CONFIGURE_STATIC_ASSERT_IMPL(condition, __LINE__)
-#define CONFIGURE_STATIC_ASSERT_IMPL(condition, line) CONFIGURE_STATIC_ASSERT_IMPL2(condition, line)
-#define CONFIGURE_STATIC_ASSERT_IMPL2(condition, line) typedef int static_assert_line_##line[(condition) ? 1 : -1]
-'
-
-dnl test that the macros actually work:
-AC_MSG_CHECKING(that static assertion macros used in autoconf tests work)
-AC_CACHE_VAL(ac_cv_static_assertion_macros_work,
- [AC_LANG_SAVE
-  AC_LANG_C
-  ac_cv_static_assertion_macros_work="yes"
-  AC_TRY_COMPILE([$configure_static_assert_macros],
-                 [CONFIGURE_STATIC_ASSERT(1)],
-                 ,
-                 ac_cv_static_assertion_macros_work="no")
-  AC_TRY_COMPILE([$configure_static_assert_macros],
-                 [CONFIGURE_STATIC_ASSERT(0)],
-                 ac_cv_static_assertion_macros_work="no",
-                 )
-  AC_LANG_CPLUSPLUS
-  AC_TRY_COMPILE([$configure_static_assert_macros],
-                 [CONFIGURE_STATIC_ASSERT(1)],
-                 ,
-                 ac_cv_static_assertion_macros_work="no")
-  AC_TRY_COMPILE([$configure_static_assert_macros],
-                 [CONFIGURE_STATIC_ASSERT(0)],
-                 ac_cv_static_assertion_macros_work="no",
-                 )
-  AC_LANG_RESTORE
- ])
-AC_MSG_RESULT("$ac_cv_static_assertion_macros_work")
-if test "$ac_cv_static_assertion_macros_work" = "no"; then
-    AC_MSG_ERROR([Compiler cannot compile macros used in autoconf tests.])
-fi
-fi # COMPILE_ENVIRONMENT
-
 dnl ========================================================
 dnl Checking for 64-bit OS
 dnl ========================================================
 if test "$COMPILE_ENVIRONMENT"; then
 AC_LANG_SAVE
 AC_LANG_C
 AC_MSG_CHECKING(for 64-bit OS)
 AC_TRY_COMPILE([$configure_static_assert_macros],
@@ -4438,16 +4515,27 @@ MOZ_ARG_ENABLE_BOOL(tracevis,
 if test -n "$MOZ_TRACEVIS"; then
     AC_DEFINE(MOZ_TRACEVIS)
     if test -z "$ENABLE_TRACEJIT"; then
        AC_MSG_ERROR([--enable-tracevis is incompatible with --disable-tracejit])
     fi
 fi
 
 dnl ========================================================
+dnl = Use incremental GC
+dnl ========================================================
+JSGC_INCREMENTAL=1
+MOZ_ARG_DISABLE_BOOL(gcincremental,
+[  --disable-gcincremental Disable incremental GC],
+    JSGC_INCREMENTAL= )
+if test -n "$JSGC_INCREMENTAL"; then
+    AC_DEFINE(JSGC_INCREMENTAL)
+fi
+
+dnl ========================================================
 dnl = Use Valgrind
 dnl ========================================================
 MOZ_ARG_ENABLE_BOOL(valgrind,
 [  --enable-valgrind       Enable Valgrind integration hooks (default=no)],
     MOZ_VALGRIND=1,
     MOZ_VALGRIND= )
 if test -n "$MOZ_VALGRIND"; then
     AC_CHECK_HEADER([valgrind/valgrind.h], [],
@@ -4782,28 +4870,28 @@ AC_LANG_CPLUSPLUS
 dnl ========================================================
 dnl Test for -pedantic bustage
 dnl ========================================================
 MOZ_ARG_DISABLE_BOOL(pedantic,
 [  --disable-pedantic      Issue all warnings demanded by strict ANSI C ],
 _PEDANTIC= )
 if test "$_PEDANTIC"; then
     _SAVE_CXXFLAGS=$CXXFLAGS
-    CXXFLAGS="$CXXFLAGS ${_WARNINGS_CXXFLAGS} ${_COMPILER_PREFIX}-pedantic ${_COMPILER_PREFIX}-Wno-long-long"
+    CXXFLAGS="$CXXFLAGS ${_COMPILER_PREFIX}-pedantic ${_WARNINGS_CXXFLAGS} ${_COMPILER_PREFIX}-Wno-long-long"
     AC_MSG_CHECKING([whether C++ compiler has -pedantic long long bug])
     AC_TRY_COMPILE([$configure_static_assert_macros],
                    [CONFIGURE_STATIC_ASSERT(sizeof(long long) == 8)],
                    result="no", result="yes" )
     AC_MSG_RESULT([$result])
     CXXFLAGS="$_SAVE_CXXFLAGS"
 
     case "$result" in
     no)
-        _WARNINGS_CFLAGS="${_WARNINGS_CFLAGS} ${_COMPILER_PREFIX}-pedantic ${_COMPILER_PREFIX}-Wno-long-long"
-        _WARNINGS_CXXFLAGS="${_WARNINGS_CXXFLAGS} ${_COMPILER_PREFIX}-pedantic ${_COMPILER_PREFIX}-Wno-long-long"
+        _WARNINGS_CFLAGS="${_COMPILER_PREFIX}-pedantic ${_WARNINGS_CFLAGS} ${_COMPILER_PREFIX}-Wno-long-long"
+        _WARNINGS_CXXFLAGS="${_COMPILER_PREFIX}-pedantic ${_WARNINGS_CXXFLAGS} ${_COMPILER_PREFIX}-Wno-long-long"
         ;;
     yes)
         AC_MSG_ERROR([Your compiler appears to have a known bug where long long is miscompiled when using -pedantic.  Reconfigure using --disable-pedantic. ])
         ;;
     esac
 fi
 
 dnl ========================================================
new file mode 100644
--- /dev/null
+++ b/js/src/frontend/BytecodeEmitter-inl.h
@@ -0,0 +1,73 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*-
+ * vim: set ts=8 sw=4 et tw=99:
+ *
+ * ***** BEGIN LICENSE BLOCK *****
+ * Version: MPL 1.1/GPL 2.0/LGPL 2.1
+ *
+ * The contents of this file are subject to the Mozilla Public License Version
+ * 1.1 (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ * http://www.mozilla.org/MPL/
+ *
+ * Software distributed under the License is distributed on an "AS IS" basis,
+ * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
+ * for the specific language governing rights and limitations under the
+ * License.
+ *
+ * The Original Code is Mozilla Communicator client code, released
+ * March 31, 1998.
+ *
+ * The Initial Developer of the Original Code is
+ * Netscape Communications Corporation.
+ * Portions created by the Initial Developer are Copyright (C) 1998
+ * the Initial Developer. All Rights Reserved.
+ *
+ * Contributor(s):
+ *
+ * Alternatively, the contents of this file may be used under the terms of
+ * either of the GNU General Public License Version 2 or later (the "GPL"),
+ * or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
+ * in which case the provisions of the GPL or the LGPL are applicable instead
+ * of those above. If you wish to allow use of your version of this file only
+ * under the terms of either the GPL or the LGPL, and not to allow others to
+ * use your version of this file under the terms of the MPL, indicate your
+ * decision by deleting the provisions above and replace them with the notice
+ * and other provisions required by the GPL or the LGPL. If you do not delete
+ * the provisions above, a recipient may use your version of this file under
+ * the terms of any one of the MPL, the GPL or the LGPL.
+ *
+ * ***** END LICENSE BLOCK ***** */
+
+#ifndef BytecodeEmitter_inl_h__
+#define BytecodeEmitter_inl_h__
+
+#include "frontend/ParseNode.h"
+#include "frontend/TokenStream.h"
+
+namespace js {
+
+inline
+TreeContext::TreeContext(Parser *prs)
+  : flags(0), bodyid(0), blockidGen(0), parenDepth(0), yieldCount(0), argumentsCount(0),
+    topStmt(NULL), topScopeStmt(NULL), blockChainBox(NULL), blockNode(NULL),
+    decls(prs->context), parser(prs), yieldNode(NULL), argumentsNode(NULL), scopeChain_(NULL),
+    lexdeps(prs->context), parent(prs->tc), staticLevel(0), funbox(NULL), functionList(NULL),
+    innermostWith(NULL), bindings(prs->context), sharpSlotBase(-1)
+{
+    prs->tc = this;
+}
+
+/*
+ * For functions the tree context is constructed and destructed a second
+ * time during code generation. To avoid a redundant stats update in such
+ * cases, we store uint16(-1) in maxScopeDepth.
+ */
+inline
+TreeContext::~TreeContext()
+{
+    parser->tc = this->parent;
+}
+
+} /* namespace js */
+
+#endif /* BytecodeEmitter_inl_h__ */
--- a/js/src/frontend/BytecodeEmitter.cpp
+++ b/js/src/frontend/BytecodeEmitter.cpp
@@ -66,20 +66,20 @@
 #include "ds/LifoAlloc.h"
 #include "frontend/BytecodeCompiler.h"
 #include "frontend/BytecodeEmitter.h"
 #include "frontend/Parser.h"
 #include "frontend/TokenStream.h"
 #include "vm/RegExpObject.h"
 
 #include "jsatominlines.h"
-#include "jsobjinlines.h"
 #include "jsscopeinlines.h"
 #include "jsscriptinlines.h"
 
+#include "frontend/BytecodeEmitter-inl.h"
 #include "frontend/ParseMaps-inl.h"
 
 /* Allocation chunk counts, must be powers of two in general. */
 #define BYTECODE_CHUNK_LENGTH  1024    /* initial bytecode chunk length */
 #define SRCNOTE_CHUNK_LENGTH   1024    /* initial srcnote chunk length */
 
 /* Macros to compute byte sizes from typed element counts. */
 #define BYTECODE_SIZE(n)        ((n) * sizeof(jsbytecode))
@@ -7772,32 +7772,32 @@ CGObjectList::index(ObjectBox *objbox)
 }
 
 void
 CGObjectList::finish(JSObjectArray *array)
 {
     JS_ASSERT(length <= INDEX_LIMIT);
     JS_ASSERT(length == array->length);
 
-    JSObject **cursor = array->vector + array->length;
+    js::HeapPtrObject *cursor = array->vector + array->length;
     ObjectBox *objbox = lastbox;
     do {
         --cursor;
         JS_ASSERT(!*cursor);
         *cursor = objbox->object;
     } while ((objbox = objbox->emitLink) != NULL);
     JS_ASSERT(cursor == array->vector);
 }
 
 void
 GCConstList::finish(JSConstArray *array)
 {
     JS_ASSERT(array->length == list.length());
     Value *src = list.begin(), *srcend = list.end();
-    Value *dst = array->vector;
+    HeapValue *dst = array->vector;
     for (; src != srcend; ++src, ++dst)
         *dst = *src;
 }
 
 /*
  * We should try to get rid of offsetBias (always 0 or 1, where 1 is
  * JSOP_{NOP,POP}_LENGTH), which is used only by SRC_FOR and SRC_DECL.
  */
--- a/js/src/frontend/BytecodeEmitter.h
+++ b/js/src/frontend/BytecodeEmitter.h
@@ -354,34 +354,18 @@ struct TreeContext {                /* t
 
     ParseNode       *innermostWith; /* innermost WITH parse node */
 
     Bindings        bindings;       /* bindings in this code, including
                                        arguments if we're compiling a function */
 
     void trace(JSTracer *trc);
 
-    TreeContext(Parser *prs)
-      : flags(0), bodyid(0), blockidGen(0), parenDepth(0), yieldCount(0), argumentsCount(0),
-        topStmt(NULL), topScopeStmt(NULL), blockChainBox(NULL), blockNode(NULL),
-        decls(prs->context), parser(prs), yieldNode(NULL), argumentsNode(NULL), scopeChain_(NULL),
-        lexdeps(prs->context), parent(prs->tc), staticLevel(0), funbox(NULL), functionList(NULL),
-        innermostWith(NULL), bindings(prs->context), sharpSlotBase(-1)
-    {
-        prs->tc = this;
-    }
-
-    /*
-     * For functions the tree context is constructed and destructed a second
-     * time during code generation. To avoid a redundant stats update in such
-     * cases, we store uint16(-1) in maxScopeDepth.
-     */
-    ~TreeContext() {
-        parser->tc = this->parent;
-    }
+    inline TreeContext(Parser *prs);
+    inline ~TreeContext();
 
     /*
      * js::BytecodeEmitter derives from js::TreeContext; however, only the
      * top-level BytecodeEmitters are actually used as full-fledged tree contexts
      * (to hold decls and lexdeps). We can avoid allocation overhead by making
      * this distinction explicit.
      */
     enum InitBehavior {
--- a/js/src/frontend/Parser.cpp
+++ b/js/src/frontend/Parser.cpp
@@ -87,19 +87,19 @@
 #include "jsxml.h"
 #endif
 
 #if JS_HAS_DESTRUCTURING
 #include "jsdhash.h"
 #endif
 
 #include "jsatominlines.h"
-#include "jsobjinlines.h"
 #include "jsscriptinlines.h"
 
+#include "frontend/BytecodeEmitter-inl.h"
 #include "frontend/ParseMaps-inl.h"
 #include "frontend/ParseNode-inl.h"
 #include "vm/RegExpObject-inl.h"
 
 using namespace js;
 using namespace js::gc;
 using namespace js::frontend;
 
@@ -241,17 +241,17 @@ Parser::newFunctionBox(JSObject *obj, Pa
     return funbox;
 }
 
 void
 Parser::trace(JSTracer *trc)
 {
     ObjectBox *objbox = traceListHead;
     while (objbox) {
-        MarkObject(trc, *objbox->object, "parser.object");
+        MarkRoot(trc, objbox->object, "parser.object");
         if (objbox->isFunctionBox)
             static_cast<FunctionBox *>(objbox)->bindings.trace(trc);
         objbox = objbox->traceLink;
     }
 
     for (TreeContext *tc = this->tc; tc; tc = tc->parent)
         tc->trace(trc);
 }
--- a/js/src/frontend/SemanticAnalysis.cpp
+++ b/js/src/frontend/SemanticAnalysis.cpp
@@ -40,16 +40,17 @@
 
 #include "frontend/SemanticAnalysis.h"
 
 #include "jsfun.h"
 
 #include "frontend/BytecodeEmitter.h"
 #include "frontend/Parser.h"
 
+#include "jsobjinlines.h"
 #include "jsfuninlines.h"
 
 using namespace js;
 using namespace js::frontend;
 
 /*
  * Walk the function box list at |*funboxHead|, removing boxes for deleted
  * functions and cleaning up method lists. We do this once, before
new file mode 100644
--- /dev/null
+++ b/js/src/gc/Barrier-inl.h
@@ -0,0 +1,259 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*-
+ * vim: set ts=8 sw=4 et tw=78:
+ *
+ * ***** BEGIN LICENSE BLOCK *****
+ * Version: MPL 1.1/GPL 2.0/LGPL 2.1
+ *
+ * The contents of this file are subject to the Mozilla Public License Version
+ * 1.1 (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ * http://www.mozilla.org/MPL/
+ *
+ * Software distributed under the License is distributed on an "AS IS" basis,
+ * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
+ * for the specific language governing rights and limitations under the
+ * License.
+ *
+ * The Original Code is SpiderMonkey global object code.
+ *
+ * The Initial Developer of the Original Code is
+ * the Mozilla Foundation.
+ * Portions created by the Initial Developer are Copyright (C) 2011
+ * the Initial Developer. All Rights Reserved.
+ *
+ * Contributor(s):
+ *
+ * Alternatively, the contents of this file may be used under the terms of
+ * either of the GNU General Public License Version 2 or later (the "GPL"),
+ * or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
+ * in which case the provisions of the GPL or the LGPL are applicable instead
+ * of those above. If you wish to allow use of your version of this file only
+ * under the terms of either the GPL or the LGPL, and not to allow others to
+ * use your version of this file under the terms of the MPL, indicate your
+ * decision by deleting the provisions above and replace them with the notice
+ * and other provisions required by the GPL or the LGPL. If you do not delete
+ * the provisions above, a recipient may use your version of this file under
+ * the terms of any one of the MPL, the GPL or the LGPL.
+ *
+ * ***** END LICENSE BLOCK ***** */
+
+#include "jsgcmark.h"
+
+#include "gc/Barrier.h"
+
+#ifndef jsgc_barrier_inl_h___
+#define jsgc_barrier_inl_h___
+
+namespace js {
+
+static JS_ALWAYS_INLINE void
+ClearValueRange(JSCompartment *comp, HeapValue *vec, uintN len, bool useHoles)
+{
+    if (useHoles) {
+        for (uintN i = 0; i < len; i++)
+            vec[i].set(comp, MagicValue(JS_ARRAY_HOLE));
+    } else {
+        for (uintN i = 0; i < len; i++)
+            vec[i].set(comp, UndefinedValue());
+    }
+}
+
+static JS_ALWAYS_INLINE void
+InitValueRange(HeapValue *vec, uintN len, bool useHoles)
+{
+    if (useHoles) {
+        for (uintN i = 0; i < len; i++)
+            vec[i].init(MagicValue(JS_ARRAY_HOLE));
+    } else {
+        for (uintN i = 0; i < len; i++)
+            vec[i].init(UndefinedValue());
+    }
+}
+
+static JS_ALWAYS_INLINE void
+DestroyValueRange(HeapValue *vec, uintN len)
+{
+    for (uintN i = 0; i < len; i++)
+        vec[i].~HeapValue();
+}
+
+inline
+HeapValue::HeapValue(const Value &v)
+    : value(v)
+{
+    post();
+}
+
+inline
+HeapValue::HeapValue(const HeapValue &v)
+    : value(v.value)
+{
+    post();
+}
+
+inline
+HeapValue::~HeapValue()
+{
+    pre();
+}
+
+inline void
+HeapValue::init(const Value &v)
+{
+    value = v;
+    post();
+}
+
+inline void
+HeapValue::writeBarrierPre(const Value &value)
+{
+#ifdef JSGC_INCREMENTAL
+    if (value.isMarkable()) {
+        js::gc::Cell *cell = (js::gc::Cell *)value.toGCThing();
+        writeBarrierPre(cell->compartment(), value);
+    }
+#endif
+}
+
+inline void
+HeapValue::writeBarrierPost(const Value &value, void *addr)
+{
+}
+
+inline void
+HeapValue::writeBarrierPre(JSCompartment *comp, const Value &value)
+{
+#ifdef JSGC_INCREMENTAL
+    if (comp->needsBarrier())
+        js::gc::MarkValueUnbarriered(comp->barrierTracer(), value, "write barrier");
+#endif
+}
+
+inline void
+HeapValue::writeBarrierPost(JSCompartment *comp, const Value &value, void *addr)
+{
+}
+
+inline void
+HeapValue::pre()
+{
+    writeBarrierPre(value);
+}
+
+inline void
+HeapValue::post()
+{
+}
+
+inline void
+HeapValue::pre(JSCompartment *comp)
+{
+    writeBarrierPre(comp, value);
+}
+
+inline void
+HeapValue::post(JSCompartment *comp)
+{
+}
+
+inline HeapValue &
+HeapValue::operator=(const Value &v)
+{
+    pre();
+    value = v;
+    post();
+    return *this;
+}
+
+inline HeapValue &
+HeapValue::operator=(const HeapValue &v)
+{
+    pre();
+    value = v.value;
+    post();
+    return *this;
+}
+
+inline void
+HeapValue::set(JSCompartment *comp, const Value &v)
+{
+#ifdef DEBUG
+    if (value.isMarkable()) {
+        js::gc::Cell *cell = (js::gc::Cell *)value.toGCThing();
+        JS_ASSERT(cell->compartment() == comp ||
+                  cell->compartment() == comp->rt->atomsCompartment);
+    }
+#endif
+
+    pre(comp);
+    value = v;
+    post(comp);
+}
+
+inline void
+HeapValue::boxNonDoubleFrom(JSValueType type, uint64 *out)
+{
+    pre();
+    value.boxNonDoubleFrom(type, out);
+    post();
+}
+
+inline
+HeapId::HeapId(jsid id)
+    : value(id)
+{
+    post();
+}
+
+inline
+HeapId::~HeapId()
+{
+    pre();
+}
+
+inline void
+HeapId::init(jsid id)
+{
+    value = id;
+    post();
+}
+
+inline void
+HeapId::pre()
+{
+#ifdef JSGC_INCREMENTAL
+    if (JS_UNLIKELY(JSID_IS_OBJECT(value))) {
+        JSObject *obj = JSID_TO_OBJECT(value);
+        JSCompartment *comp = obj->compartment();
+        if (comp->needsBarrier())
+            js::gc::MarkObjectUnbarriered(comp->barrierTracer(), obj, "write barrier");
+    }
+#endif
+}
+
+inline void
+HeapId::post()
+{
+}
+
+inline HeapId &
+HeapId::operator=(jsid id)
+{
+    pre();
+    value = id;
+    post();
+    return *this;
+}
+
+inline HeapId &
+HeapId::operator=(const HeapId &v)
+{
+    pre();
+    value = v.value;
+    post();
+    return *this;
+}
+
+} /* namespace js */
+
+#endif /* jsgc_barrier_inl_h___ */
new file mode 100644
--- /dev/null
+++ b/js/src/gc/Barrier.h
@@ -0,0 +1,450 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*-
+ * vim: set ts=8 sw=4 et tw=78:
+ *
+ * ***** BEGIN LICENSE BLOCK *****
+ * Version: MPL 1.1/GPL 2.0/LGPL 2.1
+ *
+ * The contents of this file are subject to the Mozilla Public License Version
+ * 1.1 (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ * http://www.mozilla.org/MPL/
+ *
+ * Software distributed under the License is distributed on an "AS IS" basis,
+ * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
+ * for the specific language governing rights and limitations under the
+ * License.
+ *
+ * The Original Code is SpiderMonkey global object code.
+ *
+ * The Initial Developer of the Original Code is
+ * the Mozilla Foundation.
+ * Portions created by the Initial Developer are Copyright (C) 2011
+ * the Initial Developer. All Rights Reserved.
+ *
+ * Contributor(s):
+ *
+ * Alternatively, the contents of this file may be used under the terms of
+ * either of the GNU General Public License Version 2 or later (the "GPL"),
+ * or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
+ * in which case the provisions of the GPL or the LGPL are applicable instead
+ * of those above. If you wish to allow use of your version of this file only
+ * under the terms of either the GPL or the LGPL, and not to allow others to
+ * use your version of this file under the terms of the MPL, indicate your
+ * decision by deleting the provisions above and replace them with the notice
+ * and other provisions required by the GPL or the LGPL. If you do not delete
+ * the provisions above, a recipient may use your version of this file under
+ * the terms of any one of the MPL, the GPL or the LGPL.
+ *
+ * ***** END LICENSE BLOCK ***** */
+
+#ifndef jsgc_barrier_h___
+#define jsgc_barrier_h___
+
+#include "jsapi.h"
+#include "jscell.h"
+
+#include "js/HashTable.h"
+
+/*
+ * A write barrier is a mechanism used by incremental or generation GCs to
+ * ensure that every value that needs to be marked is marked. In general, the
+ * write barrier should be invoked whenever a write can cause the set of things
+ * traced through by the GC to change. This includes:
+ *   - writes to object properties
+ *   - writes to array slots
+ *   - writes to fields like JSObject::lastProp that we trace through
+ *   - writes to fields in private data, like JSGenerator::obj
+ *   - writes to non-markable fields like JSObject::private that point to
+ *     markable data
+ * The last category is the trickiest. Even though the private pointers does not
+ * point to a GC thing, changing the private pointer may change the set of
+ * objects that are traced by the GC. Therefore it needs a write barrier.
+ *
+ * Every barriered write should have the following form:
+ *   <pre-barrier>
+ *   obj->field = value; // do the actual write
+ *   <post-barrier>
+ * The pre-barrier is used for incremental GC and the post-barrier is for
+ * generational GC.
+ *
+ *                               PRE-BARRIER
+ *
+ * To understand the pre-barrier, let's consider how incremental GC works. The
+ * GC itself is divided into "slices". Between each slice, JS code is allowed to
+ * run. Each slice should be short so that the user doesn't notice the
+ * interruptions. In our GC, the structure of the slices is as follows:
+ *
+ * 1. ... JS work, which leads to a request to do GC ...
+ * 2. [first GC slice, which performs all root marking and possibly more marking]
+ * 3. ... more JS work is allowed to run ...
+ * 4. [GC mark slice, which runs entirely in drainMarkStack]
+ * 5. ... more JS work ...
+ * 6. [GC mark slice, which runs entirely in drainMarkStack]
+ * 7. ... more JS work ...
+ * 8. [GC marking finishes; sweeping done non-incrementally; GC is done]
+ * 9. ... JS continues uninterrupted now that GC is finishes ...
+ *
+ * Of course, there may be a different number of slices depending on how much
+ * marking is to be done.
+ *
+ * The danger inherent in this scheme is that the JS code in steps 3, 5, and 7
+ * might change the heap in a way that causes the GC to collect an object that
+ * is actually reachable. The write barrier prevents this from happening. We use
+ * a variant of incremental GC called "snapshot at the beginning." This approach
+ * guarantees the invariant that if an object is reachable in step 2, then we
+ * will mark it eventually. The name comes from the idea that we take a
+ * theoretical "snapshot" of all reachable objects in step 2; all objects in
+ * that snapshot should eventually be marked. (Note that the write barrier
+ * verifier code takes an actual snapshot.)
+ *
+ * The basic correctness invariant of a snapshot-at-the-beginning collector is
+ * that any object reachable at the end of the GC (step 9) must either:
+ *   (1) have been reachable at the beginning (step 2) and thus in the snapshot
+ *   (2) or must have been newly allocated, in steps 3, 5, or 7.
+ * To deal with case (2), any objects allocated during an incremental GC are
+ * automatically marked black.
+ *
+ * This strategy is actually somewhat conservative: if an object becomes
+ * unreachable between steps 2 and 8, it would be safe to collect it. We won't,
+ * mainly for simplicity. (Also, note that the snapshot is entirely
+ * theoretical. We don't actually do anything special in step 2 that we wouldn't
+ * do in a non-incremental GC.
+ *
+ * It's the pre-barrier's job to maintain the snapshot invariant. Consider the
+ * write "obj->field = value". Let the prior value of obj->field be
+ * value0. Since it's possible that value0 may have been what obj->field
+ * contained in step 2, when the snapshot was taken, the barrier marks
+ * value0. Note that it only does this if we're in the middle of an incremental
+ * GC. Since this is rare, the cost of the write barrier is usually just an
+ * extra branch.
+ *
+ * In practice, we implement the pre-barrier differently based on the type of
+ * value0. E.g., see JSObject::writeBarrierPre, which is used if obj->field is
+ * a JSObject*. It takes value0 as a parameter.
+ *
+ *                                POST-BARRIER
+ *
+ * These are not yet implemented. Once we get generational GC, they will allow
+ * us to keep track of pointers from non-nursery space into the nursery.
+ *
+ *                            IMPLEMENTATION DETAILS
+ *
+ * Since it would be awkward to change every write to memory into a function
+ * call, this file contains a bunch of C++ classes and templates that use
+ * operator overloading to take care of barriers automatically. In many cases,
+ * all that's necessary to make some field be barriered is to replace
+ *     Type *field;
+ * with
+ *     HeapPtr<Type> field;
+ * There are also special classes HeapValue and HeapId, which barrier js::Value
+ * and jsid, respectively.
+ *
+ * One additional note: not all object writes need to be barriered. Writes to
+ * newly allocated objects do not need a barrier as long as the GC is not
+ * allowed to run in between the allocation and the write. 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, and that no GCs have taken place between the
+ * object allocation and the assignment.
+ */
+
+namespace js {
+
+/*
+ * Ideally, we would like to make the argument to functions like MarkShape be a
+ * HeapPtr<const js::Shape>. That would ensure that we don't forget to
+ * barrier any fields that we mark through. However, that would prohibit us from
+ * passing in a derived class like HeapPtr<js::EmptyShape>.
+ *
+ * To overcome the problem, we make the argument to MarkShape be a
+ * MarkablePtr<const js::Shape>. And we allow conversions from HeapPtr<T>
+ * to MarkablePtr<U> as long as T can be converted to U.
+ */
+template<class T>
+class MarkablePtr
+{
+  public:
+    T *value;
+
+    explicit MarkablePtr(T *value) : value(value) {}
+};
+
+template<class T, typename Unioned = uintptr_t>
+class HeapPtr
+{
+    union {
+        T *value;
+        Unioned other;
+    };
+
+  public:
+    HeapPtr() : value(NULL) {}
+    explicit HeapPtr(T *v) : value(v) { post(); }
+    explicit HeapPtr(const HeapPtr<T> &v) : value(v.value) { post(); }
+
+    ~HeapPtr() { pre(); }
+
+    /* Use this to install a ptr into a newly allocated object. */
+    void init(T *v) {
+        value = v;
+        post();
+    }
+
+    /* Use to set the pointer to NULL. */
+    void clear() {
+	pre();
+	value = NULL;
+    }
+
+    /* Use this if the automatic coercion to T* isn't working. */
+    T *get() const { return value; }
+
+    /*
+     * Use these if you want to change the value without invoking the barrier.
+     * Obviously this is dangerous unless you know the barrier is not needed.
+     */
+    T **unsafeGet() { return &value; }
+    void unsafeSet(T *v) { value = v; }
+
+    Unioned *unsafeGetUnioned() { return &other; }
+
+    HeapPtr<T, Unioned> &operator=(T *v) {
+        pre();
+        value = v;
+        post();
+        return *this;
+    }
+
+    HeapPtr<T, Unioned> &operator=(const HeapPtr<T> &v) {
+        pre();
+        value = v.value;
+        post();
+        return *this;
+    }
+
+    T &operator*() const { return *value; }
+    T *operator->() const { return value; }
+
+    operator T*() const { return value; }
+
+    /*
+     * This coerces to MarkablePtr<U> as long as T can coerce to U. See the
+     * comment for MarkablePtr above.
+     */
+    template<class U>
+    operator MarkablePtr<U>() const { return MarkablePtr<U>(value); }
+
+  private:
+    void pre() { T::writeBarrierPre(value); }
+    void post() { T::writeBarrierPost(value, (void *)&value); }
+
+    /* Make this friend so it can access pre() and post(). */
+    template<class T1, class T2>
+    friend inline void
+    BarrieredSetPair(JSCompartment *comp,
+                     HeapPtr<T1> &v1, T1 *val1,
+                     HeapPtr<T2> &v2, T2 *val2);
+};
+
+/*
+ * This is a hack for RegExpStatics::updateFromMatch. It allows us to do two
+ * barriers with only one branch to check if we're in an incremental GC.
+ */
+template<class T1, class T2>
+static inline void
+BarrieredSetPair(JSCompartment *comp,
+                 HeapPtr<T1> &v1, T1 *val1,
+                 HeapPtr<T2> &v2, T2 *val2)
+{
+    if (T1::needWriteBarrierPre(comp)) {
+        v1.pre();
+        v2.pre();
+    }
+    v1.unsafeSet(val1);
+    v2.unsafeSet(val2);
+    v1.post();
+    v2.post();
+}
+
+typedef HeapPtr<JSObject> HeapPtrObject;
+typedef HeapPtr<JSFunction> HeapPtrFunction;
+typedef HeapPtr<JSString> HeapPtrString;
+typedef HeapPtr<JSScript> HeapPtrScript;
+typedef HeapPtr<Shape> HeapPtrShape;
+typedef HeapPtr<const Shape> HeapPtrConstShape;
+typedef HeapPtr<JSXML> HeapPtrXML;
+
+/* Useful for hashtables with a HeapPtr as key. */
+template<class T>
+struct HeapPtrHasher
+{
+    typedef HeapPtr<T> Key;
+    typedef T *Lookup;
+
+    static HashNumber hash(Lookup obj) { return DefaultHasher<T *>::hash(obj); }
+    static bool match(const Key &k, Lookup l) { return k.get() == l; }
+};
+
+/* Specialized hashing policy for HeapPtrs. */
+template <class T>
+struct DefaultHasher< HeapPtr<T> >: HeapPtrHasher<T> { };
+
+class HeapValue
+{
+    Value value;
+
+  public:
+    explicit HeapValue() : value(UndefinedValue()) {}
+    explicit inline HeapValue(const Value &v);
+    explicit inline HeapValue(const HeapValue &v);
+
+    inline ~HeapValue();
+
+    inline void init(const Value &v);
+
+    inline HeapValue &operator=(const Value &v);
+    inline HeapValue &operator=(const HeapValue &v);
+
+    /*
+     * This is a faster version of operator=. Normally, operator= has to
+     * determine the compartment of the value before it can decide whether to do
+     * the barrier. If you already know the compartment, it's faster to pass it
+     * in.
+     */
+    inline void set(JSCompartment *comp, const Value &v);
+
+    const Value &get() const { return value; }
+    operator const Value &() const { return value; }
+
+    bool isMarkable() const { return value.isMarkable(); }
+    bool isMagic(JSWhyMagic why) const { return value.isMagic(why); }
+    bool isUndefined() const { return value.isUndefined(); }
+    bool isObject() const { return value.isObject(); }
+    bool isGCThing() const { return value.isGCThing(); }
+    bool isTrue() const { return value.isTrue(); }
+    bool isFalse() const { return value.isFalse(); }
+    bool isInt32() const { return value.isInt32(); }
+    bool isNull() const { return value.isNull(); }
+
+    JSObject &toObject() const { return value.toObject(); }
+    JSObject *toObjectOrNull() const { return value.toObjectOrNull(); }
+    void *toGCThing() const { return value.toGCThing(); }
+    double toDouble() const { return value.toDouble(); }
+    int32 toInt32() const { return value.toInt32(); }
+    JSString *toString() const { return value.toString(); }
+    bool toBoolean() const { return value.toBoolean(); }
+    double toNumber() const { return value.toNumber(); }
+
+    unsigned gcKind() const { return value.gcKind(); }
+
+    inline void boxNonDoubleFrom(JSValueType type, uint64 *out);
+
+    uint64 asRawBits() const { return value.asRawBits(); }
+
+#ifdef DEBUG
+    JSWhyMagic whyMagic() const { return value.whyMagic(); }
+#endif
+
+    static inline void writeBarrierPre(const Value &v);
+    static inline void writeBarrierPost(const Value &v, void *addr);
+
+    static inline void writeBarrierPre(JSCompartment *comp, const Value &v);
+    static inline void writeBarrierPost(JSCompartment *comp, const Value &v, void *addr);
+
+  private:
+    inline void pre();
+    inline void post();
+
+    inline void pre(JSCompartment *comp);
+    inline void post(JSCompartment *comp);
+};
+
+static inline const Value *
+Valueify(const HeapValue *array)
+{
+    JS_ASSERT(sizeof(HeapValue) == sizeof(Value));
+    return (const Value *)array;
+}
+
+class HeapValueArray
+{
+    HeapValue *array;
+
+  public:
+    HeapValueArray(HeapValue *array) : array(array) {}
+
+    operator const Value *() const { return Valueify(array); }
+    operator HeapValue *() const { return array; }
+
+    HeapValueArray operator +(int offset) const { return HeapValueArray(array + offset); }
+    HeapValueArray operator +(uint32 offset) const { return HeapValueArray(array + offset); }
+};
+
+class HeapId
+{
+    jsid value;
+
+  public:
+    explicit HeapId() : value(JSID_VOID) {}
+    explicit inline HeapId(jsid id);
+
+    inline ~HeapId();
+
+    inline void init(jsid id);
+
+    inline HeapId &operator=(jsid id);
+    inline HeapId &operator=(const HeapId &v);
+
+    bool operator==(jsid id) const { return value == id; }
+    bool operator!=(jsid id) const { return value != id; }
+
+    jsid get() const { return value; }
+    operator jsid() const { return value; }
+
+  private:
+    inline void pre();
+    inline void post();
+
+    HeapId(const HeapId &v);
+};
+
+/*
+ * Incremental GC requires that weak pointers have read barriers. This is mostly
+ * an issue for empty shapes stored in JSCompartment. The problem happens when,
+ * during an incremental GC, some JS code stores one of the compartment's empty
+ * shapes into an object already marked black. Normally, this would not be a
+ * problem, because the empty shape would have been part of the initial snapshot
+ * when the GC started. However, since this is a weak pointer, it isn't. So we
+ * may collect the empty shape even though a live object points to it. To fix
+ * this, we mark these empty shapes black whenever they get read out.
+ */
+template<class T>
+class ReadBarriered
+{
+    T *value;
+
+  public:
+    ReadBarriered(T *value) : value(value) {}
+
+    T *get() const {
+        if (!value)
+            return NULL;
+        T::readBarrier(value);
+        return value;
+    }
+
+    operator T*() const { return get(); }
+
+    T *unsafeGet() { return value; }
+
+    void set(T *v) { value = v; }
+
+    operator bool() { return !!value; }
+
+    template<class U>
+    operator MarkablePtr<U>() const { return MarkablePtr<U>(value); }
+};
+
+}
+
+#endif /* jsgc_barrier_h___ */
--- a/js/src/jit-test/jit_test.py
+++ b/js/src/jit-test/jit_test.py
@@ -262,47 +262,50 @@ def print_tinderbox(label, test, message
         result += ": " + message
     print result
 
 def run_tests(tests, test_dir, lib_dir, shell_args):
     pb = None
     if not OPTIONS.hide_progress and not OPTIONS.show_cmd:
         try:
             from progressbar import ProgressBar
-            pb = ProgressBar('', len(tests), 16)
+            pb = ProgressBar('', len(tests), 24)
         except ImportError:
             pass
 
     failures = []
+    timeouts = 0
     complete = False
     doing = 'before starting'
     try:
         for i, test in enumerate(tests):
             doing = 'on %s'%test.path
             ok, out, err, code, timed_out = run_test(test, lib_dir, shell_args)
             doing = 'after %s'%test.path
 
             if not ok:
                 failures.append([ test, out, err, code, timed_out ])
+            if timed_out:
+                timeouts += 1
 
             if OPTIONS.tinderbox:
                 if ok:
                     print_tinderbox("TEST-PASS", test);
                 else:
                     lines = [ _ for _ in out.split('\n') + err.split('\n')
                               if _ != '' ]
                     if len(lines) >= 1:
                         msg = lines[-1]
                     else:
                         msg = ''
                     print_tinderbox("TEST-UNEXPECTED-FAIL", test, msg);
 
             n = i + 1
             if pb:
-                pb.label = '[%4d|%4d|%4d]'%(n - len(failures), len(failures), n)
+                pb.label = '[%4d|%4d|%4d|%4d]'%(n - len(failures), len(failures), timeouts, n)
                 pb.update(n)
         complete = True
     except KeyboardInterrupt:
         print_tinderbox("TEST-UNEXPECTED-FAIL", test);
 
     if pb:
         pb.finish()
 
new file mode 100644
--- /dev/null
+++ b/js/src/jit-test/tests/basic/testBug701227.js
@@ -0,0 +1,1 @@
+(function f() { try {} catch(e) { let x } }).toString()
new file mode 100644
--- /dev/null
+++ b/js/src/jit-test/tests/basic/testBug701239.js
@@ -0,0 +1,1 @@
+(function f(w) { for([w] in 1) {} }).toString();
new file mode 100644
--- /dev/null
+++ b/js/src/jit-test/tests/basic/testBug701244.js
@@ -0,0 +1,1 @@
+(function f({length}) {}).toString();
--- a/js/src/jsapi-tests/testArgumentsObject.cpp
+++ b/js/src/jsapi-tests/testArgumentsObject.cpp
@@ -1,16 +1,18 @@
 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*-
  * vim: set ts=8 sw=4 et tw=99:
  */
 
 #include "tests.h"
 
 #include "vm/Stack-inl.h"
 
+#include "jsobjinlines.h"
+
 using namespace js;
 
 static const char NORMAL_ZERO[] =
     "function f() { return arguments; }";
 static const char NORMAL_ONE[] =
     "function f(a) { return arguments; }";
 static const char NORMAL_TWO[] =
     "function f(a, b) { return arguments; }";
--- a/js/src/jsapi-tests/testBug604087.cpp
+++ b/js/src/jsapi-tests/testBug604087.cpp
@@ -3,16 +3,18 @@
  *
  * Tests JS_TransplantObject
  */
 
 #include "tests.h"
 #include "jsobj.h"
 #include "jswrapper.h"
 
+#include "jsobjinlines.h"
+
 struct OuterWrapper : js::Wrapper
 {
     OuterWrapper() : Wrapper(0) {}
 
     virtual bool isOuterWindow() {
         return true;
     }
 
--- a/js/src/jsapi-tests/testConservativeGC.cpp
+++ b/js/src/jsapi-tests/testConservativeGC.cpp
@@ -2,28 +2,30 @@
 #include "jsobj.h"
 #include "vm/String.h"
 
 BEGIN_TEST(testConservativeGC)
 {
     jsval v2;
     EVAL("({foo: 'bar'});", &v2);
     CHECK(JSVAL_IS_OBJECT(v2));
-    JSObject objCopy = *JSVAL_TO_OBJECT(v2);
+    char objCopy[sizeof(JSObject)];
+    memcpy(&objCopy, JSVAL_TO_OBJECT(v2), sizeof(JSObject));
 
     jsval v3;
     EVAL("String(Math.PI);", &v3);
     CHECK(JSVAL_IS_STRING(v3));
     JSString strCopy = *JSVAL_TO_STRING(v3);
 
     jsval tmp;
     EVAL("({foo2: 'bar2'});", &tmp);
     CHECK(JSVAL_IS_OBJECT(tmp));
     JSObject *obj2 = JSVAL_TO_OBJECT(tmp);
-    JSObject obj2Copy = *obj2;
+    char obj2Copy[sizeof(JSObject)];
+    memcpy(&obj2Copy, obj2, sizeof(JSObject));
 
     EVAL("String(Math.sqrt(3));", &tmp);
     CHECK(JSVAL_IS_STRING(tmp));
     JSString *str2 = JSVAL_TO_STRING(tmp);
     JSString str2Copy = *str2;
 
     tmp = JSVAL_NULL;
 
@@ -31,20 +33,20 @@ BEGIN_TEST(testConservativeGC)
 
     EVAL("var a = [];\n"
          "for (var i = 0; i != 10000; ++i) {\n"
          "a.push(i + 0.1, [1, 2], String(Math.sqrt(i)), {a: i});\n"
          "}", &tmp);
 
     JS_GC(cx);
 
-    checkObjectFields(&objCopy, JSVAL_TO_OBJECT(v2));
+    checkObjectFields((JSObject *)objCopy, JSVAL_TO_OBJECT(v2));
     CHECK(!memcmp(&strCopy, JSVAL_TO_STRING(v3), sizeof(strCopy)));
 
-    checkObjectFields(&obj2Copy, obj2);
+    checkObjectFields((JSObject *)obj2Copy, obj2);
     CHECK(!memcmp(&str2Copy, str2, sizeof(str2Copy)));
 
     return true;
 }
 
 bool checkObjectFields(JSObject *savedCopy, JSObject *obj)
 {
     /* Ignore fields which are unstable across GCs. */
--- a/js/src/jsapi-tests/testIndexToString.cpp
+++ b/js/src/jsapi-tests/testIndexToString.cpp
@@ -4,16 +4,18 @@
 
 #include "tests.h"
 
 #include "jscntxt.h"
 #include "jscompartment.h"
 #include "jsnum.h"
 #include "jsstr.h"
 
+#include "jsobjinlines.h"
+
 #include "vm/String-inl.h"
 
 using namespace mozilla;
 
 template<size_t N> JSFlatString *
 NewString(JSContext *cx, const jschar (&chars)[N])
 {
     return js_NewStringCopyN(cx, chars, N);
--- a/js/src/jsapi.cpp
+++ b/js/src/jsapi.cpp
@@ -91,16 +91,17 @@
 
 #include "jsatominlines.h"
 #include "jsinferinlines.h"
 #include "jsobjinlines.h"
 #include "jsscopeinlines.h"
 #include "jsscriptinlines.h"
 
 #include "vm/RegExpObject-inl.h"
+#include "vm/RegExpStatics-inl.h"
 #include "vm/Stack-inl.h"
 #include "vm/String-inl.h"
 
 #if ENABLE_YARR_JIT
 #include "assembler/jit/ExecutableAllocator.h"
 #include "methodjit/Logging.h"
 #endif
 
@@ -652,17 +653,18 @@ JSRuntime::JSRuntime()
     gcKeepAtoms(0),
     gcBytes(0),
     gcTriggerBytes(0),
     gcLastBytes(0),
     gcMaxBytes(0),
     gcMaxMallocBytes(0),
     gcEmptyArenaPoolLifespan(0),
     gcNumber(0),
-    gcMarkingTracer(NULL),
+    gcIncrementalTracer(NULL),
+    gcVerifyData(NULL),
     gcChunkAllocationSinceLastGC(false),
     gcNextFullGCTime(0),
     gcJitReleaseTime(0),
     gcMode(JSGC_MODE_GLOBAL),
     gcIsNeeded(0),
     gcWeakMapList(NULL),
     gcStats(thisFromCtor()),
     gcTriggerCompartment(NULL),
@@ -1322,17 +1324,17 @@ Class dummy_class = {
 
 } /*namespace js */
 
 JS_PUBLIC_API(JSCrossCompartmentCall *)
 JS_EnterCrossCompartmentCallScript(JSContext *cx, JSScript *target)
 {
     CHECK_REQUEST(cx);
     JS_ASSERT(!target->isCachedEval);
-    GlobalObject *global = target->u.globalObject;
+    GlobalObject *global = target->globalObject;
     if (!global) {
         SwitchToCompartment sc(cx, target->compartment());
         global = GlobalObject::create(cx, &dummy_class);
         if (!global)
             return NULL;
     }
     return JS_EnterCrossCompartmentCall(cx, global);
 }
@@ -1947,32 +1949,28 @@ JS_EnumerateStandardClasses(JSContext *c
         {
                 return JS_FALSE;
         }
     }
 
     return JS_TRUE;
 }
 
-namespace js {
-
-JSIdArray *
+static JSIdArray *
 NewIdArray(JSContext *cx, jsint length)
 {
     JSIdArray *ida;
 
     ida = (JSIdArray *)
         cx->calloc_(offsetof(JSIdArray, vector) + length * sizeof(jsval));
     if (ida)
         ida->length = length;
     return ida;
 }
 
-}
-
 /*
  * Unlike realloc(3), this function frees ida on failure.
  */
 static JSIdArray *
 SetIdArrayLength(JSContext *cx, JSIdArray *ida, jsint length)
 {
     JSIdArray *rida;
 
@@ -1995,17 +1993,17 @@ AddAtomToArray(JSContext *cx, JSAtom *at
     i = *ip;
     length = ida->length;
     if (i >= length) {
         ida = SetIdArrayLength(cx, ida, JS_MAX(length * 2, 8));
         if (!ida)
             return NULL;
         JS_ASSERT(i < ida->length);
     }
-    ida->vector[i] = ATOM_TO_JSID(atom);
+    ida->vector[i].init(ATOM_TO_JSID(atom));
     *ip = i + 1;
     return ida;
 }
 
 static JSIdArray *
 EnumerateIfResolved(JSContext *cx, JSObject *obj, JSAtom *atom, JSIdArray *ida,
                     jsint *ip, JSBool *foundp)
 {
@@ -2326,20 +2324,25 @@ JS_SetExtraGCRootsTracer(JSRuntime *rt, 
 
 JS_PUBLIC_API(void)
 JS_TraceRuntime(JSTracer *trc)
 {
     TraceRuntime(trc);
 }
 
 JS_PUBLIC_API(void)
+JS_TraceChildren(JSTracer *trc, void *thing, JSGCTraceKind kind)
+{
+    js::TraceChildren(trc, thing, kind);
+}
+
+JS_PUBLIC_API(void)
 JS_CallTracer(JSTracer *trc, void *thing, JSGCTraceKind kind)
 {
-    JS_ASSERT(thing);
-    MarkKind(trc, thing, kind);
+    js::CallTracer(trc, thing, kind);
 }
 
 #ifdef DEBUG
 
 #ifdef HAVE_XPCONNECT
 #include "dump_xpc.h"
 #endif
 
@@ -2739,16 +2742,17 @@ JS_IsGCMarkingTracer(JSTracer *trc)
 JS_PUBLIC_API(void)
 JS_CompartmentGC(JSContext *cx, JSCompartment *comp)
 {
     /* We cannot GC the atoms compartment alone; use a full GC instead. */
     JS_ASSERT(comp != cx->runtime->atomsCompartment);
 
     LeaveTrace(cx);
 
+    js::gc::VerifyBarriers(cx, true);
     js_GC(cx, comp, GC_NORMAL, gcstats::PUBLIC_API);
 }
 
 JS_PUBLIC_API(void)
 JS_GC(JSContext *cx)
 {
     JS_CompartmentGC(cx, NULL);
 }
@@ -2777,18 +2781,18 @@ JS_SetGCCallbackRT(JSRuntime *rt, JSGCCa
     rt->gcCallback = cb;
     return oldcb;
 }
 
 JS_PUBLIC_API(JSBool)
 JS_IsAboutToBeFinalized(JSContext *cx, void *thing)
 {
     JS_ASSERT(thing);
-    JS_ASSERT(!cx->runtime->gcMarkingTracer);
-    return IsAboutToBeFinalized(cx, thing);
+    JS_ASSERT(!cx->runtime->gcIncrementalTracer);
+    return IsAboutToBeFinalized(cx, (gc::Cell *)thing);
 }
 
 JS_PUBLIC_API(void)
 JS_SetGCParameter(JSRuntime *rt, JSGCParamKey key, uint32 value)
 {
     switch (key) {
       case JSGC_MAX_BYTES:
         rt->gcMaxBytes = value;
@@ -2937,16 +2941,29 @@ JS_SetNativeStackQuota(JSContext *cx, si
         JS_ASSERT(stackBase >= stackSize);
         cx->stackLimit = stackBase - (stackSize - 1);
     }
 #endif
 }
 
 /************************************************************************/
 
+JS_PUBLIC_API(jsint)
+JS_IdArrayLength(JSContext *cx, JSIdArray *ida)
+{
+    return ida->length;
+}
+
+JS_PUBLIC_API(jsid)
+JS_IdArrayGet(JSContext *cx, JSIdArray *ida, jsint index)
+{
+    JS_ASSERT(index >= 0 && index < ida->length);
+    return ida->vector[index];
+}
+
 JS_PUBLIC_API(void)
 JS_DestroyIdArray(JSContext *cx, JSIdArray *ida)
 {
     cx->free_(ida);
 }
 
 JS_PUBLIC_API(JSBool)
 JS_ValueToId(JSContext *cx, jsval v, jsid *idp)
@@ -4100,22 +4117,26 @@ prop_iter_finalize(JSContext *cx, JSObje
 static void
 prop_iter_trace(JSTracer *trc, JSObject *obj)
 {
     void *pdata = obj->getPrivate();
     if (!pdata)
         return;
 
     if (obj->getSlot(JSSLOT_ITER_INDEX).toInt32() < 0) {
-        /* Native case: just mark the next property to visit. */
-        MarkShape(trc, (Shape *)pdata, "prop iter shape");
+        /*
+         * Native case: just mark the next property to visit. We don't need a
+         * barrier here because the pointer is updated via setPrivate, which
+         * always takes a barrier.
+         */
+        MarkShapeUnbarriered(trc, (Shape *)pdata, "prop iter shape");
     } else {
         /* Non-native case: mark each id in the JSIdArray private. */
         JSIdArray *ida = (JSIdArray *) pdata;
-        MarkIdRange(trc, ida->length, ida->vector, "prop iter");
+        MarkIdRange(trc, ida->vector, ida->vector + ida->length, "prop iter");
     }
 }
 
 static Class prop_iter_class = {
     "PropertyIterator",
     JSCLASS_HAS_PRIVATE | JSCLASS_HAS_RESERVED_SLOTS(1),
     JS_PropertyStub,         /* addProperty */
     JS_PropertyStub,         /* delProperty */
@@ -4133,29 +4154,29 @@ static Class prop_iter_class = {
     NULL,           /* hasInstance */
     prop_iter_trace
 };
 
 JS_PUBLIC_API(JSObject *)
 JS_NewPropertyIterator(JSContext *cx, JSObject *obj)
 {
     JSObject *iterobj;
-    const void *pdata;
+    void *pdata;
     jsint index;
     JSIdArray *ida;
 
     CHECK_REQUEST(cx);
     assertSameCompartment(cx, obj);
     iterobj = NewNonFunction<WithProto::Class>(cx, &prop_iter_class, NULL, obj);
     if (!iterobj)
         return NULL;
 
     if (obj->isNative()) {
         /* Native case: start with the last property in obj. */
-        pdata = obj->lastProperty();
+        pdata = (void *)obj->lastProperty();
         index = -1;
     } else {
         /*
          * Non-native case: enumerate a JSIdArray and keep it via private.
          *
          * Note: we have to make sure that we root obj around the call to
          * JS_Enumerate to protect against multiple allocations under it.
          */
@@ -4163,17 +4184,17 @@ JS_NewPropertyIterator(JSContext *cx, JS
         ida = JS_Enumerate(cx, obj);
         if (!ida)
             return NULL;
         pdata = ida;
         index = ida->length;
     }
 
     /* iterobj cannot escape to other threads here. */
-    iterobj->setPrivate(const_cast<void *>(pdata));
+    iterobj->setPrivate(pdata);
     iterobj->setSlot(JSSLOT_ITER_INDEX, Int32Value(index));
     return iterobj;
 }
 
 JS_PUBLIC_API(JSBool)
 JS_NextProperty(JSContext *cx, JSObject *iterobj, jsid *idp)
 {
     jsint i;
@@ -4426,17 +4447,17 @@ JS_CloneFunctionObject(JSContext *cx, JS
                 return NULL;
             }
             obj = obj->getParent();
         }
 
         Value v;
         if (!obj->getGeneric(cx, r.front().propid, &v))
             return NULL;
-        clone->getFlatClosureUpvars()[i] = v;
+        clone->setFlatClosureUpvar(i, v);
     }
 
     return clone;
 }
 
 JS_PUBLIC_API(JSObject *)
 JS_GetFunctionObject(JSFunction *fun)
 {
@@ -4877,19 +4898,19 @@ JS_CompileFileHandle(JSContext *cx, JSOb
     JS_THREADSAFE_ASSERT(cx->compartment != cx->runtime->atomsCompartment);
     return JS_CompileFileHandleForPrincipals(cx, obj, filename, file, NULL);
 }
 
 JS_PUBLIC_API(JSObject *)
 JS_GetGlobalFromScript(JSScript *script)
 {
     JS_ASSERT(!script->isCachedEval);
-    JS_ASSERT(script->u.globalObject);
-
-    return script->u.globalObject;
+    JS_ASSERT(script->globalObject);
+
+    return script->globalObject;
 }
 
 static JSFunction *
 CompileUCFunctionForPrincipalsCommon(JSContext *cx, JSObject *obj,
                                      JSPrincipals *principals, const char *name,
                                      uintN nargs, const char **argnames,
                                      const jschar *chars, size_t length,
                                      const char *filename, uintN lineno, JSVersion version)
@@ -6340,19 +6361,20 @@ JS_ClearContextThread(JSContext *cx)
     return 0;
 #endif
 }
 
 #ifdef JS_GC_ZEAL
 JS_PUBLIC_API(void)
 JS_SetGCZeal(JSContext *cx, uint8 zeal, uint32 frequency, JSBool compartment)
 {
+    bool schedule = zeal >= js::gc::ZealAllocThreshold && zeal < js::gc::ZealVerifierThreshold;
     cx->runtime->gcZeal_ = zeal;
     cx->runtime->gcZealFrequency = frequency;
-    cx->runtime->gcNextScheduled = zeal >= 2 ? frequency : 0;
+    cx->runtime->gcNextScheduled = schedule ? frequency : 0;
     cx->runtime->gcDebugCompartmentGC = !!compartment;
 }
 
 JS_PUBLIC_API(void)
 JS_ScheduleGC(JSContext *cx, uint32 count, JSBool compartment)
 {
     cx->runtime->gcNextScheduled = count;
     cx->runtime->gcDebugCompartmentGC = !!compartment;
@@ -6362,16 +6384,73 @@ JS_ScheduleGC(JSContext *cx, uint32 coun
 JS_FRIEND_API(void *)
 js_GetCompartmentPrivate(JSCompartment *compartment)
 {
     return compartment->data;
 }
 
 /************************************************************************/
 
+JS_PUBLIC_API(void)
+JS_RegisterReference(void **ref)
+{
+}
+
+JS_PUBLIC_API(void)
+JS_ModifyReference(void **ref, void *newval)
+{
+    // XPConnect uses the lower bits of its JSObject refs for evil purposes,
+    // so we need to fix this.
+    void *thing = *ref;
+    *ref = newval;
+    thing = (void *)((uintptr_t)thing & ~7);
+    if (!thing)
+        return;
+    uint32 kind = GetGCThingTraceKind(thing);
+    if (kind == JSTRACE_OBJECT)
+        JSObject::writeBarrierPre((JSObject *) thing);
+    else if (kind == JSTRACE_STRING)
+        JSString::writeBarrierPre((JSString *) thing);
+    else
+        JS_NOT_REACHED("invalid trace kind");
+}
+
+JS_PUBLIC_API(void)
+JS_UnregisterReference(void **ref)
+{
+    // For now we just want to trigger a write barrier.
+    JS_ModifyReference(ref, NULL);
+}
+
+JS_PUBLIC_API(void)
+JS_RegisterValue(jsval *val)
+{
+}
+
+JS_PUBLIC_API(void)
+JS_ModifyValue(jsval *val, jsval newval)
+{
+    HeapValue::writeBarrierPre(*val);
+    *val = newval;
+}
+
+JS_PUBLIC_API(void)
+JS_UnregisterValue(jsval *val)
+{
+    JS_ModifyValue(val, JSVAL_VOID);
+}
+
+JS_PUBLIC_API(JSTracer *)
+JS_GetIncrementalGCTracer(JSRuntime *rt)
+{
+    return rt->gcIncrementalTracer;
+}
+
+/************************************************************************/
+
 #if !defined(STATIC_EXPORTABLE_JS_API) && !defined(STATIC_JS_API) && defined(XP_WIN)
 
 #include "jswin.h"
 
 /*
  * Initialization routine for the JS DLL.
  */
 BOOL WINAPI DllMain (HINSTANCE hDLL, DWORD dwReason, LPVOID lpReserved)
--- a/js/src/jsapi.h
+++ b/js/src/jsapi.h
@@ -2693,16 +2693,17 @@ JSVAL_TRACE_KIND(jsval v)
  * If eagerlyTraceWeakMaps is true, when we trace a WeakMap visit all
  * of its mappings.  This should be used in cases where the tracer
  * wants to use the existing liveness of entries.
  */
 typedef void
 (* JSTraceCallback)(JSTracer *trc, void *thing, JSGCTraceKind kind);
 
 struct JSTracer {
+    JSRuntime           *runtime;
     JSContext           *context;
     JSTraceCallback     callback;
     JSTraceNamePrinter  debugPrinter;
     const void          *debugPrintArg;
     size_t              debugPrintIndex;
     JSBool              eagerlyTraceWeakMaps;
 };
 
@@ -2793,16 +2794,17 @@ JS_CallTracer(JSTracer *trc, void *thing
         JS_CALL_TRACER((trc), str_, JSTRACE_STRING, name);                    \
     JS_END_MACRO
 
 /*
  * API for JSTraceCallback implementations.
  */
 # define JS_TRACER_INIT(trc, cx_, callback_)                                  \
     JS_BEGIN_MACRO                                                            \
+        (trc)->runtime = (cx_)->runtime;                                      \
         (trc)->context = (cx_);                                               \
         (trc)->callback = (callback_);                                        \
         (trc)->debugPrinter = NULL;                                           \
         (trc)->debugPrintArg = NULL;                                          \
         (trc)->debugPrintIndex = (size_t)-1;                                  \
         (trc)->eagerlyTraceWeakMaps = JS_TRUE;                                \
     JS_END_MACRO
 
@@ -2838,16 +2840,98 @@ JS_GetTraceEdgeName(JSTracer *trc, char 
  */
 extern JS_PUBLIC_API(JSBool)
 JS_DumpHeap(JSContext *cx, FILE *fp, void* startThing, JSGCTraceKind kind,
             void *thingToFind, size_t maxDepth, void *thingToIgnore);
 
 #endif
 
 /*
+ * Write barrier API.
+ *
+ * This API is used to inform SpiderMonkey of pointers to JS GC things in the
+ * malloc heap. There is no need to use this API unless incremental GC is
+ * enabled. When they are, the requirements for using the API are as follows:
+ *
+ * All pointers to JS GC things from the malloc heap must be registered and
+ * unregistered with the API functions below. This is *in addition* to the
+ * normal rooting and tracing that must be done normally--these functions will
+ * not take care of rooting for you.
+ *
+ * Besides registration, the JS_ModifyReference function must be called to
+ * change the value of these references. You should not change them using
+ * assignment.
+ *
+ * To avoid the headache of using these API functions, the JSBarrieredObjectPtr
+ * C++ class is provided--simply replace your JSObject* with a
+ * JSBarrieredObjectPtr. It will take care of calling the registration and
+ * modification APIs.
+ *
+ * For more explanation, see the comment in gc/Barrier.h.
+ */
+
+/* These functions are to be used for objects and strings. */
+extern JS_PUBLIC_API(void)
+JS_RegisterReference(void **ref);
+
+extern JS_PUBLIC_API(void)
+JS_ModifyReference(void **ref, void *newval);
+
+extern JS_PUBLIC_API(void)
+JS_UnregisterReference(void **ref);
+
+/* These functions are for values. */
+extern JS_PUBLIC_API(void)
+JS_RegisterValue(jsval *val);
+
+extern JS_PUBLIC_API(void)
+JS_ModifyValue(jsval *val, jsval newval);
+
+extern JS_PUBLIC_API(void)
+JS_UnregisterValue(jsval *val);
+
+extern JS_PUBLIC_API(JSTracer *)
+JS_GetIncrementalGCTracer(JSRuntime *rt);
+
+#ifdef __cplusplus
+JS_END_EXTERN_C
+
+namespace JS {
+
+class HeapPtrObject
+{
+    JSObject *value;
+
+  public:
+    HeapPtrObject() : value(NULL) { JS_RegisterReference((void **) &value); }
+
+    HeapPtrObject(JSObject *obj) : value(obj) { JS_RegisterReference((void **) &value); }
+
+    ~HeapPtrObject() { JS_UnregisterReference((void **) &value); }
+
+    void init(JSObject *obj) { value = obj; }
+
+    JSObject *get() const { return value; }
+
+    HeapPtrObject &operator=(JSObject *obj) {
+        JS_ModifyReference((void **) &value, obj);
+        return *this;
+    }
+
+    JSObject &operator*() const { return *value; }
+    JSObject *operator->() const { return value; }
+    operator JSObject *() const { return value; }
+};
+
+} /* namespace JS */
+
+JS_BEGIN_EXTERN_C
+#endif
+
+/*
  * Garbage collector API.
  */
 extern JS_PUBLIC_API(void)
 JS_GC(JSContext *cx);
 
 extern JS_PUBLIC_API(void)
 JS_CompartmentGC(JSContext *cx, JSCompartment *comp);
 
@@ -3110,20 +3194,21 @@ struct JSClass {
                                          (((clasp)->flags                     \
                                            >> JSCLASS_CACHED_PROTO_SHIFT)     \
                                           & JSCLASS_CACHED_PROTO_MASK))
 
 /* Initializer for unused members of statically initialized JSClass structs. */
 #define JSCLASS_NO_INTERNAL_MEMBERS     0,{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}
 #define JSCLASS_NO_OPTIONAL_MEMBERS     0,0,0,0,0,0,0,JSCLASS_NO_INTERNAL_MEMBERS
 
-struct JSIdArray {
-    jsint length;
-    jsid  vector[1];    /* actually, length jsid words */
-};
+extern JS_PUBLIC_API(jsint)
+JS_IdArrayLength(JSContext *cx, JSIdArray *ida);
+
+extern JS_PUBLIC_API(jsid)
+JS_IdArrayGet(JSContext *cx, JSIdArray *ida, jsint index);
 
 extern JS_PUBLIC_API(void)
 JS_DestroyIdArray(JSContext *cx, JSIdArray *ida);
 
 extern JS_PUBLIC_API(JSBool)
 JS_ValueToId(JSContext *cx, jsval v, jsid *idp);
 
 extern JS_PUBLIC_API(JSBool)
--- a/js/src/jsarray.cpp
+++ b/js/src/jsarray.cpp
@@ -644,24 +644,23 @@ array_length_setter(JSContext *cx, JSObj
     if (obj->isDenseArray()) {
         /*
          * Don't reallocate if we're not actually shrinking our slots. If we do
          * shrink slots here, shrink the initialized length too.  This permits us
          * us to disregard length when reading from arrays as long we are within
          * the initialized capacity.
          */
         jsuint oldcap = obj->getDenseArrayCapacity();
+        jsuint oldinit = obj->getDenseArrayInitializedLength();
+        if (oldinit > newlen)
+            obj->setDenseArrayInitializedLength(newlen);
         if (oldcap > newlen)
             obj->shrinkDenseArrayElements(cx, newlen);
-        jsuint oldinit = obj->getDenseArrayInitializedLength();
-        if (oldinit > newlen) {
-            obj->setDenseArrayInitializedLength(newlen);
-            if (!cx->typeInferenceEnabled())
-                obj->backfillDenseArrayHoles(cx);
-        }
+        if (oldinit > newlen && !cx->typeInferenceEnabled())
+            obj->backfillDenseArrayHoles(cx);
     } else if (oldlen - newlen < (1 << 24)) {
         do {
             --oldlen;
             if (!JS_CHECK_OPERATION_LIMIT(cx)) {
                 obj->setArrayLength(cx, oldlen + 1);
                 return false;
             }
             int deletion = DeleteArrayElement(cx, obj, oldlen, strict);
@@ -1335,18 +1334,21 @@ JSObject::makeDenseArraySlow(JSContext *
      * Save old map now, before calling InitScopeForObject. We'll have to undo
      * on error. This is gross, but a better way is not obvious. Note: the
      * exact contents of the array are not preserved on error.
      */
     js::Shape *oldMap = lastProp;
 
     /* Create a native scope. */
     gc::AllocKind kind = getAllocKind();
-    if (!InitScopeForObject(cx, this, &SlowArrayClass, getProto()->getNewType(cx), kind))
+    js::EmptyShape *empty = InitScopeForObject(cx, this, &SlowArrayClass,
+                                               getProto()->getNewType(cx), kind);
+    if (!empty)
         return false;
+    setMap(empty);
 
     backfillDenseArrayHoles(cx);
 
     uint32 arrayCapacity = getDenseArrayCapacity();
     uint32 arrayInitialized = getDenseArrayInitializedLength();
 
     /*
      * Adjust the slots to account for the different layout between dense
@@ -1362,30 +1364,30 @@ JSObject::makeDenseArraySlow(JSContext *
     }
     capacity = numFixedSlots() + arrayCapacity;
     clasp = &SlowArrayClass;
 
     /*
      * Root all values in the array during conversion, as SlowArrayClass only
      * protects up to its slot span.
      */
-    AutoValueArray autoArray(cx, slots, arrayInitialized);
+    AutoValueArray autoArray(cx, Valueify(slots), arrayInitialized);
 
     /* The initialized length is used iff this is a dense array. */
-    initializedLength = 0;
+    initializedLength() = 0;
     JS_ASSERT(newType == NULL);
 
     /*
      * Begin with the length property to share more of the property tree.
      * The getter/setter here will directly access the object's private value.
      */
     if (!AddLengthProperty(cx, this)) {
         setMap(oldMap);
         capacity = arrayCapacity;
-        initializedLength = arrayInitialized;
+        initializedLength() = arrayInitialized;
         clasp = &ArrayClass;
         return false;
     }
 
     /*
      * Create new properties pointing to existing elements. Pack the array to
      * remove holes, so that shapes use successive slots (as for other objects).
      */
@@ -1398,17 +1400,17 @@ JSObject::makeDenseArraySlow(JSContext *
         if (slots[i].isMagic(JS_ARRAY_HOLE))
             continue;
 
         setSlot(next, slots[i]);
 
         if (!addDataProperty(cx, id, next, JSPROP_ENUMERATE)) {
             setMap(oldMap);
             capacity = arrayCapacity;
-            initializedLength = arrayInitialized;
+            initializedLength() = arrayInitialized;
             clasp = &ArrayClass;
             return false;
         }
 
         next++;
     }
 
     clearSlotRange(next, capacity - next);
@@ -2492,17 +2494,17 @@ NewbornArrayPushImpl(JSContext *cx, JSOb
     JS_ASSERT(length <= obj->getDenseArrayCapacity());
 
     if (length == obj->getDenseArrayCapacity() && !obj->ensureSlots(cx, length + 1))
         return false;
 
     if (cx->typeInferenceEnabled())
         obj->setDenseArrayInitializedLength(length + 1);
     obj->setDenseArrayLength(length + 1);
-    obj->setDenseArrayElementWithType(cx, length, v);
+    obj->initDenseArrayElementWithType(cx, length, v);
     return true;
 }
 
 JSBool
 js_NewbornArrayPush(JSContext *cx, JSObject *obj, const Value &vp)
 {
     return NewbornArrayPushImpl(cx, obj, vp);
 }
@@ -2888,26 +2890,26 @@ array_splice(JSContext *cx, uintN argc, 
         uint32 sourceIndex = actualStart + actualDeleteCount;
         uint32 targetIndex = actualStart + itemCount;
         uint32 finalLength = len - actualDeleteCount + itemCount;
 
         if (CanOptimizeForDenseStorage(obj, 0, len, cx)) {
             /* Steps 12(a)-(b). */
             obj->moveDenseArrayElements(targetIndex, sourceIndex, len - sourceIndex);
 
-            /* Steps 12(c)-(d). */
-            obj->shrinkDenseArrayElements(cx, finalLength);
-
             /*
-             * The array's initialized length is now out of sync with the array
-             * elements: resynchronize it.
+             * Update the initialized length. Do so before shrinking so that we
+             * can apply the write barrier to the old slots.
              */
             if (cx->typeInferenceEnabled())
                 obj->setDenseArrayInitializedLength(finalLength);
 
+            /* Steps 12(c)-(d). */
+            obj->shrinkDenseArrayElements(cx, finalLength);
+
             /* Fix running enumerators for the deleted items. */
             if (!js_SuppressDeletedElements(cx, obj, finalLength, len))
                 return false;
         } else {
             /*
              * This is all very slow if the length is very large. We don't yet
              * have the ability to iterate in sorted order, so we just do the
              * pessimistic thing and let JS_CHECK_OPERATION_LIMIT handle the
@@ -3014,20 +3016,22 @@ mjit::stubs::ArrayConcatTwoArrays(VMFram
     JS_ASSERT(initlen2 == obj2->getArrayLength());
 
     /* No overflow here due to nslots limit. */
     uint32 len = initlen1 + initlen2;
 
     if (!result->ensureSlots(f.cx, len))
         THROW();
 
-    result->copyDenseArrayElements(0, obj1->getDenseArrayElements(), initlen1);
-    result->copyDenseArrayElements(initlen1, obj2->getDenseArrayElements(), initlen2);
-
+    JS_ASSERT(!result->getDenseArrayInitializedLength());
     result->setDenseArrayInitializedLength(len);
+
+    result->initDenseArrayElements(0, obj1->getDenseArrayElements(), initlen1);
+    result->initDenseArrayElements(initlen1, obj2->getDenseArrayElements(), initlen2);
+
     result->setDenseArrayLength(len);
 }
 #endif /* JS_METHODJIT */
 
 /*
  * Python-esque sequence operations.
  */
 JSBool
@@ -3915,17 +3919,17 @@ NewDenseCopiedArray(JSContext *cx, uint3
         return NULL;
 
     JS_ASSERT(obj->getDenseArrayCapacity() >= length);
 
     if (cx->typeInferenceEnabled())
         obj->setDenseArrayInitializedLength(vp ? length : 0);
 
     if (vp)
-        obj->copyDenseArrayElements(0, vp, length);
+        obj->initDenseArrayElements(0, vp, length);
 
     return obj;
 }
 
 #ifdef JS_TRACER
 JS_DEFINE_CALLINFO_2(extern, OBJECT, NewDenseEmptyArray, CONTEXT, OBJECT, 0,
                      nanojit::ACCSET_STORE_ANY)
 JS_DEFINE_CALLINFO_3(extern, OBJECT, NewDenseAllocatedArray, CONTEXT, UINT32, OBJECT, 0,
--- a/js/src/jsarray.h
+++ b/js/src/jsarray.h
@@ -50,17 +50,17 @@
 
 /* Small arrays are dense, no matter what. */
 const uintN MIN_SPARSE_INDEX = 256;
 
 inline uint32
 JSObject::getDenseArrayInitializedLength()
 {
     JS_ASSERT(isDenseArray());
-    return initializedLength;
+    return initializedLength();
 }
 
 inline bool
 JSObject::isPackedDenseArray()
 {
     JS_ASSERT(isDenseArray());
     return flags & PACKED_ARRAY;
 }
--- a/js/src/jsarrayinlines.h
+++ b/js/src/jsarrayinlines.h
@@ -43,17 +43,19 @@
 #include "jsinferinlines.h"
 #include "jsobjinlines.h"
 
 inline void
 JSObject::setDenseArrayInitializedLength(uint32 length)
 {
     JS_ASSERT(isDenseArray());
     JS_ASSERT(length <= getDenseArrayCapacity());
-    initializedLength = length;
+    uint32 cur = initializedLength();
+    prepareSlotRangeForOverwrite(length, cur);
+    initializedLength() = length;
 }
 
 inline void
 JSObject::markDenseArrayNotPacked(JSContext *cx)
 {
     JS_ASSERT(isDenseArray());
     if (flags & PACKED_ARRAY) {
         flags ^= PACKED_ARRAY;
@@ -72,22 +74,23 @@ inline void
 JSObject::ensureDenseArrayInitializedLength(JSContext *cx, uint32 index, uint32 extra)
 {
     /*
      * Ensure that the array's contents have been initialized up to index, and
      * mark the elements through 'index + extra' as initialized in preparation
      * for a write.
      */
     JS_ASSERT(index + extra <= capacity);
-    if (initializedLength < index) {
+    if (initializedLength() < index)
         markDenseArrayNotPacked(cx);
-        js::ClearValueRange(slots + initializedLength, index - initializedLength, true);
+
+    if (initializedLength() < index + extra) {
+        js::InitValueRange(slots + initializedLength(), index + extra - initializedLength(), true);
+        initializedLength() = index + extra;
     }
-    if (initializedLength < index + extra)
-        initializedLength = index + extra;
 }
 
 inline JSObject::EnsureDenseResult
 JSObject::ensureDenseArrayElements(JSContext *cx, uintN index, uintN extra)
 {
     JS_ASSERT(isDenseArray());
 
     uintN currentCapacity = numSlots();
--- a/js/src/jsatom.cpp
+++ b/js/src/jsatom.cpp
@@ -384,36 +384,36 @@ js_FinishCommonAtoms(JSContext *cx)
 {
     cx->runtime->emptyString = NULL;
     cx->runtime->atomState.junkAtoms();
 }
 
 void
 js_TraceAtomState(JSTracer *trc)
 {
-    JSRuntime *rt = trc->context->runtime;
+    JSRuntime *rt = trc->runtime;
     JSAtomState *state = &rt->atomState;
 
 #ifdef DEBUG
     size_t number = 0;
 #endif
 
     if (rt->gcKeepAtoms) {
         for (AtomSet::Range r = state->atoms.all(); !r.empty(); r.popFront()) {
             JS_SET_TRACING_INDEX(trc, "locked_atom", number++);
-            MarkString(trc, r.front().asPtr());
+            MarkAtom(trc, r.front().asPtr());
         }
     } else {
         for (AtomSet::Range r = state->atoms.all(); !r.empty(); r.popFront()) {
             AtomStateEntry entry = r.front();
             if (!entry.isTagged())
                 continue;
 
             JS_SET_TRACING_INDEX(trc, "interned_atom", number++);
-            MarkString(trc, entry.asPtr());
+            MarkAtom(trc, entry.asPtr());
         }
     }
 }
 
 void
 js_SweepAtomState(JSContext *cx)
 {
     JSAtomState *state = &cx->runtime->atomState;
--- a/js/src/jsatom.h
+++ b/js/src/jsatom.h
@@ -44,19 +44,25 @@
 #include "jsversion.h"
 #include "jsalloc.h"
 #include "jsapi.h"
 #include "jsprvtd.h"
 #include "jshash.h"
 #include "jspubtd.h"
 #include "jslock.h"
 
+#include "gc/Barrier.h"
 #include "js/HashTable.h"
 #include "vm/String.h"
 
+struct JSIdArray {
+    jsint length;
+    js::HeapId vector[1];    /* actually, length jsid words */
+};
+
 /* Engine-internal extensions of jsid */
 
 static JS_ALWAYS_INLINE jsid
 JSID_FROM_BITS(size_t bits)
 {
     jsid id;
     JSID_BITS(id) = bits;
     return id;
--- a/js/src/jscell.h
+++ b/js/src/jscell.h
@@ -74,17 +74,19 @@ enum AllocKind {
     FINALIZE_XML,
 #endif
     FINALIZE_SHORT_STRING,
     FINALIZE_STRING,
     FINALIZE_EXTERNAL_STRING,
     FINALIZE_LAST = FINALIZE_EXTERNAL_STRING
 };
 
-const size_t FINALIZE_LIMIT = FINALIZE_LAST + 1;
+static const unsigned FINALIZE_LIMIT = FINALIZE_LAST + 1;
+static const unsigned FINALIZE_OBJECT_LIMIT = FINALIZE_OBJECT_LAST + 1;
+static const unsigned FINALIZE_FUNCTION_AND_OBJECT_LIMIT = FINALIZE_FUNCTION_AND_OBJECT_LAST + 1;
 
 /*
  * Live objects are marked black. How many other additional colors are available
  * depends on the size of the GCThing. Objects marked gray are eligible for
  * cycle collection.
  */
 static const uint32 BLACK = 0;
 static const uint32 GRAY = 1;
--- a/js/src/jscntxt.cpp
+++ b/js/src/jscntxt.cpp
@@ -119,23 +119,26 @@ ThreadData::ThreadData()
 {
 #ifdef DEBUG
     noGCOrAllocationCheck = 0;
 #endif
 }
 
 ThreadData::~ThreadData()
 {
+    JS_ASSERT(!repCache);
+
     if (dtoaState)
         js_DestroyDtoaState(dtoaState);
 }
 
 bool
 ThreadData::init()
 {
+    JS_ASSERT(!repCache);
     return stackSpace.init() && !!(dtoaState = js_NewDtoaState());
 }
 
 void
 ThreadData::triggerOperationCallback(JSRuntime *rt)
 {
     /*
      * Use JS_ATOMIC_SET and JS_ATOMIC_INCREMENT in the hope that it ensures
@@ -167,19 +170,16 @@ ThreadData::createRegExpPrivateCache(JSR
 
     repCache = newCache;
     return repCache;
 }
 
 void
 ThreadData::purgeRegExpPrivateCache(JSRuntime *rt)
 {
-    if (!repCache)
-        return;
-
     rt->delete_<RegExpPrivateCache>(repCache);
     repCache = NULL;
 }
 
 } /* namespace js */
 
 JSScript *
 js_GetCurrentScript(JSContext *cx)
@@ -1596,17 +1596,17 @@ JSContext::purge()
         parseMapPool_ = NULL;
     }
 }
 
 #if defined(JS_TRACER) || defined(JS_METHODJIT)
 static bool
 ComputeIsJITBroken()
 {
-#ifndef ANDROID
+#if !defined(ANDROID) || defined(GONK)
     return false;
 #else  // ANDROID
     if (getenv("JS_IGNORE_JIT_BROKENNESS")) {
         return false;
     }
 
     std::string line;
 
--- a/js/src/jscntxt.h
+++ b/js/src/jscntxt.h
@@ -455,21 +455,23 @@ struct JSRuntime
     uint32              gcTriggerBytes;
     size_t              gcLastBytes;
     size_t              gcMaxBytes;
     size_t              gcMaxMallocBytes;
     uint32              gcEmptyArenaPoolLifespan;
     /* We access this without the GC lock, however a race will not affect correctness */
     volatile uint32     gcNumFreeArenas;
     uint32              gcNumber;
-    js::GCMarker        *gcMarkingTracer;
+    js::GCMarker        *gcIncrementalTracer;
+    void                *gcVerifyData;
     bool                gcChunkAllocationSinceLastGC;
     int64               gcNextFullGCTime;
     int64               gcJitReleaseTime;
     JSGCMode            gcMode;
+    volatile jsuword    gcBarrierFailed;
     volatile jsuword    gcIsNeeded;
     js::WeakMapBase     *gcWeakMapList;
     js::gcstats::Statistics gcStats;
 
     /* The reason that an interrupt-triggered GC should be called. */
     js::gcstats::Reason gcTriggerReason;
 
     /* Pre-allocated space for the GC mark stacks. Pointer type ensures alignment. */
@@ -517,28 +519,31 @@ struct JSRuntime
      * You can control these values in several ways:
      *   - Pass the -Z flag to the shell (see the usage info for details)
      *   - Call gczeal() or schedulegc() from inside shell-executed JS code
      *     (see the help for details)
      *
      * Additionally, if gzZeal_ == 1 then we perform GCs in select places
      * (during MaybeGC and whenever a GC poke happens). This option is mainly
      * useful to embedders.
+     *
+     * We use gcZeal_ == 4 to enable write barrier verification. See the comment
+     * in jsgc.cpp for more information about this.
      */
 #ifdef JS_GC_ZEAL
     int                 gcZeal_;
     int                 gcZealFrequency;
     int                 gcNextScheduled;
     bool                gcDebugCompartmentGC;
 
     int gcZeal() { return gcZeal_; }
 
     bool needZealousGC() {
         if (gcNextScheduled > 0 && --gcNextScheduled == 0) {
-            if (gcZeal() >= 2)
+            if (gcZeal() >= js::gc::ZealAllocThreshold && gcZeal() < js::gc::ZealVerifierThreshold)
                 gcNextScheduled = gcZealFrequency;
             return true;
         }
         return false;
     }
 #else
     int gcZeal() { return 0; }
     bool needZealousGC() { return false; }
@@ -2211,28 +2216,16 @@ js_RegenerateShapeForGC(JSRuntime *rt)
     return shape;
 }
 
 namespace js {
 
 /************************************************************************/
 
 static JS_ALWAYS_INLINE void
-ClearValueRange(Value *vec, uintN len, bool useHoles)
-{
-    if (useHoles) {
-        for (uintN i = 0; i < len; i++)
-            vec[i].setMagic(JS_ARRAY_HOLE);
-    } else {
-        for (uintN i = 0; i < len; i++)
-            vec[i].setUndefined();
-    }
-}
-
-static JS_ALWAYS_INLINE void
 MakeRangeGCSafe(Value *vec, size_t len)
 {
     PodZero(vec, len);
 }
 
 static JS_ALWAYS_INLINE void
 MakeRangeGCSafe(Value *beg, Value *end)
 {
@@ -2411,36 +2404,33 @@ class AutoShapeVector : public AutoVecto
         JS_GUARD_OBJECT_NOTIFIER_INIT;
     }
 
     JS_DECL_USE_GUARD_OBJECT_NOTIFIER
 };
 
 class AutoValueArray : public AutoGCRooter
 {
-    js::Value *start_;
+    const js::Value *start_;
     unsigned length_;
 
   public:
-    AutoValueArray(JSContext *cx, js::Value *start, unsigned length
+    AutoValueArray(JSContext *cx, const js::Value *start, unsigned length
                    JS_GUARD_OBJECT_NOTIFIER_PARAM)
         : AutoGCRooter(cx, VALARRAY), start_(start), length_(length)
     {
         JS_GUARD_OBJECT_NOTIFIER_INIT;
     }
 
-    Value *start() const { return start_; }
+    const Value *start() const { return start_; }
     unsigned length() const { return length_; }
 
     JS_DECL_USE_GUARD_OBJECT_NOTIFIER
 };
 
-JSIdArray *
-NewIdArray(JSContext *cx, jsint length);
-
 /*
  * Allocation policy that uses JSRuntime::malloc_ and friends, so that
  * memory pressure is properly accounted for. This is suitable for
  * long-lived objects owned by the JSRuntime.
  *
  * Since it doesn't hold a JSContext (those may not live long enough), it
  * can't report out-of-memory conditions itself; the caller must check for
  * OOM and take the appropriate action.
--- a/js/src/jscntxtinlines.h
+++ b/js/src/jscntxtinlines.h
@@ -110,17 +110,17 @@ class AutoNamespaceArray : protected Aut
         array.finish(context);
     }
 
     uint32 length() const { return array.length; }
 
   public:
     friend void AutoGCRooter::trace(JSTracer *trc);
 
-    JSXMLArray array;
+    JSXMLArray<JSObject> array;
 };
 
 #ifdef DEBUG
 class CompartmentChecker
 {
   private:
     JSContext *context;
     JSCompartment *compartment;
@@ -203,18 +203,18 @@ class CompartmentChecker
                     check(ida->vector[i]);
             }
         }
     }
 
     void check(JSScript *script) {
         if (script) {
             check(script->compartment());
-            if (!script->isCachedEval && script->u.globalObject)
-                check(script->u.globalObject);
+            if (!script->isCachedEval && script->globalObject)
+                check(script->globalObject);
         }
     }
 
     void check(StackFrame *fp) {
         check(&fp->scopeChain());
     }
 };
 
--- a/js/src/jscompartment.cpp
+++ b/js/src/jscompartment.cpp
@@ -53,29 +53,32 @@
 #include "assembler/jit/ExecutableAllocator.h"
 #include "yarr/BumpPointerAllocator.h"
 #include "methodjit/MethodJIT.h"
 #include "methodjit/PolyIC.h"
 #include "methodjit/MonoIC.h"
 #include "vm/Debugger.h"
 
 #include "jsgcinlines.h"
+#include "jsobjinlines.h"
 #include "jsscopeinlines.h"
 
 #if ENABLE_YARR_JIT
 #include "assembler/jit/ExecutableAllocator.h"
 #endif
 
 using namespace mozilla;
 using namespace js;
 using namespace js::gc;
 
 JSCompartment::JSCompartment(JSRuntime *rt)
   : rt(rt),
     principals(NULL),
+    needsBarrier_(false),
+    gcIncrementalTracer(NULL),
     gcBytes(0),
     gcTriggerBytes(0),
     gcLastBytes(0),
     hold(false),
     typeLifoAlloc(TYPE_LIFO_ALLOC_PRIMARY_CHUNK_SIZE),
 #ifdef JS_TRACER
     traceMonitor_(NULL),
 #endif
@@ -344,16 +347,26 @@ JSCompartment::wrap(JSContext *cx, JSStr
     AutoValueRooter tvr(cx, StringValue(*strp));
     if (!wrap(cx, tvr.addr()))
         return false;
     *strp = tvr.value().toString();
     return true;
 }
 
 bool
+JSCompartment::wrap(JSContext *cx, HeapPtrString *strp)
+{
+    AutoValueRooter tvr(cx, StringValue(*strp));
+    if (!wrap(cx, tvr.addr()))
+        return false;
+    *strp = tvr.value().toString();
+    return true;
+}
+
+bool
 JSCompartment::wrap(JSContext *cx, JSObject **objp)
 {
     if (!*objp)
         return true;
     AutoValueRooter tvr(cx, ObjectValue(**objp));
     if (!wrap(cx, tvr.addr()))
         return false;
     *objp = &tvr.value().toObject();
@@ -415,61 +428,61 @@ JSCompartment::wrap(JSContext *cx, AutoI
 /*
  * This method marks pointers that cross compartment boundaries. It should be
  * called only for per-compartment GCs, since full GCs naturally follow pointers
  * across compartments.
  */
 void
 JSCompartment::markCrossCompartmentWrappers(JSTracer *trc)
 {
-    JS_ASSERT(trc->context->runtime->gcCurrentCompartment);
+    JS_ASSERT(trc->runtime->gcCurrentCompartment);
 
     for (WrapperMap::Enum e(crossCompartmentWrappers); !e.empty(); e.popFront())
-        MarkValue(trc, e.front().key, "cross-compartment wrapper");
+        MarkRoot(trc, e.front().key, "cross-compartment wrapper");
 }
 
 void
 JSCompartment::markTypes(JSTracer *trc)
 {
     /*
      * Mark all scripts, type objects and singleton JS objects in the
      * compartment. These can be referred to directly by type sets, which we
      * cannot modify while code which depends on these type sets is active.
      */
     JS_ASSERT(activeAnalysis);
 
     for (CellIterUnderGC i(this, FINALIZE_SCRIPT); !i.done(); i.next()) {
         JSScript *script = i.get<JSScript>();
-        MarkScript(trc, script, "mark_types_script");
+        MarkRoot(trc, script, "mark_types_script");
     }
 
     for (size_t thingKind = FINALIZE_OBJECT0;
-         thingKind <= FINALIZE_FUNCTION_AND_OBJECT_LAST;
+         thingKind < FINALIZE_FUNCTION_AND_OBJECT_LIMIT;
          thingKind++) {
         for (CellIterUnderGC i(this, AllocKind(thingKind)); !i.done(); i.next()) {
             JSObject *object = i.get<JSObject>();
             if (!object->isNewborn() && object->hasSingletonType())
-                MarkObject(trc, *object, "mark_types_singleton");
+                MarkRoot(trc, object, "mark_types_singleton");
         }
     }
 
     for (CellIterUnderGC i(this, FINALIZE_TYPE_OBJECT); !i.done(); i.next())
-        MarkTypeObject(trc, i.get<types::TypeObject>(), "mark_types_scan");
+        MarkRoot(trc, i.get<types::TypeObject>(), "mark_types_scan");
 }
 
 void
 JSCompartment::sweep(JSContext *cx, bool releaseTypes)
 {
     /* Remove dead wrappers from the table. */
     for (WrapperMap::Enum e(crossCompartmentWrappers); !e.empty(); e.popFront()) {
-        JS_ASSERT_IF(IsAboutToBeFinalized(cx, e.front().key.toGCThing()) &&
-                     !IsAboutToBeFinalized(cx, e.front().value.toGCThing()),
+        JS_ASSERT_IF(IsAboutToBeFinalized(cx, e.front().key) &&
+                     !IsAboutToBeFinalized(cx, e.front().value),
                      e.front().key.isString());
-        if (IsAboutToBeFinalized(cx, e.front().key.toGCThing()) ||
-            IsAboutToBeFinalized(cx, e.front().value.toGCThing())) {
+        if (IsAboutToBeFinalized(cx, e.front().key) ||
+            IsAboutToBeFinalized(cx, e.front().value)) {
             e.removeFront();
         }
     }
 
     /* Remove dead empty shapes. */
     if (emptyArgumentsShape && IsAboutToBeFinalized(cx, emptyArgumentsShape))
         emptyArgumentsShape = NULL;
     if (emptyBlockShape && IsAboutToBeFinalized(cx, emptyBlockShape))
@@ -579,17 +592,17 @@ JSCompartment::purge(JSContext *cx)
      * not null when we have script owned by an object and not from the eval
      * cache.
      */
     for (size_t i = 0; i < ArrayLength(evalCache); ++i) {
         for (JSScript **listHeadp = &evalCache[i]; *listHeadp; ) {
             JSScript *script = *listHeadp;
             JS_ASSERT(GetGCThingTraceKind(script) == JSTRACE_SCRIPT);
             *listHeadp = NULL;
-            listHeadp = &script->u.evalHashLink;
+            listHeadp = &script->evalHashLink();
         }
     }
 
     nativeIterCache.purge();
     toSourceCache.destroyIfConstructed();
 
 #ifdef JS_TRACER
     /*
@@ -822,17 +835,17 @@ JSCompartment::markTrapClosuresIterative
     bool markedAny = false;
     JSContext *cx = trc->context;
     for (BreakpointSiteMap::Range r = breakpointSites.all(); !r.empty(); r.popFront()) {
         BreakpointSite *site = r.front().value;
 
         // Put off marking trap state until we know the script is live.
         if (site->trapHandler && !IsAboutToBeFinalized(cx, site->script)) {
             if (site->trapClosure.isMarkable() &&
-                IsAboutToBeFinalized(cx, site->trapClosure.toGCThing()))
+                IsAboutToBeFinalized(cx, site->trapClosure))
             {
                 markedAny = true;
             }
             MarkValue(trc, site->trapClosure, "trap closure");
         }
     }
     return markedAny;
 }
@@ -853,8 +866,15 @@ JSCompartment::sweepBreakpoints(JSContex
             if (scriptGone || IsAboutToBeFinalized(cx, bp->debugger->toJSObject()))
                 bp->destroy(cx, &e);
         }
         
         if (clearTrap)
             site->clearTrap(cx, &e);
     }
 }
+
+GCMarker *
+JSCompartment::createBarrierTracer()
+{
+    JS_ASSERT(!gcIncrementalTracer);
+    return NULL;
+}
--- a/js/src/jscompartment.h
+++ b/js/src/jscompartment.h
@@ -392,16 +392,30 @@ typedef HashSet<ScriptFilenameEntry *,
 } /* namespace js */
 
 struct JS_FRIEND_API(JSCompartment) {
     JSRuntime                    *rt;
     JSPrincipals                 *principals;
 
     js::gc::ArenaLists           arenas;
 
+    bool                         needsBarrier_;
+    js::GCMarker                 *gcIncrementalTracer;
+
+    bool needsBarrier() {
+        return needsBarrier_;
+    }
+
+    js::GCMarker *barrierTracer() {
+        JS_ASSERT(needsBarrier_);
+        if (gcIncrementalTracer)
+            return gcIncrementalTracer;
+        return createBarrierTracer();
+    }
+
     uint32                       gcBytes;
     uint32                       gcTriggerBytes;
     size_t                       gcLastBytes;
 
     bool                         hold;
     bool                         isSystemCompartment;
 
     /*
@@ -469,44 +483,47 @@ struct JS_FRIEND_API(JSCompartment) {
 #ifdef DEBUG
     /* Property metering. */
     jsrefcount                   livePropTreeNodes;
     jsrefcount                   totalPropTreeNodes;
     jsrefcount                   propTreeKidsChunks;
     jsrefcount                   liveDictModeNodes;
 #endif
 
+    typedef js::ReadBarriered<js::EmptyShape> BarrieredEmptyShape;
+    typedef js::ReadBarriered<const js::Shape> BarrieredShape;
+
     /*
      * Runtime-shared empty scopes for well-known built-in objects that lack
      * class prototypes (the usual locus of an emptyShape). Mnemonic: ABCDEW
      */
-    js::EmptyShape               *emptyArgumentsShape;
-    js::EmptyShape               *emptyBlockShape;
-    js::EmptyShape               *emptyCallShape;
-    js::EmptyShape               *emptyDeclEnvShape;
-    js::EmptyShape               *emptyEnumeratorShape;
-    js::EmptyShape               *emptyWithShape;
+    BarrieredEmptyShape          emptyArgumentsShape;
+    BarrieredEmptyShape          emptyBlockShape;
+    BarrieredEmptyShape          emptyCallShape;
+    BarrieredEmptyShape          emptyDeclEnvShape;
+    BarrieredEmptyShape          emptyEnumeratorShape;
+    BarrieredEmptyShape          emptyWithShape;
 
     typedef js::HashSet<js::EmptyShape *,
                         js::DefaultHasher<js::EmptyShape *>,
                         js::SystemAllocPolicy> EmptyShapeSet;
 
     EmptyShapeSet                emptyShapes;
 
     /*
      * Initial shapes given to RegExp and String objects, encoding the initial
      * sets of built-in instance properties and the fixed slots where they must
      * be stored (see JSObject::JSSLOT_(REGEXP|STRING)_*). Later property
      * additions may cause these shapes to not be used by a RegExp or String
      * (even along the entire shape parent chain, should the object go into
      * dictionary mode). But because all the initial properties are
      * non-configurable, they will always map to fixed slots.
      */
-    const js::Shape              *initialRegExpShape;
-    const js::Shape              *initialStringShape;
+    BarrieredShape               initialRegExpShape;
+    BarrieredShape               initialStringShape;
 
   private:
     enum { DebugFromC = 1, DebugFromJS = 2 };
 
     uintN                        debugModeBits;  // see debugMode() below
 
   public:
     js::NativeIterCache          nativeIterCache;
@@ -521,16 +538,17 @@ struct JS_FRIEND_API(JSCompartment) {
 
     bool init(JSContext *cx);
 
     /* Mark cross-compartment wrappers. */
     void markCrossCompartmentWrappers(JSTracer *trc);
 
     bool wrap(JSContext *cx, js::Value *vp);
     bool wrap(JSContext *cx, JSString **strp);
+    bool wrap(JSContext *cx, js::HeapPtrString *strp);
     bool wrap(JSContext *cx, JSObject **objp);
     bool wrapId(JSContext *cx, jsid *idp);
     bool wrap(JSContext *cx, js::PropertyOp *op);
     bool wrap(JSContext *cx, js::StrictPropertyOp *op);
     bool wrap(JSContext *cx, js::PropertyDescriptor *desc);
     bool wrap(JSContext *cx, js::AutoIdVector &props);
 
     void markTypes(JSTracer *trc);
@@ -619,16 +637,18 @@ struct JS_FRIEND_API(JSCompartment) {
                                                   js::GlobalObject *scriptGlobal);
     void clearBreakpointsIn(JSContext *cx, js::Debugger *dbg, JSScript *script, JSObject *handler);
     void clearTraps(JSContext *cx, JSScript *script);
     bool markTrapClosuresIteratively(JSTracer *trc);
 
   private:
     void sweepBreakpoints(JSContext *cx);
 
+    js::GCMarker *createBarrierTracer();
+
   public:
     js::WatchpointMap *watchpointMap;
 };
 
 #define JS_PROPERTY_TREE(cx)    ((cx)->compartment->propertyTree)
 
 /*
  * N.B. JS_ON_TRACE(cx) is true if JIT code is on the stack in the current
--- a/js/src/jsdbgapi.cpp
+++ b/js/src/jsdbgapi.cpp
@@ -2134,29 +2134,63 @@ JS_DumpBytecode(JSContext *cx, JSScript 
 
     fprintf(stdout, "--- SCRIPT %s:%d ---\n", script->filename, script->lineno);
     js_Disassemble(cx, script, true, &sprinter);
     fputs(sprinter.base, stdout);
     fprintf(stdout, "--- END SCRIPT %s:%d ---\n", script->filename, script->lineno);
 #endif
 }
 
+extern JS_PUBLIC_API(void)
+JS_DumpPCCounts(JSContext *cx, JSScript *script)
+{
+#if defined(DEBUG)
+    JS_ASSERT(script->pcCounters);
+
+    LifoAlloc lifoAlloc(1024);
+    Sprinter sprinter;
+    INIT_SPRINTER(cx, &sprinter, &lifoAlloc, 0);
+
+    fprintf(stdout, "--- SCRIPT %s:%d ---\n", script->filename, script->lineno);
+    js_DumpPCCounts(cx, script, &sprinter);
+    fputs(sprinter.base, stdout);
+    fprintf(stdout, "--- END SCRIPT %s:%d ---\n", script->filename, script->lineno);
+#endif
+}
+
 static void
 DumpBytecodeScriptCallback(JSContext *cx, void *data, void *thing,
                            JSGCTraceKind traceKind, size_t thingSize)
 {
     JS_ASSERT(traceKind == JSTRACE_SCRIPT);
     JS_ASSERT(!data);
     JSScript *script = static_cast<JSScript *>(thing);
     JS_DumpBytecode(cx, script);
 }
 
 JS_PUBLIC_API(void)
 JS_DumpCompartmentBytecode(JSContext *cx)
 {
     IterateCells(cx, cx->compartment, gc::FINALIZE_SCRIPT, NULL, DumpBytecodeScriptCallback);
 }
 
+static void
+DumpPCCountsScriptCallback(JSContext *cx, void *data, void *thing,
+                           JSGCTraceKind traceKind, size_t thingSize)
+{
+    JS_ASSERT(traceKind == JSTRACE_SCRIPT);
+    JS_ASSERT(!data);
+    JSScript *script = static_cast<JSScript *>(thing);
+    if (script->pcCounters)
+        JS_DumpPCCounts(cx, script);
+}
+
+JS_PUBLIC_API(void)
+JS_DumpCompartmentPCCounts(JSContext *cx)
+{
+    IterateCells(cx, cx->compartment, gc::FINALIZE_SCRIPT, NULL, DumpPCCountsScriptCallback);
+}
+
 JS_PUBLIC_API(JSObject *)
 JS_UnwrapObject(JSObject *obj)
 {
     return UnwrapObject(obj);
 }
--- a/js/src/jsdbgapi.h
+++ b/js/src/jsdbgapi.h
@@ -607,14 +607,20 @@ JS_GetFunctionCallback(JSContext *cx);
 #endif /* MOZ_TRACE_JSCALLS */
 
 extern JS_PUBLIC_API(void)
 JS_DumpBytecode(JSContext *cx, JSScript *script);
 
 extern JS_PUBLIC_API(void)
 JS_DumpCompartmentBytecode(JSContext *cx);
 
+extern JS_PUBLIC_API(void)
+JS_DumpPCCounts(JSContext *cx, JSScript *script);
+
+extern JS_PUBLIC_API(void)
+JS_DumpCompartmentPCCounts(JSContext *cx);
+
 extern JS_PUBLIC_API(JSObject *)
 JS_UnwrapObject(JSObject *obj);
 
 JS_END_EXTERN_C
 
 #endif /* jsdbgapi_h___ */
--- a/js/src/jsexn.cpp
+++ b/js/src/jsexn.cpp
@@ -64,18 +64,20 @@
 #include "jsscope.h"
 #include "jsscript.h"
 #include "jswrapper.h"
 
 #include "vm/GlobalObject.h"
 
 #include "jsinferinlines.h"
 #include "jsobjinlines.h"
+#include "jsstrinlines.h"
 
 #include "vm/Stack-inl.h"
+#include "vm/String-inl.h"
 
 using namespace mozilla;
 using namespace js;
 using namespace js::gc;
 using namespace js::types;
 
 /* Forward declarations for ErrorClass's initializer. */
 static JSBool
@@ -108,27 +110,27 @@ Class js::ErrorClass = {
     NULL,                 /* call        */
     NULL,                 /* construct   */
     NULL,                 /* xdrObject   */
     NULL,                 /* hasInstance */
     exn_trace
 };
 
 typedef struct JSStackTraceElem {
-    JSString            *funName;
+    js::HeapPtrString   funName;
     size_t              argc;
     const char          *filename;
     uintN               ulineno;
 } JSStackTraceElem;
 
 typedef struct JSExnPrivate {
     /* A copy of the JSErrorReport originally generated. */
     JSErrorReport       *errorReport;
-    JSString            *message;
-    JSString            *filename;
+    js::HeapPtrString   message;
+    js::HeapPtrString   filename;
     uintN               lineno;
     size_t              stackDepth;
     intN                exnType;
     JSStackTraceElem    stackElems[1];
 } JSExnPrivate;
 
 static JSString *
 StackTraceToString(JSContext *cx, JSExnPrivate *priv);
@@ -323,22 +325,22 @@ InitExnPrivate(JSContext *cx, JSObject *
                 if (!checkAccess(cx, &fp->callee(), callerid, JSACC_READ, &v))
                     break;
             }
 
             if (!frames.growBy(1))
                 return false;
             JSStackTraceElem &frame = frames.back();
             if (fp->isNonEvalFunctionFrame()) {
-                frame.funName = fp->fun()->atom ? fp->fun()->atom : cx->runtime->emptyString;
+                frame.funName.init(fp->fun()->atom ? fp->fun()->atom : cx->runtime->emptyString);
                 frame.argc = fp->numActualArgs();
                 if (!fp->forEachCanonicalActualArg(AppendArg(values)))
                     return false;
             } else {
-                frame.funName = NULL;
+                frame.funName.init(NULL);
                 frame.argc = 0;
             }
             if (fp->isScriptFrame()) {
                 frame.filename = fp->script()->filename;
                 frame.ulineno = js_FramePCToLineNumber(cx, fp, i.pc());
             } else {
                 frame.ulineno = 0;
                 frame.filename = NULL;
@@ -352,34 +354,37 @@ InitExnPrivate(JSContext *cx, JSObject *
     size_t nbytes = offsetof(JSExnPrivate, stackElems) +
                     frames.length() * sizeof(JSStackTraceElem) +
                     values.length() * sizeof(Value);
 
     JSExnPrivate *priv = (JSExnPrivate *)cx->malloc_(nbytes);
     if (!priv)
         return false;
 
+    /* Initialize to zero so that write barriers don't witness undefined values. */
+    memset(priv, 0, nbytes);
+
     if (report) {
         /*
          * Construct a new copy of the error report struct. We can't use the
          * error report struct that was passed in, because it's allocated on
          * the stack, and also because it may point to transient data in the
          * TokenStream.
          */
         priv->errorReport = CopyErrorReport(cx, report);
         if (!priv->errorReport) {
             cx->free_(priv);
             return false;
         }
     } else {
         priv->errorReport = NULL;
     }
 
-    priv->message = message;
-    priv->filename = filename;
+    priv->message.init(message);
+    priv->filename.init(filename);
     priv->lineno = lineno;
     priv->stackDepth = frames.length();
     priv->exnType = exnType;
 
     JSStackTraceElem *framesDest = priv->stackElems;
     Value *valuesDest = reinterpret_cast<Value *>(framesDest + frames.length());
     JS_ASSERT(valuesDest == GetStackTraceValueBuffer(priv));
 
@@ -417,18 +422,19 @@ exn_trace(JSTracer *trc, JSObject *obj)
             if (elem->funName)
                 MarkString(trc, elem->funName, "stack trace function name");
             if (IS_GC_MARKING_TRACER(trc) && elem->filename)
                 js_MarkScriptFilename(elem->filename);
             vcount += elem->argc;
         }
         vp = GetStackTraceValueBuffer(priv);
         for (i = 0; i != vcount; ++i, ++vp) {
+            /* This value is read-only, so it's okay for it to be Unbarriered. */
             v = *vp;
-            JS_CALL_VALUE_TRACER(trc, v, "stack trace argument");
+            MarkValueUnbarriered(trc, v, "stack trace argument");
         }
     }
 }
 
 static void
 exn_finalize(JSContext *cx, JSObject *obj)
 {
     if (JSExnPrivate *priv = GetExnPrivate(obj)) {
@@ -489,18 +495,16 @@ exn_resolve(JSContext *cx, JSObject *obj
         }
 
         atom = cx->runtime->atomState.stackAtom;
         if (str == atom) {
             stack = StackTraceToString(cx, priv);
             if (!stack)
                 return false;
 
-            /* Allow to GC all things that were used to build stack trace. */
-            priv->stackDepth = 0;
             prop = js_stack_str;
             v = STRING_TO_JSVAL(stack);
             attrs = JSPROP_ENUMERATE;
             goto define;
         }
     }
     return true;
 
@@ -1337,21 +1341,21 @@ js_CopyErrorObject(JSContext *cx, JSObje
     // Copy each field. Don't bother copying the stack elements.
     if (priv->errorReport) {
         copy->errorReport = CopyErrorReport(cx, priv->errorReport);
         if (!copy->errorReport)
             return NULL;
     } else {
         copy->errorReport = NULL;
     }
-    copy->message = priv->message;
+    copy->message.init(priv->message);
     if (!cx->compartment->wrap(cx, &copy->message))
         return NULL;
     JS::Anchor<JSString *> messageAnchor(copy->message);
-    copy->filename = priv->filename;
+    copy->filename.init(priv->filename);
     if (!cx->compartment->wrap(cx, &copy->filename))
         return NULL;
     JS::Anchor<JSString *> filenameAnchor(copy->filename);
     copy->lineno = priv->lineno;
     copy->stackDepth = 0;
     copy->exnType = priv->exnType;
 
     // Create the Error object.
--- a/js/src/jsfun.cpp
+++ b/js/src/jsfun.cpp
@@ -146,42 +146,45 @@ ArgumentsObject::create(JSContext *cx, u
     EmptyShape *emptyArgumentsShape = EmptyShape::getEmptyArgumentsShape(cx);
     if (!emptyArgumentsShape)
         return NULL;
 
     ArgumentsData *data = (ArgumentsData *)
         cx->malloc_(offsetof(ArgumentsData, slots) + argc * sizeof(Value));
     if (!data)
         return NULL;
-    SetValueRangeToUndefined(data->slots, argc);
+
+    data->callee.init(ObjectValue(callee));
+    InitValueRange(data->slots, argc, false);
 
     /* Can't fail from here on, so initialize everything in argsobj. */
     obj->init(cx, callee.getFunctionPrivate()->inStrictMode()
               ? &StrictArgumentsObjectClass
               : &NormalArgumentsObjectClass,
               type, proto->getParent(), NULL, false);
-    obj->setMap(emptyArgumentsShape);
+    obj->initMap(emptyArgumentsShape);
 
     ArgumentsObject *argsobj = obj->asArguments();
 
     JS_ASSERT(UINT32_MAX > (uint64(argc) << PACKED_BITS_COUNT));
-    argsobj->setInitialLength(argc);
-
-    argsobj->setCalleeAndData(callee, data);
+    argsobj->initInitialLength(argc);
+    argsobj->initData(data);
 
     return argsobj;
 }
 
 struct STATIC_SKIP_INFERENCE PutArg
 {
-    PutArg(Value *dst) : dst(dst) {}
-    Value *dst;
+    PutArg(JSCompartment *comp, HeapValue *dst) : dst(dst), compartment(comp) {}
+    HeapValue *dst;
+    JSCompartment *compartment;
     bool operator()(uintN, Value *src) {
+        JS_ASSERT(dst->isMagic(JS_ARGS_HOLE) || dst->isUndefined());
         if (!dst->isMagic(JS_ARGS_HOLE))
-            *dst = *src;
+            dst->set(compartment, *src);
         ++dst;
         return true;
     }
 };
 
 JSObject *
 js_GetArgsObject(JSContext *cx, StackFrame *fp)
 {
@@ -215,31 +218,32 @@ js_GetArgsObject(JSContext *cx, StackFra
      * actual parameter values.  It is the caller's responsibility to get the
      * arguments object before any parameters are modified!  (The emitter
      * ensures this by synthesizing an arguments access at the start of any
      * strict mode function that contains an assignment to a parameter, or
      * that calls eval.)  Non-strict mode arguments use the frame pointer to
      * retrieve up-to-date parameter values.
      */
     if (argsobj->isStrictArguments())
-        fp->forEachCanonicalActualArg(PutArg(argsobj->data()->slots));
+        fp->forEachCanonicalActualArg(PutArg(cx->compartment, argsobj->data()->slots));
     else
         argsobj->setStackFrame(fp);
 
     fp->setArgsObj(*argsobj);
     return argsobj;
 }
 
 void
 js_PutArgsObject(StackFrame *fp)
 {
     ArgumentsObject &argsobj = fp->argsObj();
     if (argsobj.isNormalArguments()) {
         JS_ASSERT(argsobj.maybeStackFrame() == fp);
-        fp->forEachCanonicalActualArg(PutArg(argsobj.data()->slots));
+        JSCompartment *comp = fp->scopeChain().compartment();
+        fp->forEachCanonicalActualArg(PutArg(comp, argsobj.data()->slots));
         argsobj.setStackFrame(NULL);
     } else {
         JS_ASSERT(!argsobj.maybeStackFrame());
     }
 }
 
 #ifdef JS_TRACER
 
@@ -277,20 +281,21 @@ js_PutArgumentsOnTrace(JSContext *cx, JS
     JS_ASSERT(argsobj->onTrace());
 
     /*
      * TraceRecorder::putActivationObjects builds a single, contiguous array of
      * the arguments, regardless of whether #actuals > #formals so there is no
      * need to worry about actual vs. formal arguments.
      */
     Value *srcend = argv + argsobj->initialLength();
-    Value *dst = argsobj->data()->slots;
+    HeapValue *dst = argsobj->data()->slots;
+    JSCompartment *comp = cx->compartment;
     for (Value *src = argv; src < srcend; ++src, ++dst) {
         if (!dst->isMagic(JS_ARGS_HOLE))
-            *dst = *src;
+            dst->set(comp, *src);
     }
 
     argsobj->clearOnTrace();
     return true;
 }
 JS_DEFINE_CALLINFO_3(extern, BOOL, js_PutArgumentsOnTrace, CONTEXT, OBJECT, VALUEPTR, 0,
                      nanojit::ACCSET_STORE_ANY)
 
@@ -596,35 +601,32 @@ args_finalize(JSContext *cx, JSObject *o
  * generator object), we use the JSFRAME_FLOATING_GENERATOR flag, which is only
  * set on the StackFrame kept in the generator object's JSGenerator.
  */
 static inline void
 MaybeMarkGenerator(JSTracer *trc, JSObject *obj)
 {
 #if JS_HAS_GENERATORS
     StackFrame *fp = (StackFrame *) obj->getPrivate();
-    if (fp && fp->isFloatingGenerator()) {
-        JSObject *genobj = js_FloatingFrameToGenerator(fp)->obj;
-        MarkObject(trc, *genobj, "generator object");
-    }
+    if (fp && fp->isFloatingGenerator())
+        MarkObject(trc, js_FloatingFrameToGenerator(fp)->obj, "generator object");
 #endif
 }
 
 static void
 args_trace(JSTracer *trc, JSObject *obj)
 {
     ArgumentsObject *argsobj = obj->asArguments();
     if (argsobj->onTrace()) {
         JS_ASSERT(!argsobj->isStrictArguments());
         return;
     }
 
     ArgumentsData *data = argsobj->data();
-    if (data->callee.isObject())
-        MarkObject(trc, data->callee.toObject(), js_callee_str);
+    MarkValue(trc, data->callee, js_callee_str);
     MarkValueRange(trc, argsobj->initialLength(), data->slots, js_arguments_str);
 
     MaybeMarkGenerator(trc, argsobj);
 }
 
 /*
  * The classes below collaborate to lazily reflect and synchronize actual
  * argument values, argument count, and callee function object stored in a
@@ -702,17 +704,17 @@ NewDeclEnvObject(JSContext *cx, StackFra
     JSObject *envobj = js_NewGCObject(cx, FINALIZE_OBJECT2);
     if (!envobj)
         return NULL;
 
     EmptyShape *emptyDeclEnvShape = EmptyShape::getEmptyDeclEnvShape(cx);
     if (!emptyDeclEnvShape)
         return NULL;
     envobj->init(cx, &DeclEnvClass, &emptyTypeObject, &fp->scopeChain(), fp, false);
-    envobj->setMap(emptyDeclEnvShape);
+    envobj->initMap(emptyDeclEnvShape);
 
     return envobj;
 }
 
 namespace js {
 
 CallObject *
 CreateFunCallObject(JSContext *cx, StackFrame *fp)
@@ -781,17 +783,17 @@ js_PutCallObject(StackFrame *fp)
     CallObject &callobj = fp->callObj().asCall();
     JS_ASSERT(callobj.maybeStackFrame() == fp);
     JS_ASSERT_IF(fp->isEvalFrame(), fp->isStrictEvalFrame());
     JS_ASSERT(fp->isEvalFrame() == callobj.isForEval());
 
     /* Get the arguments object to snapshot fp's actual argument values. */
     if (fp->hasArgsObj()) {
         if (!fp->hasOverriddenArgs())
-            callobj.setArguments(ObjectValue(fp->argsObj()));
+            callobj.initArguments(ObjectValue(fp->argsObj()));
         js_PutArgsObject(fp);
     }
 
     JSScript *script = fp->script();
     Bindings &bindings = script->bindings;
 
     if (callobj.isForEval()) {
         JS_ASSERT(script->strictModeCode);
@@ -818,28 +820,39 @@ js_PutCallObject(StackFrame *fp)
 #ifdef JS_METHODJIT
                 || script->debugMode
 #endif
                 ) {
                 callobj.copyValues(nargs, fp->formalArgs(), nvars, fp->slots());
             } else {
                 /*
                  * For each arg & var that is closed over, copy it from the stack
-                 * into the call object.
+                 * into the call object. We use initArg/VarUnchecked because,
+                 * when you call a getter on a call object, js_NativeGetInline
+                 * caches the return value in the slot, so we can't assert that
+                 * it's undefined.
                  */
                 uint32 nclosed = script->nClosedArgs;
                 for (uint32 i = 0; i < nclosed; i++) {
                     uint32 e = script->getClosedArg(i);
+#ifdef JS_GC_ZEAL
                     callobj.setArg(e, fp->formalArg(e));
+#else
+                    callobj.initArgUnchecked(e, fp->formalArg(e));
+#endif
                 }
 
                 nclosed = script->nClosedVars;
                 for (uint32 i = 0; i < nclosed; i++) {
                     uint32 e = script->getClosedVar(i);
+#ifdef JS_GC_ZEAL
                     callobj.setVar(e, fp->slots()[e]);
+#else
+                    callobj.initVarUnchecked(e, fp->slots()[e]);
+#endif
                 }
             }
 
             /*
              * Update the args and vars for the active call if this is an outer
              * function in a script nesting.
              */
             types::TypeScriptNesting *nesting = script->nesting();
@@ -1587,29 +1600,34 @@ static void
 fun_trace(JSTracer *trc, JSObject *obj)
 {
     /* A newborn function object may have a not yet initialized private slot. */
     JSFunction *fun = (JSFunction *) obj->getPrivate();
     if (!fun)
         return;
 
     if (fun != obj) {
-        /* obj is a cloned function object, trace the clone-parent, fun. */
-        MarkObject(trc, *fun, "private");
+        /*
+         * obj is a cloned function object, trace the clone-parent, fun.
+         * This is safe to leave Unbarriered for incremental GC because any
+         * change to fun will trigger a setPrivate barrer. But we'll need to
+         * fix this for generational GC.
+         */
+        MarkObjectUnbarriered(trc, fun, "private");
 
         /* The function could be a flat closure with upvar copies in the clone. */
         if (fun->isFlatClosure() && fun->script()->bindings.hasUpvars()) {
             MarkValueRange(trc, fun->script()->bindings.countUpvars(),
-                           obj->getFlatClosureUpvars(), "upvars");
+                           obj->getFlatClosureData()->upvars, "upvars");
         }
         return;
     }
 
     if (fun->atom)
-        MarkString(trc, fun->atom, "atom");
+        MarkAtom(trc, fun->atom, "atom");
 
     if (fun->isInterpreted() && fun->script())
         MarkScript(trc, fun->script(), "script");
 }
 
 static void
 fun_finalize(JSContext *cx, JSObject *obj)
 {
@@ -1844,17 +1862,17 @@ JSObject::initBoundFunction(JSContext *c
 
         empty->slotSpan += argslen;
         setMap(empty);
 
         if (!ensureInstanceReservedSlots(cx, argslen))
             return false;
 
         JS_ASSERT(numSlots() >= argslen + FUN_CLASS_RESERVED_SLOTS);
-        copySlotRange(FUN_CLASS_RESERVED_SLOTS, args, argslen);
+        copySlotRange(FUN_CLASS_RESERVED_SLOTS, args, argslen, false);
     }
     return true;
 }
 
 inline JSObject *
 JSObject::getBoundFunctionTarget() const
 {
     JS_ASSERT(isFunction());
@@ -2273,17 +2291,17 @@ js_NewFunction(JSContext *cx, JSObject *
 
     /* Initialize all function members. */
     fun->nargs = uint16(nargs);
     fun->flags = flags & (JSFUN_FLAGS_MASK | JSFUN_KINDMASK | JSFUN_TRCINFO);
     if ((flags & JSFUN_KINDMASK) >= JSFUN_INTERPRETED) {
         JS_ASSERT(!native);
         JS_ASSERT(nargs == 0);