merge inbound to m-c
authorWes Kocher <wkocher@mozilla.com>
Tue, 17 Dec 2013 21:00:02 -0800
changeset 160973 862cb6a1cc88f7512c555f6c3b2966da7858b639
parent 160972 28ccc1a2ef10b6f6656dad73c5c858d78e56ffa7 (current diff)
parent 160936 41a8213774080c318e8a6ba52a78a9c50e018f29 (diff)
child 160974 e0c39376676db938b7625a21407e7e27f15ce1f2
child 160995 a234b6934a99ae4bce1b931cf51e39fbb1e4b67e
child 161016 eaadc30df6e7378209bdfb683d5a7a586854b4cb
push id37759
push userkwierso@gmail.com
push dateWed, 18 Dec 2013 05:23:30 +0000
treeherdermozilla-inbound@e0c39376676d [default view] [failures only]
perfherder[talos] [build metrics] [platform microbench] (compared to previous push)
milestone29.0a1
first release with
nightly linux32
862cb6a1cc88 / 29.0a1 / 20131218030217 / files
nightly linux64
862cb6a1cc88 / 29.0a1 / 20131218030217 / files
nightly mac
862cb6a1cc88 / 29.0a1 / 20131218030217 / files
nightly win32
862cb6a1cc88 / 29.0a1 / 20131218030217 / files
nightly win64
862cb6a1cc88 / 29.0a1 / 20131218030217 / files
last release without
nightly linux32
nightly linux64
nightly mac
nightly win32
nightly win64
releases
nightly linux32
nightly linux64
nightly mac
nightly win32
nightly win64
merge inbound to m-c
browser/metro/base/content/contenthandlers/Content.js
build/ConfigStatus.py
js/src/build/ConfigStatus.py
--- a/accessible/src/jsat/moz.build
+++ b/accessible/src/jsat/moz.build
@@ -11,8 +11,10 @@ EXTRA_JS_MODULES += [
     'Constants.jsm',
     'EventManager.jsm',
     'OutputGenerator.jsm',
     'Presentation.jsm',
     'TouchAdapter.jsm',
     'TraversalRules.jsm',
     'Utils.jsm'
 ]
+
+JAR_MANIFESTS += ['jar.mn']
\ No newline at end of file
--- a/b2g/branding/official/content/moz.build
+++ b/b2g/branding/official/content/moz.build
@@ -1,6 +1,7 @@
 # -*- Mode: python; c-basic-offset: 4; indent-tabs-mode: nil; tab-width: 40 -*-
 # vim: set filetype=python:
 # This Source Code Form is subject to the terms of the Mozilla Public
 # License, v. 2.0. If a copy of the MPL was not distributed with this
 # file, You can obtain one at http://mozilla.org/MPL/2.0/.
 
+JAR_MANIFESTS += ['jar.mn']
\ No newline at end of file
--- a/b2g/branding/official/locales/moz.build
+++ b/b2g/branding/official/locales/moz.build
@@ -1,6 +1,7 @@
 # -*- Mode: python; c-basic-offset: 4; indent-tabs-mode: nil; tab-width: 40 -*-
 # vim: set filetype=python:
 # This Source Code Form is subject to the terms of the Mozilla Public
 # License, v. 2.0. If a copy of the MPL was not distributed with this
 # file, You can obtain one at http://mozilla.org/MPL/2.0/.
 
+JAR_MANIFESTS += ['jar.mn']
\ No newline at end of file
--- a/b2g/branding/unofficial/content/moz.build
+++ b/b2g/branding/unofficial/content/moz.build
@@ -1,6 +1,7 @@
 # -*- Mode: python; c-basic-offset: 4; indent-tabs-mode: nil; tab-width: 40 -*-
 # vim: set filetype=python:
 # This Source Code Form is subject to the terms of the Mozilla Public
 # License, v. 2.0. If a copy of the MPL was not distributed with this
 # file, You can obtain one at http://mozilla.org/MPL/2.0/.
 
+JAR_MANIFESTS += ['jar.mn']
\ No newline at end of file
--- a/b2g/branding/unofficial/locales/moz.build
+++ b/b2g/branding/unofficial/locales/moz.build
@@ -1,6 +1,7 @@
 # -*- Mode: python; c-basic-offset: 4; indent-tabs-mode: nil; tab-width: 40 -*-
 # vim: set filetype=python:
 # This Source Code Form is subject to the terms of the Mozilla Public
 # License, v. 2.0. If a copy of the MPL was not distributed with this
 # file, You can obtain one at http://mozilla.org/MPL/2.0/.
 
+JAR_MANIFESTS += ['jar.mn']
\ No newline at end of file
--- a/b2g/chrome/moz.build
+++ b/b2g/chrome/moz.build
@@ -2,8 +2,10 @@
 # vim: set filetype=python:
 # This Source Code Form is subject to the terms of the Mozilla Public
 # License, v. 2.0. If a copy of the MPL was not distributed with this
 # file, You can obtain one at http://mozilla.org/MPL/2.0/.
 
 DEFINES['AB_CD'] = CONFIG['MOZ_UI_LOCALE']
 DEFINES['PACKAGE'] = 'browser'
 DEFINES['MOZ_APP_VERSION'] = CONFIG['MOZ_APP_VERSION']
+
+JAR_MANIFESTS += ['jar.mn']
\ No newline at end of file
--- a/b2g/components/ErrorPage.jsm
+++ b/b2g/components/ErrorPage.jsm
@@ -156,17 +156,17 @@ let ErrorPage = {
 
   observe: function errorPageObserve(aSubject, aTopic, aData) {
     let frameLoader = aSubject.QueryInterface(Ci.nsIFrameLoader);
     let mm = frameLoader.messageManager;
 
     // This won't happen from dom/ipc/preload.js in non-OOP builds.
     try {
       if (Services.prefs.getBoolPref("dom.ipc.tabs.disabled") === true) {
-        mm.loadFrameScript(kErrorPageFrameScript, true);
+        mm.loadFrameScript(kErrorPageFrameScript, true, true);
       }
     } catch (e) {
       dump('Error loading ' + kErrorPageFrameScript + ' as frame script: ' + e + '\n');
     }
     mm.addMessageListener('ErrorPage:AddCertException', this._addCertException.bind(this));
   }
 };
 
--- a/b2g/components/PaymentGlue.js
+++ b/b2g/components/PaymentGlue.js
@@ -138,17 +138,17 @@ PaymentUI.prototype = {
 
       // Try to load the payment shim file containing the payment callbacks
       // in the content script.
       let frame = msg.frame;
       let frameLoader = frame.QueryInterface(Ci.nsIFrameLoaderOwner)
                              .frameLoader;
       let mm = frameLoader.messageManager;
       try {
-        mm.loadFrameScript(kPaymentShimFile, true);
+        mm.loadFrameScript(kPaymentShimFile, true, true);
         mm.sendAsyncMessage("Payment:LoadShim", { requestId: aRequestId });
       } catch (e) {
         if (this._debug) {
           this.LOG("Error loading " + kPaymentShimFile + " as a frame script: "
                     + e);
         }
         _error("ERROR_LOADING_PAYMENT_SHIM");
       } finally {
--- a/b2g/components/SignInToWebsite.jsm
+++ b/b2g/components/SignInToWebsite.jsm
@@ -282,17 +282,17 @@ Pipe.prototype = {
             // The window has opened.  Inject the identity shim file containing
             // the callbacks in the content script.  This could be either the
             // visible popup that the user interacts with, or it could be an
             // invisible frame.
             let frame = evt.detail.frame;
             let frameLoader = frame.QueryInterface(Ci.nsIFrameLoaderOwner).frameLoader;
             mm = frameLoader.messageManager;
             try {
-              mm.loadFrameScript(kIdentityShimFile, true);
+              mm.loadFrameScript(kIdentityShimFile, true, true);
               log("Loaded shim", kIdentityShimFile);
             } catch (e) {
               log("Error loading", kIdentityShimFile, "as a frame script:", e);
             }
 
             // There are two messages that the delegate can send back: a "do
             // method" event, and a "finished" event.  We pass the do-method
             // events straight to the caller for interpretation and handling.
--- a/b2g/locales/moz.build
+++ b/b2g/locales/moz.build
@@ -1,6 +1,7 @@
 # -*- Mode: python; c-basic-offset: 4; indent-tabs-mode: nil; tab-width: 40 -*-
 # vim: set filetype=python:
 # This Source Code Form is subject to the terms of the Mozilla Public
 # License, v. 2.0. If a copy of the MPL was not distributed with this
 # file, You can obtain one at http://mozilla.org/MPL/2.0/.
 
+JAR_MANIFESTS += ['jar.mn']
\ No newline at end of file
--- a/browser/base/content/test/general/browser.ini
+++ b/browser/base/content/test/general/browser.ini
@@ -109,16 +109,17 @@ run-if = crashreporter
 [browser_CTP_hideBar.js]
 [browser_CTP_multi_allow.js]
 [browser_CTP_nonplugins.js]
 [browser_CTP_resize.js]
 [browser_URLBarSetURI.js]
 [browser_aboutHealthReport.js]
 skip-if = os == "linux" # Bug 924307
 [browser_aboutHome.js]
+skip-if = os == "linux" # Bug 945667
 [browser_aboutSyncProgress.js]
 [browser_addKeywordSearch.js]
 [browser_alltabslistener.js]
 [browser_backButtonFitts.js]
 skip-if = os != "win" # The Fitts Law back button is only supported on Windows (bug 571454)
 [browser_blob-channelname.js]
 [browser_bookmark_titles.js]
 skip-if = toolkit == "windows" # Disabled on Windows due to frequent failures (bugs 825739, 841341)
--- a/browser/base/content/test/social/social_crash_content_helper.js
+++ b/browser/base/content/test/social/social_crash_content_helper.js
@@ -1,11 +1,13 @@
 /* Any copyright is dedicated to the Public Domain.
 * http://creativecommons.org/publicdomain/zero/1.0/ */
 
+let Cu = Components.utils;
+
 // Ideally we would use CrashTestUtils.jsm, but that's only available for
 // xpcshell tests - so we just copy a ctypes crasher from it.
 Cu.import("resource://gre/modules/ctypes.jsm");
 let crash = function() { // this will crash when called.
   let zero = new ctypes.intptr_t(8);
   let badptr = ctypes.cast(zero, ctypes.PointerType(ctypes.int32_t));
   badptr.contents
 };
--- a/browser/base/moz.build
+++ b/browser/base/moz.build
@@ -29,8 +29,10 @@ if CONFIG['MOZ_WIDGET_TOOLKIT'] in ('win
     DEFINES['HAVE_SHELL_SERVICE'] = 1
     DEFINES['CONTEXT_COPY_IMAGE_CONTENTS'] = 1
 
 if CONFIG['MOZ_WIDGET_TOOLKIT'] in ('windows', 'cocoa'):
     DEFINES['CAN_DRAW_IN_TITLEBAR'] = 1
 
 if CONFIG['MOZ_WIDGET_TOOLKIT'] in ('windows', 'gtk2', 'gtk3'):
     DEFINES['MENUBAR_CAN_AUTOHIDE'] = 1
+
+JAR_MANIFESTS += ['jar.mn']
\ No newline at end of file
--- a/browser/branding/aurora/content/moz.build
+++ b/browser/branding/aurora/content/moz.build
@@ -1,6 +1,7 @@
 # -*- Mode: python; c-basic-offset: 4; indent-tabs-mode: nil; tab-width: 40 -*-
 # vim: set filetype=python:
 # This Source Code Form is subject to the terms of the Mozilla Public
 # License, v. 2.0. If a copy of the MPL was not distributed with this
 # file, You can obtain one at http://mozilla.org/MPL/2.0/.
 
+JAR_MANIFESTS += ['jar.mn']
\ No newline at end of file
--- a/browser/branding/aurora/locales/moz.build
+++ b/browser/branding/aurora/locales/moz.build
@@ -1,7 +1,9 @@
 # -*- Mode: python; c-basic-offset: 4; indent-tabs-mode: nil; tab-width: 40 -*-
 # vim: set filetype=python:
 # This Source Code Form is subject to the terms of the Mozilla Public
 # License, v. 2.0. If a copy of the MPL was not distributed with this
 # file, You can obtain one at http://mozilla.org/MPL/2.0/.
 
 DEFINES['MOZ_DISTRIBUTION_ID_UNQUOTED'] = CONFIG['MOZ_DISTRIBUTION_ID']
+
+JAR_MANIFESTS += ['jar.mn']
\ No newline at end of file
--- a/browser/branding/nightly/content/moz.build
+++ b/browser/branding/nightly/content/moz.build
@@ -1,6 +1,7 @@
 # -*- Mode: python; c-basic-offset: 4; indent-tabs-mode: nil; tab-width: 40 -*-
 # vim: set filetype=python:
 # This Source Code Form is subject to the terms of the Mozilla Public
 # License, v. 2.0. If a copy of the MPL was not distributed with this
 # file, You can obtain one at http://mozilla.org/MPL/2.0/.
 
+JAR_MANIFESTS += ['jar.mn']
\ No newline at end of file
--- a/browser/branding/nightly/locales/moz.build
+++ b/browser/branding/nightly/locales/moz.build
@@ -1,7 +1,9 @@
 # -*- Mode: python; c-basic-offset: 4; indent-tabs-mode: nil; tab-width: 40 -*-
 # vim: set filetype=python:
 # This Source Code Form is subject to the terms of the Mozilla Public
 # License, v. 2.0. If a copy of the MPL was not distributed with this
 # file, You can obtain one at http://mozilla.org/MPL/2.0/.
 
 DEFINES['MOZ_DISTRIBUTION_ID_UNQUOTED'] = CONFIG['MOZ_DISTRIBUTION_ID']
+
+JAR_MANIFESTS += ['jar.mn']
\ No newline at end of file
--- a/browser/branding/official/content/moz.build
+++ b/browser/branding/official/content/moz.build
@@ -1,6 +1,7 @@
 # -*- Mode: python; c-basic-offset: 4; indent-tabs-mode: nil; tab-width: 40 -*-
 # vim: set filetype=python:
 # This Source Code Form is subject to the terms of the Mozilla Public
 # License, v. 2.0. If a copy of the MPL was not distributed with this
 # file, You can obtain one at http://mozilla.org/MPL/2.0/.
 
+JAR_MANIFESTS += ['jar.mn']
\ No newline at end of file
--- a/browser/branding/official/locales/moz.build
+++ b/browser/branding/official/locales/moz.build
@@ -1,6 +1,7 @@
 # -*- Mode: python; c-basic-offset: 4; indent-tabs-mode: nil; tab-width: 40 -*-
 # vim: set filetype=python:
 # This Source Code Form is subject to the terms of the Mozilla Public
 # License, v. 2.0. If a copy of the MPL was not distributed with this
 # file, You can obtain one at http://mozilla.org/MPL/2.0/.
 
+JAR_MANIFESTS += ['jar.mn']
\ No newline at end of file
--- a/browser/branding/unofficial/content/moz.build
+++ b/browser/branding/unofficial/content/moz.build
@@ -1,6 +1,7 @@
 # -*- Mode: python; c-basic-offset: 4; indent-tabs-mode: nil; tab-width: 40 -*-
 # vim: set filetype=python:
 # This Source Code Form is subject to the terms of the Mozilla Public
 # License, v. 2.0. If a copy of the MPL was not distributed with this
 # file, You can obtain one at http://mozilla.org/MPL/2.0/.
 
+JAR_MANIFESTS += ['jar.mn']
\ No newline at end of file
--- a/browser/branding/unofficial/locales/moz.build
+++ b/browser/branding/unofficial/locales/moz.build
@@ -1,7 +1,9 @@
 # -*- Mode: python; c-basic-offset: 4; indent-tabs-mode: nil; tab-width: 40 -*-
 # vim: set filetype=python:
 # This Source Code Form is subject to the terms of the Mozilla Public
 # License, v. 2.0. If a copy of the MPL was not distributed with this
 # file, You can obtain one at http://mozilla.org/MPL/2.0/.
 
 DEFINES['MOZ_DISTRIBUTION_ID_UNQUOTED'] = CONFIG['MOZ_DISTRIBUTION_ID']
+
+JAR_MANIFESTS += ['jar.mn']
\ No newline at end of file
--- a/browser/components/certerror/moz.build
+++ b/browser/components/certerror/moz.build
@@ -2,8 +2,10 @@
 # vim: set filetype=python:
 # This Source Code Form is subject to the terms of the Mozilla Public
 # License, v. 2.0. If a copy of the MPL was not distributed with this
 # file, You can obtain one at http://mozilla.org/MPL/2.0/.
 
 BROWSER_CHROME_MANIFESTS += [
     'test/browser.ini',
 ]
+
+JAR_MANIFESTS += ['jar.mn']
\ No newline at end of file
--- a/browser/components/customizableui/content/moz.build
+++ b/browser/components/customizableui/content/moz.build
@@ -1,6 +1,7 @@
 # -*- Mode: python; c-basic-offset: 4; indent-tabs-mode: nil; tab-width: 40 -*-
 # vim: set filetype=python:
 # This Source Code Form is subject to the terms of the Mozilla Public
 # License, v. 2.0. If a copy of the MPL was not distributed with this
 # file, You can obtain one at http://mozilla.org/MPL/2.0/.
 
+JAR_MANIFESTS += ['jar.mn']
\ No newline at end of file
--- a/browser/components/downloads/moz.build
+++ b/browser/components/downloads/moz.build
@@ -8,8 +8,10 @@ DIRS += ['src']
 
 XPCSHELL_TESTS_MANIFESTS += [
     'test/unit/xpcshell.ini',
 ]
 
 BROWSER_CHROME_MANIFESTS += [
     'test/browser/browser.ini',
 ]
+
+JAR_MANIFESTS += ['jar.mn']
\ No newline at end of file
--- a/browser/components/feeds/moz.build
+++ b/browser/components/feeds/moz.build
@@ -12,8 +12,10 @@ XPCSHELL_TESTS_MANIFESTS += [
 
 MOCHITEST_CHROME_MANIFESTS += [
     'test/chrome/chrome.ini',
 ]
 
 MOCHITEST_MANIFESTS += [
     'test/mochitest.ini'
 ]
+
+JAR_MANIFESTS += ['jar.mn']
\ No newline at end of file
--- a/browser/components/migration/moz.build
+++ b/browser/components/migration/moz.build
@@ -4,8 +4,10 @@
 # License, v. 2.0. If a copy of the MPL was not distributed with this
 # file, You can obtain one at http://mozilla.org/MPL/2.0/.
 
 DIRS += ['public', 'src']
 
 XPCSHELL_TESTS_MANIFESTS += [
     'tests/unit/xpcshell.ini',
 ]
+
+JAR_MANIFESTS += ['jar.mn']
\ No newline at end of file
--- a/browser/components/places/moz.build
+++ b/browser/components/places/moz.build
@@ -12,8 +12,10 @@ XPCSHELL_TESTS_MANIFESTS += [
 
 MOCHITEST_CHROME_MANIFESTS += [
     'tests/chrome/chrome.ini'
 ]
 
 BROWSER_CHROME_MANIFESTS += [
     'tests/browser/browser.ini',
 ]
+
+JAR_MANIFESTS += ['jar.mn']
\ No newline at end of file
--- a/browser/components/preferences/in-content/moz.build
+++ b/browser/components/preferences/in-content/moz.build
@@ -4,8 +4,10 @@
 # License, v. 2.0. If a copy of the MPL was not distributed with this
 # file, You can obtain one at http://mozilla.org/MPL/2.0/.
 
 for var in ('MOZ_APP_NAME', 'MOZ_MACBUNDLE_NAME'):
     DEFINES[var] = CONFIG[var]
 
 if CONFIG['MOZ_WIDGET_TOOLKIT'] in ('windows', 'gtk2', 'cocoa'):
     DEFINES['HAVE_SHELL_SERVICE'] = 1
+
+JAR_MANIFESTS += ['jar.mn']
\ No newline at end of file
--- a/browser/components/preferences/moz.build
+++ b/browser/components/preferences/moz.build
@@ -11,8 +11,10 @@ BROWSER_CHROME_MANIFESTS += [
     'tests/browser.ini',
 ]
 
 for var in ('MOZ_APP_NAME', 'MOZ_MACBUNDLE_NAME'):
     DEFINES[var] = CONFIG[var]
 
 if CONFIG['MOZ_WIDGET_TOOLKIT'] in ('windows', 'gtk2', 'gtk3', 'cocoa'):
     DEFINES['HAVE_SHELL_SERVICE'] = 1
+
+JAR_MANIFESTS += ['jar.mn']
\ No newline at end of file
--- a/browser/components/privatebrowsing/moz.build
+++ b/browser/components/privatebrowsing/moz.build
@@ -2,8 +2,10 @@
 # vim: set filetype=python:
 # This Source Code Form is subject to the terms of the Mozilla Public
 # License, v. 2.0. If a copy of the MPL was not distributed with this
 # file, You can obtain one at http://mozilla.org/MPL/2.0/.
 
 BROWSER_CHROME_MANIFESTS += [
     'test/browser/browser.ini',
 ]
+
+JAR_MANIFESTS += ['jar.mn']
\ No newline at end of file
--- a/browser/components/search/moz.build
+++ b/browser/components/search/moz.build
@@ -2,8 +2,10 @@
 # vim: set filetype=python:
 # This Source Code Form is subject to the terms of the Mozilla Public
 # License, v. 2.0. If a copy of the MPL was not distributed with this
 # file, You can obtain one at http://mozilla.org/MPL/2.0/.
 
 BROWSER_CHROME_MANIFESTS += [
     'test/browser.ini',
 ]
+
+JAR_MANIFESTS += ['jar.mn']
\ No newline at end of file
--- a/browser/components/search/test/Makefile.in
+++ b/browser/components/search/test/Makefile.in
@@ -1,13 +1,20 @@
 # This Source Code Form is subject to the terms of the Mozilla Public
 # License, v. 2.0. If a copy of the MPL was not distributed with this
 # file, You can obtain one at http://mozilla.org/MPL/2.0/.
 
 ifdef ENABLE_TESTS
 pp_mochitest_browser_files := \
   browser_google.js \
+  $(NULL)
+
+# This test depends on browser_aboutHome.js, which was disabled (bug 945667)
+ifndef MOZ_WIDGET_GTK
+pp_mochitest_browser_files += \
   browser_google_behavior.js \
   $(NULL)
+endif
+  
 pp_mochitest_browser_files_PATH := $(DEPTH)/_tests/testing/mochitest/browser/$(relativesrcdir)
 pp_mochitest_browser_files_FLAGS := -DMOZ_DISTRIBUTION_ID=$(MOZ_DISTRIBUTION_ID)
 PP_TARGETS += pp_mochitest_browser_files
 endif # ENABLE_TESTS
--- a/browser/components/sessionstore/moz.build
+++ b/browser/components/sessionstore/moz.build
@@ -15,8 +15,10 @@ XPIDL_MODULE = 'sessionstore'
 
 XPCSHELL_TESTS_MANIFESTS += [
     'test/unit/xpcshell.ini',
 ]
 
 BROWSER_CHROME_MANIFESTS += [
     'test/browser.ini',
 ]
+
+JAR_MANIFESTS += ['jar.mn']
\ No newline at end of file
--- a/browser/components/sessionstore/test/content.js
+++ b/browser/components/sessionstore/test/content.js
@@ -1,12 +1,14 @@
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
+let Ci = Components.interfaces;
+
 /**
  * This frame script is only loaded for sessionstore mochitests. It enables us
  * to modify and query docShell data when running with multiple processes.
  */
 
 addEventListener("MozStorageChanged", function () {
   sendSyncMessage("ss-test:MozStorageChanged");
 });
--- a/browser/components/shell/moz.build
+++ b/browser/components/shell/moz.build
@@ -8,8 +8,10 @@ DIRS += ['public', 'src']
 
 XPCSHELL_TESTS_MANIFESTS += [
     'test/unit/xpcshell.ini'
 ]
 
 BROWSER_CHROME_MANIFESTS += [
     'test/browser.ini',
 ]
+
+JAR_MANIFESTS += ['jar.mn']
\ No newline at end of file
--- a/browser/components/tabview/content.js
+++ b/browser/components/tabview/content.js
@@ -1,15 +1,16 @@
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this file,
  * You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 "use strict";
 
 let Cu = Components.utils;
+let Ci = Components.interfaces;
 
 Cu.import("resource:///modules/tabview/utils.jsm");
 
 // Bug 671101 - directly using webProgress in this context
 // causes docShells to leak
 this.__defineGetter__("webProgress", function () {
   let ifaceReq = docShell.QueryInterface(Ci.nsIInterfaceRequestor);
   return ifaceReq.getInterface(Ci.nsIWebProgress);
--- a/browser/components/tabview/moz.build
+++ b/browser/components/tabview/moz.build
@@ -5,8 +5,10 @@
 # file, You can obtain one at http://mozilla.org/MPL/2.0/.
 
 EXTRA_JS_MODULES = ['modules/utils.jsm']
 JS_MODULES_PATH  = 'modules/tabview'
 
 BROWSER_CHROME_MANIFESTS += [
     'test/browser.ini',
 ]
+
+JAR_MANIFESTS += ['jar.mn']
\ No newline at end of file
--- a/browser/devtools/moz.build
+++ b/browser/devtools/moz.build
@@ -25,8 +25,10 @@ DIRS += [
     'tilt',
     'webconsole',
 ]
 
 EXTRA_COMPONENTS += [
     'devtools-clhandler.js',
     'devtools-clhandler.manifest',
 ]
+
+JAR_MANIFESTS += ['jar.mn']
\ No newline at end of file
--- a/browser/installer/package-manifest.in
+++ b/browser/installer/package-manifest.in
@@ -57,16 +57,19 @@
 #endif
 @BINPATH@/@DLL_PREFIX@mozalloc@DLL_SUFFIX@
 #ifdef MOZ_SHARED_MOZGLUE
 @BINPATH@/@DLL_PREFIX@mozglue@DLL_SUFFIX@
 #endif
 #ifndef MOZ_STATIC_JS
 @BINPATH@/@DLL_PREFIX@mozjs@DLL_SUFFIX@
 #endif
+#ifdef MOZ_DMD
+@BINPATH@/@DLL_PREFIX@dmd@DLL_SUFFIX@
+#endif
 #ifndef MOZ_NATIVE_NSPR
 #ifndef MOZ_FOLD_LIBS
 @BINPATH@/@DLL_PREFIX@nspr4@DLL_SUFFIX@
 @BINPATH@/@DLL_PREFIX@plc4@DLL_SUFFIX@
 @BINPATH@/@DLL_PREFIX@plds4@DLL_SUFFIX@
 #endif
 #endif
 #ifdef XP_MACOSX
--- a/browser/locales/moz.build
+++ b/browser/locales/moz.build
@@ -1,6 +1,7 @@
 # -*- Mode: python; c-basic-offset: 4; indent-tabs-mode: nil; tab-width: 40 -*-
 # vim: set filetype=python:
 # This Source Code Form is subject to the terms of the Mozilla Public
 # License, v. 2.0. If a copy of the MPL was not distributed with this
 # file, You can obtain one at http://mozilla.org/MPL/2.0/.
 
+JAR_MANIFESTS += ['jar.mn']
\ No newline at end of file
--- a/browser/metro/base/content/Util.js
+++ b/browser/metro/base/content/Util.js
@@ -1,12 +1,15 @@
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
+let Cc = Components.classes;
+let Ci = Components.interfaces;
+
 Components.utils.import("resource:///modules/ContentUtil.jsm");
 
 let Util = {
   /*
    * General purpose utilities
    */
 
   getWindowUtils: function getWindowUtils(aWindow) {
@@ -404,8 +407,10 @@ Util.Timeout.prototype = {
 // Mixin the ContentUtil module exports
 {
   for (let name in ContentUtil) {
     let copy = ContentUtil[name];
     if (copy !== undefined)
       Util[name] = copy;
   }
 }
+
+this.Util = Util;
--- a/browser/metro/base/content/bindings/browser.js
+++ b/browser/metro/base/content/bindings/browser.js
@@ -616,16 +616,17 @@ let ContentScroll =  {
           sendAsyncMessage("Content:UpdateDisplayPort");
         }, false);
 
         break;
       }
     }
   }
 };
+this.ContentScroll = ContentScroll;
 
 ContentScroll.init();
 
 let ContentActive =  {
   init: function() {
     addMessageListener("Content:Activate", this);
     addMessageListener("Content:Deactivate", this);
   },
--- a/browser/metro/base/content/contenthandlers/ConsoleAPIObserver.js
+++ b/browser/metro/base/content/contenthandlers/ConsoleAPIObserver.js
@@ -1,12 +1,15 @@
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
+let Ci = Components.interfaces;
+let Cc = Components.classes;
+
 dump("### ConsoleAPIObserver.js loaded\n");
 
 /*
  * ConsoleAPIObserver
  *
  */ 
 
 var ConsoleAPIObserver = {
@@ -111,11 +114,12 @@ var ConsoleAPIObserver = {
     // Remove all but the last path component.
     let slashIndex = aSourceURL.lastIndexOf("/");
     if (slashIndex > -1)
       aSourceURL = aSourceURL.substring(slashIndex + 1);
 
     return aSourceURL;
   }
 };
+this.ConsoleAPIObserver = ConsoleAPIObserver;
 
 ConsoleAPIObserver.init();
 
--- a/browser/metro/base/content/contenthandlers/Content.js
+++ b/browser/metro/base/content/contenthandlers/Content.js
@@ -32,23 +32,23 @@ XPCOMUtils.defineLazyModuleGetter(this, 
   "resource://gre/modules/LoginManagerContent.jsm");
 
 XPCOMUtils.defineLazyServiceGetter(this, "gFocusManager",
   "@mozilla.org/focus-manager;1", "nsIFocusManager");
 
 XPCOMUtils.defineLazyServiceGetter(this, "gDOMUtils",
   "@mozilla.org/inspector/dom-utils;1", "inIDOMUtils");
 
-let XULDocument = Ci.nsIDOMXULDocument;
-let HTMLHtmlElement = Ci.nsIDOMHTMLHtmlElement;
-let HTMLIFrameElement = Ci.nsIDOMHTMLIFrameElement;
-let HTMLFrameElement = Ci.nsIDOMHTMLFrameElement;
-let HTMLFrameSetElement = Ci.nsIDOMHTMLFrameSetElement;
-let HTMLSelectElement = Ci.nsIDOMHTMLSelectElement;
-let HTMLOptionElement = Ci.nsIDOMHTMLOptionElement;
+this.XULDocument = Ci.nsIDOMXULDocument;
+this.HTMLHtmlElement = Ci.nsIDOMHTMLHtmlElement;
+this.HTMLIFrameElement = Ci.nsIDOMHTMLIFrameElement;
+this.HTMLFrameElement = Ci.nsIDOMHTMLFrameElement;
+this.HTMLFrameSetElement = Ci.nsIDOMHTMLFrameSetElement;
+this.HTMLSelectElement = Ci.nsIDOMHTMLSelectElement;
+this.HTMLOptionElement = Ci.nsIDOMHTMLOptionElement;
 
 const kReferenceDpi = 240; // standard "pixel" size used in some preferences
 
 const kStateActive = 0x00000001; // :active pseudoclass for elements
 
 const kZoomToElementMargin = 16; // in px
 
 /*
@@ -77,16 +77,17 @@ function getBoundingContentRect(aElement
     let rect = frame.frameElement.getBoundingClientRect();
     let left = frame.getComputedStyle(frame.frameElement, "").borderLeftWidth;
     let top = frame.getComputedStyle(frame.frameElement, "").borderTopWidth;
     offset.add(rect.left + parseInt(left), rect.top + parseInt(top));
   }
 
   return new Rect(r.left + offset.x, r.top + offset.y, r.width, r.height);
 }
+this.getBoundingContentRect = getBoundingContentRect;
 
 /*
  * getOverflowContentBoundingRect
  *
  * @param aElement
  * @return Bounding content rect adjusted for scroll and frame offsets.
  */
 
@@ -103,16 +104,17 @@ function getOverflowContentBoundingRect(
   }
 
   for (let i = 0; i < aElement.childElementCount; i++) {
     r = r.union(getBoundingContentRect(aElement.children[i]));
   }
 
   return r;
 }
+this.getOverflowContentBoundingRect = getOverflowContentBoundingRect;
 
 /*
  * Content
  *
  * Browser event receiver for content.
  */
 let Content = {
   _debugEvents: false,
@@ -578,10 +580,11 @@ var FormSubmitObserver = {
   QueryInterface : function(aIID) {
     if (!aIID.equals(Ci.nsIFormSubmitObserver) &&
         !aIID.equals(Ci.nsISupportsWeakReference) &&
         !aIID.equals(Ci.nsISupports))
       throw Cr.NS_ERROR_NO_INTERFACE;
     return this;
   }
 };
+this.Content = Content;
 
 FormSubmitObserver.init();
--- a/browser/metro/base/content/contenthandlers/ContextMenuHandler.js
+++ b/browser/metro/base/content/contenthandlers/ContextMenuHandler.js
@@ -1,13 +1,16 @@
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
-const kXLinkNamespace = "http://www.w3.org/1999/xlink";
+let Ci = Components.interfaces;
+let Cc = Components.classes;
+
+this.kXLinkNamespace = "http://www.w3.org/1999/xlink";
 
 dump("### ContextMenuHandler.js loaded\n");
 
 var ContextMenuHandler = {
   _types: [],
   _previousState: null,
 
   init: function ch_init() {
@@ -424,10 +427,11 @@ var ContextMenuHandler = {
     this._types.push({name: aName, handler: aHandler});
   },
 
   /** Remove all handlers registered for a given type. */
   unregisterType: function unregisterType(aName) {
     this._types = this._types.filter(function(type) type.name != aName);
   }
 };
+this.ContextMenuHandler = ContextMenuHandler;
 
 ContextMenuHandler.init();
--- a/browser/metro/base/content/contenthandlers/FindHandler.js
+++ b/browser/metro/base/content/contenthandlers/FindHandler.js
@@ -1,12 +1,15 @@
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
+let Ci = Components.interfaces;
+let Cc = Components.classes;
+
 dump("### FindHandler.js loaded\n");
 
 var FindHandler = {
   get _fastFind() {
     delete this._fastFind;
     this._fastFind = Cc["@mozilla.org/typeaheadfind;1"].createInstance(Ci.nsITypeAheadFind);
     this._fastFind.init(docShell);
     return this._fastFind;
@@ -78,10 +81,11 @@ var FindHandler = {
         rect: rect.isEmpty() ? null: rect,
         contentHeight: content.document.documentElement.scrollHeight,
         result: findResult
       });
     });
     timer.once(0);
   }
 };
+this.FindHandler = FindHandler;
 
 FindHandler.init();
--- a/browser/metro/base/content/contenthandlers/FormHelper.js
+++ b/browser/metro/base/content/contenthandlers/FormHelper.js
@@ -555,16 +555,17 @@ FormAssistant.prototype = {
       let node = aNodes[i];
       if (node.type == "radio" && chosenRadios[node.name] != node)
         continue;
       result.push(node);
     }
     return result;
   }
 };
+this.FormAssistant = FormAssistant;
 
 
 /******************************************************************************
  * The next classes wraps some forms elements such as different type of list to
  * abstract the difference between html and xul element while manipulating them
  *  - SelectWrapper   : <html:select>
  *  - MenulistWrapper : <xul:menulist>
  *****************************************************************************/
@@ -683,16 +684,17 @@ SelectWrapper.prototype = {
     evt.initEvent("change", true, true, this._control.ownerDocument.defaultView, 0,
                   false, false,
                   false, false, null);
     content.setTimeout(function() {
       control.dispatchEvent(evt);
     }, 0);
   }
 };
+this.SelectWrapper = SelectWrapper;
 
 
 // bug 559792
 // Use wrappedJSObject when control is in content for extra protection
 function MenulistWrapper(aControl) {
   this._control = aControl;
 }
 
@@ -740,8 +742,9 @@ MenulistWrapper.prototype = {
     evt.initCommandEvent("command", true, true, window, 0,
                          false, false,
                          false, false, null);
     content.setTimeout(function() {
       control.dispatchEvent(evt);
     }, 0);
   }
 };
+this.MenulistWrapper = MenulistWrapper;
--- a/browser/metro/base/content/contenthandlers/SelectionHandler.js
+++ b/browser/metro/base/content/contenthandlers/SelectionHandler.js
@@ -1,12 +1,15 @@
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
+let Ci = Components.interfaces;
+let Cc = Components.classes;
+
 dump("### SelectionHandler.js loaded\n");
 
 var SelectionHandler = {
   init: function init() {
     this.type = kContentSelector;
     this.snap = true;
     this.lastYPos = this.lastXPos = null;
     addMessageListener("Browser:SelectionStart", this);
@@ -591,12 +594,13 @@ var SelectionHandler = {
       if (docShell == null)
         return null;
       return docShell.QueryInterface(Ci.nsIInterfaceRequestor)
                      .getInterface(Ci.nsISelectionDisplay)
                      .QueryInterface(Ci.nsISelectionController);
     }
   },
 };
+this.SelectionHandler = SelectionHandler;
 
 SelectionHandler.__proto__ = new SelectionPrototype();
 SelectionHandler.init();
 
--- a/browser/metro/base/content/library/SelectionPrototype.js
+++ b/browser/metro/base/content/library/SelectionPrototype.js
@@ -1,24 +1,27 @@
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 "use strict";
 
+let Ci = Components.interfaces;
+let Cc = Components.classes;
+
 /*
  * SelectionPrototype - common base class used by both chrome and content selection logic.
  */
 
 // selection node parameters for various apis
-const kSelectionNodeAnchor = 1;
-const kSelectionNodeFocus = 2;
+this.kSelectionNodeAnchor = 1;
+this.kSelectionNodeFocus = 2;
 
 // selection type property constants
-const kChromeSelector = 1;
-const kContentSelector = 2;
+this.kChromeSelector = 1;
+this.kContentSelector = 2;
 
 dump("### SelectionPrototype.js loaded\n");
 
 /*
   http://mxr.mozilla.org/mozilla-central/source/docshell/base/nsIDocShell.idl
   http://mxr.mozilla.org/mozilla-central/source/content/base/public/nsISelectionDisplay.idl
   http://mxr.mozilla.org/mozilla-central/source/content/base/public/nsISelectionListener.idl
   http://mxr.mozilla.org/mozilla-central/source/content/base/public/nsISelectionPrivate.idl
@@ -946,8 +949,9 @@ SelectionPrototype.prototype = {
    * in init().
    */
   _setDebugPoint: function _setDebugPoint(aX, aY, aColor) {
     let rect = { left: aX - 2, top: aY - 2,
                  right: aX + 2, bottom: aY + 2 };
     this._setDebugRect(rect, aColor, true);
   },
 };
+this.SelectionPrototype = SelectionPrototype;
--- a/browser/metro/base/moz.build
+++ b/browser/metro/base/moz.build
@@ -7,8 +7,10 @@
 METRO_CHROME_MANIFESTS += ['tests/mochiperf/metro.ini', 'tests/mochitest/metro.ini']
 XPCSHELL_TESTS_MANIFESTS += ['tests/unit/xpcshell.ini']
 
 DIST_SUBDIR = 'metro'
 
 DEFINES['AB_CD'] = CONFIG['MOZ_UI_LOCALE']
 DEFINES['PACKAGE'] = 'browser'
 DEFINES['MOZ_APP_VERSION'] = CONFIG['MOZ_APP_VERSION']
+
+JAR_MANIFESTS += ['jar.mn']
\ No newline at end of file
--- a/browser/metro/locales/moz.build
+++ b/browser/metro/locales/moz.build
@@ -2,8 +2,9 @@
 # vim: set filetype=python:
 # This Source Code Form is subject to the terms of the Mozilla Public
 # License, v. 2.0. If a copy of the MPL was not distributed with this
 # file, You can obtain one at http://mozilla.org/MPL/2.0/.
 
 # Process desktop related resource we reuse here.
 DIRS += ['import']
 
+JAR_MANIFESTS += ['jar.mn']
\ No newline at end of file
--- a/browser/metro/theme/moz.build
+++ b/browser/metro/theme/moz.build
@@ -1,6 +1,7 @@
 # -*- Mode: python; c-basic-offset: 4; indent-tabs-mode: nil; tab-width: 40 -*-
 # vim: set filetype=python:
 # This Source Code Form is subject to the terms of the Mozilla Public
 # License, v. 2.0. If a copy of the MPL was not distributed with this
 # file, You can obtain one at http://mozilla.org/MPL/2.0/.
 
+JAR_MANIFESTS += ['jar.mn']
\ No newline at end of file
--- a/browser/modules/BrowserNewTabPreloader.jsm
+++ b/browser/modules/BrowserNewTabPreloader.jsm
@@ -327,17 +327,17 @@ HiddenBrowser.prototype = {
     }
 
     // Swap docShells.
     tabbrowser.swapNewTabWithBrowser(aTab, this._browser);
 
     // Load all default frame scripts attached to the target window.
     let mm = aTab.linkedBrowser.messageManager;
     let scripts = win.messageManager.getDelayedFrameScripts();
-    Array.forEach(scripts, script => mm.loadFrameScript(script, true));
+    Array.forEach(scripts, ([script, runGlobal]) => mm.loadFrameScript(script, true, runGlobal));
 
     // Remove the browser, it will be recreated by a timer.
     this._removeBrowser();
 
     // Start a timer that will kick off preloading the next newtab page.
     this._timer = createTimer(this, PRELOADER_INTERVAL_MS);
 
     // Signal that we swapped docShells.
--- a/browser/themes/linux/communicator/moz.build
+++ b/browser/themes/linux/communicator/moz.build
@@ -1,6 +1,7 @@
 # -*- Mode: python; c-basic-offset: 4; indent-tabs-mode: nil; tab-width: 40 -*-
 # vim: set filetype=python:
 # This Source Code Form is subject to the terms of the Mozilla Public
 # License, v. 2.0. If a copy of the MPL was not distributed with this
 # file, You can obtain one at http://mozilla.org/MPL/2.0/.
 
+JAR_MANIFESTS += ['jar.mn']
\ No newline at end of file
--- a/browser/themes/linux/moz.build
+++ b/browser/themes/linux/moz.build
@@ -1,8 +1,9 @@
 # -*- Mode: python; c-basic-offset: 4; indent-tabs-mode: nil; tab-width: 40 -*-
 # vim: set filetype=python:
 # This Source Code Form is subject to the terms of the Mozilla Public
 # License, v. 2.0. If a copy of the MPL was not distributed with this
 # file, You can obtain one at http://mozilla.org/MPL/2.0/.
 
 DIRS += ['communicator']
 
+JAR_MANIFESTS += ['jar.mn']
\ No newline at end of file
--- a/browser/themes/osx/communicator/moz.build
+++ b/browser/themes/osx/communicator/moz.build
@@ -1,6 +1,7 @@
 # -*- Mode: python; c-basic-offset: 4; indent-tabs-mode: nil; tab-width: 40 -*-
 # vim: set filetype=python:
 # This Source Code Form is subject to the terms of the Mozilla Public
 # License, v. 2.0. If a copy of the MPL was not distributed with this
 # file, You can obtain one at http://mozilla.org/MPL/2.0/.
 
+JAR_MANIFESTS += ['jar.mn']
\ No newline at end of file
--- a/browser/themes/osx/moz.build
+++ b/browser/themes/osx/moz.build
@@ -1,8 +1,9 @@
 # -*- Mode: python; c-basic-offset: 4; indent-tabs-mode: nil; tab-width: 40 -*-
 # vim: set filetype=python:
 # This Source Code Form is subject to the terms of the Mozilla Public
 # License, v. 2.0. If a copy of the MPL was not distributed with this
 # file, You can obtain one at http://mozilla.org/MPL/2.0/.
 
 DIRS += ['communicator']
 
+JAR_MANIFESTS += ['jar.mn']
\ No newline at end of file
--- a/browser/themes/windows/communicator/moz.build
+++ b/browser/themes/windows/communicator/moz.build
@@ -1,6 +1,7 @@
 # -*- Mode: python; c-basic-offset: 4; indent-tabs-mode: nil; tab-width: 40 -*-
 # vim: set filetype=python:
 # This Source Code Form is subject to the terms of the Mozilla Public
 # License, v. 2.0. If a copy of the MPL was not distributed with this
 # file, You can obtain one at http://mozilla.org/MPL/2.0/.
 
+JAR_MANIFESTS += ['jar.mn']
\ No newline at end of file
--- a/browser/themes/windows/moz.build
+++ b/browser/themes/windows/moz.build
@@ -1,8 +1,9 @@
 # -*- Mode: python; c-basic-offset: 4; indent-tabs-mode: nil; tab-width: 40 -*-
 # vim: set filetype=python:
 # This Source Code Form is subject to the terms of the Mozilla Public
 # License, v. 2.0. If a copy of the MPL was not distributed with this
 # file, You can obtain one at http://mozilla.org/MPL/2.0/.
 
 DIRS += ['communicator']
 
+JAR_MANIFESTS += ['jar.mn']
\ No newline at end of file
--- a/build/autoconf/arch.m4
+++ b/build/autoconf/arch.m4
@@ -211,17 +211,17 @@ if test "$CPU_ARCH" = "arm"; then
   AC_MSG_RESULT("$result")
   if test "$result" = "yes"; then
       AC_DEFINE(HAVE_ARM_SIMD)
       HAVE_ARM_SIMD=1
   fi
 
   AC_MSG_CHECKING(ARM version support in compiler)
   dnl Determine the target ARM architecture (5 for ARMv5, v5T, v5E, etc.; 6 for ARMv6, v6K, etc.)
-  ARM_ARCH=`${CC-cc} ${CFLAGS} -dM -E - < /dev/null | sed -n 's/.*__ARM_ARCH_\([[0-9]]*\).*/\1/p'`
+  ARM_ARCH=`${CC-cc} ${CFLAGS} -dM -E - < /dev/null | sed -n 's/.*__ARM_ARCH_\([[0-9]][[0-9]]*\).*/\1/p'`
   AC_MSG_RESULT("$ARM_ARCH")
 
   AC_MSG_CHECKING(for ARM NEON support in compiler)
   # We try to link so that this also fails when
   # building with LTO.
   AC_TRY_LINK([],
                  [asm(".fpu neon\n vadd.i8 d0, d0, d0");],
                  result="yes", result="no")
--- a/build/autoconf/config.status.m4
+++ b/build/autoconf/config.status.m4
@@ -148,20 +148,17 @@ fi
 cat >> $CONFIG_STATUS <<EOF
 ]
 
 __all__ = ['topobjdir', 'topsrcdir', 'defines', 'non_global_defines', 'substs']
 
 dnl Do the actual work
 if __name__ == '__main__':
     args = dict([(name, globals()[name]) for name in __all__])
-    import sys
-dnl Don't rely on virtualenv here. Standalone js doesn't use it.
-    sys.path.append(os.path.join(topsrcdir, ${extra_python_path}'build'))
-    from ConfigStatus import config_status
+    from mozbuild.config_status import config_status
     config_status(**args)
 EOF
 changequote([, ])
 chmod +x $CONFIG_STATUS
 rm -fr confdefs* $ac_clean_files
 dnl Execute config.status, unless --no-create was passed to configure.
 if test "$no_create" != yes && ! ${PYTHON} $CONFIG_STATUS; then
     trap '' EXIT
--- a/build/docs/jar-manifests.rst
+++ b/build/docs/jar-manifests.rst
@@ -2,17 +2,18 @@
 
 =============
 JAR Manifests
 =============
 
 JAR Manifests are plaintext files in the tree that are used to package chrome
 files into the correct JARs, and create
 `Chrome Registration <https://developer.mozilla.org/en-US/docs/Chrome_Registration>`_
-manifests. JAR Manifests are named ``jar.mn``.
+manifests. JAR Manifests are commonly named ``jar.mn``. They are
+declared in ``moz.build`` files using the ``JAR_MANIFESTS`` variable.
 
 ``jar.mn`` files are automatically processed by the build system when building a
 source directory that contains one. The ``jar``.mn is run through the
 :ref:`preprocessor` before being passed to the manifest processor. In order to
 have ``@variables@`` expanded (such as ``@AB_CD@``) throughout the file, add
 the line ``#filter substitution`` at the top of your ``jar.mn`` file.
 
 The format of a jar.mn is fairly simple; it consists of a heading specifying
--- a/config/config.mk
+++ b/config/config.mk
@@ -46,16 +46,17 @@ endif
   FORCE_STATIC_LIB \
   FINAL_LIBRARY \
   HOST_CSRCS \
   HOST_CMMSRCS \
   HOST_LIBRARY_NAME \
   HOST_PROGRAM \
   HOST_SIMPLE_PROGRAMS \
   IS_COMPONENT \
+  JAR_MANIFEST \
   JAVA_JAR_TARGETS \
   JS_MODULES_PATH \
   LIBRARY_NAME \
   LIBXUL_LIBRARY \
   MODULE \
   MSVC_ENABLE_PGO \
   NO_DIST_INSTALL \
   PARALLEL_DIRS \
--- a/config/rules.mk
+++ b/config/rules.mk
@@ -1279,27 +1279,25 @@ SDK_BINARY_FILES := $(SDK_BINARY)
 SDK_BINARY_DEST := $(SDK_BIN_DIR)
 INSTALL_TARGETS += SDK_BINARY
 endif
 endif # SDK_BINARY
 
 ################################################################################
 # CHROME PACKAGING
 
-JAR_MANIFEST := $(srcdir)/jar.mn
-
 chrome::
 	$(MAKE) realchrome
 	$(LOOP_OVER_PARALLEL_DIRS)
 	$(LOOP_OVER_DIRS)
 	$(LOOP_OVER_TOOL_DIRS)
 
 $(FINAL_TARGET)/chrome: $(call mkdir_deps,$(FINAL_TARGET)/chrome)
 
-ifneq (,$(wildcard $(JAR_MANIFEST)))
+ifneq (,$(JAR_MANIFEST))
 ifndef NO_DIST_INSTALL
 
 ifdef XPI_NAME
 ifdef XPI_ROOT_APPID
 # For add-on packaging we may specify that an application
 # sub-dir should be added to the root chrome manifest with
 # a specific application id.
 MAKE_JARS_FLAGS += --root-manifest-entry-appid='$(XPI_ROOT_APPID)'
@@ -1316,16 +1314,23 @@ endif
 
 libs realchrome:: $(FINAL_TARGET)/chrome
 	$(call py_action,jar_maker,\
 	  $(QUIET) -j $(FINAL_TARGET)/chrome \
 	  $(MAKE_JARS_FLAGS) $(XULPPFLAGS) $(DEFINES) $(ACDEFINES) \
 	  $(JAR_MANIFEST))
 
 endif
+
+# This is a temporary check to ensure patches relying on the old behavior
+# of silently picking up jar.mn files continue to work.
+else # No JAR_MANIFEST
+ifneq (,$(wildcard $(srcdir)/jar.mn))
+$(error $(srcdir) contains a jar.mn file but this file is not declared in a JAR_MANIFESTS variable in a moz.build file)
+endif
 endif
 
 ifneq ($(DIST_FILES),)
 DIST_FILES_PATH := $(FINAL_TARGET)
 DIST_FILES_FLAGS := $(XULAPP_DEFINES)
 PP_TARGETS += DIST_FILES
 endif
 
--- a/config/tests/src-simple/Makefile.in
+++ b/config/tests/src-simple/Makefile.in
@@ -1,16 +1,18 @@
 #
 # This Source Code Form is subject to the terms of the Mozilla Public
 # License, v. 2.0. If a copy of the MPL was not distributed with this
 # file, You can obtain one at http://mozilla.org/MPL/2.0/.
 
 LOCALE_SRCDIR = $(srcdir)/l10n
 
+EXTERNALLY_MANAGED_MAKE_FILE := 1
 STANDALONE_MAKEFILE := 1
+JAR_MANIFEST := $(srcdir)/jar.mn
 
 include $(topsrcdir)/config/config.mk
 
 XPI_NAME = test_jar_mn
 
 DEFINES += \
 	-DAB_CD=ab-X-stuff \
 	$(NULL)
--- a/config/tests/src-simple/moz.build
+++ b/config/tests/src-simple/moz.build
@@ -1,6 +1,7 @@
 # -*- Mode: python; c-basic-offset: 4; indent-tabs-mode: nil; tab-width: 40 -*-
 # vim: set filetype=python:
 # This Source Code Form is subject to the terms of the Mozilla Public
 # License, v. 2.0. If a copy of the MPL was not distributed with this
 # file, You can obtain one at http://mozilla.org/MPL/2.0/.
 
+JAR_MANIFESTS += ['jar.mn']
\ No newline at end of file
--- a/content/base/public/nsIMessageManager.idl
+++ b/content/base/public/nsIMessageManager.idl
@@ -354,38 +354,41 @@ interface nsIContentFrameMessageManager 
 };
 
 [uuid(a2325927-9c0c-437d-9215-749c79235031)]
 interface nsIInProcessContentFrameMessageManager : nsIContentFrameMessageManager
 {
   [notxpcom] nsIContent getOwnerContent();
 };
 
-[scriptable, builtinclass, uuid(ecebfb8c-ff51-11e2-9d65-7af553959281)]
+[scriptable, builtinclass, uuid(6fb78110-45ae-11e3-8f96-0800200c9a66)]
 interface nsIFrameScriptLoader : nsISupports
 {
   /**
    * Load a script in the (remote) frame. aURL must be the absolute URL.
    * data: URLs are also supported. For example data:,dump("foo\n");
    * If aAllowDelayedLoad is true, script will be loaded when the
    * remote frame becomes available. Otherwise the script will be loaded
    * only if the frame is already available.
    */
-  void loadFrameScript(in AString aURL, in boolean aAllowDelayedLoad);
+  void loadFrameScript(in AString aURL, in boolean aAllowDelayedLoad,
+                       [optional] in boolean aRunInGlobalScope);
 
   /**
    * Removes aURL from the list of scripts which support delayed load.
    */
   void removeDelayedFrameScript(in AString aURL);
 
   /**
-   * Returns a list of all delayed scripts that will be loaded once
-   * a (remote) frame becomes available.
+   * Returns all delayed scripts that will be loaded once a (remote)
+   * frame becomes available. The return value is a list of pairs
+   * [<URL>, <WasLoadedInGlobalScope>].
    */
-  nsIDOMDOMStringList getDelayedFrameScripts();
+  [implicit_jscontext]
+  jsval getDelayedFrameScripts();
 };
 
 [scriptable, builtinclass, uuid(ad57800b-ff21-4e2f-91d3-e68615ae8afe)]
 interface nsIProcessChecker : nsISupports
 {
 
   /**
    * Return true if the "remote" process has |aPermission|.  This is
--- a/content/base/src/nsDocument.cpp
+++ b/content/base/src/nsDocument.cpp
@@ -8560,21 +8560,27 @@ static void
 FireOrClearDelayedEvents(nsTArray<nsCOMPtr<nsIDocument> >& aDocuments,
                          bool aFireEvents)
 {
   nsIFocusManager* fm = nsFocusManager::GetFocusManager();
   if (!fm)
     return;
 
   for (uint32_t i = 0; i < aDocuments.Length(); ++i) {
+    // NB: Don't bother trying to fire delayed events on documents that were
+    // closed before this event ran.
     if (!aDocuments[i]->EventHandlingSuppressed()) {
       fm->FireDelayedEvents(aDocuments[i]);
       nsCOMPtr<nsIPresShell> shell = aDocuments[i]->GetShell();
       if (shell) {
-        shell->FireOrClearDelayedEvents(aFireEvents);
+        // Only fire events for active documents.
+        bool fire = aFireEvents &&
+                    aDocuments[i]->GetInnerWindow() &&
+                    aDocuments[i]->GetInnerWindow()->IsCurrentInnerWindow();
+        shell->FireOrClearDelayedEvents(fire);
       }
     }
   }
 }
 
 void
 nsDocument::MaybePreLoadImage(nsIURI* uri, const nsAString &aCrossOriginAttr)
 {
--- a/content/base/src/nsFrameLoader.cpp
+++ b/content/base/src/nsFrameLoader.cpp
@@ -1682,17 +1682,18 @@ nsFrameLoader::MaybeCreateDocShell()
     if (os) {
       os->NotifyObservers(NS_ISUPPORTS_CAST(nsIFrameLoader*, this),
                           "in-process-browser-or-app-frame-shown", nullptr);
     }
 
     if (mMessageManager) {
       mMessageManager->LoadFrameScript(
         NS_LITERAL_STRING("chrome://global/content/BrowserElementChild.js"),
-        /* allowDelayedLoad = */ true);
+        /* allowDelayedLoad = */ true,
+        /* aRunInGlobalScope */ true);
     }
   }
 
   return NS_OK;
 }
 
 void
 nsFrameLoader::GetURL(nsString& aURI)
@@ -2183,26 +2184,26 @@ nsFrameLoader::CreateStaticClone(nsIFram
   nsCOMPtr<nsIDocument> clonedDoc = doc->CreateStaticClone(dest->mDocShell);
   nsCOMPtr<nsIDOMDocument> clonedDOMDoc = do_QueryInterface(clonedDoc);
 
   viewer->SetDOMDocument(clonedDOMDoc);
   return NS_OK;
 }
 
 bool
-nsFrameLoader::DoLoadFrameScript(const nsAString& aURL)
+nsFrameLoader::DoLoadFrameScript(const nsAString& aURL, bool aRunInGlobalScope)
 {
   mozilla::dom::PBrowserParent* tabParent = GetRemoteBrowser();
   if (tabParent) {
-    return tabParent->SendLoadRemoteScript(nsString(aURL));
+    return tabParent->SendLoadRemoteScript(nsString(aURL), aRunInGlobalScope);
   }
   nsRefPtr<nsInProcessTabChildGlobal> tabChild =
     static_cast<nsInProcessTabChildGlobal*>(GetTabChildGlobalAsEventTarget());
   if (tabChild) {
-    tabChild->LoadFrameScript(aURL);
+    tabChild->LoadFrameScript(aURL, aRunInGlobalScope);
   }
   return true;
 }
 
 class nsAsyncMessageToChild : public nsRunnable
 {
 public:
   nsAsyncMessageToChild(JSContext* aCx,
--- a/content/base/src/nsFrameLoader.h
+++ b/content/base/src/nsFrameLoader.h
@@ -180,17 +180,18 @@ public:
   void Finalize();
   nsIDocShell* GetExistingDocShell() { return mDocShell; }
   mozilla::dom::EventTarget* GetTabChildGlobalAsEventTarget();
   nsresult CreateStaticClone(nsIFrameLoader* aDest);
 
   /**
    * MessageManagerCallback methods that we override.
    */
-  virtual bool DoLoadFrameScript(const nsAString& aURL) MOZ_OVERRIDE;
+  virtual bool DoLoadFrameScript(const nsAString& aURL,
+                                 bool aRunInGlobalScope) MOZ_OVERRIDE;
   virtual bool DoSendAsyncMessage(JSContext* aCx,
                                   const nsAString& aMessage,
                                   const mozilla::dom::StructuredCloneData& aData,
                                   JS::Handle<JSObject *> aCpows,
                                   nsIPrincipal* aPrincipal) MOZ_OVERRIDE;
   virtual bool CheckPermission(const nsAString& aPermission) MOZ_OVERRIDE;
   virtual bool CheckManifestURL(const nsAString& aManifestURL) MOZ_OVERRIDE;
   virtual bool CheckAppHasPermission(const nsAString& aPermission) MOZ_OVERRIDE;
--- a/content/base/src/nsFrameMessageManager.cpp
+++ b/content/base/src/nsFrameMessageManager.cpp
@@ -389,73 +389,98 @@ nsFrameMessageManager::RemoveWeakMessage
 
   return NS_OK;
 }
 
 // nsIFrameScriptLoader
 
 NS_IMETHODIMP
 nsFrameMessageManager::LoadFrameScript(const nsAString& aURL,
-                                       bool aAllowDelayedLoad)
+                                       bool aAllowDelayedLoad,
+                                       bool aRunInGlobalScope)
 {
   if (aAllowDelayedLoad) {
     if (IsGlobal() || IsWindowLevel()) {
       // Cache for future windows or frames
       mPendingScripts.AppendElement(aURL);
+      mPendingScriptsGlobalStates.AppendElement(aRunInGlobalScope);
     } else if (!mCallback) {
       // We're frame message manager, which isn't connected yet.
       mPendingScripts.AppendElement(aURL);
+      mPendingScriptsGlobalStates.AppendElement(aRunInGlobalScope);
       return NS_OK;
     }
   }
 
   if (mCallback) {
 #ifdef DEBUG_smaug
     printf("Will load %s \n", NS_ConvertUTF16toUTF8(aURL).get());
 #endif
-    NS_ENSURE_TRUE(mCallback->DoLoadFrameScript(aURL), NS_ERROR_FAILURE);
+    NS_ENSURE_TRUE(mCallback->DoLoadFrameScript(aURL, aRunInGlobalScope),
+                   NS_ERROR_FAILURE);
   }
 
   for (int32_t i = 0; i < mChildManagers.Count(); ++i) {
     nsRefPtr<nsFrameMessageManager> mm =
       static_cast<nsFrameMessageManager*>(mChildManagers[i]);
     if (mm) {
       // Use false here, so that child managers don't cache the script, which
       // is already cached in the parent.
-      mm->LoadFrameScript(aURL, false);
+      mm->LoadFrameScript(aURL, false, aRunInGlobalScope);
     }
   }
   return NS_OK;
 }
 
 NS_IMETHODIMP
 nsFrameMessageManager::RemoveDelayedFrameScript(const nsAString& aURL)
 {
-  mPendingScripts.RemoveElement(aURL);
+  for (uint32_t i = 0; i < mPendingScripts.Length(); ++i) {
+    if (mPendingScripts[i] == aURL) {
+      mPendingScripts.RemoveElementAt(i);
+      mPendingScriptsGlobalStates.RemoveElementAt(i);
+      break;
+    }
+  }
   return NS_OK;
 }
 
 NS_IMETHODIMP
-nsFrameMessageManager::GetDelayedFrameScripts(nsIDOMDOMStringList** aList)
+nsFrameMessageManager::GetDelayedFrameScripts(JSContext* aCx, JS::Value* aList)
 {
   // Frame message managers may return an incomplete list because scripts
   // that were loaded after it was connected are not added to the list.
   if (!IsGlobal() && !IsWindowLevel()) {
     NS_WARNING("Cannot retrieve list of pending frame scripts for frame"
                "message managers as it may be incomplete");
     return NS_ERROR_NOT_IMPLEMENTED;
   }
 
-  nsRefPtr<nsDOMStringList> scripts = new nsDOMStringList();
+  JS::Rooted<JSObject*> array(aCx, JS_NewArrayObject(aCx, mPendingScripts.Length(), nullptr));
+  NS_ENSURE_TRUE(array, NS_ERROR_OUT_OF_MEMORY);
+
+  JS::Rooted<JSString*> url(aCx);
+  JS::Rooted<JSObject*> pair(aCx);
+  JS::Rooted<JS::Value> pairVal(aCx);
+  for (uint32_t i = 0; i < mPendingScripts.Length(); ++i) {
+    url = JS_NewUCStringCopyN(aCx, mPendingScripts[i].get(), mPendingScripts[i].Length());
+    NS_ENSURE_TRUE(url, NS_ERROR_OUT_OF_MEMORY);
 
-  for (uint32_t i = 0; i < mPendingScripts.Length(); ++i) {
-    scripts->Add(mPendingScripts[i]);
+    JS::Value pairElts[] = { JS::StringValue(url),
+                             JS::BooleanValue(mPendingScriptsGlobalStates[i]) };
+
+    pair = JS_NewArrayObject(aCx, 2, pairElts);
+    NS_ENSURE_TRUE(pair, NS_ERROR_OUT_OF_MEMORY);
+
+    pairVal = JS::ObjectValue(*pair);
+    NS_ENSURE_TRUE(JS_SetElement(aCx, array, i, &pairVal),
+                   NS_ERROR_OUT_OF_MEMORY);
   }
 
-  scripts.forget(aList);
+  *aList = JS::ObjectValue(*array);
 
   return NS_OK;
 }
 
 static bool
 JSONCreator(const jschar* aBuf, uint32_t aLen, void* aData)
 {
   nsAString* result = static_cast<nsAString*>(aData);
@@ -1044,21 +1069,23 @@ nsFrameMessageManager::AddChildManager(n
     nsRefPtr<nsFrameMessageManager> kungfuDeathGrip = this;
     nsRefPtr<nsFrameMessageManager> kungfuDeathGrip2 = aManager;
     // We have parent manager if we're a window message manager.
     // In that case we want to load the pending scripts from global
     // message manager.
     if (mParentManager) {
       nsRefPtr<nsFrameMessageManager> globalMM = mParentManager;
       for (uint32_t i = 0; i < globalMM->mPendingScripts.Length(); ++i) {
-        aManager->LoadFrameScript(globalMM->mPendingScripts[i], false);
+        aManager->LoadFrameScript(globalMM->mPendingScripts[i], false,
+                                  globalMM->mPendingScriptsGlobalStates[i]);
       }
     }
     for (uint32_t i = 0; i < mPendingScripts.Length(); ++i) {
-      aManager->LoadFrameScript(mPendingScripts[i], false);
+      aManager->LoadFrameScript(mPendingScripts[i], false,
+                                mPendingScriptsGlobalStates[i]);
     }
   }
 }
 
 void
 nsFrameMessageManager::SetCallback(MessageManagerCallback* aCallback, bool aLoadScripts)
 {
   NS_ASSERTION(!mIsBroadcaster || !mCallback,
@@ -1069,17 +1096,17 @@ nsFrameMessageManager::SetCallback(Messa
       mOwnedCallback = aCallback;
     }
     // First load global scripts by adding this to parent manager.
     if (mParentManager) {
       mParentManager->AddChildManager(this, aLoadScripts);
     }
     if (aLoadScripts) {
       for (uint32_t i = 0; i < mPendingScripts.Length(); ++i) {
-        LoadFrameScript(mPendingScripts[i], false);
+        LoadFrameScript(mPendingScripts[i], false, mPendingScriptsGlobalStates[i]);
       }
     }
   }
 }
 
 void
 nsFrameMessageManager::RemoveFromParent()
 {
@@ -1297,41 +1324,46 @@ NS_NewGlobalMessageManager(nsIMessageBro
                  NS_ERROR_NOT_AVAILABLE);
   nsFrameMessageManager* mm = new nsFrameMessageManager(nullptr,
                                                         nullptr,
                                                         MM_CHROME | MM_GLOBAL | MM_BROADCASTER);
   RegisterStrongMemoryReporter(new MessageManagerReporter());
   return CallQueryInterface(mm, aResult);
 }
 
-nsDataHashtable<nsStringHashKey, nsFrameJSScriptExecutorHolder*>*
+nsDataHashtable<nsStringHashKey, nsFrameScriptObjectExecutorHolder*>*
   nsFrameScriptExecutor::sCachedScripts = nullptr;
 nsScriptCacheCleaner* nsFrameScriptExecutor::sScriptCacheCleaner = nullptr;
 
 void
 nsFrameScriptExecutor::DidCreateGlobal()
 {
   NS_ASSERTION(mGlobal, "Should have mGlobal!");
   if (!sCachedScripts) {
     sCachedScripts =
-      new nsDataHashtable<nsStringHashKey, nsFrameJSScriptExecutorHolder*>;
+      new nsDataHashtable<nsStringHashKey, nsFrameScriptObjectExecutorHolder*>;
 
     nsRefPtr<nsScriptCacheCleaner> scriptCacheCleaner =
       new nsScriptCacheCleaner();
     scriptCacheCleaner.forget(&sScriptCacheCleaner);
   }
 }
 
 static PLDHashOperator
 CachedScriptUnrooter(const nsAString& aKey,
-                       nsFrameJSScriptExecutorHolder*& aData,
-                       void* aUserArg)
+                     nsFrameScriptObjectExecutorHolder*& aData,
+                     void* aUserArg)
 {
   JSContext* cx = static_cast<JSContext*>(aUserArg);
-  JS_RemoveScriptRoot(cx, &(aData->mScript));
+  if (aData->mScript) {
+    JS_RemoveScriptRoot(cx, &aData->mScript);
+  }
+  if (aData->mFunction) {
+    JS_RemoveObjectRoot(cx, &aData->mFunction);
+  }
   delete aData;
   return PL_DHASH_REMOVE;
 }
 
 // static
 void
 nsFrameScriptExecutor::Shutdown()
 {
@@ -1344,41 +1376,63 @@ nsFrameScriptExecutor::Shutdown()
     sCachedScripts = nullptr;
 
     nsRefPtr<nsScriptCacheCleaner> scriptCacheCleaner;
     scriptCacheCleaner.swap(sScriptCacheCleaner);
   }
 }
 
 void
-nsFrameScriptExecutor::LoadFrameScriptInternal(const nsAString& aURL)
+nsFrameScriptExecutor::LoadFrameScriptInternal(const nsAString& aURL,
+                                               bool aRunInGlobalScope)
 {
   if (!mGlobal || !sCachedScripts) {
     return;
   }
 
-  nsFrameJSScriptExecutorHolder* holder = sCachedScripts->Get(aURL);
-  if (!holder) {
-    TryCacheLoadAndCompileScript(aURL, EXECUTE_IF_CANT_CACHE);
-    holder = sCachedScripts->Get(aURL);
+  AutoSafeJSContext cx;
+  JS::Rooted<JSScript*> script(cx);
+  JS::Rooted<JSObject*> funobj(cx);
+
+  nsFrameScriptObjectExecutorHolder* holder = sCachedScripts->Get(aURL);
+  if (holder && holder->WillRunInGlobalScope() == aRunInGlobalScope) {
+    script = holder->mScript;
+    funobj = holder->mFunction;
+  } else {
+    // Don't put anything in the cache if we already have an entry
+    // with a different WillRunInGlobalScope() value.
+    bool shouldCache = !holder;
+    TryCacheLoadAndCompileScript(aURL, aRunInGlobalScope,
+                                 shouldCache, &script, &funobj);
   }
 
-  if (holder) {
-    AutoSafeJSContext cx;
-    JS::Rooted<JSObject*> global(cx, mGlobal->GetJSObject());
-    if (global) {
-      JSAutoCompartment ac(cx, global);
-      (void) JS_ExecuteScript(cx, global, holder->mScript, nullptr);
+  JS::Rooted<JSObject*> global(cx, mGlobal->GetJSObject());
+  if (global) {
+    JSAutoCompartment ac(cx, global);
+    if (funobj) {
+      JS::Rooted<JSObject*> method(cx, JS_CloneFunctionObject(cx, funobj, global));
+      if (!method) {
+        return;
+      }
+      JS::Rooted<JS::Value> rval(cx);
+      JS::Rooted<JS::Value> methodVal(cx, JS::ObjectValue(*method));
+      (void) JS_CallFunctionValue(cx, global, methodVal,
+                                  0, nullptr, rval.address());
+    } else if (script) {
+      (void) JS_ExecuteScript(cx, global, script, nullptr);
     }
   }
 }
 
 void
 nsFrameScriptExecutor::TryCacheLoadAndCompileScript(const nsAString& aURL,
-                                                    CacheFailedBehavior aBehavior)
+                                                    bool aRunInGlobalScope,
+                                                    bool aShouldCache,
+                                                    JS::MutableHandle<JSScript*> aScriptp,
+                                                    JS::MutableHandle<JSObject*> aFunp)
 {
   nsCString url = NS_ConvertUTF16toUTF8(aURL);
   nsCOMPtr<nsIURI> uri;
   nsresult rv = NS_NewURI(getter_AddRefs(uri), url);
   if (NS_FAILED(rv)) {
     return;
   }
 
@@ -1415,42 +1469,75 @@ nsFrameScriptExecutor::TryCacheLoadAndCo
   }
 
   if (!dataString.IsEmpty()) {
     AutoSafeJSContext cx;
     JS::Rooted<JSObject*> global(cx, mGlobal->GetJSObject());
     if (global) {
       JSAutoCompartment ac(cx, global);
       JS::CompileOptions options(cx);
-      options.setNoScriptRval(true)
-             .setFileAndLine(url.get(), 1)
+      options.setFileAndLine(url.get(), 1)
              .setPrincipals(nsJSPrincipals::get(mPrincipal));
-      JS::Rooted<JSScript*> script(cx,
-        JS::Compile(cx, JS::NullPtr(), options, dataString.get(),
-                    dataString.Length()));
+      JS::Rooted<JSScript*> script(cx);
+      JS::Rooted<JSObject*> funobj(cx);
+      if (aRunInGlobalScope) {
+        options.setNoScriptRval(true);
+        script = JS::Compile(cx, JS::NullPtr(), options, dataString.get(),
+                             dataString.Length());
+      } else {
+        JS::Rooted<JSFunction *> fun(cx);
+        fun = JS::CompileFunction(cx, JS::NullPtr(), options,
+                                  nullptr, 0, nullptr, /* name, nargs, args */
+                                  dataString.get(),
+                                  dataString.Length());
+        if (!fun) {
+          return;
+        }
+        funobj = JS_GetFunctionObject(fun);
+      }
 
-      if (script) {
-        nsAutoCString scheme;
-        uri->GetScheme(scheme);
-        // We don't cache data: scripts!
-        if (!scheme.EqualsLiteral("data")) {
-          nsFrameJSScriptExecutorHolder* holder =
-            new nsFrameJSScriptExecutorHolder(script);
-          // Root the object also for caching.
-          JS_AddNamedScriptRoot(cx, &(holder->mScript),
+      if (!script && !funobj) {
+        return;
+      }
+
+      aScriptp.set(script);
+      aFunp.set(funobj);
+
+      nsAutoCString scheme;
+      uri->GetScheme(scheme);
+      // We don't cache data: scripts!
+      if (aShouldCache && !scheme.EqualsLiteral("data")) {
+        nsFrameScriptObjectExecutorHolder* holder;
+
+        // Root the object also for caching.
+        if (script) {
+          holder = new nsFrameScriptObjectExecutorHolder(script);
+          JS_AddNamedScriptRoot(cx, &holder->mScript,
                                 "Cached message manager script");
-          sCachedScripts->Put(aURL, holder);
-        } else if (aBehavior == EXECUTE_IF_CANT_CACHE) {
-          (void) JS_ExecuteScript(cx, global, script, nullptr);
+        } else {
+          holder = new nsFrameScriptObjectExecutorHolder(funobj);
+          JS_AddNamedObjectRoot(cx, &holder->mFunction,
+                                "Cached message manager function");
         }
+        sCachedScripts->Put(aURL, holder);
       }
     }
   }
 }
 
+void
+nsFrameScriptExecutor::TryCacheLoadAndCompileScript(const nsAString& aURL,
+                                                    bool aRunInGlobalScope)
+{
+  AutoSafeJSContext cx;
+  JS::Rooted<JSScript*> script(cx);
+  JS::Rooted<JSObject*> funobj(cx);
+  TryCacheLoadAndCompileScript(aURL, aRunInGlobalScope, true, &script, &funobj);
+}
+
 bool
 nsFrameScriptExecutor::InitTabChildGlobalInternal(nsISupports* aScope,
                                                   const nsACString& aID)
 {
 
   nsCOMPtr<nsIJSRuntimeService> runtimeSvc =
     do_GetService("@mozilla.org/js/xpc/RuntimeService;1");
   NS_ENSURE_TRUE(runtimeSvc, false);
--- a/content/base/src/nsFrameMessageManager.h
+++ b/content/base/src/nsFrameMessageManager.h
@@ -48,17 +48,17 @@ enum MessageManagerFlags {
   MM_OWNSCALLBACK = 16
 };
 
 class MessageManagerCallback
 {
 public:
   virtual ~MessageManagerCallback() {}
 
-  virtual bool DoLoadFrameScript(const nsAString& aURL)
+  virtual bool DoLoadFrameScript(const nsAString& aURL, bool aRunInGlobalScope)
   {
     return true;
   }
 
   virtual bool DoSendBlockingMessage(JSContext* aCx,
                                      const nsAString& aMessage,
                                      const StructuredCloneData& aData,
                                      JS::Handle<JSObject*> aCpows,
@@ -291,16 +291,17 @@ protected:
   bool mIsBroadcaster; // true if the message manager is a broadcaster
   bool mOwnsCallback;
   bool mHandlingMessage;
   bool mDisconnected;
   mozilla::dom::ipc::MessageManagerCallback* mCallback;
   nsAutoPtr<mozilla::dom::ipc::MessageManagerCallback> mOwnedCallback;
   nsFrameMessageManager* mParentManager;
   nsTArray<nsString> mPendingScripts;
+  nsTArray<bool> mPendingScriptsGlobalStates;
 public:
   static nsFrameMessageManager* sParentProcessManager;
   static nsFrameMessageManager* sChildProcessManager;
   static nsFrameMessageManager* sSameProcessParentManager;
   static nsTArray<nsCOMPtr<nsIRunnable> >* sPendingSameProcessAsyncMessages;
 private:
   enum ProcessCheckerType {
     PROCESS_CHECKER_PERMISSION,
@@ -309,49 +310,63 @@ private:
   };
   nsresult AssertProcessInternal(ProcessCheckerType aType,
                                  const nsAString& aCapability,
                                  bool* aValid);
 };
 
 class nsScriptCacheCleaner;
 
-struct nsFrameJSScriptExecutorHolder
+struct nsFrameScriptObjectExecutorHolder
 {
-  nsFrameJSScriptExecutorHolder(JSScript* aScript) : mScript(aScript)
-  { MOZ_COUNT_CTOR(nsFrameJSScriptExecutorHolder); }
-  ~nsFrameJSScriptExecutorHolder()
-  { MOZ_COUNT_DTOR(nsFrameJSScriptExecutorHolder); }
+  nsFrameScriptObjectExecutorHolder(JSScript* aScript) : mScript(aScript), mFunction(nullptr)
+  { MOZ_COUNT_CTOR(nsFrameScriptObjectExecutorHolder); }
+  nsFrameScriptObjectExecutorHolder(JSObject* aFunction) : mScript(nullptr), mFunction(aFunction)
+  { MOZ_COUNT_CTOR(nsFrameScriptObjectExecutorHolder); }
+  ~nsFrameScriptObjectExecutorHolder()
+  { MOZ_COUNT_DTOR(nsFrameScriptObjectExecutorHolder); }
+
+  bool WillRunInGlobalScope() { return mScript; }
+
+  // We use JS_AddNamed{Script,Object}Root to root these fields explicitly, so
+  // no need for Heap<T>.
   JSScript* mScript;
+  JSObject* mFunction;
 };
 
+class nsFrameScriptObjectExecutorStackHolder;
+
 class nsFrameScriptExecutor
 {
 public:
   static void Shutdown();
   already_AddRefed<nsIXPConnectJSObjectHolder> GetGlobal()
   {
     nsCOMPtr<nsIXPConnectJSObjectHolder> ref = mGlobal;
     return ref.forget();
   }
 protected:
   friend class nsFrameScriptCx;
   nsFrameScriptExecutor()
   { MOZ_COUNT_CTOR(nsFrameScriptExecutor); }
   ~nsFrameScriptExecutor()
   { MOZ_COUNT_DTOR(nsFrameScriptExecutor); }
   void DidCreateGlobal();
-  void LoadFrameScriptInternal(const nsAString& aURL);
-  enum CacheFailedBehavior { EXECUTE_IF_CANT_CACHE, DONT_EXECUTE };
+  void LoadFrameScriptInternal(const nsAString& aURL, bool aRunInGlobalScope);
   void TryCacheLoadAndCompileScript(const nsAString& aURL,
-                                    CacheFailedBehavior aBehavior = DONT_EXECUTE);
+                                    bool aRunInGlobalScope,
+                                    bool aShouldCache,
+                                    JS::MutableHandle<JSScript*> aScriptp,
+                                    JS::MutableHandle<JSObject*> aFunp);
+  void TryCacheLoadAndCompileScript(const nsAString& aURL,
+                                    bool aRunInGlobalScope);
   bool InitTabChildGlobalInternal(nsISupports* aScope, const nsACString& aID);
   nsCOMPtr<nsIXPConnectJSObjectHolder> mGlobal;
   nsCOMPtr<nsIPrincipal> mPrincipal;
-  static nsDataHashtable<nsStringHashKey, nsFrameJSScriptExecutorHolder*>* sCachedScripts;
+  static nsDataHashtable<nsStringHashKey, nsFrameScriptObjectExecutorHolder*>* sCachedScripts;
   static nsScriptCacheCleaner* sScriptCacheCleaner;
 };
 
 class nsScriptCacheCleaner MOZ_FINAL : public nsIObserver
 {
   NS_DECL_ISUPPORTS
 
   nsScriptCacheCleaner()
--- a/content/base/src/nsInProcessTabChildGlobal.cpp
+++ b/content/base/src/nsInProcessTabChildGlobal.cpp
@@ -1,9 +1,9 @@
-/* -*- Mode: C++; c-basic-offset: 4; indent-tabs-mode: nil; tab-width: 8; -*- */
+/* -*- Mode: C++; c-basic-offset: 2; indent-tabs-mode: nil; tab-width: 8; -*- */
 /* vim: set sw=4 ts=8 et tw=80 : */
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #include "nsInProcessTabChildGlobal.h"
 #include "nsContentUtils.h"
 #include "nsIScriptSecurityManager.h"
@@ -330,40 +330,42 @@ nsInProcessTabChildGlobal::InitTabChildG
   nsISupports* scopeSupports = NS_ISUPPORTS_CAST(EventTarget*, this);
   NS_ENSURE_STATE(InitTabChildGlobalInternal(scopeSupports, id));
   return NS_OK;
 }
 
 class nsAsyncScriptLoad : public nsRunnable
 {
 public:
-  nsAsyncScriptLoad(nsInProcessTabChildGlobal* aTabChild, const nsAString& aURL)
-  : mTabChild(aTabChild), mURL(aURL) {}
+    nsAsyncScriptLoad(nsInProcessTabChildGlobal* aTabChild, const nsAString& aURL,
+                      bool aRunInGlobalScope)
+      : mTabChild(aTabChild), mURL(aURL), mRunInGlobalScope(aRunInGlobalScope) {}
 
   NS_IMETHOD Run()
   {
-    mTabChild->LoadFrameScript(mURL);
+    mTabChild->LoadFrameScript(mURL, mRunInGlobalScope);
     return NS_OK;
   }
   nsRefPtr<nsInProcessTabChildGlobal> mTabChild;
   nsString mURL;
+  bool mRunInGlobalScope;
 };
 
 void
-nsInProcessTabChildGlobal::LoadFrameScript(const nsAString& aURL)
+nsInProcessTabChildGlobal::LoadFrameScript(const nsAString& aURL, bool aRunInGlobalScope)
 {
   if (!nsContentUtils::IsSafeToRunScript()) {
-    nsContentUtils::AddScriptRunner(new nsAsyncScriptLoad(this, aURL));
+    nsContentUtils::AddScriptRunner(new nsAsyncScriptLoad(this, aURL, aRunInGlobalScope));
     return;
   }
   if (!mInitialized) {
     mInitialized = true;
     Init();
   }
   bool tmp = mLoadingScript;
   mLoadingScript = true;
-  LoadFrameScriptInternal(aURL);
+  LoadFrameScriptInternal(aURL, aRunInGlobalScope);
   mLoadingScript = tmp;
   if (!mLoadingScript && mDelayedDisconnect) {
     mDelayedDisconnect = false;
     Disconnect();
   }
 }
--- a/content/base/src/nsInProcessTabChildGlobal.h
+++ b/content/base/src/nsInProcessTabChildGlobal.h
@@ -114,17 +114,17 @@ public:
                                                     aUseCapture,
                                                     aWantsUntrusted,
                                                     optional_argc);
   }
   using nsDOMEventTargetHelper::AddEventListener;
 
   virtual JSContext* GetJSContextForEventHandlers() MOZ_OVERRIDE { return nsContentUtils::GetSafeJSContext(); }
   virtual nsIPrincipal* GetPrincipal() MOZ_OVERRIDE { return mPrincipal; }
-  void LoadFrameScript(const nsAString& aURL);
+  void LoadFrameScript(const nsAString& aURL, bool aRunInGlobalScope);
   void Disconnect();
   void SendMessageToParent(const nsString& aMessage, bool aSync,
                            const nsString& aJSON,
                            nsTArray<nsString>* aJSONRetVal);
   nsFrameMessageManager* GetInnerManager()
   {
     return static_cast<nsFrameMessageManager*>(mMessageManager.get());
   }
--- a/content/media/wmf/WMFByteStream.cpp
+++ b/content/media/wmf/WMFByteStream.cpp
@@ -21,19 +21,19 @@
 #include "mozilla/DebugOnly.h"
 #include <algorithm>
 #include <cassert>
 
 namespace mozilla {
 
 #ifdef PR_LOGGING
 PRLogModuleInfo* gWMFByteStreamLog = nullptr;
-#define LOG(...) PR_LOG(gWMFByteStreamLog, PR_LOG_DEBUG, (__VA_ARGS__))
+#define WMF_BS_LOG(...) PR_LOG(gWMFByteStreamLog, PR_LOG_DEBUG, (__VA_ARGS__))
 #else
-#define LOG(...)
+#define WMF_BS_LOG(...)
 #endif
 
 // Limit the number of threads that we use for IO.
 static const uint32_t NumWMFIoThreads = 4;
 
 // Thread pool listener which ensures that MSCOM is initialized and
 // deinitialized on the thread pool thread. We can call back into WMF
 // on this thread, so we need MSCOM working.
@@ -111,30 +111,30 @@ WMFByteStream::WMFByteStream(MediaResour
   NS_ASSERTION(NS_IsMainThread(), "Must be on main thread.");
   NS_ASSERTION(mSourceReaderCallback, "Must have a source reader callback.");
 
 #ifdef PR_LOGGING
   if (!gWMFByteStreamLog) {
     gWMFByteStreamLog = PR_NewLogModule("WMFByteStream");
   }
 #endif
-  LOG("[%p] WMFByteStream CTOR", this);
+  WMF_BS_LOG("[%p] WMFByteStream CTOR", this);
   MOZ_COUNT_CTOR(WMFByteStream);
 }
 
 WMFByteStream::~WMFByteStream()
 {
   MOZ_COUNT_DTOR(WMFByteStream);
   // The WMFByteStream can be deleted from a thread pool thread, so we
   // dispatch an event to the main thread to deref the thread pool and
   // deref the MediaResource.
   nsCOMPtr<nsIRunnable> event =
     new ReleaseWMFByteStreamResourcesEvent(mResource.forget());
   NS_DispatchToMainThread(event, NS_DISPATCH_NORMAL);
-  LOG("[%p] WMFByteStream DTOR", this);
+  WMF_BS_LOG("[%p] WMFByteStream DTOR", this);
 }
 
 nsresult
 WMFByteStream::Init()
 {
   NS_ASSERTION(NS_IsMainThread(), "Must be on main thread.");
 
   if (!sThreadPool) {
@@ -175,17 +175,17 @@ WMFByteStream::Init()
   if (!contentTypeUTF16.IsEmpty()) {
     HRESULT hr = wmf::MFCreateAttributes(byRef(mAttributes), 1);
     NS_ENSURE_TRUE(SUCCEEDED(hr), NS_ERROR_FAILURE);
 
     hr = mAttributes->SetString(MF_BYTESTREAM_CONTENT_TYPE,
                                 contentTypeUTF16.get());
     NS_ENSURE_TRUE(SUCCEEDED(hr), NS_ERROR_FAILURE);
 
-    LOG("[%p] WMFByteStream has Content-Type=%s", this, mResource->GetContentType().get());
+    WMF_BS_LOG("[%p] WMFByteStream has Content-Type=%s", this, mResource->GetContentType().get());
   }
   return NS_OK;
 }
 
 nsresult
 WMFByteStream::Shutdown()
 {
   {
@@ -195,17 +195,17 @@ WMFByteStream::Shutdown()
   mSourceReaderCallback->Cancel();
   return NS_OK;
 }
 
 // IUnknown Methods
 STDMETHODIMP
 WMFByteStream::QueryInterface(REFIID aIId, void **aInterface)
 {
-  LOG("[%p] WMFByteStream::QueryInterface %s", this, GetGUIDName(aIId).get());
+  WMF_BS_LOG("[%p] WMFByteStream::QueryInterface %s", this, GetGUIDName(aIId).get());
 
   if (aIId == IID_IMFByteStream) {
     return DoGetInterface(static_cast<IMFByteStream*>(this), aInterface);
   }
   if (aIId == IID_IUnknown) {
     return DoGetInterface(static_cast<IMFByteStream*>(this), aInterface);
   }
   if (aIId == IID_IMFAttributes) {
@@ -247,17 +247,17 @@ public:
 
 NS_IMPL_ADDREF(ReadRequest)
 NS_IMPL_RELEASE(ReadRequest)
 
 // IUnknown Methods
 STDMETHODIMP
 ReadRequest::QueryInterface(REFIID aIId, void **aInterface)
 {
-  LOG("ReadRequest::QueryInterface %s", GetGUIDName(aIId).get());
+  WMF_BS_LOG("ReadRequest::QueryInterface %s", GetGUIDName(aIId).get());
 
   if (aIId == IID_IUnknown) {
     return DoGetInterface(static_cast<IUnknown*>(this), aInterface);
   }
 
   *aInterface = nullptr;
   return E_NOINTERFACE;
 }
@@ -287,18 +287,18 @@ WMFByteStream::BeginRead(BYTE *aBuffer,
                          ULONG aLength,
                          IMFAsyncCallback *aCallback,
                          IUnknown *aCallerState)
 {
   NS_ENSURE_TRUE(aBuffer, E_POINTER);
   NS_ENSURE_TRUE(aCallback, E_POINTER);
 
   ReentrantMonitorAutoEnter mon(mReentrantMonitor);
-  LOG("[%p] WMFByteStream::BeginRead() mOffset=%lld tell=%lld length=%lu mIsShutdown=%d",
-      this, mOffset, mResource->Tell(), aLength, mIsShutdown);
+  WMF_BS_LOG("[%p] WMFByteStream::BeginRead() mOffset=%lld tell=%lld length=%lu mIsShutdown=%d",
+             this, mOffset, mResource->Tell(), aLength, mIsShutdown);
 
   if (mIsShutdown || mOffset < 0) {
     return E_INVALIDARG;
   }
 
   // Create an object to store our state.
   RefPtr<ReadRequest> requestState = new ReadRequest(mOffset, aBuffer, aLength);
 
@@ -354,49 +354,49 @@ WMFByteStream::Read(ReadRequest* aReques
 void
 WMFByteStream::ProcessReadRequest(IMFAsyncResult* aResult,
                                   ReadRequest* aRequestState)
 {
   if (mResource->GetLength() > -1 &&
       aRequestState->mOffset > mResource->GetLength()) {
     aResult->SetStatus(S_OK);
     wmf::MFInvokeCallback(aResult);
-    LOG("[%p] WMFByteStream::ProcessReadRequest() read offset greater than length, soft-failing read", this);
+    WMF_BS_LOG("[%p] WMFByteStream::ProcessReadRequest() read offset greater than length, soft-failing read", this);
     return;
   }
 
   nsresult rv = Read(aRequestState);
   if (NS_FAILED(rv)) {
     Shutdown();
     aResult->SetStatus(E_ABORT);
   } else {
     aResult->SetStatus(S_OK);
   }
 
-  LOG("[%p] WMFByteStream::ProcessReadRequest() read %d at %lld finished rv=%x",
-       this, aRequestState->mBytesRead, aRequestState->mOffset, rv);
+  WMF_BS_LOG("[%p] WMFByteStream::ProcessReadRequest() read %d at %lld finished rv=%x",
+             this, aRequestState->mBytesRead, aRequestState->mOffset, rv);
 
   // Let caller know read is complete.
   DebugOnly<HRESULT> hr = wmf::MFInvokeCallback(aResult);
   NS_ASSERTION(SUCCEEDED(hr), "Failed to invoke callback!");
 }
 
 STDMETHODIMP
 WMFByteStream::BeginWrite(const BYTE *, ULONG ,
                           IMFAsyncCallback *,
                           IUnknown *)
 {
-  LOG("[%p] WMFByteStream::BeginWrite()", this);
+  WMF_BS_LOG("[%p] WMFByteStream::BeginWrite()", this);
   return E_NOTIMPL;
 }
 
 STDMETHODIMP
 WMFByteStream::Close()
 {
-  LOG("[%p] WMFByteStream::Close()", this);
+  WMF_BS_LOG("[%p] WMFByteStream::Close()", this);
   return S_OK;
 }
 
 STDMETHODIMP
 WMFByteStream::EndRead(IMFAsyncResult* aResult, ULONG *aBytesRead)
 {
   NS_ENSURE_TRUE(aResult, E_POINTER);
   NS_ENSURE_TRUE(aBytesRead, E_POINTER);
@@ -410,40 +410,40 @@ WMFByteStream::EndRead(IMFAsyncResult* a
     return E_INVALIDARG;
   }
   ReadRequest* requestState =
     static_cast<ReadRequest*>(unknown.get());
 
   // Report result.
   *aBytesRead = requestState->mBytesRead;
 
-  LOG("[%p] WMFByteStream::EndRead() offset=%lld *aBytesRead=%u mOffset=%lld status=0x%x hr=0x%x eof=%d",
-      this, requestState->mOffset, *aBytesRead, mOffset, aResult->GetStatus(), hr, IsEOS());
+  WMF_BS_LOG("[%p] WMFByteStream::EndRead() offset=%lld *aBytesRead=%u mOffset=%lld status=0x%x hr=0x%x eof=%d",
+             this, requestState->mOffset, *aBytesRead, mOffset, aResult->GetStatus(), hr, IsEOS());
 
   return aResult->GetStatus();
 }
 
 STDMETHODIMP
 WMFByteStream::EndWrite(IMFAsyncResult *, ULONG *)
 {
-  LOG("[%p] WMFByteStream::EndWrite()", this);
+  WMF_BS_LOG("[%p] WMFByteStream::EndWrite()", this);
   return E_NOTIMPL;
 }
 
 STDMETHODIMP
 WMFByteStream::Flush()
 {
-  LOG("[%p] WMFByteStream::Flush()", this);
+  WMF_BS_LOG("[%p] WMFByteStream::Flush()", this);
   return S_OK;
 }
 
 STDMETHODIMP
 WMFByteStream::GetCapabilities(DWORD *aCapabilities)
 {
-  LOG("[%p] WMFByteStream::GetCapabilities()", this);
+  WMF_BS_LOG("[%p] WMFByteStream::GetCapabilities()", this);
   NS_ENSURE_TRUE(aCapabilities, E_POINTER);
   ReentrantMonitorAutoEnter mon(mReentrantMonitor);
   bool seekable = mResource->IsTransportSeekable();
   bool cached = mResource->IsDataCachedToEndOfResource(0);
   *aCapabilities = MFBYTESTREAM_IS_READABLE |
                    MFBYTESTREAM_IS_SEEKABLE |
                    (!cached ? MFBYTESTREAM_IS_PARTIALLY_DOWNLOADED : 0) |
                    (!seekable ? MFBYTESTREAM_HAS_SLOW_SEEK : 0);
@@ -458,27 +458,27 @@ WMFByteStream::GetCurrentPosition(QWORD 
   // Note: Returning the length of stream as position when read
   // cursor is < 0 seems to be the behaviour expected by WMF, but
   // also note it doesn't seem to expect that the position is an
   // unsigned value since if you seek to > length and read WMF
   // expects the read to succeed after reading 0 bytes, but if you
   // seek to < 0 and read, the read is expected to fails... So
   // go figure...
   *aPosition = mOffset < 0 ? mResource->GetLength() : mOffset;
-  LOG("[%p] WMFByteStream::GetCurrentPosition() %lld", this, mOffset);
+  WMF_BS_LOG("[%p] WMFByteStream::GetCurrentPosition() %lld", this, mOffset);
   return S_OK;
 }
 
 STDMETHODIMP
 WMFByteStream::GetLength(QWORD *aLength)
 {
   NS_ENSURE_TRUE(aLength, E_POINTER);
   ReentrantMonitorAutoEnter mon(mReentrantMonitor);
   *aLength = mResource->GetLength();
-  LOG("[%p] WMFByteStream::GetLength() %lld", this, *aLength);
+  WMF_BS_LOG("[%p] WMFByteStream::GetLength() %lld", this, *aLength);
   return S_OK;
 }
 
 bool
 WMFByteStream::IsEOS()
 {
   ReentrantMonitorAutoEnter mon(mReentrantMonitor);
   return mResource->GetLength() > -1 &&
@@ -486,45 +486,45 @@ WMFByteStream::IsEOS()
           mOffset >= mResource->GetLength());
 }
 
 STDMETHODIMP
 WMFByteStream::IsEndOfStream(BOOL *aEndOfStream)
 {
   NS_ENSURE_TRUE(aEndOfStream, E_POINTER);
   *aEndOfStream = IsEOS();
-  LOG("[%p] WMFByteStream::IsEndOfStream() %d", this, *aEndOfStream);
+  WMF_BS_LOG("[%p] WMFByteStream::IsEndOfStream() %d", this, *aEndOfStream);
   return S_OK;
 }
 
 STDMETHODIMP
 WMFByteStream::Read(BYTE* aBuffer, ULONG aBufferLength, ULONG* aOutBytesRead)
 {
   ReentrantMonitorAutoEnter mon(mReentrantMonitor);
   ReadRequest request(mOffset, aBuffer, aBufferLength);
   if (NS_FAILED(Read(&request))) {
-    LOG("[%p] WMFByteStream::Read() offset=%lld failed!", this, mOffset);
+    WMF_BS_LOG("[%p] WMFByteStream::Read() offset=%lld failed!", this, mOffset);
     return E_FAIL;
   }
   if (aOutBytesRead) {
     *aOutBytesRead = request.mBytesRead;
   }
-  LOG("[%p] WMFByteStream::Read() offset=%lld length=%u bytesRead=%u",
-      this, mOffset, aBufferLength, request.mBytesRead);
+  WMF_BS_LOG("[%p] WMFByteStream::Read() offset=%lld length=%u bytesRead=%u",
+             this, mOffset, aBufferLength, request.mBytesRead);
   mOffset += request.mBytesRead;
   return S_OK;
 }
 
 STDMETHODIMP
 WMFByteStream::Seek(MFBYTESTREAM_SEEK_ORIGIN aSeekOrigin,
                     LONGLONG aSeekOffset,
                     DWORD aSeekFlags,
                     QWORD *aCurrentPosition)
 {
-  LOG("[%p] WMFByteStream::Seek(%d, %lld)", this, aSeekOrigin, aSeekOffset);
+  WMF_BS_LOG("[%p] WMFByteStream::Seek(%d, %lld)", this, aSeekOrigin, aSeekOffset);
 
   ReentrantMonitorAutoEnter mon(mReentrantMonitor);
 
   int64_t offset = mOffset;
   if (aSeekOrigin == msoBegin) {
     offset = aSeekOffset;
   } else {
     offset += aSeekOffset;
@@ -541,40 +541,40 @@ WMFByteStream::Seek(MFBYTESTREAM_SEEK_OR
 
   return S_OK;
 }
 
 STDMETHODIMP
 WMFByteStream::SetCurrentPosition(QWORD aPosition)
 {
   ReentrantMonitorAutoEnter mon(mReentrantMonitor);
-  LOG("[%p] WMFByteStream::SetCurrentPosition(%lld)",
-      this, aPosition);
+  WMF_BS_LOG("[%p] WMFByteStream::SetCurrentPosition(%lld)",
+             this, aPosition);
 
   int64_t length = mResource->GetLength();
   if (length > -1) {
     mOffset = std::min<int64_t>(aPosition, length);
   } else {
     mOffset = aPosition;
   }
 
   return S_OK;
 }
 
 STDMETHODIMP
 WMFByteStream::SetLength(QWORD)
 {
-  LOG("[%p] WMFByteStream::SetLength()", this);
+  WMF_BS_LOG("[%p] WMFByteStream::SetLength()", this);
   return E_NOTIMPL;
 }
 
 STDMETHODIMP
 WMFByteStream::Write(const BYTE *, ULONG, ULONG *)
 {
-  LOG("[%p] WMFByteStream::Write()", this);
+  WMF_BS_LOG("[%p] WMFByteStream::Write()", this);
   return E_NOTIMPL;
 }
 
 // IMFAttributes methods
 STDMETHODIMP
 WMFByteStream::GetItem(REFGUID guidKey, PROPVARIANT* pValue)
 {
     MOZ_ASSERT(mAttributes);
--- a/content/media/wmf/WMFReader.cpp
+++ b/content/media/wmf/WMFReader.cpp
@@ -27,19 +27,19 @@
 using mozilla::layers::Image;
 using mozilla::layers::LayerManager;
 using mozilla::layers::LayersBackend;
 
 namespace mozilla {
 
 #ifdef PR_LOGGING
 extern PRLogModuleInfo* gMediaDecoderLog;
-#define LOG(...) PR_LOG(gMediaDecoderLog, PR_LOG_DEBUG, (__VA_ARGS__))
+#define DECODER_LOG(...) PR_LOG(gMediaDecoderLog, PR_LOG_DEBUG, (__VA_ARGS__))
 #else
-#define LOG(...)
+#define DECODER_LOG(...)
 #endif
 
 // Uncomment to enable verbose per-sample logging.
 //#define LOG_SAMPLE_DECODE 1
 
 WMFReader::WMFReader(AbstractMediaDecoder* aDecoder)
   : MediaDecoderReader(aDecoder),
     mSourceReader(nullptr),
@@ -203,17 +203,17 @@ ConfigureSourceReaderStream(IMFSourceRea
   for (uint32_t i = 0; i < aNumAllowedInSubTypes; i++) {
     if (aAllowedInSubTypes[i] == subType) {
       isSubTypeAllowed = true;
       break;
     }
   }
   if (!isSubTypeAllowed) {
     nsCString name = GetGUIDName(subType);
-    LOG("ConfigureSourceReaderStream subType=%s is not allowed to be decoded", name.get());
+    DECODER_LOG("ConfigureSourceReaderStream subType=%s is not allowed to be decoded", name.get());
     return E_FAIL;
   }
 
   // Find the major type.
   GUID majorType;
   hr = nativeType->GetGUID(MF_MT_MAJOR_TYPE, &majorType);
   NS_ENSURE_TRUE(SUCCEEDED(hr), hr);
 
@@ -318,22 +318,22 @@ WMFReader::ConfigureVideoFrameGeometry(I
 
   // Success! Save state.
   mInfo.mVideo.mDisplay = displaySize;
   GetDefaultStride(aMediaType, &mVideoStride);
   mVideoWidth = width;
   mVideoHeight = height;
   mPictureRegion = pictureRegion;
 
-  LOG("WMFReader frame geometry frame=(%u,%u) stride=%u picture=(%d, %d, %d, %d) display=(%d,%d) PAR=%d:%d",
-      width, height,
-      mVideoStride,
-      mPictureRegion.x, mPictureRegion.y, mPictureRegion.width, mPictureRegion.height,
-      displaySize.width, displaySize.height,
-      aspectNum, aspectDenom);
+  DECODER_LOG("WMFReader frame geometry frame=(%u,%u) stride=%u picture=(%d, %d, %d, %d) display=(%d,%d) PAR=%d:%d",
+              width, height,
+              mVideoStride,
+              mPictureRegion.x, mPictureRegion.y, mPictureRegion.width, mPictureRegion.height,
+              displaySize.width, displaySize.height,
+              aspectNum, aspectDenom);
 
   return S_OK;
 }
 
 HRESULT
 WMFReader::ConfigureVideoDecoder()
 {
   NS_ASSERTION(mSourceReader, "Must have a SourceReader before configuring decoders!");
@@ -349,34 +349,34 @@ WMFReader::ConfigureVideoDecoder()
     MFVideoFormat_H264
   };
   HRESULT hr = ConfigureSourceReaderStream(mSourceReader,
                                            MF_SOURCE_READER_FIRST_VIDEO_STREAM,
                                            mUseHwAccel ? MFVideoFormat_NV12 : MFVideoFormat_YV12,
                                            MP4VideoTypes,
                                            NS_ARRAY_LENGTH(MP4VideoTypes));
   if (FAILED(hr)) {
-    LOG("Failed to configured video output");
+    DECODER_LOG("Failed to configured video output");
     return hr;
   }
 
   RefPtr<IMFMediaType> mediaType;
   hr = mSourceReader->GetCurrentMediaType(MF_SOURCE_READER_FIRST_VIDEO_STREAM,
                                           byRef(mediaType));
   if (FAILED(hr)) {
     NS_WARNING("Failed to get configured video media type");
     return hr;
   }
 
   if (FAILED(ConfigureVideoFrameGeometry(mediaType))) {
     NS_WARNING("Failed configured video frame dimensions");
     return hr;
   }
 
-  LOG("Successfully configured video stream");
+  DECODER_LOG("Successfully configured video stream");
 
   mHasVideo = mInfo.mVideo.mHasVideo = true;
 
   return S_OK;
 }
 
 void
 WMFReader::GetSupportedAudioCodecs(const GUID** aCodecs, uint32_t* aNumCodecs)
@@ -439,43 +439,43 @@ WMFReader::ConfigureAudioDecoder()
   mAudioRate = MFGetAttributeUINT32(mediaType, MF_MT_AUDIO_SAMPLES_PER_SECOND, 0);
   mAudioChannels = MFGetAttributeUINT32(mediaType, MF_MT_AUDIO_NUM_CHANNELS, 0);
   mAudioBytesPerSample = MFGetAttributeUINT32(mediaType, MF_MT_AUDIO_BITS_PER_SAMPLE, 16) / 8;
 
   mInfo.mAudio.mChannels = mAudioChannels;
   mInfo.mAudio.mRate = mAudioRate;
   mHasAudio = mInfo.mAudio.mHasAudio = true;
 
-  LOG("Successfully configured audio stream. rate=%u channels=%u bitsPerSample=%u",
-      mAudioRate, mAudioChannels, mAudioBytesPerSample);
+  DECODER_LOG("Successfully configured audio stream. rate=%u channels=%u bitsPerSample=%u",
+              mAudioRate, mAudioChannels, mAudioBytesPerSample);
 
   return S_OK;
 }
 
 nsresult
 WMFReader::ReadMetadata(MediaInfo* aInfo,
                         MetadataTags** aTags)
 {
   NS_ASSERTION(mDecoder->OnDecodeThread(), "Should be on decode thread.");
 
-  LOG("WMFReader::ReadMetadata()");
+  DECODER_LOG("WMFReader::ReadMetadata()");
   HRESULT hr;
 
   RefPtr<IMFAttributes> attr;
   hr = wmf::MFCreateAttributes(byRef(attr), 1);
   NS_ENSURE_TRUE(SUCCEEDED(hr), NS_ERROR_FAILURE);
 
   hr = attr->SetUnknown(MF_SOURCE_READER_ASYNC_CALLBACK, mSourceReaderCallback);
   NS_ENSURE_TRUE(SUCCEEDED(hr), NS_ERROR_FAILURE);
 
   if (mUseHwAccel) {
     hr = attr->SetUnknown(MF_SOURCE_READER_D3D_MANAGER,
                           mDXVA2Manager->GetDXVADeviceManager());
     if (FAILED(hr)) {
-      LOG("Failed to set DXVA2 D3D Device manager on source reader attributes");
+      DECODER_LOG("Failed to set DXVA2 D3D Device manager on source reader attributes");
       mUseHwAccel = false;
     }
   }
 
   hr = wmf::MFCreateSourceReaderFromByteStream(mByteStream, attr, byRef(mSourceReader));
   NS_ENSURE_TRUE(SUCCEEDED(hr), NS_ERROR_FAILURE);
 
   hr = ConfigureVideoDecoder();
@@ -499,28 +499,28 @@ WMFReader::ReadMetadata(MediaInfo* aInfo
         // Ignore MF_E_TRANSFORM_TYPE_NOT_SET. Vista returns this here
         // on some, perhaps all, video cards. This may be because activating
         // DXVA changes the available output types. It seems to be safe to
         // ignore this error.
         hr = S_OK;
       }
     }
     if (FAILED(hr)) {
-      LOG("Failed to set DXVA2 D3D Device manager on decoder hr=0x%x", hr);
+      DECODER_LOG("Failed to set DXVA2 D3D Device manager on decoder hr=0x%x", hr);
       mUseHwAccel = false;
       // Re-run the configuration process, so that the output video format
       // is set correctly to reflect that hardware acceleration is disabled.
       // Without this, we'd be running with !mUseHwAccel and the output format
       // set to NV12, which is the format we expect when using hardware
       // acceleration. This would cause us to misinterpret the frame contents.
       hr = ConfigureVideoDecoder();
     }
   }
   if (mInfo.HasVideo()) {
-    LOG("Using DXVA: %s", (mUseHwAccel ? "Yes" : "No"));
+    DECODER_LOG("Using DXVA: %s", (mUseHwAccel ? "Yes" : "No"));
   }
 
   // Abort if both video and audio failed to initialize.
   NS_ENSURE_TRUE(mInfo.HasValidMedia(), NS_ERROR_FAILURE);
 
   // Get the duration, and report it to the decoder if we have it.
   int64_t duration = 0;
   hr = GetSourceReaderDuration(mSourceReader, duration);
@@ -554,31 +554,31 @@ WMFReader::DecodeAudioData()
   hr = mSourceReader->ReadSample(MF_SOURCE_READER_FIRST_AUDIO_STREAM,
                                  0, // control flags
                                  0, // read stream index
                                  nullptr,
                                  nullptr,
                                  nullptr);
 
   if (FAILED(hr)) {
-    LOG("WMFReader::DecodeAudioData() ReadSample failed with hr=0x%x", hr);
+    DECODER_LOG("WMFReader::DecodeAudioData() ReadSample failed with hr=0x%x", hr);
     // End the stream.
     return false;
   }
 
   DWORD flags = 0;
   LONGLONG timestampHns = 0;
   RefPtr<IMFSample> sample;
   hr = mSourceReaderCallback->Wait(&flags, &timestampHns, byRef(sample));
   if (FAILED(hr) ||
       (flags & MF_SOURCE_READERF_ERROR) ||
       (flags & MF_SOURCE_READERF_ENDOFSTREAM) ||
       (flags & MF_SOURCE_READERF_CURRENTMEDIATYPECHANGED)) {
-    LOG("WMFReader::DecodeAudioData() ReadSample failed with hr=0x%x flags=0x%x",
-        hr, flags);
+    DECODER_LOG("WMFReader::DecodeAudioData() ReadSample failed with hr=0x%x flags=0x%x",
+                hr, flags);
     // End the stream.
     return false;
   }
 
   if (!sample) {
     // Not enough data? Try again...
     return true;
   }
@@ -627,18 +627,18 @@ WMFReader::DecodeAudioData()
   mAudioQueue.Push(new AudioData(mDecoder->GetResource()->Tell(),
                                  timestamp,
                                  duration,
                                  numFrames,
                                  pcmSamples.forget(),
                                  mAudioChannels));
 
   #ifdef LOG_SAMPLE_DECODE
-  LOG("Decoded audio sample! timestamp=%lld duration=%lld currentLength=%u",
-      timestamp, duration, currentLength);
+  DECODER_LOG("Decoded audio sample! timestamp=%lld duration=%lld currentLength=%u",
+              timestamp, duration, currentLength);
   #endif
 
   return true;
 }
 
 HRESULT
 WMFReader::CreateBasicVideoFrame(IMFSample* aSample,
                                  int64_t aTimestampUsecs,
@@ -788,17 +788,17 @@ WMFReader::DecodeVideoFrame(bool &aKeyfr
 
   hr = mSourceReader->ReadSample(MF_SOURCE_READER_FIRST_VIDEO_STREAM,
                                  0, // control flags
                                  0, // read stream index
                                  nullptr,
                                  nullptr,
                                  nullptr);
   if (FAILED(hr)) {
-    LOG("WMFReader::DecodeVideoData() ReadSample failed with hr=0x%x", hr);
+    DECODER_LOG("WMFReader::DecodeVideoData() ReadSample failed with hr=0x%x", hr);
     return false;
   }
 
   DWORD flags = 0;
   LONGLONG timestampHns = 0;
   RefPtr<IMFSample> sample;
   hr = mSourceReaderCallback->Wait(&flags, &timestampHns, byRef(sample));
 
@@ -810,25 +810,25 @@ WMFReader::DecodeVideoFrame(bool &aKeyfr
 
   if (FAILED(hr)) {
     // Unknown failure, ask caller to try again?
     return true;
   }
 
   if (!sample) {
     if ((flags & MF_SOURCE_READERF_ENDOFSTREAM)) {
-      LOG("WMFReader; Null sample after video decode, at end of stream");
+      DECODER_LOG("WMFReader; Null sample after video decode, at end of stream");
       return false;
     }
-    LOG("WMFReader; Null sample after video decode. Maybe insufficient data...");
+    DECODER_LOG("WMFReader; Null sample after video decode. Maybe insufficient data...");
     return true;
   }
 
   if ((flags & MF_SOURCE_READERF_CURRENTMEDIATYPECHANGED)) {
-    LOG("WMFReader: Video media type changed!");
+    DECODER_LOG("WMFReader: Video media type changed!");
     RefPtr<IMFMediaType> mediaType;
     hr = mSourceReader->GetCurrentMediaType(MF_SOURCE_READER_FIRST_VIDEO_STREAM,
                                             byRef(mediaType));
     if (FAILED(hr) ||
         FAILED(ConfigureVideoFrameGeometry(mediaType))) {
       NS_WARNING("Failed to reconfigure video media type");
       return false;
     }
@@ -849,36 +849,36 @@ WMFReader::DecodeVideoFrame(bool &aKeyfr
   }
   NS_ENSURE_TRUE(SUCCEEDED(hr) && v, false);
 
   parsed++;
   decoded++;
   mVideoQueue.Push(v);
 
   #ifdef LOG_SAMPLE_DECODE
-  LOG("Decoded video sample timestamp=%lld duration=%lld stride=%d height=%u flags=%u",
-      timestamp, duration, mVideoStride, mVideoHeight, flags);
+  DECODER_LOG("Decoded video sample timestamp=%lld duration=%lld stride=%d height=%u flags=%u",
+              timestamp, duration, mVideoStride, mVideoHeight, flags);
   #endif
 
   if ((flags & MF_SOURCE_READERF_ENDOFSTREAM)) {
     // End of stream.
-    LOG("End of video stream");
+    DECODER_LOG("End of video stream");
     return false;
   }
 
   return true;
 }
 
 nsresult
 WMFReader::Seek(int64_t aTargetUs,
                 int64_t aStartTime,
                 int64_t aEndTime,
                 int64_t aCurrentTime)
 {
-  LOG("WMFReader::Seek() %lld", aTargetUs);
+  DECODER_LOG("WMFReader::Seek() %lld", aTargetUs);
 
   NS_ASSERTION(mDecoder->OnDecodeThread(), "Should be on decode thread.");
 #ifdef DEBUG
   bool canSeek = false;
   GetSourceReaderCanSeek(mSourceReader, canSeek);
   NS_ASSERTION(canSeek, "WMFReader::Seek() should only be called if we can seek!");
 #endif
 
--- a/content/media/wmf/WMFSourceReaderCallback.cpp
+++ b/content/media/wmf/WMFSourceReaderCallback.cpp
@@ -6,26 +6,26 @@
 
 #include "WMFSourceReaderCallback.h"
 #include "WMFUtils.h"
 
 namespace mozilla {
 
 #ifdef PR_LOGGING
 static PRLogModuleInfo* gWMFSourceReaderCallbackLog = nullptr;
-#define LOG(...) PR_LOG(gWMFSourceReaderCallbackLog, PR_LOG_DEBUG, (__VA_ARGS__))
+#define WMF_CB_LOG(...) PR_LOG(gWMFSourceReaderCallbackLog, PR_LOG_DEBUG, (__VA_ARGS__))
 #else
-#define LOG(...)
+#define WMF_CB_LOG(...)
 #endif
 
 // IUnknown Methods
 STDMETHODIMP
 WMFSourceReaderCallback::QueryInterface(REFIID aIId, void **aInterface)
 {
-  LOG("WMFSourceReaderCallback::QueryInterface %s", GetGUIDName(aIId).get());
+  WMF_CB_LOG("WMFSourceReaderCallback::QueryInterface %s", GetGUIDName(aIId).get());
 
   if (aIId == IID_IMFSourceReaderCallback) {
     return DoGetInterface(static_cast<WMFSourceReaderCallback*>(this), aInterface);
   }
   if (aIId == IID_IUnknown) {
     return DoGetInterface(static_cast<WMFSourceReaderCallback*>(this), aInterface);
   }
 
@@ -91,29 +91,29 @@ WMFSourceReaderCallback::NotifyReadCompl
 
 STDMETHODIMP
 WMFSourceReaderCallback::OnReadSample(HRESULT aReadStatus,
                                       DWORD aStreamIndex,
                                       DWORD aStreamFlags,
                                       LONGLONG aTimestamp,
                                       IMFSample *aSample)
 {
-  LOG("WMFSourceReaderCallback::OnReadSample() hr=0x%x flags=0x%x time=%lld sample=%p",
-      aReadStatus, aStreamFlags, aTimestamp, aSample);
+  WMF_CB_LOG("WMFSourceReaderCallback::OnReadSample() hr=0x%x flags=0x%x time=%lld sample=%p",
+             aReadStatus, aStreamFlags, aTimestamp, aSample);
   return NotifyReadComplete(aReadStatus,
                             aStreamIndex,
                             aStreamFlags,
                             aTimestamp,
                             aSample);
 }
 
 HRESULT
 WMFSourceReaderCallback::Cancel()
 {
-  LOG("WMFSourceReaderCallback::Cancel()");
+  WMF_CB_LOG("WMFSourceReaderCallback::Cancel()");
   return NotifyReadComplete(E_ABORT,
                             0,
                             0,
                             0,
                             nullptr);
 }
 
 STDMETHODIMP
@@ -129,22 +129,22 @@ WMFSourceReaderCallback::OnFlush(DWORD)
 }
 
 HRESULT
 WMFSourceReaderCallback::Wait(DWORD* aStreamFlags,
                               LONGLONG* aTimeStamp,
                               IMFSample** aSample)
 {
   ReentrantMonitorAutoEnter mon(mMonitor);
-  LOG("WMFSourceReaderCallback::Wait() starting wait");
+  WMF_CB_LOG("WMFSourceReaderCallback::Wait() starting wait");
   while (!mReadFinished) {
     mon.Wait();
   }
   mReadFinished = false;
-  LOG("WMFSourceReaderCallback::Wait() done waiting");
+  WMF_CB_LOG("WMFSourceReaderCallback::Wait() done waiting");
 
   *aStreamFlags = mStreamFlags;
   *aTimeStamp = mTimestamp;
   *aSample = mSample;
   HRESULT hr = mResultStatus;
 
   mSample = nullptr;
   mTimestamp = 0;
--- a/content/xbl/builtin/android/moz.build
+++ b/content/xbl/builtin/android/moz.build
@@ -1,6 +1,7 @@
 # -*- Mode: python; c-basic-offset: 4; indent-tabs-mode: nil; tab-width: 40 -*-
 # vim: set filetype=python:
 # This Source Code Form is subject to the terms of the Mozilla Public
 # License, v. 2.0. If a copy of the MPL was not distributed with this
 # file, You can obtain one at http://mozilla.org/MPL/2.0/.
 
+JAR_MANIFESTS += ['jar.mn']
\ No newline at end of file
--- a/content/xbl/builtin/emacs/moz.build
+++ b/content/xbl/builtin/emacs/moz.build
@@ -1,6 +1,7 @@
 # -*- Mode: python; c-basic-offset: 4; indent-tabs-mode: nil; tab-width: 40 -*-
 # vim: set filetype=python:
 # This Source Code Form is subject to the terms of the Mozilla Public
 # License, v. 2.0. If a copy of the MPL was not distributed with this
 # file, You can obtain one at http://mozilla.org/MPL/2.0/.
 
+JAR_MANIFESTS += ['jar.mn']
\ No newline at end of file
--- a/content/xbl/builtin/mac/moz.build
+++ b/content/xbl/builtin/mac/moz.build
@@ -1,6 +1,7 @@
 # -*- Mode: python; c-basic-offset: 4; indent-tabs-mode: nil; tab-width: 40 -*-
 # vim: set filetype=python:
 # This Source Code Form is subject to the terms of the Mozilla Public
 # License, v. 2.0. If a copy of the MPL was not distributed with this
 # file, You can obtain one at http://mozilla.org/MPL/2.0/.
 
+JAR_MANIFESTS += ['jar.mn']
\ No newline at end of file
--- a/content/xbl/builtin/unix/moz.build
+++ b/content/xbl/builtin/unix/moz.build
@@ -1,6 +1,7 @@
 # -*- Mode: python; c-basic-offset: 4; indent-tabs-mode: nil; tab-width: 40 -*-
 # vim: set filetype=python:
 # This Source Code Form is subject to the terms of the Mozilla Public
 # License, v. 2.0. If a copy of the MPL was not distributed with this
 # file, You can obtain one at http://mozilla.org/MPL/2.0/.
 
+JAR_MANIFESTS += ['jar.mn']
\ No newline at end of file
--- a/content/xbl/builtin/win/moz.build
+++ b/content/xbl/builtin/win/moz.build
@@ -1,6 +1,7 @@
 # -*- Mode: python; c-basic-offset: 4; indent-tabs-mode: nil; tab-width: 40 -*-
 # vim: set filetype=python:
 # This Source Code Form is subject to the terms of the Mozilla Public
 # License, v. 2.0. If a copy of the MPL was not distributed with this
 # file, You can obtain one at http://mozilla.org/MPL/2.0/.
 
+JAR_MANIFESTS += ['jar.mn']
\ No newline at end of file
--- a/content/xml/document/resources/moz.build
+++ b/content/xml/document/resources/moz.build
@@ -1,6 +1,7 @@
 # -*- Mode: python; c-basic-offset: 4; indent-tabs-mode: nil; tab-width: 40 -*-
 # vim: set filetype=python:
 # This Source Code Form is subject to the terms of the Mozilla Public
 # License, v. 2.0. If a copy of the MPL was not distributed with this
 # file, You can obtain one at http://mozilla.org/MPL/2.0/.
 
+JAR_MANIFESTS += ['jar.mn']
\ No newline at end of file
--- a/content/xslt/tests/buster/moz.build
+++ b/content/xslt/tests/buster/moz.build
@@ -1,6 +1,7 @@
 # -*- Mode: python; c-basic-offset: 4; indent-tabs-mode: nil; tab-width: 40 -*-
 # vim: set filetype=python:
 # This Source Code Form is subject to the terms of the Mozilla Public
 # License, v. 2.0. If a copy of the MPL was not distributed with this
 # file, You can obtain one at http://mozilla.org/MPL/2.0/.
 
+JAR_MANIFESTS += ['jar.mn']
\ No newline at end of file
--- a/docshell/resources/content/moz.build
+++ b/docshell/resources/content/moz.build
@@ -1,6 +1,7 @@
 # -*- Mode: python; c-basic-offset: 4; indent-tabs-mode: nil; tab-width: 40 -*-
 # vim: set filetype=python:
 # This Source Code Form is subject to the terms of the Mozilla Public
 # License, v. 2.0. If a copy of the MPL was not distributed with this
 # file, You can obtain one at http://mozilla.org/MPL/2.0/.
 
+JAR_MANIFESTS += ['jar.mn']
\ No newline at end of file
--- a/dom/base/nsFocusManager.cpp
+++ b/dom/base/nsFocusManager.cpp
@@ -987,26 +987,33 @@ nsFocusManager::WindowHidden(nsIDOMWindo
 }
 
 NS_IMETHODIMP
 nsFocusManager::FireDelayedEvents(nsIDocument* aDocument)
 {
   NS_ENSURE_ARG(aDocument);
 
   // fire any delayed focus and blur events in the same order that they were added
-  for (uint32_t i = 0; i < mDelayedBlurFocusEvents.Length(); i++)
-  {
-    if (mDelayedBlurFocusEvents[i].mDocument == aDocument &&
-        !aDocument->EventHandlingSuppressed()) {
-      uint32_t type = mDelayedBlurFocusEvents[i].mType;
-      nsCOMPtr<EventTarget> target = mDelayedBlurFocusEvents[i].mTarget;
-      nsCOMPtr<nsIPresShell> presShell = mDelayedBlurFocusEvents[i].mPresShell;
-      mDelayedBlurFocusEvents.RemoveElementAt(i);
-      SendFocusOrBlurEvent(type, presShell, aDocument, target, 0, false);
-      --i;
+  for (uint32_t i = 0; i < mDelayedBlurFocusEvents.Length(); i++) {
+    if (mDelayedBlurFocusEvents[i].mDocument == aDocument) {
+      if (!aDocument->GetInnerWindow() ||
+          !aDocument->GetInnerWindow()->IsCurrentInnerWindow()) {
+        // If the document was navigated away from or is defunct, don't bother
+        // firing events on it. Note the symmetry between this condition and
+        // the similar one in nsDocument.cpp:FireOrClearDelayedEvents.
+        mDelayedBlurFocusEvents.RemoveElementAt(i);
+        --i;
+      } else if (!aDocument->EventHandlingSuppressed()) {
+        uint32_t type = mDelayedBlurFocusEvents[i].mType;
+        nsCOMPtr<EventTarget> target = mDelayedBlurFocusEvents[i].mTarget;
+        nsCOMPtr<nsIPresShell> presShell = mDelayedBlurFocusEvents[i].mPresShell;
+        mDelayedBlurFocusEvents.RemoveElementAt(i);
+        SendFocusOrBlurEvent(type, presShell, aDocument, target, 0, false);
+        --i;
+      }
     }
   }
 
   return NS_OK;
 }
 
 NS_IMETHODIMP
 nsFocusManager::FocusPlugin(nsIContent* aContent)
--- a/dom/base/nsGlobalWindow.cpp
+++ b/dom/base/nsGlobalWindow.cpp
@@ -1261,16 +1261,18 @@ nsGlobalWindow::~nsGlobalWindow()
     // alive, iterate through the inner windows and null out their
     // back pointer to this outer, and pull them out of the list of
     // inner windows.
 
     nsGlobalWindow *w;
     while ((w = (nsGlobalWindow *)PR_LIST_HEAD(this)) != this) {
       PR_REMOVE_AND_INIT_LINK(w);
     }
+
+    DropOuterWindowDocs();
   } else {
     Telemetry::Accumulate(Telemetry::INNERWINDOWS_WITH_MUTATION_LISTENERS,
                           mMutationBits ? 1 : 0);
 
     if (mListenerManager) {
       mListenerManager->Disconnect();
       mListenerManager = nullptr;
     }
@@ -1281,19 +1283,19 @@ nsGlobalWindow::~nsGlobalWindow()
     PR_REMOVE_LINK(this);
 
     // If our outer window's inner window is this window, null out the
     // outer window's reference to this window that's being deleted.
     nsGlobalWindow *outer = GetOuterWindowInternal();
     if (outer) {
       outer->MaybeClearInnerWindow(this);
     }
-  }
-
-  ClearDelayedEventsAndDropDocument();
+
+    MOZ_ASSERT_IF(mDoc, !mDoc->EventHandlingSuppressed());
+  }
 
   // Outer windows are always supposed to call CleanUp before letting themselves
   // be destroyed. And while CleanUp generally seems to be intended to clean up
   // outers, we've historically called it for both. Changing this would probably
   // involve auditing all of the references that inners and outers can have, and
   // separating the handling into CleanUp() and FreeInnerObjects.
   if (IsInnerWindow()) {
     CleanUp();
@@ -1355,22 +1357,21 @@ nsGlobalWindow::MaybeForgiveSpamCount()
     SetPopupSpamWindow(false);
     --gOpenPopupSpamCount;
     NS_ASSERTION(gOpenPopupSpamCount >= 0,
                  "Unbalanced decrement of gOpenPopupSpamCount");
   }
 }
 
 void
-nsGlobalWindow::ClearDelayedEventsAndDropDocument()
-{
-  if (mDoc && mDoc->EventHandlingSuppressed()) {
-    mDoc->UnsuppressEventHandlingAndFireEvents(false);
-  }
+nsGlobalWindow::DropOuterWindowDocs()
+{
+  MOZ_ASSERT(IsOuterWindow());
   mDoc = nullptr;
+  mSuspendedDoc = nullptr;
 }
 
 void
 nsGlobalWindow::CleanUp()
 {
   // Guarantee idempotence.
   if (mCleanedUp)
     return;
@@ -1540,16 +1541,20 @@ nsGlobalWindow::FreeInnerObjects()
     mScreen = nullptr;
   }
 
   if (mDoc) {
     // Remember the document's principal and URI.
     mDocumentPrincipal = mDoc->NodePrincipal();
     mDocumentURI = mDoc->GetDocumentURI();
     mDocBaseURI = mDoc->GetDocBaseURI();
+
+    if (mDoc->EventHandlingSuppressed()) {
+      mDoc->UnsuppressEventHandlingAndFireEvents(false);
+    }
   }
 
   // Remove our reference to the document and the document principal.
   mFocusedNode = nullptr;
 
   if (mApplicationCache) {
     static_cast<nsDOMOfflineResourceList*>(mApplicationCache.get())->Disconnect();
     mApplicationCache = nullptr;
@@ -2266,16 +2271,20 @@ nsGlobalWindow::SetNewDocument(nsIDocume
 
   nsresult rv = NS_OK;
 
   // Set mDoc even if this is an outer window to avoid
   // having to *always* reach into the inner window to find the
   // document.
   mDoc = aDocument;
 
+  // Take this opportunity to clear mSuspendedDoc. Our old inner window is now
+  // responsible for unsuspending it.
+  mSuspendedDoc = nullptr;
+
 #ifdef DEBUG
   mLastOpenedURI = aDocument->GetDocumentURI();
 #endif
 
   mContext->WillInitializeContext();
 
   nsGlobalWindow *currentInner = GetCurrentInnerWindowInternal();
 
@@ -2761,17 +2770,17 @@ nsGlobalWindow::DetachFromDocShell()
     NS_ASSERTION(mDoc, "Must have doc!");
 
     // Remember the document's principal and URI.
     mDocumentPrincipal = mDoc->NodePrincipal();
     mDocumentURI = mDoc->GetDocumentURI();
     mDocBaseURI = mDoc->GetDocBaseURI();
 
     // Release our document reference
-    ClearDelayedEventsAndDropDocument();
+    DropOuterWindowDocs();
     mFocusedNode = nullptr;
   }
 
   ClearControllers();
 
   mChromeEventHandler = nullptr; // force release now
 
   if (mContext) {
@@ -8165,16 +8174,18 @@ nsGlobalWindow::ReallyCloseWindow()
 
     CleanUp();
   }
 }
 
 void
 nsGlobalWindow::EnterModalState()
 {
+  FORWARD_TO_OUTER_VOID(EnterModalState, ());
+
   // GetScriptableTop, not GetTop, so that EnterModalState works properly with
   // <iframe mozbrowser>.
   nsGlobalWindow* topWin = GetScriptableTop();
 
   if (!topWin) {
     NS_ERROR("Uh, EnterModalState() called w/o a reachable top window?");
     return;
   }
@@ -8198,20 +8209,18 @@ nsGlobalWindow::EnterModalState()
       }
     }
   }
 
   if (topWin->mModalStateDepth == 0) {
     NS_ASSERTION(!mSuspendedDoc, "Shouldn't have mSuspendedDoc here!");
 
     mSuspendedDoc = topWin->GetExtantDoc();
-    if (mSuspendedDoc && mSuspendedDoc->EventHandlingSuppressed()) {
+    if (mSuspendedDoc) {
       mSuspendedDoc->SuppressEventHandling();
-    } else {
-      mSuspendedDoc = nullptr;
     }
   }
   topWin->mModalStateDepth++;
 }
 
 // static
 void
 nsGlobalWindow::RunPendingTimeoutsRecursive(nsGlobalWindow *aTopWindow,
@@ -8280,16 +8289,18 @@ public:
 
 private:
   nsRefPtr<nsGlobalWindow> mWindow;
 };
 
 void
 nsGlobalWindow::LeaveModalState()
 {
+  FORWARD_TO_OUTER_VOID(LeaveModalState, ());
+
   nsGlobalWindow* topWin = GetScriptableTop();
 
   if (!topWin) {
     NS_ERROR("Uh, LeaveModalState() called w/o a reachable top window?");
     return;
   }
 
   topWin->mModalStateDepth--;
--- a/dom/base/nsGlobalWindow.h
+++ b/dom/base/nsGlobalWindow.h
@@ -976,17 +976,17 @@ protected:
 
   static bool sIdleObserversAPIFuzzTimeDisabled;
 
   friend class HashchangeCallback;
   friend class mozilla::dom::BarProp;
 
   // Object Management
   virtual ~nsGlobalWindow();
-  void ClearDelayedEventsAndDropDocument();
+  void DropOuterWindowDocs();
   void CleanUp();
   void ClearControllers();
   nsresult FinalClose();
 
   inline void MaybeClearInnerWindow(nsGlobalWindow* aExpectedInner)
   {
     if(mInnerWindow == aExpectedInner) {
       mInnerWindow = nullptr;
@@ -1471,16 +1471,22 @@ protected:
 #endif // MOZ_B2G
 
   bool mCleanedUp;
 
   nsCOMPtr<nsIDOMOfflineResourceList> mApplicationCache;
 
   nsAutoPtr<nsJSThingHashtable<nsPtrHashKey<nsXBLPrototypeHandler>, JSObject*> > mCachedXBLPrototypeHandlers;
 
+  // mSuspendedDoc is only set on outer windows. It's useful when we get matched
+  // EnterModalState/LeaveModalState calls, in which case the outer window is
+  // responsible for unsuspending events on the document. If we don't (for
+  // example, if the outer window is closed before the LeaveModalState call),
+  // then the inner window whose mDoc is our mSuspendedDoc is responsible for
+  // unsuspending it.
   nsCOMPtr<nsIDocument> mSuspendedDoc;
 
   nsRefPtr<mozilla::dom::indexedDB::IDBFactory> mIndexedDB;
 
   // This counts the number of windows that have been opened in rapid succession
   // (i.e. within dom.successive_dialog_time_limit of each other). It is reset
   // to 0 once a dialog is opened after dom.successive_dialog_time_limit seconds
   // have elapsed without any other dialogs.
--- a/dom/bindings/Codegen.py
+++ b/dom/bindings/Codegen.py
@@ -2590,36 +2590,55 @@ class CastableObjectUnwrapper():
     based on the passed-in descriptor and storing it in a variable
     called by the name in the "target" argument.
 
     codeOnFailure is the code to run if unwrapping fails.
 
     If isCallbackReturnValue is "JSImpl" and our descriptor is also
     JS-implemented, fall back to just creating the right object if what we
     have isn't one already.
+
+    If allowCrossOriginObj is True, then we'll first do an
+    UncheckedUnwrap and then operate on the result.
     """
     def __init__(self, descriptor, source, target, codeOnFailure,
-                 exceptionCode=None, isCallbackReturnValue=False):
+                 exceptionCode=None, isCallbackReturnValue=False,
+                 allowCrossOriginObj=False):
         if not exceptionCode:
             exceptionCode = codeOnFailure
         self.substitution = { "type" : descriptor.nativeType,
                               "protoID" : "prototypes::id::" + descriptor.name,
-                              "source" : source,
                               "target" : target,
                               "codeOnFailure" : CGIndenter(CGGeneric(codeOnFailure)).define(),
                               "exceptionCode" : CGIndenter(CGGeneric(exceptionCode), 4).define() }
+        if allowCrossOriginObj:
+            self.substitution["uncheckedObjDecl"] = (
+                "\n  JS::Rooted<JSObject*> uncheckedObj(cx, js::UncheckedUnwrap(%s));" % source)
+            self.substitution["source"] = "uncheckedObj"
+            xpconnectUnwrap = (
+                "nsresult rv;\n"
+                "{ // Scope for the JSAutoCompartment, because we only\n"
+                "  // want to be in that compartment for the UnwrapArg call.\n"
+                "  JSAutoCompartment ac(cx, ${source});\n"
+                "  rv = UnwrapArg<${type}>(cx, val, &objPtr, &objRef.ptr, &val);\n"
+                "}\n")
+        else:
+            self.substitution["uncheckedObjDecl"] = ""
+            self.substitution["source"] = source
+            xpconnectUnwrap = "nsresult rv = UnwrapArg<${type}>(cx, val, &objPtr, &objRef.ptr, &val);\n"
+
         if descriptor.hasXPConnectImpls:
             # We don't use xpc_qsUnwrapThis because it will always throw on
             # unwrap failure, whereas we want to control whether we throw or
             # not.
             self.substitution["codeOnFailure"] = CGIndenter(CGGeneric(string.Template(
                 "${type} *objPtr;\n"
                 "SelfRef objRef;\n"
-                "JS::Rooted<JS::Value> val(cx, JS::ObjectValue(*${source}));\n"
-                "nsresult rv = UnwrapArg<${type}>(cx, val, &objPtr, &objRef.ptr, &val);\n"
+                "JS::Rooted<JS::Value> val(cx, JS::ObjectValue(*${source}));\n" +
+                xpconnectUnwrap +
                 "if (NS_FAILED(rv)) {\n"
                 "${codeOnFailure}\n"
                 "}\n"
                 "// We should be castable!\n"
                 "MOZ_ASSERT(!objRef.ptr);\n"
                 "// We should have an object, too!\n"
                 "MOZ_ASSERT(objPtr);\n"
                 "${target} = objPtr;").substitute(self.substitution)), 4).define()
@@ -2642,17 +2661,17 @@ class CastableObjectUnwrapper():
                 "}").substitute(self.substitution)), 4).define()
         else:
             self.substitution["codeOnFailure"] = CGIndenter(
                 CGGeneric(self.substitution["codeOnFailure"])).define()
 
     def __str__(self):
         codeOnFailure = self.substitution["codeOnFailure"] % {'securityError': 'rv == NS_ERROR_XPC_SECURITY_MANAGER_VETO'}
         return string.Template(
-"""{
+"""{${uncheckedObjDecl}
   nsresult rv = UnwrapObject<${protoID}, ${type}>(${source}, ${target});
   if (NS_FAILED(rv)) {
 ${codeOnFailure}
   }
 }""").substitute(self.substitution, codeOnFailure=codeOnFailure)
 
 class FailureFatalCastableObjectUnwrapper(CastableObjectUnwrapper):
     """
@@ -4638,19 +4657,31 @@ def getRetvalDeclarationForType(returnTy
             result = CGTemplatedType("nsRefPtr", result)
         else:
             result = CGWrapper(result, post="*")
         return result, False, None, None
     if returnType.isCallback():
         name = returnType.unroll().identifier.name
         return CGGeneric("nsRefPtr<%s>" % name), False, None, None
     if returnType.isAny():
-        return CGGeneric("JS::Value"), False, None, None
+        result = CGGeneric("JS::Value")
+        if isMember:
+            resultArgs = None
+        else:
+            result = CGTemplatedType("JS::Rooted", result)
+            resultArgs = "cx"
+        return result, False, None, resultArgs
     if returnType.isObject() or returnType.isSpiderMonkeyInterface():
-        return CGGeneric("JSObject*"), False, None, None
+        result = CGGeneric("JSObject*")
+        if isMember:
+            resultArgs = None
+        else:
+            result = CGTemplatedType("JS::Rooted", result)
+            resultArgs = "cx"
+        return result, False, None, resultArgs
     if returnType.isSequence():
         nullable = returnType.nullable()
         if nullable:
             returnType = returnType.inner
         # If our result is already addrefed, use the right type in the
         # sequence argument here.
         (result, _, _, _) = getRetvalDeclarationForType(returnType.inner,
                                                         descriptorProvider,
@@ -5747,28 +5778,21 @@ class CGAbstractBindingMethod(CGAbstract
         # know that we're the real deal.  So fake a descriptor here for
         # consumption by CastableObjectUnwrapper.
         getThis = CGList([
                 CGGeneric(self.callArgs) if self.callArgs != "" else None,
                 self.getThisObj,
                 CGGeneric("%s* self;" % self.descriptor.nativeType)
                 ], "\n")
 
-        objName = "uncheckedObj" if self.allowCrossOriginThis else "obj"
         unwrapThis = CGGeneric(
             str(CastableObjectUnwrapper(
                         self.descriptor,
-                        objName, "self", self.unwrapFailureCode)))
-        if self.allowCrossOriginThis:
-            unwrapThis = CGWrapper(
-                CGIndenter(unwrapThis),
-                pre=("{ // Scope for the uncheckedObj JSAutoCompartment\n"
-                     "  JS::Rooted<JSObject*> uncheckedObj(cx, js::UncheckedUnwrap(obj));\n"
-                     "  JSAutoCompartment ac(cx, uncheckedObj);\n"),
-                post="\n}")
+                        "obj", "self", self.unwrapFailureCode,
+                        allowCrossOriginObj=self.allowCrossOriginThis)))
         return CGList([ CGIndenter(getThis), CGIndenter(unwrapThis),
                         self.generate_code() ], "\n").define()
 
     def generate_code(self):
         assert(False) # Override me
 
 class CGAbstractStaticBindingMethod(CGAbstractStaticMethod):
     """
new file mode 100644
--- /dev/null
+++ b/dom/bindings/crashtests/949940.html
@@ -0,0 +1,16 @@
+<!DOCTYPE html>
+<html>
+<head>
+<meta charset="UTF-8">
+<script>
+function boom()
+{
+  var frameWin =  document.getElementById("f").contentWindow;
+  Object.create(frameWin).self;
+}
+</script>
+</head>
+<body onload="boom()">
+<iframe id="f" src="data:text/html,3"></iframe>
+</body>
+</html>
--- a/dom/bindings/crashtests/crashtests.list
+++ b/dom/bindings/crashtests/crashtests.list
@@ -2,8 +2,9 @@ skip-if(1) load 769464.html # bug 823822
 load 822340-1.html
 load 822340-2.html
 load 832899.html
 load 860591.html
 load 860551.html
 load 862610.html
 load 862092.html
 load 869038.html
+load 949940.html
--- a/dom/inputmethod/moz.build
+++ b/dom/inputmethod/moz.build
@@ -13,8 +13,10 @@ XPIDL_MODULE = 'dom_inputmethod'
 EXTRA_COMPONENTS += [
     'InputMethod.manifest',
     'MozKeyboard.js',
 ]
 
 EXTRA_JS_MODULES += [
     'Keyboard.jsm',
 ]
+
+JAR_MANIFESTS += ['jar.mn']
\ No newline at end of file
--- a/dom/ipc/PBrowser.ipdl
+++ b/dom/ipc/PBrowser.ipdl
@@ -396,17 +396,17 @@ child:
 
     SelectionEvent(WidgetSelectionEvent event);
 
     /**
      * Activate event forwarding from client to parent.
      */
     ActivateFrameEvent(nsString aType, bool capture);
 
-    LoadRemoteScript(nsString aURL);
+    LoadRemoteScript(nsString aURL, bool aRunInGlobalScope);
 
     /**
      * Create a asynchronous request to render whatever document is
      * loaded in the child when this message arrives.  When the
      * request finishes, PDocumentRenderer:__delete__ is sent back to
      * this side to notify completion.
      *
      * |documentRect| is the area of the remote document to draw,
--- a/dom/ipc/TabChild.cpp
+++ b/dom/ipc/TabChild.cpp
@@ -218,20 +218,21 @@ TabChild::PreloadSlowThings()
 
     nsRefPtr<TabChild> tab(new TabChild(ContentChild::GetSingleton(),
                                         TabContext(), /* chromeFlags */ 0));
     if (!NS_SUCCEEDED(tab->Init()) ||
         !tab->InitTabChildGlobal(DONT_LOAD_SCRIPTS)) {
         return;
     }
     // Just load and compile these scripts, but don't run them.
-    tab->TryCacheLoadAndCompileScript(BROWSER_ELEMENT_CHILD_SCRIPT);
+    tab->TryCacheLoadAndCompileScript(BROWSER_ELEMENT_CHILD_SCRIPT, true);
     // Load, compile, and run these scripts.
     tab->RecvLoadRemoteScript(
-        NS_LITERAL_STRING("chrome://global/content/preload.js"));
+        NS_LITERAL_STRING("chrome://global/content/preload.js"),
+        true);
 
     nsCOMPtr<nsIDocShell> docShell = do_GetInterface(tab->mWebNav);
     if (nsIPresShell* presShell = docShell->GetPresShell()) {
         // Initialize and do an initial reflow of the about:blank
         // PresShell to let it preload some things for us.
         presShell->Initialize(0, 0);
         nsIDocument* doc = presShell->GetDocument();
         doc->FlushPendingNotifications(Flush_Layout);
@@ -2061,24 +2062,24 @@ bool
 TabChild::DeallocPOfflineCacheUpdateChild(POfflineCacheUpdateChild* actor)
 {
   OfflineCacheUpdateChild* offlineCacheUpdate = static_cast<OfflineCacheUpdateChild*>(actor);
   delete offlineCacheUpdate;
   return true;
 }
 
 bool
-TabChild::RecvLoadRemoteScript(const nsString& aURL)
+TabChild::RecvLoadRemoteScript(const nsString& aURL, const bool& aRunInGlobalScope)
 {
   if (!mGlobal && !InitTabChildGlobal())
     // This can happen if we're half-destroyed.  It's not a fatal
     // error.
     return true;
 
-  LoadFrameScriptInternal(aURL);
+  LoadFrameScriptInternal(aURL, aRunInGlobalScope);
   return true;
 }
 
 bool
 TabChild::RecvAsyncMessage(const nsString& aMessage,
                            const ClonedMessageData& aData,
                            const InfallibleTArray<CpowEntry>& aCpows,
                            const IPC::Principal& aPrincipal)
@@ -2198,17 +2199,17 @@ TabChild::InitTabChildGlobal(FrameScript
     chromeHandler->AddEventListener(NS_LITERAL_STRING("DOMMetaAdded"), this, false);
   }
 
   if (aScriptLoading != DONT_LOAD_SCRIPTS && !mTriedBrowserInit) {
     mTriedBrowserInit = true;
     // Initialize the child side of the browser element machinery,
     // if appropriate.
     if (IsBrowserOrApp()) {
-      RecvLoadRemoteScript(BROWSER_ELEMENT_CHILD_SCRIPT);
+      RecvLoadRemoteScript(BROWSER_ELEMENT_CHILD_SCRIPT, true);
     }
   }
 
   return true;
 }
 
 bool
 TabChild::InitRenderingState()
--- a/dom/ipc/TabChild.h
+++ b/dom/ipc/TabChild.h
@@ -242,17 +242,17 @@ public:
                               const int32_t&  aKeyCode,
                               const int32_t&  aCharCode,
                               const int32_t&  aModifiers,
                               const bool&     aPreventDefault);
     virtual bool RecvCompositionEvent(const mozilla::WidgetCompositionEvent& event);
     virtual bool RecvTextEvent(const mozilla::WidgetTextEvent& event);
     virtual bool RecvSelectionEvent(const mozilla::WidgetSelectionEvent& event);
     virtual bool RecvActivateFrameEvent(const nsString& aType, const bool& capture);
-    virtual bool RecvLoadRemoteScript(const nsString& aURL);
+    virtual bool RecvLoadRemoteScript(const nsString& aURL, const bool& aRunInGlobalScope);
     virtual bool RecvAsyncMessage(const nsString& aMessage,
                                   const ClonedMessageData& aData,
                                   const InfallibleTArray<CpowEntry>& aCpows,
                                   const IPC::Principal& aPrincipal) MOZ_OVERRIDE;
 
     virtual PDocumentRendererChild*
     AllocPDocumentRendererChild(const nsRect& documentRect, const gfxMatrix& transform,
                                 const nsString& bgcolor,
--- a/dom/ipc/moz.build
+++ b/dom/ipc/moz.build
@@ -111,8 +111,10 @@ LOCAL_INCLUDES += [
 DEFINES['BIN_SUFFIX'] = '"%s"' % CONFIG['BIN_SUFFIX']
 
 if CONFIG['MOZ_WIDGET_TOOLKIT'] in ('android', 'gtk2', 'gonk', 'qt'):
     DEFINES['MOZ_ENABLE_FREETYPE'] = True
 
 for var in ('MOZ_PERMISSIONS', 'MOZ_CHILD_PERMISSIONS'):
     if CONFIG[var]:
         DEFINES[var] = True
+
+JAR_MANIFESTS += ['jar.mn']
\ No newline at end of file
--- a/dom/locales/moz.build
+++ b/dom/locales/moz.build
@@ -1,6 +1,7 @@
 # -*- Mode: python; c-basic-offset: 4; indent-tabs-mode: nil; tab-width: 40 -*-
 # vim: set filetype=python:
 # This Source Code Form is subject to the terms of the Mozilla Public
 # License, v. 2.0. If a copy of the MPL was not distributed with this
 # file, You can obtain one at http://mozilla.org/MPL/2.0/.
 
+JAR_MANIFESTS += ['jar.mn']
\ No newline at end of file
--- a/dom/src/moz.build
+++ b/dom/src/moz.build
@@ -8,8 +8,10 @@ DIRS += [
     'jsurl',
     'events',
     'storage',
     'offline',
     'json',
     'geolocation',
     'notification',
 ]
+
+JAR_MANIFESTS += ['jar.mn']
\ No newline at end of file
--- a/dom/workers/WorkerPrivate.cpp
+++ b/dom/workers/WorkerPrivate.cpp
@@ -2148,17 +2148,17 @@ JSObject*
 WorkerPrivateParent<Derived>::WrapObject(JSContext* aCx,
                                          JS::Handle<JSObject*> aScope)
 {
   MOZ_ASSERT(!IsSharedWorker(),
              "We should never wrap a WorkerPrivate for a SharedWorker");
 
   AssertIsOnParentThread();
 
-  JSObject* obj = WorkerBinding::Wrap(aCx, aScope, ParentAsWorkerPrivate());
+  JS::Rooted<JSObject*> obj(aCx, WorkerBinding::Wrap(aCx, aScope, ParentAsWorkerPrivate()));
 
   if (mRooted) {
     PreserveWrapper(this);
   }
 
   return obj;
 }
 
--- a/gfx/thebes/gfxDrawable.cpp
+++ b/gfx/thebes/gfxDrawable.cpp
@@ -2,16 +2,17 @@
  * This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #include "gfxDrawable.h"
 #include "gfxASurface.h"
 #include "gfxContext.h"
 #include "gfxPlatform.h"
+#include "gfxColor.h"
 #ifdef MOZ_X11
 #include "cairo.h"
 #include "gfxXlibSurface.h"
 #endif
 
 using namespace mozilla;
 using namespace mozilla::gfx;
 
@@ -160,16 +161,19 @@ gfxSurfaceDrawable::Draw(gfxContext* aCo
         PreparePatternForUntiledDrawing(pattern, deviceSpaceToImageSpace,
                                         currentTarget, filter);
     }
     pattern->SetMatrix(gfxMatrix(aTransform).Multiply(mTransform));
     aContext->NewPath();
     aContext->SetPattern(pattern);
     aContext->Rectangle(aFillRect);
     aContext->Fill();
+    // clear the pattern so that the snapshot is released before the
+    // drawable is destroyed
+    aContext->SetDeviceColor(gfxRGBA(0.0, 0.0, 0.0, 0.0));
     return true;
 }
 
 already_AddRefed<gfxImageSurface>
 gfxSurfaceDrawable::GetAsImageSurface()
 {
     if (mDrawTarget || mSourceSurface) {
       // TODO: Find a way to implement this. The caller really wants a 'sub-image' of
--- a/image/decoders/nsBMPDecoder.cpp
+++ b/image/decoders/nsBMPDecoder.cpp
@@ -184,17 +184,17 @@ NS_METHOD nsBMPDecoder::CalcBitShift()
     // blue
     calcBitmask(mBitFields.blue, begin, length);
     mBitFields.blueRightShift = begin;
     mBitFields.blueLeftShift = 8 - length;
     return NS_OK;
 }
 
 void
-nsBMPDecoder::WriteInternal(const char* aBuffer, uint32_t aCount)
+nsBMPDecoder::WriteInternal(const char* aBuffer, uint32_t aCount, DecodeStrategy)
 {
     NS_ABORT_IF_FALSE(!HasError(), "Shouldn't call WriteInternal after error!");
 
     // aCount=0 means EOF, mCurLine=0 means we're past end of image
     if (!aCount || !mCurLine)
         return;
 
     if (mPos < BFH_INTERNAL_LENGTH) { /* In BITMAPFILEHEADER */
--- a/image/decoders/nsBMPDecoder.h
+++ b/image/decoders/nsBMPDecoder.h
@@ -40,17 +40,17 @@ public:
     // Obtains the internal output image buffer
     uint32_t* GetImageData();
     // Obtains the size of the compressed image resource
     int32_t GetCompressedImageSize() const;
     // Obtains whether or not a BMP file had alpha data in its 4th byte
     // for 32BPP bitmaps.  Only use after the bitmap has been processed.
     bool HasAlphaData() const;
 
-    virtual void WriteInternal(const char* aBuffer, uint32_t aCount);
+    virtual void WriteInternal(const char* aBuffer, uint32_t aCount, DecodeStrategy aStrategy);
     virtual void FinishInternal();
 
 private:
 
     /** Calculates the red-, green- and blueshift in mBitFields using
      * the bitmasks from mBitFields */
     NS_METHOD CalcBitShift();
 
--- a/image/decoders/nsGIFDecoder2.cpp
+++ b/image/decoders/nsGIFDecoder2.cpp
@@ -539,17 +539,17 @@ static void ConvertColormap(uint32_t *aC
   // NB: can't use 32-bit reads, they might read off the end of the buffer
   while (c--) {
     from -= 3;
     *--to = gfxPackedPixel(0xFF, from[0], from[1], from[2]);
   }
 }
 
 void
-nsGIFDecoder2::WriteInternal(const char *aBuffer, uint32_t aCount)
+nsGIFDecoder2::WriteInternal(const char *aBuffer, uint32_t aCount, DecodeStrategy)
 {
   NS_ABORT_IF_FALSE(!HasError(), "Shouldn't call WriteInternal after error!");
 
   // These variables changed names, and renaming would make a much bigger patch :(
   const uint8_t *buf = (const uint8_t *)aBuffer;
   uint32_t len = aCount;
 
   const uint8_t *q = buf;
--- a/image/decoders/nsGIFDecoder2.h
+++ b/image/decoders/nsGIFDecoder2.h
@@ -21,17 +21,17 @@ class RasterImage;
 
 class nsGIFDecoder2 : public Decoder
 {
 public:
 
   nsGIFDecoder2(RasterImage &aImage);
   ~nsGIFDecoder2();
 
-  virtual void WriteInternal(const char* aBuffer, uint32_t aCount);
+  virtual void WriteInternal(const char* aBuffer, uint32_t aCount, DecodeStrategy aStrategy);
   virtual void FinishInternal();
   virtual Telemetry::ID SpeedHistogram();
 
 private:
   /* These functions will be called when the decoder has a decoded row,
    * frame size information, etc. */
 
   void      BeginGIF();
--- a/image/decoders/nsICODecoder.cpp
+++ b/image/decoders/nsICODecoder.cpp
@@ -204,23 +204,23 @@ nsICODecoder::SetHotSpotIfCursor() {
   if (!mIsCursor) {
     return;
   }
 
   mImageMetadata.SetHotspot(mDirEntry.mXHotspot, mDirEntry.mYHotspot);
 }
 
 void
-nsICODecoder::WriteInternal(const char* aBuffer, uint32_t aCount)
+nsICODecoder::WriteInternal(const char* aBuffer, uint32_t aCount, DecodeStrategy aStrategy)
 {
   NS_ABORT_IF_FALSE(!HasError(), "Shouldn't call WriteInternal after error!");
 
   if (!aCount) {
     if (mContainedDecoder) {
-      WriteToContainedDecoder(aBuffer, aCount);
+      WriteToContainedDecoder(aBuffer, aCount, aStrategy);
     }
     return;
   }
 
   while (aCount && (mPos < ICONCOUNTOFFSET)) { // Skip to the # of icons.
     if (mPos == 2) { // if the third byte is 1: This is an icon, 2: a cursor
       if ((*aBuffer != 1) && (*aBuffer != 2)) {
         PostDataError();
@@ -332,25 +332,25 @@ nsICODecoder::WriteInternal(const char* 
                      PNGSIGNATURESIZE);
     if (mIsPNG) {
       mContainedDecoder = new nsPNGDecoder(mImage);
       mContainedDecoder->SetObserver(mObserver);
       mContainedDecoder->SetSizeDecode(IsSizeDecode());
       mContainedDecoder->InitSharedDecoder(mImageData, mImageDataLength,
                                            mColormap, mColormapSize,
                                            mCurrentFrame);
-      if (!WriteToContainedDecoder(mSignature, PNGSIGNATURESIZE)) {
+      if (!WriteToContainedDecoder(mSignature, PNGSIGNATURESIZE, aStrategy)) {
         return;
       }
     }
   }
 
   // If we have a PNG, let the PNG decoder do all of the rest of the work
   if (mIsPNG && mContainedDecoder && mPos >= mImageOffset + PNGSIGNATURESIZE) {
-    if (!WriteToContainedDecoder(aBuffer, aCount)) {
+    if (!WriteToContainedDecoder(aBuffer, aCount, aStrategy)) {
       return;
     }
 
     if (!HasSize() && mContainedDecoder->HasSize()) {
       PostSize(mContainedDecoder->GetImageMetadata().GetWidth(),
                mContainedDecoder->GetImageMetadata().GetHeight());
     }
 
@@ -418,17 +418,17 @@ nsICODecoder::WriteInternal(const char* 
     // The ICO format when containing a BMP does not include the 14 byte
     // bitmap file header. To use the code of the BMP decoder we need to 
     // generate this header ourselves and feed it to the BMP decoder.
     int8_t bfhBuffer[BMPFILEHEADERSIZE];
     if (!FillBitmapFileHeaderBuffer(bfhBuffer)) {
       PostDataError();
       return;
     }
-    if (!WriteToContainedDecoder((const char*)bfhBuffer, sizeof(bfhBuffer))) {
+    if (!WriteToContainedDecoder((const char*)bfhBuffer, sizeof(bfhBuffer), aStrategy)) {
       return;
     }
 
     // Setup the cursor hot spot if one is present
     SetHotSpotIfCursor();
 
     // Fix the ICO height from the BIH.
     // Fix the height on the BIH to be /2 so our BMP decoder will understand.
@@ -439,17 +439,17 @@ nsICODecoder::WriteInternal(const char* 
 
     // Fix the ICO width from the BIH.
     if (!FixBitmapWidth(reinterpret_cast<int8_t*>(mBIHraw))) {
       PostDataError();
       return;
     }
 
     // Write out the BMP's bitmap info header
-    if (!WriteToContainedDecoder(mBIHraw, sizeof(mBIHraw))) {
+    if (!WriteToContainedDecoder(mBIHraw, sizeof(mBIHraw), aStrategy)) {
       return;
     }
 
     PostSize(mContainedDecoder->GetImageMetadata().GetWidth(),
              mContainedDecoder->GetImageMetadata().GetHeight());
 
     // We have the size. If we're doing a size decode, we got what
     // we came for.
@@ -487,17 +487,17 @@ nsICODecoder::WriteInternal(const char* 
     if (mPos >= bmpDataOffset && mPos < bmpDataEnd) {
 
       // Figure out how much data the BMP decoder wants
       uint32_t toFeed = bmpDataEnd - mPos;
       if (toFeed > aCount) {
         toFeed = aCount;
       }
 
-      if (!WriteToContainedDecoder(aBuffer, toFeed)) {
+      if (!WriteToContainedDecoder(aBuffer, toFeed, aStrategy)) {
         return;
       }
 
       mPos += toFeed;
       aCount -= toFeed;
       aBuffer += toFeed;
     }
   
@@ -563,19 +563,19 @@ nsICODecoder::WriteInternal(const char* 
           }
         }
       }
     }
   }
 }
 
 bool
-nsICODecoder::WriteToContainedDecoder(const char* aBuffer, uint32_t aCount)
+nsICODecoder::WriteToContainedDecoder(const char* aBuffer, uint32_t aCount, DecodeStrategy aStrategy)
 {
-  mContainedDecoder->Write(aBuffer, aCount);
+  mContainedDecoder->Write(aBuffer, aCount, aStrategy);
   if (mContainedDecoder->HasDataError()) {
     mDataError = mContainedDecoder->HasDataError();
   }
   if (mContainedDecoder->HasDecoderError()) {
     PostDecoderError(mContainedDecoder->GetDecoderError());
   }
   return !HasError();
 }
--- a/image/decoders/nsICODecoder.h
+++ b/image/decoders/nsICODecoder.h
@@ -32,25 +32,25 @@ public:
   }
 
   // Obtains the height of the icon directory entry
   uint32_t GetRealHeight() const
   {
     return mDirEntry.mHeight == 0 ? 256 : mDirEntry.mHeight; 
   }
 
-  virtual void WriteInternal(const char* aBuffer, uint32_t aCount);
+  virtual void WriteInternal(const char* aBuffer, uint32_t aCount, DecodeStrategy aStrategy);
   virtual void FinishInternal();
   virtual bool NeedsNewFrame() const;
   virtual nsresult AllocateFrame();
 
 private:
   // Writes to the contained decoder and sets the appropriate errors
   // Returns true if there are no errors.
-  bool WriteToContainedDecoder(const char* aBuffer, uint32_t aCount);
+  bool WriteToContainedDecoder(const char* aBuffer, uint32_t aCount, DecodeStrategy aStrategy);
 
   // Processes a single dir entry of the icon resource
   void ProcessDirEntry(IconDirEntry& aTarget);
   // Sets the hotspot property of if we have a cursor
   void SetHotSpotIfCursor();
   // Creates a bitmap file header buffer, returns true if successful
   bool FillBitmapFileHeaderBuffer(int8_t *bfh);
   // Fixes the ICO height to match that of the BIH.
--- a/image/decoders/nsIconDecoder.cpp
+++ b/image/decoders/nsIconDecoder.cpp
@@ -25,17 +25,17 @@ nsIconDecoder::nsIconDecoder(RasterImage
 {
   // Nothing to do
 }
 
 nsIconDecoder::~nsIconDecoder()
 { }
 
 void
-nsIconDecoder::WriteInternal(const char *aBuffer, uint32_t aCount)
+nsIconDecoder::WriteInternal(const char *aBuffer, uint32_t aCount, DecodeStrategy)
 {
   NS_ABORT_IF_FALSE(!HasError(), "Shouldn't call WriteInternal after error!");
 
   // We put this here to avoid errors about crossing initialization with case
   // jumps on linux.
   uint32_t bytesToRead = 0;
 
   // Loop until the input data is gone
--- a/image/decoders/nsIconDecoder.h
+++ b/image/decoders/nsIconDecoder.h
@@ -36,17 +36,17 @@ class RasterImage;
 
 class nsIconDecoder : public Decoder
 {
 public:
 
   nsIconDecoder(RasterImage &aImage);
   virtual ~nsIconDecoder();
 
-  virtual void WriteInternal(const char* aBuffer, uint32_t aCount);
+  virtual void WriteInternal(const char* aBuffer, uint32_t aCount, DecodeStrategy aStrategy);
 
   uint8_t mWidth;
   uint8_t mHeight;
   uint32_t mPixBytesRead;
   uint32_t mState;
 };
 
 enum {
--- a/image/decoders/nsJPEGDecoder.cpp
+++ b/image/decoders/nsJPEGDecoder.cpp
@@ -176,25 +176,30 @@ nsJPEGDecoder::InitInternal()
 void
 nsJPEGDecoder::FinishInternal()
 {
   /* If we're not in any sort of error case, flush the decoder.
    *
    * XXXbholley - It seems wrong that this should be necessary, but at the
    * moment I'm just folding the contents of Flush() into Close() so that
    * we can get rid of it.
+   *
+   * XXX(seth): It'd be great to get rid of this. For now, we treat this as a
+   * write to a synchronous decoder, which means that this must be called only
+   * on the main thread. (That's asserted in Decoder::Finish and
+   * Decoder::FinishSharedDecoder.)
    */
   if ((mState != JPEG_DONE && mState != JPEG_SINK_NON_JPEG_TRAILER) &&
       (mState != JPEG_ERROR) &&
       !IsSizeDecode())
-    this->Write(nullptr, 0);
+    this->Write(nullptr, 0, DECODE_SYNC);
 }
 
 void
-nsJPEGDecoder::WriteInternal(const char *aBuffer, uint32_t aCount)
+nsJPEGDecoder::WriteInternal(const char *aBuffer, uint32_t aCount, DecodeStrategy)
 {
   mSegment = (const JOCTET *)aBuffer;
   mSegmentLen = aCount;
 
   NS_ABORT_IF_FALSE(!HasError(), "Shouldn't call WriteInternal after error!");
 
   /* Return here if there is a fatal error within libjpeg. */
   nsresult error_code;
--- a/image/decoders/nsJPEGDecoder.h
+++ b/image/decoders/nsJPEGDecoder.h
@@ -51,17 +51,17 @@ class Orientation;
 
 class nsJPEGDecoder : public Decoder
 {
 public:
   nsJPEGDecoder(RasterImage &aImage, Decoder::DecodeStyle aDecodeStyle);
   virtual ~nsJPEGDecoder();
 
   virtual void InitInternal();
-  virtual void WriteInternal(const char* aBuffer, uint32_t aCount);
+  virtual void WriteInternal(const char* aBuffer, uint32_t aCount, DecodeStrategy aStrategy);
   virtual void FinishInternal();
 
   virtual Telemetry::ID SpeedHistogram();
   void NotifyDone();
 
 protected:
   Orientation ReadOrientationFromEXIF();
   void OutputScanlines(bool* suspend);
--- a/image/decoders/nsPNGDecoder.cpp
+++ b/image/decoders/nsPNGDecoder.cpp
@@ -281,17 +281,17 @@ nsPNGDecoder::InitInternal()
   png_set_progressive_read_fn(mPNG, static_cast<png_voidp>(this),
                               nsPNGDecoder::info_callback,
                               nsPNGDecoder::row_callback,
                               nsPNGDecoder::end_callback);
 
 }
 
 void
-nsPNGDecoder::WriteInternal(const char *aBuffer, uint32_t aCount)
+nsPNGDecoder::WriteInternal(const char *aBuffer, uint32_t aCount, DecodeStrategy)
 {
   NS_ABORT_IF_FALSE(!HasError(), "Shouldn't call WriteInternal after error!");
 
   // If we only want width/height, we don't need to go through libpng
   if (IsSizeDecode()) {
 
     // Are we done?
     if (mHeaderBytesRead == BYTES_NEEDED_FOR_DIMENSIONS)
--- a/image/decoders/nsPNGDecoder.h
+++ b/image/decoders/nsPNGDecoder.h
@@ -23,17 +23,17 @@ class RasterImage;
 
 class nsPNGDecoder : public Decoder
 {
 public:
   nsPNGDecoder(RasterImage &aImage);
   virtual ~nsPNGDecoder();
 
   virtual void InitInternal();
-  virtual void WriteInternal(const char* aBuffer, uint32_t aCount);
+  virtual void WriteInternal(const char* aBuffer, uint32_t aCount, DecodeStrategy aStrategy);
   virtual Telemetry::ID SpeedHistogram();
 
   void CreateFrame(png_uint_32 x_offset, png_uint_32 y_offset,
                    int32_t width, int32_t height,
                    gfxImageFormat format);
   void EndImageFrame();
 
   // Check if PNG is valid ICO (32bpp RGBA)
new file mode 100644
--- /dev/null
+++ b/image/src/DecodeStrategy.h
@@ -0,0 +1,36 @@
+/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
+ *
+ * This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+/** @file
+ * An enumeration used by RasterImage and Decoder to specify which 'strategy' to
+ * use for image decoding - synchronous or asynchronous.
+ */
+
+#ifndef mozilla_imagelib_DecodeStrategy_h_
+#define mozilla_imagelib_DecodeStrategy_h_
+
+namespace mozilla {
+namespace image {
+
+enum DecodeStrategy {
+  // DECODE_SYNC requests a synchronous decode, which will continue decoding
+  // frames as long as it has more source data. It returns to the caller only
+  // once decoding is complete (or until it needs more source data before
+  // continuing). Because DECODE_SYNC can involve allocating new imgFrames, it
+  // can only be run on the main thread.
+  DECODE_SYNC,
+
+  // DECODE_ASYNC requests an asynchronous decode, which will continue decoding
+  // until it either finishes a frame or runs out of source data. Because
+  // DECODE_ASYNC does not allocate new imgFrames, it can be safely run off the
+  // main thread. (And hence workers in the decode pool always use it.)
+  DECODE_ASYNC
+};
+
+} // namespace image
+} // namespace mozilla
+
+#endif
--- a/image/src/Decoder.cpp
+++ b/image/src/Decoder.cpp
@@ -24,17 +24,16 @@ Decoder::Decoder(RasterImage &aImage)
   , mDataError(false)
   , mFrameCount(0)
   , mFailCode(NS_OK)
   , mNeedsNewFrame(false)
   , mInitialized(false)
   , mSizeDecode(false)
   , mInFrame(false)
   , mIsAnimated(false)
-  , mSynchronous(false)
 {
 }
 
 Decoder::~Decoder()
 {
   mInitialized = false;
 }
 
@@ -81,51 +80,54 @@ Decoder::InitSharedDecoder(uint8_t* imag
   }
 
   // Implementation-specific initialization
   InitInternal();
   mInitialized = true;
 }
 
 void
-Decoder::Write(const char* aBuffer, uint32_t aCount)
+Decoder::Write(const char* aBuffer, uint32_t aCount, DecodeStrategy aStrategy)
 {
   PROFILER_LABEL("ImageDecoder", "Write");
+  MOZ_ASSERT(NS_IsMainThread() || aStrategy == DECODE_ASYNC);
 
   // We're strict about decoder errors
   NS_ABORT_IF_FALSE(!HasDecoderError(),
                     "Not allowed to make more decoder calls after error!");
 
   // If a data error occured, just ignore future data
   if (HasDataError())
     return;
 
   if (IsSizeDecode() && HasSize()) {
     // More data came in since we found the size. We have nothing to do here.
     return;
   }
 
   // Pass the data along to the implementation
-  WriteInternal(aBuffer, aCount);
+  WriteInternal(aBuffer, aCount, aStrategy);
 
   // If we're a synchronous decoder and we need a new frame to proceed, let's
   // create one and call it again.
-  while (mSynchronous && NeedsNewFrame() && !HasDataError()) {
+  while (aStrategy == DECODE_SYNC && NeedsNewFrame() && !HasDataError()) {
     nsresult rv = AllocateFrame();
 
     if (NS_SUCCEEDED(rv)) {
       // Tell the decoder to use the data it saved when it asked for a new frame.
-      WriteInternal(nullptr, 0);
+      WriteInternal(nullptr, 0, aStrategy);
     }
   }
 }
 
 void
 Decoder::Finish(RasterImage::eShutdownIntent aShutdownIntent)
 {
+  MOZ_ASSERT(NS_IsMainThread());
+
   // Implementation-specific finalization
   if (!HasError())
     FinishInternal();
 
   // If the implementation left us mid-frame, finish that up.
   if (mInFrame && !HasError())
     PostFrameStop();
 
@@ -181,16 +183,18 @@ Decoder::Finish(RasterImage::eShutdownIn
   if (mDecodeDone) {
     mImage.DecodingComplete();
   }
 }
 
 void
 Decoder::FinishSharedDecoder()
 {
+  MOZ_ASSERT(NS_IsMainThread());
+
   if (!HasError()) {
     FinishInternal();
   }
 }
 
 nsresult
 Decoder::AllocateFrame()
 {
@@ -275,17 +279,17 @@ Decoder::SetSizeOnImage()
                  mImageMetadata.GetOrientation());
 }
 
 /*
  * Hook stubs. Override these as necessary in decoder implementations.
  */
 
 void Decoder::InitInternal() { }
-void Decoder::WriteInternal(const char* aBuffer, uint32_t aCount) { }
+void Decoder::WriteInternal(const char* aBuffer, uint32_t aCount, DecodeStrategy aStrategy) { }
 void Decoder::FinishInternal() { }
 
 /*
  * Progress Notifications
  */
 
 void
 Decoder::PostSize(int32_t aWidth,
--- a/image/src/Decoder.h
+++ b/image/src/Decoder.h
@@ -4,16 +4,17 @@
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #ifndef MOZILLA_IMAGELIB_DECODER_H_
 #define MOZILLA_IMAGELIB_DECODER_H_
 
 #include "RasterImage.h"
 #include "imgDecoderObserver.h"
 #include "mozilla/RefPtr.h"
+#include "DecodeStrategy.h"
 #include "ImageMetadata.h"
 #include "Orientation.h"
 #include "mozilla/Telemetry.h"
 
 namespace mozilla {
 namespace image {
 
 class Decoder
@@ -45,17 +46,17 @@ public:
    *
    * @param aBuffer buffer containing the data to be written
    * @param aCount the number of bytes to write
    *
    * Any errors are reported by setting the appropriate state on the decoder.
    *
    * Notifications Sent: TODO
    */
-  void Write(const char* aBuffer, uint32_t aCount);
+  void Write(const char* aBuffer, uint32_t aCount, DecodeStrategy aStrategy);
 
   /**
    * Informs the decoder that all the data has been written.
    *
    * Notifications Sent: TODO
    */
   void Finish(RasterImage::eShutdownIntent aShutdownIntent);
 
@@ -89,21 +90,16 @@ public:
   // must be enabled by SetSizeDecode() _before_calling Init().
   bool IsSizeDecode() { return mSizeDecode; }
   void SetSizeDecode(bool aSizeDecode)
   {
     NS_ABORT_IF_FALSE(!mInitialized, "Can't set size decode after Init()!");
     mSizeDecode = aSizeDecode;
   }
 
-  bool IsSynchronous() const
-  {
-    return mSynchronous;
-  }
-
   void SetObserver(imgDecoderObserver* aObserver)
   {
     MOZ_ASSERT(aObserver);
     mObserver = aObserver;
   }
 
   // The number of frames we have, including anything in-progress. Thus, this
   // is only 0 if we haven't begun any frames.
@@ -172,17 +168,17 @@ public:
 
 protected:
 
   /*
    * Internal hooks. Decoder implementations may override these and
    * only these methods.
    */
   virtual void InitInternal();
-  virtual void WriteInternal(const char* aBuffer, uint32_t aCount);
+  virtual void WriteInternal(const char* aBuffer, uint32_t aCount, DecodeStrategy aStrategy);
   virtual void FinishInternal();
 
   /*
    * Progress notifications.
    */
 
   // Called by decoders when they determine the size of the image. Informs
   // the image of its size and sends notifications.
@@ -236,27 +232,16 @@ protected:
   uint32_t* mColormap;       // Current colormap to be used in Cairo format
   uint32_t mColormapSize;
 
   uint32_t mDecodeFlags;
   bool mDecodeDone;
   bool mDataError;
 
 private:
-  // Decode in synchronous mode. This is unsafe off-main-thread since it may
-  // attempt to allocate frames. To ensure that we never accidentally leave the
-  // decoder in synchronous mode, this should only be called by
-  // AutoSetSyncDecode.
-  void SetSynchronous(bool aSynchronous)
-  {
-    mSynchronous = aSynchronous;
-  }
-
-  friend class AutoSetSyncDecode;
-
   uint32_t mFrameCount; // Number of frames, including anything in-progress
 
   nsIntRect mInvalidRect; // Tracks an invalidation region in the current frame.
 
   nsresult mFailCode;
 
   struct NewFrameData
   {
@@ -283,43 +268,14 @@ private:
     uint8_t mPaletteDepth;
   };
   NewFrameData mNewFrameData;
   bool mNeedsNewFrame;
   bool mInitialized;
   bool mSizeDecode;
   bool mInFrame;
   bool mIsAnimated;
-  bool mSynchronous;
-};
-
-// A RAII helper class to automatically pair a call to SetSynchronous(true)
-// with a call to SetSynchronous(false), since failing to do so can lead us
-// to try to allocate frames off-main-thread, which is unsafe. Synchronous
-// decoding may only happen within the scope of an AutoSetSyncDecode. Nested
-// AutoSetSyncDecode's are OK.
-class AutoSetSyncDecode
-{
-public:
-  AutoSetSyncDecode(Decoder* aDecoder)
-    : mDecoder(aDecoder)
-  {
-    MOZ_ASSERT(NS_IsMainThread());
-    MOZ_ASSERT(mDecoder);
-
-    mOriginalValue = mDecoder->IsSynchronous();
-    mDecoder->SetSynchronous(true);
-  }
-
-  ~AutoSetSyncDecode()
-  {
-    mDecoder->SetSynchronous(mOriginalValue);
-  }
-
-private:
-  nsRefPtr<Decoder> mDecoder;
-  bool              mOriginalValue;
 };
 
 } // namespace image
 } // namespace mozilla
 
 #endif // MOZILLA_IMAGELIB_DECODER_H_
--- a/image/src/RasterImage.cpp
+++ b/image/src/RasterImage.cpp
@@ -385,17 +385,17 @@ RasterImage::RasterImage(imgStatusTracke
   mFrameDecodeFlags(DECODE_FLAGS_DEFAULT),
   mMultipartDecodedFrame(nullptr),
   mAnim(nullptr),
   mLockCount(0),
   mDecodeCount(0),
 #ifdef DEBUG
   mFramesNotified(0),
 #endif
-  mDecodingMutex("RasterImage"),
+  mDecodingMonitor("RasterImage Decoding Monitor"),
   mDecoder(nullptr),
   mBytesDecoded(0),
   mInDecoder(false),
   mStatusDiff(ImageStatusDiff::NoChange()),
   mNotifying(false),
   mHasSize(false),
   mDecodeOnDraw(false),
   mMultipart(false),
@@ -437,17 +437,17 @@ RasterImage::~RasterImage()
              num_discardable_containers,
              total_source_bytes,
              discardable_source_bytes));
   }
 
   if (mDecoder) {
     // Kill off our decode request, if it's pending.  (If not, this call is
     // harmless.)
-    MutexAutoLock lock(mDecodingMutex);
+    ReentrantMonitorAutoEnter lock(mDecodingMonitor);
     DecodePool::StopDecoding(this);
     mDecoder = nullptr;
 
     // Unlock the last frame (if we have any). Our invariant is that, while we
     // have a decoder open, the last frame is always locked.
     // This would be done in ShutdownDecoder, but since mDecoder is non-null,
     // we didn't call ShutdownDecoder and we need to do it manually.
     if (GetNumFrames() > 0) {
@@ -1202,16 +1202,17 @@ RasterImage::ApplyDecodeFlags(uint32_t a
   mFrameDecodeFlags = aNewFlags & DECODE_FLAGS_MASK;
   return true;
 }
 
 nsresult
 RasterImage::SetSize(int32_t aWidth, int32_t aHeight, Orientation aOrientation)
 {
   MOZ_ASSERT(NS_IsMainThread());
+  mDecodingMonitor.AssertCurrentThreadIn();
 
   if (mError)
     return NS_ERROR_FAILURE;
 
   // Ensure that we have positive values
   // XXX - Why isn't the size unsigned? Should this be changed?
   if ((aWidth < 0) || (aHeight < 0))
     return NS_ERROR_INVALID_ARG;
@@ -1530,17 +1531,17 @@ RasterImage::SetLoopCount(int32_t aLoopC
     // No need to set this if we're not an animation
     mFrameBlender.SetLoopCount(aLoopCount);
   }
 }
 
 nsresult
 RasterImage::AddSourceData(const char *aBuffer, uint32_t aCount)
 {
-  MutexAutoLock lock(mDecodingMutex);
+  ReentrantMonitorAutoEnter lock(mDecodingMonitor);
 
   if (mError)
     return NS_ERROR_FAILURE;
 
   NS_ENSURE_ARG_POINTER(aBuffer);
   nsresult rv = NS_OK;
 
   // We should not call this if we're not initialized
@@ -1578,21 +1579,18 @@ RasterImage::AddSourceData(const char *a
       mFrameBlender.ClearFrames();
     }
   }
 
   // If we're not storing source data and we've previously gotten the size,
   // write the data directly to the decoder. (If we haven't gotten the size,
   // we'll queue up the data and write it out when we do.)
   if (!StoringSourceData() && mHasSize) {
-    {
-      AutoSetSyncDecode syncDecode(mDecoder);
-      rv = WriteToDecoder(aBuffer, aCount);
-      CONTAINER_ENSURE_SUCCESS(rv);
-    }
+    rv = WriteToDecoder(aBuffer, aCount, DECODE_SYNC);
+    CONTAINER_ENSURE_SUCCESS(rv);
 
     // We're not storing source data, so this data is probably coming straight
     // from the network. In this case, we want to display data as soon as we
     // get it, so we want to flush invalidations after every write.
     nsRefPtr<Decoder> kungFuDeathGrip = mDecoder;
     mInDecoder = true;
     mDecoder->FlushInvalidations();
     mInDecoder = false;
@@ -1669,17 +1667,17 @@ RasterImage::DoImageDataComplete()
   // image's size, this does nothing.)  Then kick off an async decode of the
   // rest of the image.
   if (mDecoder) {
     nsresult rv = DecodePool::Singleton()->DecodeUntilSizeAvailable(this);
     CONTAINER_ENSURE_SUCCESS(rv);
   }
 
   {
-    MutexAutoLock lock(mDecodingMutex);
+    ReentrantMonitorAutoEnter lock(mDecodingMonitor);
 
     // If we're not storing any source data, then there's nothing more we can do
     // once we've tried decoding for size.
     if (!StoringSourceData() && mDecoder) {
       nsresult rv = ShutdownDecoder(eShutdownIntent_Done);
       CONTAINER_ENSURE_SUCCESS(rv);
     }
 
@@ -1719,22 +1717,23 @@ nsresult
 RasterImage::OnImageDataComplete(nsIRequest*, nsISupports*, nsresult aStatus, bool aLastPart)
 {
   nsresult finalStatus = DoImageDataComplete();
 
   // Give precedence to Necko failure codes.
   if (NS_FAILED(aStatus))
     finalStatus = aStatus;
 
-  nsRefPtr<imgStatusTracker> statusTracker = CurrentStatusTracker();
-  statusTracker->GetDecoderObserver()->OnStopRequest(aLastPart, finalStatus);
-
   // We just recorded OnStopRequest; we need to inform our listeners.
   {
-    MutexAutoLock lock(mDecodingMutex);
+    ReentrantMonitorAutoEnter lock(mDecodingMonitor);
+
+    nsRefPtr<imgStatusTracker> statusTracker = CurrentStatusTracker();
+    statusTracker->GetDecoderObserver()->OnStopRequest(aLastPart, finalStatus);
+
     FinishedSomeDecoding();
   }
 
   return finalStatus;
 }
 
 nsresult
 RasterImage::OnImageDataAvailable(nsIRequest*,
@@ -2058,17 +2057,17 @@ RasterImage::InitDecoder(bool aDoSizeDec
 // aIntent specifies the intent of the shutdown. If aIntent is
 // eShutdownIntent_Done, an error is flagged if we didn't get what we should
 // have out of the decode. If aIntent is eShutdownIntent_NotNeeded, we don't
 // check this. If aIntent is eShutdownIntent_Error, we shut down in error mode.
 nsresult
 RasterImage::ShutdownDecoder(eShutdownIntent aIntent)
 {
   MOZ_ASSERT(NS_IsMainThread());
-  mDecodingMutex.AssertCurrentThreadOwns();
+  mDecodingMonitor.AssertCurrentThreadIn();
 
   // Ensure that our intent is valid
   NS_ABORT_IF_FALSE((aIntent >= 0) && (aIntent < eShutdownIntent_AllCount),
                     "Invalid shutdown intent");
 
   // Ensure that the decoder is initialized
   NS_ABORT_IF_FALSE(mDecoder, "Calling ShutdownDecoder() with no active decoder!");
 
@@ -2124,27 +2123,27 @@ RasterImage::ShutdownDecoder(eShutdownIn
 
   mBytesDecoded = 0;
 
   return NS_OK;
 }
 
 // Writes the data to the decoder, updating the total number of bytes written.
 nsresult
-RasterImage::WriteToDecoder(const char *aBuffer, uint32_t aCount)
+RasterImage::WriteToDecoder(const char *aBuffer, uint32_t aCount, DecodeStrategy aStrategy)
 {
-  mDecodingMutex.AssertCurrentThreadOwns();
+  mDecodingMonitor.AssertCurrentThreadIn();
 
   // We should have a decoder
   NS_ABORT_IF_FALSE(mDecoder, "Trying to write to null decoder!");
 
   // Write
   nsRefPtr<Decoder> kungFuDeathGrip = mDecoder;
   mInDecoder = true;
-  mDecoder->Write(aBuffer, aCount);
+  mDecoder->Write(aBuffer, aCount, aStrategy);
   mInDecoder = false;
 
   CONTAINER_ENSURE_SUCCESS(mDecoder->GetDecoderError());
 
   // Keep track of the total number of bytes written over the lifetime of the
   // decoder
   mBytesDecoded += aCount;
 
@@ -2245,17 +2244,17 @@ RasterImage::RequestDecodeCore(RequestDe
     // If we didn't get the size out of the image, we won't until we get more
     // data, so signal that we want a full decode and give up for now.
     if (!mHasSize) {
       mWantFullDecode = true;
       return NS_OK;
     }
   }
 
-  MutexAutoLock lock(mDecodingMutex);
+  ReentrantMonitorAutoEnter lock(mDecodingMonitor);
 
   // If we don't have any bytes to flush to the decoder, we can't do anything.
   // mBytesDecoded can be bigger than mSourceData.Length() if we're not storing
   // the source data.
   if (mBytesDecoded > mSourceData.Length())
     return NS_OK;
 
   // If the image is waiting for decode work to be notified, go ahead and do that.
@@ -2302,18 +2301,17 @@ RasterImage::RequestDecodeCore(RequestDe
   if (mHasSourceData && mBytesDecoded == mSourceData.Length())
     return NS_OK;
 
   // If we can do decoding now, do so.  Small images will decode completely,
   // large images will decode a bit and post themselves to the event loop
   // to finish decoding.
   if (!mDecoded && !mInDecoder && mHasSourceData && aDecodeType == SYNCHRONOUS_NOTIFY_AND_SOME_DECODE) {
     PROFILER_LABEL_PRINTF("RasterImage", "DecodeABitOf", "%s", GetURIString().get());
-    AutoSetSyncDecode syncDecode(mDecoder);
-    DecodePool::Singleton()->DecodeABitOf(this);
+    DecodePool::Singleton()->DecodeABitOf(this, DECODE_SYNC);
     return NS_OK;
   }
 
   if (!mDecoded) {
     // If we get this far, dispatch the worker. We do this instead of starting
     // any immediate decoding to guarantee that all our decode notifications are
     // dispatched asynchronously, and to ensure we stay responsive.
     DecodePool::Singleton()->RequestDecode(this);
@@ -2336,17 +2334,17 @@ RasterImage::SyncDecode()
     // If we didn't get the size out of the image, we won't until we get more
     // data, so signal that we want a full decode and give up for now.
     if (!mHasSize) {
       mWantFullDecode = true;
       return NS_ERROR_NOT_AVAILABLE;
     }
   }
 
-  MutexAutoLock imgLock(mDecodingMutex);
+  ReentrantMonitorAutoEnter lock(mDecodingMonitor);
 
   // We really have no good way of forcing a synchronous decode if we're being
   // called in a re-entrant manner (ie, from an event listener fired by a
   // decoder), because the decoding machinery is already tied up. We thus explicitly
   // disallow this type of call in the API, and check for it in API methods.
   NS_ABORT_IF_FALSE(!mInDecoder, "Yikes, forcing sync in reentrant call!");
 
   if (mDecodeRequest) {
@@ -2385,23 +2383,19 @@ RasterImage::SyncDecode()
   }
 
   // If we don't have a decoder, create one
   if (!mDecoder) {
     rv = InitDecoder(/* aDoSizeDecode = */ false);
     CONTAINER_ENSURE_SUCCESS(rv);
   }
 
-  {
-    AutoSetSyncDecode syncDecode(mDecoder);
-
-    // Write everything we have
-    rv = DecodeSomeData(mSourceData.Length() - mBytesDecoded);
-    CONTAINER_ENSURE_SUCCESS(rv);
-  }
+  // Write everything we have
+  rv = DecodeSomeData(mSourceData.Length() - mBytesDecoded, DECODE_SYNC);
+  CONTAINER_ENSURE_SUCCESS(rv);
 
   // When we're doing a sync decode, we want to get as much information from the
   // image as possible. We've send the decoder all of our data, so now's a good
   // time  to flush any invalidations (in case we don't have all the data and what
   // we got left us mid-frame).
   nsRefPtr<Decoder> kungFuDeathGrip = mDecoder;
   mInDecoder = true;
   mDecoder->FlushInvalidations();
@@ -2704,17 +2698,17 @@ RasterImage::UnlockImage()
   // and our lock count is now zero (so nothing is forcing us to keep the
   // decoded data around), try to cancel the decode and throw away whatever
   // we've decoded.
   if (mHasBeenDecoded && mDecoder &&
       mLockCount == 0 && CanForciblyDiscard()) {
     PR_LOG(GetCompressedImageAccountingLog(), PR_LOG_DEBUG,
            ("RasterImage[0x%p] canceling decode because image "
             "is now unlocked.", this));
-    MutexAutoLock lock(mDecodingMutex);
+    ReentrantMonitorAutoEnter lock(mDecodingMonitor);
     FinishedSomeDecoding(eShutdownIntent_NotNeeded);
     ForceDiscard();
     return NS_OK;
   }
 
   // Otherwise, we might still be a candidate for discarding in the future.  If
   // we are, add ourselves to the discard tracker.
   if (CanDiscard()) {
@@ -2734,58 +2728,59 @@ RasterImage::RequestDiscard()
     ForceDiscard();
   }
 
   return NS_OK;
 }
 
 // Flushes up to aMaxBytes to the decoder.
 nsresult
-RasterImage::DecodeSomeData(uint32_t aMaxBytes)
+RasterImage::DecodeSomeData(uint32_t aMaxBytes, DecodeStrategy aStrategy)
 {
   // We should have a decoder if we get here
   NS_ABORT_IF_FALSE(mDecoder, "trying to decode without decoder!");
 
-  mDecodingMutex.AssertCurrentThreadOwns();
+  mDecodingMonitor.AssertCurrentThreadIn();
 
   // First, if we've just been called because we allocated a frame on the main
   // thread, let the decoder deal with the data it set aside at that time by
   // passing it a null buffer.
   if (mDecodeRequest->mAllocatedNewFrame) {
     mDecodeRequest->mAllocatedNewFrame = false;
-    nsresult rv = WriteToDecoder(nullptr, 0);
+    nsresult rv = WriteToDecoder(nullptr, 0, aStrategy);
     if (NS_FAILED(rv) || mDecoder->NeedsNewFrame()) {
       return rv;
     }
   }
 
   // If we have nothing else to decode, return
   if (mBytesDecoded == mSourceData.Length())
     return NS_OK;
 
   MOZ_ASSERT(mBytesDecoded < mSourceData.Length());
 
   // write the proper amount of data
   uint32_t bytesToDecode = std::min(aMaxBytes,
                                     mSourceData.Length() - mBytesDecoded);
   nsresult rv = WriteToDecoder(mSourceData.Elements() + mBytesDecoded,
-                               bytesToDecode);
+                               bytesToDecode,
+                               aStrategy);
 
   return rv;
 }
 
 // There are various indicators that tell us we're finished with the decode
 // task at hand and can shut down the decoder.
 //
 // This method may not be called if there is no decoder.
 bool
 RasterImage::IsDecodeFinished()
 {
   // Precondition
-  mDecodingMutex.AssertCurrentThreadOwns();
+  mDecodingMonitor.AssertCurrentThreadIn();
   NS_ABORT_IF_FALSE(mDecoder, "Can't call IsDecodeFinished() without decoder!");
 
   // The decode is complete if we got what we wanted.
   if (mDecoder->IsSizeDecode()) {
     if (mDecoder->HasSize()) {
       return true;
     }
   } else if (mDecoder->GetDecodeDone()) {
@@ -2823,19 +2818,22 @@ RasterImage::DoError()
     return;
 
   // We can't safely handle errors off-main-thread, so dispatch a worker to do it.
   if (!NS_IsMainThread()) {
     HandleErrorWorker::DispatchIfNeeded(this);
     return;
   }
 
+  // Calling FinishedSomeDecoding and CurrentStatusTracker requires us to be in
+  // the decoding monitor.
+  ReentrantMonitorAutoEnter lock(mDecodingMonitor);
+
   // If we're mid-decode, shut down the decoder.
   if (mDecoder) {
-    MutexAutoLock lock(mDecodingMutex);
     FinishedSomeDecoding(eShutdownIntent_Error);
   }
 
   // Put the container in an error state.
   mError = true;
 
   nsRefPtr<imgStatusTracker> statusTracker = CurrentStatusTracker();
   statusTracker->GetDecoderObserver()->OnError();
@@ -2946,17 +2944,17 @@ RasterImage::RequestDecodeIfNeeded(nsres
 }
 
 nsresult
 RasterImage::FinishedSomeDecoding(eShutdownIntent aIntent /* = eShutdownIntent_Done */,
                                   DecodeRequest* aRequest /* = nullptr */)
 {
   MOZ_ASSERT(NS_IsMainThread());
 
-  mDecodingMutex.AssertCurrentThreadOwns();
+  mDecodingMonitor.AssertCurrentThreadIn();
 
   nsRefPtr<DecodeRequest> request;
   if (aRequest) {
     request = aRequest;
   } else {
     request = mDecodeRequest;
   }
 
@@ -3013,20 +3011,16 @@ RasterImage::FinishedSomeDecoding(eShutd
     }
   }
 
   ImageStatusDiff diff =
     request ? image->mStatusTracker->Difference(request->mStatusTracker)
             : image->mStatusTracker->DecodeStateAsDifference();
   image->mStatusTracker->ApplyDifference(diff);
 
-  // Notifications can't go out with the decoding lock held, nor can we call
-  // RequestDecodeIfNeeded, so unlock for the rest of the function.
-  MutexAutoUnlock unlock(mDecodingMutex);
-
   if (mNotifying) {
     // Accumulate the status changes. We don't permit recursive notifications
     // because they cause subtle concurrency bugs, so we'll delay sending out
     // the notifications until we pop back to the lowest invocation of
     // FinishedSomeDecoding on the stack.
     NS_WARNING("Recursively notifying in RasterImage::FinishedSomeDecoding!");
     mStatusDiff.Combine(diff);
   } else {
@@ -3158,17 +3152,17 @@ RasterImage::DecodePool::Observe(nsISupp
 
   return NS_OK;
 }
 
 void
 RasterImage::DecodePool::RequestDecode(RasterImage* aImg)
 {
   MOZ_ASSERT(aImg->mDecoder);
-  aImg->mDecodingMutex.AssertCurrentThreadOwns();
+  aImg->mDecodingMonitor.AssertCurrentThreadIn();
 
   // If we're currently waiting on a new frame for this image, we can't do any
   // decoding.
   if (!aImg->mDecoder->NeedsNewFrame()) {
     // No matter whether this is currently being decoded, we need to update the
     // number of bytes we want it to decode.
     aImg->mDecodeRequest->mBytesToDecode = aImg->mSourceData.Length() - aImg->mBytesDecoded;
 
@@ -3187,29 +3181,29 @@ RasterImage::DecodePool::RequestDecode(R
       NS_DispatchToMainThread(job);
     } else {
       mThreadPool->Dispatch(job, nsIEventTarget::DISPATCH_NORMAL);
     }
   }
 }
 
 void
-RasterImage::DecodePool::DecodeABitOf(RasterImage* aImg)
+RasterImage::DecodePool::DecodeABitOf(RasterImage* aImg, DecodeStrategy aStrategy)
 {
   MOZ_ASSERT(NS_IsMainThread());
-  aImg->mDecodingMutex.AssertCurrentThreadOwns();
+  aImg->mDecodingMonitor.AssertCurrentThreadIn();
 
   if (aImg->mDecodeRequest) {
     // If the image is waiting for decode work to be notified, go ahead and do that.
     if (aImg->mDecodeRequest->mRequestStatus == DecodeRequest::REQUEST_WORK_DONE) {
       aImg->FinishedSomeDecoding();
     }
   }
 
-  DecodeSomeOfImage(aImg);
+  DecodeSomeOfImage(aImg, aStrategy);
 
   aImg->FinishedSomeDecoding();
 
   // If the decoder needs a new frame, enqueue an event to get it; that event
   // will enqueue another decode request when it's done.
   if (aImg->mDecoder && aImg->mDecoder->NeedsNewFrame()) {
     FrameNeededWorker::GetNewFrame(aImg);
   } else {
@@ -3222,29 +3216,29 @@ RasterImage::DecodePool::DecodeABitOf(Ra
       RequestDecode(aImg);
     }
   }
 }
 
 /* static */ void
 RasterImage::DecodePool::StopDecoding(RasterImage* aImg)
 {
-  aImg->mDecodingMutex.AssertCurrentThreadOwns();
+  aImg->mDecodingMonitor.AssertCurrentThreadIn();
 
   // If we haven't got a decode request, we're not currently decoding. (Having
   // a decode request doesn't imply we *are* decoding, though.)
   if (aImg->mDecodeRequest) {
     aImg->mDecodeRequest->mRequestStatus = DecodeRequest::REQUEST_STOPPED;
   }
 }
 
 NS_IMETHODIMP
 RasterImage::DecodePool::DecodeJob::Run()
 {
-  MutexAutoLock imglock(mImage->mDecodingMutex);
+  ReentrantMonitorAutoEnter lock(mImage->mDecodingMonitor);
 
   // If we were interrupted, we shouldn't do any work.
   if (mRequest->mRequestStatus == DecodeRequest::REQUEST_STOPPED) {
     DecodeDoneWorker::NotifyFinishedSomeDecoding(mImage, mRequest);
     return NS_OK;
   }
 
   // If someone came along and synchronously decoded us, there's nothing for us to do.
@@ -3267,17 +3261,17 @@ RasterImage::DecodePool::DecodeJob::Run(
   DecodeType type = DECODE_TYPE_UNTIL_DONE_BYTES;
 
   // Multithreaded decoding can be disabled. If we've done so, we don't want to
   // monopolize the main thread, and will allow a timeout in DecodeSomeOfImage.
   if (NS_IsMainThread()) {
     type = DECODE_TYPE_UNTIL_TIME;
   }
 
-  DecodePool::Singleton()->DecodeSomeOfImage(mImage, type, mRequest->mBytesToDecode);
+  DecodePool::Singleton()->DecodeSomeOfImage(mImage, DECODE_ASYNC, type, mRequest->mBytesToDecode);
 
   uint32_t bytesDecoded = mImage->mBytesDecoded - oldByteCount;
 
   mRequest->mRequestStatus = DecodeRequest::REQUEST_WORK_DONE;
 
   // If the decoder needs a new frame, enqueue an event to get it; that event
   // will enqueue another decode request when it's done.
   if (mImage->mDecoder && mImage->mDecoder->NeedsNewFrame()) {
@@ -3299,31 +3293,32 @@ RasterImage::DecodePool::DecodeJob::Run(
 
   return NS_OK;
 }
 
 nsresult
 RasterImage::DecodePool::DecodeUntilSizeAvailable(RasterImage* aImg)
 {
   MOZ_ASSERT(NS_IsMainThread());
-
-  MutexAutoLock imgLock(aImg->mDecodingMutex);
+  ReentrantMonitorAutoEnter lock(aImg->mDecodingMonitor);
 
   if (aImg->mDecodeRequest) {
     // If the image is waiting for decode work to be notified, go ahead and do that.
     if (aImg->mDecodeRequest->mRequestStatus == DecodeRequest::REQUEST_WORK_DONE) {
       nsresult rv = aImg->FinishedSomeDecoding();
       if (NS_FAILED(rv)) {
         aImg->DoError();
         return rv;
       }
     }
   }
 
-  nsresult rv = DecodeSomeOfImage(aImg, DECODE_TYPE_UNTIL_SIZE);
+  // We use DECODE_ASYNC here because we just want to get the size information
+  // here and defer the rest of the work.
+  nsresult rv = DecodeSomeOfImage(aImg, DECODE_ASYNC, DECODE_TYPE_UNTIL_SIZE);
   if (NS_FAILED(rv)) {
     return rv;
   }
 
   // If the decoder needs a new frame, enqueue an event to get it; that event
   // will enqueue another decode request when it's done.
   if (aImg->mDecoder && aImg->mDecoder->NeedsNewFrame()) {
     FrameNeededWorker::GetNewFrame(aImg);
@@ -3331,36 +3326,37 @@ RasterImage::DecodePool::DecodeUntilSize
     rv = aImg->FinishedSomeDecoding();
   }
 
   return rv;
 }
 
 nsresult
 RasterImage::DecodePool::DecodeSomeOfImage(RasterImage* aImg,
+                                           DecodeStrategy aStrategy,
                                            DecodeType aDecodeType /* = DECODE_TYPE_UNTIL_TIME */,
                                            uint32_t bytesToDecode /* = 0 */)
 {
   NS_ABORT_IF_FALSE(aImg->mInitialized,
                     "Worker active for uninitialized container!");
-  aImg->mDecodingMutex.AssertCurrentThreadOwns();
+  aImg->mDecodingMonitor.AssertCurrentThreadIn();
 
   // If an error is flagged, it probably happened while we were waiting
   // in the event queue.
   if (aImg->mError)
     return NS_OK;
 
   // If mDecoded or we don't have a decoder, we must have finished already (for
   // example, a synchronous decode request came while the worker was pending).
   if (!aImg->mDecoder || aImg->mDecoded)
     return NS_OK;
 
   // If we're doing synchronous decodes, and we're waiting on a new frame for
   // this image, get it now.
-  if (aImg->mDecoder->IsSynchronous() && aImg->mDecoder->NeedsNewFrame()) {
+  if (aStrategy == DECODE_SYNC && aImg->mDecoder->NeedsNewFrame()) {
     MOZ_ASSERT(NS_IsMainThread());
 
     aImg->mDecoder->AllocateFrame();
     aImg->mDecodeRequest->mAllocatedNewFrame = true;
   }
 
   // If we're not synchronous, we can't allocate a frame right now.
   else if (aImg->mDecoder->NeedsNewFrame()) {
@@ -3399,17 +3395,17 @@ RasterImage::DecodePool::DecodeSomeOfIma
   while ((aImg->mSourceData.Length() > aImg->mBytesDecoded &&
           bytesToDecode > 0 &&
           !aImg->IsDecodeFinished() &&
           !(aDecodeType == DECODE_TYPE_UNTIL_SIZE && aImg->mHasSize) &&
           !aImg->mDecoder->NeedsNewFrame()) ||
          (aImg->mDecodeRequest && aImg->mDecodeRequest->mAllocatedNewFrame)) {
     chunkCount++;
     uint32_t chunkSize = std::min(bytesToDecode, maxBytes);
-    nsresult rv = aImg->DecodeSomeData(chunkSize);
+    nsresult rv = aImg->DecodeSomeData(chunkSize, aStrategy);
     if (NS_FAILED(rv)) {
       aImg->DoError();
       return rv;
     }
 
     bytesToDecode -= chunkSize;
 
     // Yield if we've been decoding for too long. We check this _after_ decoding
@@ -3454,27 +3450,27 @@ RasterImage::DecodePool::DecodeSomeOfIma
 RasterImage::DecodeDoneWorker::DecodeDoneWorker(RasterImage* image, DecodeRequest* request)
  : mImage(image)
  , mRequest(request)
 {}
 
 void
 RasterImage::DecodeDoneWorker::NotifyFinishedSomeDecoding(RasterImage* image, DecodeRequest* request)
 {
-  image->mDecodingMutex.AssertCurrentThreadOwns();
+  image->mDecodingMonitor.AssertCurrentThreadIn();
 
   nsCOMPtr<DecodeDoneWorker> worker = new DecodeDoneWorker(image, request);
   NS_DispatchToMainThread(worker);
 }
 
 NS_IMETHODIMP
 RasterImage::DecodeDoneWorker::Run()
 {
   MOZ_ASSERT(NS_IsMainThread());
-  MutexAutoLock lock(mImage->mDecodingMutex);
+  ReentrantMonitorAutoEnter lock(mImage->mDecodingMonitor);
 
   mImage->FinishedSomeDecoding(eShutdownIntent_Done, mRequest);
 
   return NS_OK;
 }
 
 RasterImage::FrameNeededWorker::FrameNeededWorker(RasterImage* image)
  : mImage(image)
@@ -3486,17 +3482,17 @@ RasterImage::FrameNeededWorker::GetNewFr
 {
   nsCOMPtr<FrameNeededWorker> worker = new FrameNeededWorker(image);
   NS_DispatchToMainThread(worker);
 }
 
 NS_IMETHODIMP
 RasterImage::FrameNeededWorker::Run()
 {
-  MutexAutoLock lock(mImage->mDecodingMutex);
+  ReentrantMonitorAutoEnter lock(mImage->mDecodingMonitor);
   nsresult rv = NS_OK;
 
   // If we got a synchronous decode in the mean time, we don't need to do
   // anything.
   if (mImage->mDecoder && mImage->mDecoder->NeedsNewFrame()) {
     rv = mImage->mDecoder->AllocateFrame();
     mImage->mDecodeRequest->mAllocatedNewFrame = true;
   }
--- a/image/src/RasterImage.h
+++ b/image/src/RasterImage.h
@@ -20,24 +20,26 @@
 #include "Image.h"
 #include "FrameBlender.h"
 #include "nsCOMPtr.h"
 #include "imgIContainer.h"
 #include "nsIProperties.h"
 #include "nsTArray.h"
 #include "imgFrame.h"
 #include "nsThreadUtils.h"
+#include "DecodeStrategy.h"
 #include "DiscardTracker.h"
 #include "Orientation.h"
 #include "nsIObserver.h"
 #include "mozilla/MemoryReporting.h"
+#include "mozilla/Mutex.h"
+#include "mozilla/ReentrantMonitor.h"
 #include "mozilla/TimeStamp.h"
 #include "mozilla/StaticPtr.h"
 #include "mozilla/WeakPtr.h"
-#include "mozilla/Mutex.h"
 #ifdef DEBUG
   #include "imgIContainerDebug.h"
 #endif
 
 class nsIInputStream;
 class nsIThreadPool;
 class nsIRequest;
 
@@ -117,21 +119,23 @@ class nsIRequest;
  * @par
  * The mAnim structure has members only needed for animated images, so
  * it's not allocated until the second frame is added.
  */
 
 class ScaleRequest;
 
 namespace mozilla {
+
 namespace layers {
 class LayerManager;
 class ImageContainer;
 class Image;
 }
+
 namespace image {
 
 class Decoder;
 class FrameAnimator;
 
 class RasterImage : public ImageResource
                   , public nsIProperties
                   , public SupportsWeakPtr<RasterImage>
@@ -303,19 +307,22 @@ public:
   // Decoder shutdown
   enum eShutdownIntent {
     eShutdownIntent_Done        = 0,
     eShutdownIntent_NotNeeded   = 1,
     eShutdownIntent_Error       = 2,
     eShutdownIntent_AllCount    = 3
   };
 
+  // Decode strategy
+
 private:
   already_AddRefed<imgStatusTracker> CurrentStatusTracker()
   {
+    mDecodingMonitor.AssertCurrentThreadIn();
     nsRefPtr<imgStatusTracker> statusTracker;
     statusTracker = mDecodeRequest ? mDecodeRequest->mStatusTracker
                                    : mStatusTracker;
     MOZ_ASSERT(statusTracker);
     return statusTracker.forget();
   }
 
   nsresult OnImageDataCompleteCore(nsIRequest* aRequest, nsISupports*, nsresult aStatus);
@@ -395,17 +402,17 @@ private:
      * Ask the DecodePool to asynchronously decode this image.
      */
     void RequestDecode(RasterImage* aImg);
 
     /**
      * Decode aImg for a short amount of time, and post the remainder to the
      * queue.
      */
-    void DecodeABitOf(RasterImage* aImg);
+    void DecodeABitOf(RasterImage* aImg, DecodeStrategy aStrategy);
 
     /**
      * Ask the DecodePool to stop decoding this image.  Internally, we also
      * call this function when we finish decoding an image.
      *
      * Since the DecodePool keeps raw pointers to RasterImages, make sure you
      * call this before a RasterImage is destroyed!
      */
@@ -444,16 +451,17 @@ private:
     };
 
     /* Decode some chunks of the given image.  If aDecodeType is UNTIL_SIZE,
      * decode until we have the image's size, then stop. If bytesToDecode is
      * non-0, at most bytesToDecode bytes will be decoded. if aDecodeType is
      * UNTIL_DONE_BYTES, decode until all bytesToDecode bytes are decoded.
      */
     nsresult DecodeSomeOfImage(RasterImage* aImg,
+                               DecodeStrategy aStrategy,
                                DecodeType aDecodeType = DECODE_TYPE_UNTIL_TIME,
                                uint32_t bytesToDecode = 0);
 
     /* A decode job dispatched to a thread pool by DecodePool.
      */
     class DecodeJob : public nsRunnable
     {
     public:
@@ -467,20 +475,20 @@ private:
     private:
       nsRefPtr<DecodeRequest> mRequest;
       nsRefPtr<RasterImage> mImage;
     };
 
   private: /* members */
 
     // mThreadPoolMutex protects mThreadPool. For all RasterImages R,
-    // R::mDecodingMutex must be acquired before mThreadPoolMutex if both are
-    // acquired; the other order may cause deadlock.
-    mozilla::Mutex          mThreadPoolMutex;
-    nsCOMPtr<nsIThreadPool> mThreadPool;
+    // R::mDecodingMonitor must be acquired before mThreadPoolMutex
+    // if both are acquired; the other order may cause deadlock.
+    mozilla::Mutex            mThreadPoolMutex;
+    nsCOMPtr<nsIThreadPool>   mThreadPool;
   };
 
   class DecodeDoneWorker : public nsRunnable
   {
   public:
     /**
      * Called by the DecodePool with an image when it's done some significant
      * portion of decoding that needs to be notified about.
@@ -637,20 +645,20 @@ private: // data
   // Cached value for GetImageContainer.
   nsRefPtr<mozilla::layers::ImageContainer> mImageContainer;
 
 #ifdef DEBUG
   uint32_t                       mFramesNotified;
 #endif
 
   // Below are the pieces of data that can be accessed on more than one thread
-  // at once, and hence need to be locked by mDecodingMutex.
+  // at once, and hence need to be locked by mDecodingMonitor.
 
   // BEGIN LOCKED MEMBER VARIABLES
-  mozilla::Mutex             mDecodingMutex;
+  mozilla::ReentrantMonitor  mDecodingMonitor;
 
   FallibleTArray<char>       mSourceData;
 
   // Decoder and friends
   nsRefPtr<Decoder>          mDecoder;
   nsRefPtr<DecodeRequest>    mDecodeRequest;
   uint32_t                   mBytesDecoded;
 
@@ -694,18 +702,18 @@ private: // data
   // Decoding
   nsresult RequestDecodeIfNeeded(nsresult aStatus,
                                  eShutdownIntent aIntent,
                                  bool aDone,
                                  bool aWasSize);
   nsresult WantDecodedFrames();
   nsresult SyncDecode();
   nsresult InitDecoder(bool aDoSizeDecode);
-  nsresult WriteToDecoder(const char *aBuffer, uint32_t aCount);
-  nsresult DecodeSomeData(uint32_t aMaxBytes);
+  nsresult WriteToDecoder(const char *aBuffer, uint32_t aCount, DecodeStrategy aStrategy);
+  nsresult DecodeSomeData(uint32_t aMaxBytes, DecodeStrategy aStrategy);
   bool     IsDecodeFinished();
   TimeStamp mDrawStartTime;
 
   inline bool CanQualityScale(const gfx::Size& scale);
   inline bool CanScale(GraphicsFilter aFilter, gfx::Size aScale, uint32_t aFlags);
 
   struct ScaleResult
   {
--- a/intl/uconv/src/moz.build
+++ b/intl/uconv/src/moz.build
@@ -228,8 +228,10 @@ LOCAL_INCLUDES += [
     '../ucvko',
     '../ucvlatin',
     '../ucvtw',
     '../ucvtw2',
     '../util',
 ]
 
 FINAL_LIBRARY = 'xul'
+
+JAR_MANIFESTS += ['jar.mn']
\ No newline at end of file
--- a/ipc/chromium/src/base/chrome_application_mac.mm
+++ b/ipc/chromium/src/base/chrome_application_mac.mm
@@ -16,18 +16,18 @@
 @synthesize handlingSendEvent = handlingSendEvent_;
 
 // Initialize NSApplication using the custom subclass.  Check whether NSApp
 // was already initialized using another class, because that would break
 // some things.
 + (NSApplication*)sharedApplication {
   NSApplication* app = [super sharedApplication];
   if (![NSApp isKindOfClass:self]) {
-    LOG(ERROR) << "NSApp should be of type " << [[self className] UTF8String]
-               << ", not " << [[NSApp className] UTF8String];
+    CHROMIUM_LOG(ERROR) << "NSApp should be of type " << [[self className] UTF8String]
+                        << ", not " << [[NSApp className] UTF8String];
     DCHECK(false) << "NSApp is of wrong type";
   }
   return app;
 }
 
 - (id)init {
   if ((self = [super init])) {
     eventHooks_.reset([[NSMutableArray alloc] init]);
--- a/ipc/chromium/src/base/debug_util_win.cc
+++ b/ipc/chromium/src/base/debug_util_win.cc
@@ -111,51 +111,51 @@ class SymbolContext {
       }
     }
 
     initialized_ = true;
     return init_error_ == ERROR_SUCCESS;
   }
 
   // Returns the error code of a failed initialization.  This should only be
-  // called if Init() has been called.  We do not LOG(FATAL) here because
-  // this code is called might be triggered by a LOG(FATAL) itself.  Instead,
+  // called if Init() has been called.  We do not CHROMIUM_LOG(FATAL) here because
+  // this code is called might be triggered by a CHROMIUM_LOG(FATAL) itself.  Instead,
   // we log an ERROR, and return ERROR_INVALID_DATA.
   DWORD init_error() {
     if (!initialized_) {
-      LOG(ERROR) << "Calling GetInitError() before Init() was called.  "
-                 << "Returning ERROR_INVALID_DATA.";
+      CHROMIUM_LOG(ERROR) << "Calling GetInitError() before Init() was called.  "
+                          << "Returning ERROR_INVALID_DATA.";
       return ERROR_INVALID_DATA;
     }
 
     return init_error_;
   }
 
   // Returns the process this was initialized for.  This should only be
-  // called if Init() has been called.  We LOG(ERROR) in this situation.
-  // LOG(FATAL) is not used because this code is might be triggered 
-  // by a LOG(FATAL) itself.
+  // called if Init() has been called.  We CHROMIUM_LOG(ERROR) in this situation.
+  // CHROMIUM_LOG(FATAL) is not used because this code is might be triggered 
+  // by a CHROMIUM_LOG(FATAL) itself.
   HANDLE process() {
     if (!initialized_) {
-      LOG(ERROR) << "Calling process() before Init() was called. "
-                 << "Returning NULL.";
+      CHROMIUM_LOG(ERROR) << "Calling process() before Init() was called. "
+                          << "Returning NULL.";
       return NULL;
     }
 
     return process_;
   }
 
   // For the given trace, attempts to resolve the symbols, and output a trace
   // to the ostream os.  The format for each line of the backtrace is:
   //
   //    <tab>SymbolName[0xAddress+Offset] (FileName:LineNo)
   // 
   // This function should only be called if Init() has been called.  We do not
-  // LOG(FATAL) here because this code is called might be triggered by a
-  // LOG(FATAL) itself.
+  // CHROMIUM_LOG(FATAL) here because this code is called might be triggered by a
+  // CHROMIUM_LOG(FATAL) itself.
   void OutputTraceToStream(const std::vector<void*>& trace, std::ostream* os) {
     AutoLock lock(lock_);
 
     for (size_t i = 0; (i < trace.size()) && os->good(); ++i) {
       const int kMaxNameLength = 256;
       DWORD_PTR frame = reinterpret_cast<DWORD_PTR>(trace[i]);
 
       // Code adapted from MSDN example:
--- a/ipc/chromium/src/base/file_util_posix.cc
+++ b/ipc/chromium/src/base/file_util_posix.cc
@@ -142,17 +142,17 @@ bool CopyDirectory(const FilePath& from_
 
 #ifdef ANDROID
   // XXX Need ftsless impl for bionic
   return false;
 #else
   char* dir_list[] = { top_dir, NULL };
   FTS* fts = fts_open(dir_list, FTS_PHYSICAL | FTS_NOSTAT, NULL);
   if (!fts) {
-    LOG(ERROR) << "fts_open failed: " << strerror(errno);
+    CHROMIUM_LOG(ERROR) << "fts_open failed: " << strerror(errno);
     return false;
   }
 
   int error = 0;
   FTSENT* ent;
   while (!error && (ent = fts_read(fts)) != NULL) {
     // ent->fts_path is the source path, including from_path, so paste
     // the suffix after from_path onto to_path to create the target_path.
@@ -198,21 +198,21 @@ bool CopyDirectory(const FilePath& from_
       case FTS_DNR:  // Directory cannot be read.
       case FTS_ERR:  // Error.
       case FTS_NS:   // Stat failed.
         // Abort with the error.
         error = ent->fts_errno;
         break;
       case FTS_SL:      // Symlink.
       case FTS_SLNONE:  // Symlink with broken target.
-        LOG(WARNING) << "CopyDirectory() skipping symbolic link: " <<
+        CHROMIUM_LOG(WARNING) << "CopyDirectory() skipping symbolic link: " <<
             ent->fts_path;
         continue;
       case FTS_DEFAULT:  // Some other sort of file.
-        LOG(WARNING) << "CopyDirectory() skipping file of unknown type: " <<
+        CHROMIUM_LOG(WARNING) << "CopyDirectory() skipping file of unknown type: " <<
             ent->fts_path;
         continue;
       default:
         NOTREACHED();
         continue;  // Hope for the best!
     }
   }
   // fts_read may have returned NULL and set errno to indicate an error.
@@ -222,17 +222,17 @@ bool CopyDirectory(const FilePath& from_
   if (!fts_close(fts)) {
     // If we already have an error, let's use that error instead of the error
     // fts_close set.
     if (!error)
       error = errno;
   }
 
   if (error) {
-    LOG(ERROR) << "CopyDirectory(): " << strerror(error);
+    CHROMIUM_LOG(ERROR) << "CopyDirectory(): " << strerror(error);
     return false;
   }
   return true;
 #endif
 }
 
 bool PathExists(const FilePath& path) {
   struct stat file_info;
--- a/ipc/chromium/src/base/file_util_win.cc
+++ b/ipc/chromium/src/base/file_util_win.cc
@@ -308,35 +308,35 @@ int WriteFile(const FilePath& filename, 
   ScopedHandle file(CreateFile(filename.value().c_str(),
                                GENERIC_WRITE,
                                0,
                                NULL,
                                CREATE_ALWAYS,
                                0,
                                NULL));
   if (file == INVALID_HANDLE_VALUE) {
-    LOG(WARNING) << "CreateFile failed for path " << filename.value() <<
+    CHROMIUM_LOG(WARNING) << "CreateFile failed for path " << filename.value() <<
         " error code=" << GetLastError() <<
         " error text=" << win_util::FormatLastWin32Error();
     return -1;
   }
 
   DWORD written;
   BOOL result = ::WriteFile(file, data, size, &written, NULL);
   if (result && written == size)
     return static_cast<int>(written);
 
   if (!result) {
     // WriteFile failed.
-    LOG(WARNING) << "writing file " << filename.value() <<
+    CHROMIUM_LOG(WARNING) << "writing file " << filename.value() <<
         " failed, error code=" << GetLastError() <<
         " description=" << win_util::FormatLastWin32Error();
   } else {
     // Didn't write all the bytes.
-    LOG(WARNING) << "wrote" << written << " bytes to " <<
+    CHROMIUM_LOG(WARNING) << "wrote" << written << " bytes to " <<
         filename.value() << " expected " << size;
   }
   return -1;
 }
 
 // Gets the current working directory for the process.
 bool GetCurrentDirectory(FilePath* dir) {
   wchar_t system_buffer[MAX_PATH];
--- a/ipc/chromium/src/base/histogram.cc
+++ b/ipc/chromium/src/base/histogram.cc
@@ -16,17 +16,17 @@
 
 #include "base/logging.h"
 #include "base/pickle.h"
 #include "base/string_util.h"
 #include "base/logging.h"
 
 namespace base {
 
-#define DVLOG(x) LOG(ERROR)
+#define DVLOG(x) CHROMIUM_LOG(ERROR)
 #define CHECK_GT DCHECK_GT
 #define CHECK_LT DCHECK_LT
 typedef ::Lock Lock;
 typedef ::AutoLock AutoLock;
 
 // Static table of checksums for all possible 8 bit bytes.
 const uint32_t Histogram::kCrcTable[256] = {0x0, 0x77073096L, 0xee0e612cL,
 0x990951baL, 0x76dc419L, 0x706af48fL, 0xe963a535L, 0x9e6495a3L, 0xedb8832L,
@@ -269,25 +269,25 @@ bool Histogram::DeserializeHistogramInfo
   if (!pickle.ReadString(&iter, &histogram_name) ||
       !pickle.ReadInt(&iter, &declared_min) ||
       !pickle.ReadInt(&iter, &declared_max) ||
       !pickle.ReadSize(&iter, &bucket_count) ||
       !pickle.ReadUInt32(&iter, &range_checksum) ||
       !pickle.ReadInt(&iter, &histogram_type) ||
       !pickle.ReadInt(&iter, &pickle_flags) ||
       !sample.Histogram::SampleSet::Deserialize(&iter, pickle)) {
-    LOG(ERROR) << "Pickle error decoding Histogram: " << histogram_name;
+    CHROMIUM_LOG(ERROR) << "Pickle error decoding Histogram: " << histogram_name;
     return false;
   }
   DCHECK(pickle_flags & kIPCSerializationSourceFlag);
   // Since these fields may have come from an untrusted renderer, do additional
   // checks above and beyond those in Histogram::Initialize()
   if (declared_max <= 0 || declared_min <= 0 || declared_max < declared_min ||
       INT_MAX / sizeof(Count) <= bucket_count || bucket_count < 2) {
-    LOG(ERROR) << "Values error decoding Histogram: " << histogram_name;
+    CHROMIUM_LOG(ERROR) << "Values error decoding Histogram: " << histogram_name;
     return false;
   }
 
   Flags flags = static_cast<Flags>(pickle_flags & ~kIPCSerializationSourceFlag);
 
   DCHECK_NE(NOT_VALID_IN_RENDERER, histogram_type);
 
   Histogram* render_histogram(NULL);
@@ -296,18 +296,18 @@ bool Histogram::DeserializeHistogramInfo
     render_histogram = Histogram::FactoryGet(
         histogram_name, declared_min, declared_max, bucket_count, flags);
   } else if (histogram_type == LINEAR_HISTOGRAM) {
     render_histogram = LinearHistogram::FactoryGet(
         histogram_name, declared_min, declared_max, bucket_count, flags);
   } else if (histogram_type == BOOLEAN_HISTOGRAM) {
     render_histogram = BooleanHistogram::FactoryGet(histogram_name, flags);
   } else {
-    LOG(ERROR) << "Error Deserializing Histogram Unknown histogram_type: "
-               << histogram_type;
+    CHROMIUM_LOG(ERROR) << "Error Deserializing Histogram Unknown histogram_type: "
+                        << histogram_type;
     return false;
   }
 
   DCHECK_EQ(render_histogram->declared_min(), declared_min);
   DCHECK_EQ(render_histogram->declared_max(), declared_max);
   DCHECK_EQ(render_histogram->bucket_count(), bucket_count);
   DCHECK_EQ(render_histogram->range_checksum(), range_checksum);
   DCHECK_EQ(render_histogram->histogram_type(), histogram_type);
@@ -452,17 +452,17 @@ Histogram::Histogram(const std::string& 
     range_checksum_(0) {
   Initialize();
 }
 
 Histogram::~Histogram() {
   if (StatisticsRecorder::dump_on_exit()) {
     std::string output;
     WriteAscii(true, "\n", &output);
-    LOG(INFO) << output;
+    CHROMIUM_LOG(INFO) << output;
   }
 
   // Just to make sure most derived class did this properly...
   DCHECK(ValidateBucketRanges());
 }
 
 // Calculate what range of values are held in each bucket.
 // We have to be careful that we don't pick a ratio between starting points in
@@ -1134,17 +1134,17 @@ StatisticsRecorder::StatisticsRecorder()
 }
 
 StatisticsRecorder::~StatisticsRecorder() {
   DCHECK(histograms_ && lock_);
 
   if (dump_on_exit_) {
     std::string output;
     WriteGraph("", &output);
-    LOG(INFO) << output;
+    CHROMIUM_LOG(INFO) << output;
   }
   // Clean up.
   HistogramMap* histograms = NULL;
   {
     base::AutoLock auto_lock(*lock_);
     histograms = histograms_;
     histograms_ = NULL;
     for (HistogramMap::iterator it = histograms->begin();
--- a/ipc/chromium/src/base/logging.h
+++ b/ipc/chromium/src/base/logging.h
@@ -84,40 +84,40 @@ mozilla::Logger& operator<<(mozilla::Log
 
 template<class T>
 const mozilla::EmptyLog& operator <<(const mozilla::EmptyLog& log, const T&)
 {
   return log;
 }
 
 #ifdef NO_CHROMIUM_LOGGING
-#define LOG(info) std::stringstream()
+#define CHROMIUM_LOG(info) std::stringstream()
 #define LOG_IF(info, condition) if (!(condition)) std::stringstream()
 #else
-#define LOG(info) mozilla::LogWrapper(mozilla::LOG_ ## info, __FILE__, __LINE__)
+#define CHROMIUM_LOG(info) mozilla::LogWrapper(mozilla::LOG_ ## info, __FILE__, __LINE__)
 #define LOG_IF(info, condition) \
   if (!(condition)) mozilla::LogWrapper(mozilla::LOG_ ## info, __FILE__, __LINE__)
 #endif
 
 
 #ifdef DEBUG
-#define DLOG(info) LOG(info)
+#define DLOG(info) CHROMIUM_LOG(info)
 #define DLOG_IF(info) LOG_IF(info)
 #define DCHECK(condition) CHECK(condition)
 #else
 #define DLOG(info) mozilla::EmptyLog()
 #define DLOG_IF(info, condition) mozilla::EmptyLog()
 #define DCHECK(condition) while (false && (condition)) mozilla::EmptyLog()
 #endif
 
 #define LOG_ASSERT(cond) CHECK(0)
 #define DLOG_ASSERT(cond) DCHECK(0)
 
-#define NOTREACHED() LOG(ERROR)
-#define NOTIMPLEMENTED() LOG(ERROR)
+#define NOTREACHED() CHROMIUM_LOG(ERROR)
+#define NOTIMPLEMENTED() CHROMIUM_LOG(ERROR)
 
 #define CHECK(condition) LOG_IF(FATAL, condition)
 
 #define DCHECK_EQ(v1, v2) DCHECK((v1) == (v2))
 #define DCHECK_NE(v1, v2) DCHECK((v1) != (v2))
 #define DCHECK_LE(v1, v2) DCHECK((v1) <= (v2))
 #define DCHECK_LT(v1, v2) DCHECK((v1) < (v2))
 #define DCHECK_GE(v1, v2) DCHECK((v1) >= (v2))
--- a/ipc/chromium/src/base/process_util_mac.mm
+++ b/ipc/chromium/src/base/process_util_mac.mm
@@ -207,46 +207,46 @@ NamedProcessIterator::NamedProcessIterat
   // we get the list, we do a loop to keep trying until we get it.
   bool done = false;
   int try_num = 1;
   const int max_tries = 10;
   do {
     // Get the size of the buffer
     size_t len = 0;
     if (sysctl(mib, arraysize(mib), NULL, &len, NULL, 0) < 0) {
-      LOG(ERROR) << "failed to get the size needed for the process list";
+      CHROMIUM_LOG(ERROR) << "failed to get the size needed for the process list";
       kinfo_procs_.resize(0);
       done = true;
     } else {
       size_t num_of_kinfo_proc = len / sizeof(struct kinfo_proc);
       // Leave some spare room for process table growth (more could show up
       // between when we check and now)
       num_of_kinfo_proc += 4;
       kinfo_procs_.resize(num_of_kinfo_proc);
       len = num_of_kinfo_proc * sizeof(struct kinfo_proc);
       // Load the list of processes
       if (sysctl(mib, arraysize(mib), &kinfo_procs_[0], &len, NULL, 0) < 0) {
         // If we get a mem error, it just means we need a bigger buffer, so
         // loop around again.  Anything else is a real error and give up.
         if (errno != ENOMEM) {
-          LOG(ERROR) << "failed to get the process list";
+          CHROMIUM_LOG(ERROR) << "failed to get the process list";
           kinfo_procs_.resize(0);
           done = true;
         }
       } else {
         // Got the list, just make sure we're sized exactly right
         size_t num_of_kinfo_proc = len / sizeof(struct kinfo_proc);
         kinfo_procs_.resize(num_of_kinfo_proc);
         done = true;
       }
     }
   } while (!done && (try_num++ < max_tries));
 
   if (!done) {
-    LOG(ERROR) << "failed to collect the process list in a few tries";
+    CHROMIUM_LOG(ERROR) << "failed to collect the process list in a few tries";
     kinfo_procs_.resize(0);
   }
 }
 
 NamedProcessIterator::~NamedProcessIterator() {
 }
 
 const ProcessEntry* NamedProcessIterator::NextProcessEntry() {
@@ -275,32 +275,32 @@ bool NamedProcessIterator::CheckForNextP
     if ((kinfo->kp_proc.p_pid > 0) && (kinfo->kp_proc.p_stat == SZOMB))
       continue;
 
     int mib[] = { CTL_KERN, KERN_PROCARGS, kinfo->kp_proc.p_pid };
 
     // Found out what size buffer we need
     size_t data_len = 0;
     if (sysctl(mib, arraysize(mib), NULL, &data_len, NULL, 0) < 0) {
-      LOG(ERROR) << "failed to figure out the buffer size for a commandline";
+      CHROMIUM_LOG(ERROR) << "failed to figure out the buffer size for a commandline";
       continue;
     }
 
     data.resize(data_len);
     if (sysctl(mib, arraysize(mib), &data[0], &data_len, NULL, 0) < 0) {
-      LOG(ERROR) << "failed to fetch a commandline";
+      CHROMIUM_LOG(ERROR) << "failed to fetch a commandline";
       continue;
     }
 
     // Data starts w/ the full path null termed, so we have to extract just the
     // executable name from the path.
 
     size_t exec_name_end = data.find('\0');
     if (exec_name_end == std::string::npos) {
-      LOG(ERROR) << "command line data didn't match expected format";
+      CHROMIUM_LOG(ERROR) << "command line data didn't match expected format";
       continue;
     }
     size_t last_slash = data.rfind('/', exec_name_end);
     if (last_slash == std::string::npos)
       exec_name = data.substr(0, exec_name_end);
     else
       exec_name = data.substr(last_slash + 1, exec_name_end - last_slash - 1);
 
--- a/ipc/chromium/src/base/process_util_posix.cc
+++ b/ipc/chromium/src/base/process_util_posix.cc
@@ -246,17 +246,17 @@ ProcessMetrics::~ProcessMetrics() { }
 
 bool DidProcessCrash(bool* child_exited, ProcessHandle handle) {
   int status;
   const int result = HANDLE_EINTR(waitpid(handle, &status, WNOHANG));
   if (result == -1) {
     // The dead process originally spawned from Nuwa might be taken as not
     // crashed because the above waitpid() call returns -1 and ECHILD. The
     // caller shouldn't behave incorrectly because of this false negative.
-    LOG(ERROR) << "waitpid failed pid:" << handle << " errno:" << errno;
+    CHROMIUM_LOG(ERROR) << "waitpid failed pid:" << handle << " errno:" << errno;
     if (child_exited)
       *child_exited = false;
     return false;
   } else if (result == 0) {
     // the child hasn't exited yet.
     if (child_exited)
       *child_exited = false;
     return false;
--- a/ipc/chromium/src/base/scoped_temp_dir.cc
+++ b/ipc/chromium/src/base/scoped_temp_dir.cc
@@ -8,17 +8,17 @@
 #include "base/logging.h"
 #include "base/string_util.h"
 
 ScopedTempDir::ScopedTempDir() {
 }
 
 ScopedTempDir::~ScopedTempDir() {
   if (!path_.empty() && !file_util::Delete(path_, true))
-    LOG(ERROR) << "ScopedTempDir unable to delete " << path_.value();
+    CHROMIUM_LOG(ERROR) << "ScopedTempDir unable to delete " << path_.value();
 }
 
 bool ScopedTempDir::CreateUniqueTempDir() {
   // This "scoped_dir" prefix is only used on Windows and serves as a template
   // for the unique name.
   if (!file_util::CreateNewTempDirectory(FILE_PATH_LITERAL("scoped_dir"),
                                          &path_))
     return false;
--- a/ipc/chromium/src/base/stats_table.cc
+++ b/ipc/chromium/src/base/stats_table.cc
@@ -255,20 +255,20 @@ StatsTable::StatsTable(const std::string
     AlignedSize(max_threads * sizeof(int)) +
     AlignedSize((sizeof(int) * (max_counters * max_threads)));
 
   impl_ = StatsTablePrivate::New(name, table_size, max_threads, max_counters);
 
   // TODO(port): clean up this error reporting.
 #if defined(OS_WIN)
   if (!impl_)
-    LOG(ERROR) << "StatsTable did not initialize:" << GetLastError();
+    CHROMIUM_LOG(ERROR) << "StatsTable did not initialize:" << GetLastError();
 #elif defined(OS_POSIX)
   if (!impl_)
-    LOG(ERROR) << "StatsTable did not initialize:" << strerror(errno);
+    CHROMIUM_LOG(ERROR) << "StatsTable did not initialize:" << strerror(errno);
 #endif
 }
 
 StatsTable::~StatsTable() {
   // Before we tear down our copy of the table, be sure to
   // unregister our thread.
   UnregisterThread();
 
--- a/ipc/chromium/src/base/system_monitor.cc
+++ b/ipc/chromium/src/base/system_monitor.cc
@@ -52,28 +52,28 @@ void SystemMonitor::AddObserver(PowerObs
   observer_list_->AddObserver(obs);
 }
 
 void SystemMonitor::RemoveObserver(PowerObserver* obs) {
   observer_list_->RemoveObserver(obs);
 }
 
 void SystemMonitor::NotifyPowerStateChange() {
-  LOG(INFO) << "PowerStateChange: "
-           << (BatteryPower() ? "On" : "Off") << " battery";
+  CHROMIUM_LOG(INFO) << "PowerStateChange: "
+                     << (BatteryPower() ? "On" : "Off") << " battery";
   observer_list_->Notify(&PowerObserver::OnPowerStateChange, this);
 }
 
 void SystemMonitor::NotifySuspend() {
-  LOG(INFO) << "Power Suspending";
+  CHROMIUM_LOG(INFO) << "Power Suspending";
   observer_list_->Notify(&PowerObserver::OnSuspend, this);
 }
 
 void SystemMonitor::NotifyResume() {
-  LOG(INFO) << "Power Resuming";
+  CHROMIUM_LOG(INFO) << "Power Resuming";
   observer_list_->Notify(&PowerObserver::OnResume, this);
 }
 
 void SystemMonitor::Start() {
 #if defined(ENABLE_BATTERY_MONITORING)
   DCHECK(MessageLoop::current());  // Can't call start too early.
   SystemMonitor* monitor = Get();
   monitor->delayed_battery_check_.Start(
--- a/ipc/chromium/src/base/system_monitor_win.cc
+++ b/ipc/chromium/src/base/system_monitor_win.cc
@@ -33,17 +33,17 @@ void SystemMonitor::ProcessWmPowerBroadc
   ProcessPowerMessage(power_event);
 }
 
 // Function to query the system to see if it is currently running on
 // battery power.  Returns true if running on battery.
 bool SystemMonitor::IsBatteryPower() {
   SYSTEM_POWER_STATUS status;
   if (!GetSystemPowerStatus(&status)) {
-    LOG(ERROR) << "GetSystemPowerStatus failed: " << GetLastError();
+    CHROMIUM_LOG(ERROR) << "GetSystemPowerStatus failed: " << GetLastError();
     return false;
   }
   return (status.ACLineStatus == 0);
 }
 
 
 
 } // namespace base
--- a/ipc/chromium/src/chrome/common/chrome_switches.cc
+++ b/ipc/chromium/src/chrome/common/chrome_switches.cc
@@ -170,17 +170,17 @@ const wchar_t kEnableLogging[]          
 // Force logging to be disabled.  Logging is enabled by default in debug
 // builds.
 const wchar_t kDisableLogging[]                = L"disable-logging";
 
 // Sets the minimum log level. Valid values are from 0 to 3:
 // INFO = 0, WARNING = 1, LOG_ERROR = 2, LOG_FATAL = 3.
 const wchar_t kLoggingLevel[]                  = L"log-level";
 
-// Make plugin processes log their sent and received messages to LOG(INFO).
+// Make plugin processes log their sent and received messages to CHROMIUM_LOG(INFO).
 const wchar_t kLogPluginMessages[]             = L"log-plugin-messages";
 
 // Dump any accumualted histograms to the log when browser terminates (requires
 // logging to be enabled to really do anything).  Used by developers and test
 // scripts.
 const wchar_t kDumpHistogramsOnExit[]          = L"dump-histograms-on-exit";
 
 // enable remote debug / automation shell on the specified port
--- a/ipc/chromium/src/chrome/common/file_descriptor_set_posix.cc
+++ b/ipc/chromium/src/chrome/common/file_descriptor_set_posix.cc
@@ -12,17 +12,17 @@
 FileDescriptorSet::FileDescriptorSet()
     : consumed_descriptor_highwater_(0) {
 }
 
 FileDescriptorSet::~FileDescriptorSet() {
   if (consumed_descriptor_highwater_ == descriptors_.size())
     return;
 
-  LOG(WARNING) << "FileDescriptorSet destroyed with unconsumed descriptors";
+  CHROMIUM_LOG(WARNING) << "FileDescriptorSet destroyed with unconsumed descriptors";
   // We close all the descriptors where the close flag is set. If this
   // message should have been transmitted, then closing those with close
   // flags set mirrors the expected behaviour.
   //
   // If this message was received with more descriptors than expected
   // (which could a DOS against the browser by a rogue renderer) then all
   // the descriptors have their close flag set and we free all the extra
   // kernel resources.
--- a/ipc/chromium/src/chrome/common/ipc_channel_posix.cc
+++ b/ipc/chromium/src/chrome/common/ipc_channel_posix.cc
@@ -205,23 +205,23 @@ bool ServerAcceptFifoConnection(int serv
 
 bool ClientConnectToFifo(const std::string &pipe_name, int* client_socket) {
   DCHECK(client_socket);
   DCHECK_LT(pipe_name.length(), kMaxPipeNameLength);
 
   // Create socket.
   int fd = socket(AF_UNIX, SOCK_STREAM, 0);
   if (fd < 0) {
-    LOG(ERROR) << "fd is invalid";
+    CHROMIUM_LOG(ERROR) << "fd is invalid";
     return false;
   }
 
   // Make socket non-blocking
   if (fcntl(fd, F_SETFL, O_NONBLOCK) == -1) {
-    LOG(ERROR) << "fcntl failed";
+    CHROMIUM_LOG(ERROR) << "fcntl failed";
     HANDLE_EINTR(close(fd));
     return false;
   }
 
   // Create server side of socket.
   struct sockaddr_un  server_unix_addr;
   memset(&server_unix_addr, 0, sizeof(server_unix_addr));
   server_unix_addr.sun_family = AF_UNIX;
@@ -258,19 +258,19 @@ bool SetCloseOnExec(int fd) {
 Channel::ChannelImpl::ChannelImpl(const std::wstring& channel_id, Mode mode,
                                   Listener* listener)
     : factory_(this) {
   Init(mode, listener);
   uses_fifo_ = CommandLine::ForCurrentProcess()->HasSwitch(switches::kIPCUseFIFO);
 
   if (!CreatePipe(channel_id, mode)) {
     // The pipe may have been closed already.
-    LOG(WARNING) << "Unable to create pipe named \"" << channel_id <<
-                    "\" in " << (mode == MODE_SERVER ? "server" : "client") <<
-                    " mode error(" << strerror(errno) << ").";
+    CHROMIUM_LOG(WARNING) << "Unable to create pipe named \"" << channel_id <<
+                             "\" in " << (mode == MODE_SERVER ? "server" : "client") <<
+                             " mode error(" << strerror(errno) << ").";
   }
 }
 
 Channel::ChannelImpl::ChannelImpl(int fd, Mode mode, Listener* listener)
     : factory_(this) {
   Init(mode, listener);
   pipe_ = fd;
   waiting_connect_ = (MODE_SERVER == mode);
@@ -438,17 +438,17 @@ bool Channel::ChannelImpl::ProcessIncomi
       // recvmsg() returns 0 if the connection has closed or EAGAIN if no data
       // is waiting on the pipe.
       bytes_read = HANDLE_EINTR(recvmsg(pipe_, &msg, MSG_DONTWAIT));
 
       if (bytes_read < 0) {
         if (errno == EAGAIN) {
           return true;
         } else {
-          LOG(ERROR) << "pipe error (" << pipe_ << "): " << strerror(errno);
+          CHROMIUM_LOG(ERROR) << "pipe error (" << pipe_ << "): " << strerror(errno);
           return false;
         }
       } else if (bytes_read == 0) {
         // The pipe has closed...
         Close();
         return false;
       }
     }
@@ -486,19 +486,19 @@ bool Channel::ChannelImpl::ProcessIncomi
         if (cmsg->cmsg_level == SOL_SOCKET &&
             cmsg->cmsg_type == SCM_RIGHTS) {
           const unsigned payload_len = cmsg->cmsg_len - CMSG_LEN(0);
           DCHECK(payload_len % sizeof(int) == 0);
           wire_fds = reinterpret_cast<int*>(CMSG_DATA(cmsg));
           num_wire_fds = payload_len / 4;
 
           if (msg.msg_flags & MSG_CTRUNC) {
-            LOG(ERROR) << "SCM_RIGHTS message was truncated"
-                       << " cmsg_len:" << cmsg->cmsg_len
-                       << " fd:" << pipe_;
+            CHROMIUM_LOG(ERROR) << "SCM_RIGHTS message was truncated"
+                                << " cmsg_len:" << cmsg->cmsg_len
+                                << " fd:" << pipe_;
             for (unsigned i = 0; i < num_wire_fds; ++i)
               HANDLE_EINTR(close(wire_fds[i]));
             return false;
           }
           break;
         }
       }
     }
@@ -510,17 +510,17 @@ bool Channel::ChannelImpl::ProcessIncomi
     if (input_overflow_buf_.empty()) {
       overflowp = NULL;
       p = input_buf_;
       end = p + bytes_read;
     } else {
       if (input_overflow_buf_.size() >
          static_cast<size_t>(kMaximumMessageSize - bytes_read)) {
         ClearAndShrink(input_overflow_buf_, Channel::kReadBufferSize);
-        LOG(ERROR) << "IPC message is too big";
+        CHROMIUM_LOG(ERROR) << "IPC message is too big";
         return false;
       }
       input_overflow_buf_.append(input_buf_, bytes_read);
       overflowp = p = input_overflow_buf_.data();
       end = p + input_overflow_buf_.size();
     }
 
     // A pointer to an array of |num_fds| file descriptors which includes any
@@ -557,22 +557,22 @@ bool Channel::ChannelImpl::ProcessIncomi
 
           if (m.header()->num_fds >
               FileDescriptorSet::MAX_DESCRIPTORS_PER_MESSAGE) {
             // There are too many descriptors in this message
             error = "Message requires an excessive number of descriptors";
           }
 
           if (error) {
-            LOG(WARNING) << error
-                         << " channel:" << this
-                         << " message-type:" << m.type()
-                         << " header()->num_fds:" << m.header()->num_fds
-                         << " num_fds:" << num_fds
-                         << " fds_i:" << fds_i;
+            CHROMIUM_LOG(WARNING) << error
+                                  << " channel:" << this
+                                  << " message-type:" << m.type()
+                                  << " header()->num_fds:" << m.header()->num_fds
+                                  << " num_fds:" << num_fds
+                                  << " fds_i:" << fds_i;
             // close the existing file descriptors so that we don't leak them
             for (unsigned i = fds_i; i < num_fds; ++i)
               HANDLE_EINTR(close(fds[i]));
             input_overflow_fds_.clear();
             // abort the connection
             return false;
           }
 
@@ -663,17 +663,17 @@ bool Channel::ChannelImpl::ProcessOutgoi
 
     if (message_send_bytes_written_ == 0 &&
         !msg->file_descriptor_set()->empty()) {
       // This is the first chunk of a message which has descriptors to send
       struct cmsghdr *cmsg;
       const unsigned num_fds = msg->file_descriptor_set()->size();
 
       if (num_fds > FileDescriptorSet::MAX_DESCRIPTORS_PER_MESSAGE) {
-        LOG(FATAL) << "Too many file descriptors!";
+        CHROMIUM_LOG(FATAL) << "Too many file descriptors!";
         // This should not be reached.
         return false;
       }
 
       msgh.msg_control = buf;
       msgh.msg_controllen = CMSG_SPACE(sizeof(int) * num_fds);
       cmsg = CMSG_FIRSTHDR(&msgh);
       cmsg->cmsg_level = SOL_SOCKET;
@@ -702,17 +702,17 @@ bool Channel::ChannelImpl::ProcessOutgoi
 #if !defined(OS_MACOSX)
     // On OSX CommitAll gets called later, once we get the RECEIVED_FDS_MESSAGE_TYPE
     // message.
     if (bytes_written > 0)
       msg->file_descriptor_set()->CommitAll();
 #endif
 
     if (bytes_written < 0 && errno != EAGAIN) {
-      LOG(ERROR) << "pipe error: " << strerror(errno);
+      CHROMIUM_LOG(ERROR) << "pipe error: " << strerror(errno);
       return false;
     }
 
     if (static_cast<size_t>(bytes_written) != amt_to_write) {
       if (bytes_written > 0) {
         // If write() fails with EAGAIN then bytes_written will be -1.
         message_send_bytes_written_ += bytes_written;
       }
--- a/ipc/chromium/src/chrome/common/ipc_channel_win.cc
+++ b/ipc/chromium/src/chrome/common/ipc_channel_win.cc
@@ -36,18 +36,18 @@ Channel::ChannelImpl::ChannelImpl(const 
                               Listener* listener)
     : ALLOW_THIS_IN_INITIALIZER_LIST(input_state_(this)),
       ALLOW_THIS_IN_INITIALIZER_LIST(output_state_(this)),
       ALLOW_THIS_IN_INITIALIZER_LIST(factory_(this)) {
   Init(mode, listener);
 
   if (!CreatePipe(channel_id, mode)) {
     // The pipe may have been closed already.
-    LOG(WARNING) << "Unable to create pipe named \"" << channel_id <<
-                    "\" in " << (mode == 0 ? "server" : "client") << " mode.";
+    CHROMIUM_LOG(WARNING) << "Unable to create pipe named \"" << channel_id <<
+                             "\" in " << (mode == 0 ? "server" : "client") << " mode.";
   }
 }
 
 Channel::ChannelImpl::ChannelImpl(const std::wstring& channel_id,
                                   HANDLE server_pipe,
                                   Mode mode, Listener* listener)
     : ALLOW_THIS_IN_INITIALIZER_LIST(input_state_(this)),
       ALLOW_THIS_IN_INITIALIZER_LIST(output_state_(this)),
@@ -190,17 +190,17 @@ bool Channel::ChannelImpl::CreatePipe(co
                         NULL,
                         OPEN_EXISTING,
                         SECURITY_SQOS_PRESENT | SECURITY_IDENTIFICATION |
                             FILE_FLAG_OVERLAPPED,
                         NULL);
   }
   if (pipe_ == INVALID_HANDLE_VALUE) {
     // If this process is being closed, the pipe may be gone already.
-    LOG(WARNING) << "failed to create pipe: " << GetLastError();
+    CHROMIUM_LOG(WARNING) << "failed to create pipe: " << GetLastError();
     return false;
   }
 
   // Create the Hello message to be sent when Connect is called
   return EnqueueHelloMessage();
 }
 
 bool Channel::ChannelImpl::EnqueueHelloMessage() {
@@ -304,34 +304,34 @@ bool Channel::ChannelImpl::ProcessIncomi
                          &bytes_read,
                          &input_state_.context.overlapped);
       if (!ok) {
         DWORD err = GetLastError();
         if (err == ERROR_IO_PENDING) {
           input_state_.is_pending = true;
           return true;
         }
-        LOG(ERROR) << "pipe error: " << err;
+        CHROMIUM_LOG(ERROR) << "pipe error: " << err;
         return false;
       }
       input_state_.is_pending = true;
       return true;
     }
     DCHECK(bytes_read);
 
     // Process messages from input buffer.
 
     const char* p, *end;
     if (input_overflow_buf_.empty()) {
       p = input_buf_;
       end = p + bytes_read;
     } else {
       if (input_overflow_buf_.size() > (kMaximumMessageSize - bytes_read)) {
         input_overflow_buf_.clear();
-        LOG(ERROR) << "IPC message is too big";
+        CHROMIUM_LOG(ERROR) << "IPC message is too big";
         return false;
       }
       input_overflow_buf_.append(input_buf_, bytes_read);
       p = input_overflow_buf_.data();
       end = p + input_overflow_buf_.size();
     }
 
     while (p < end) {
@@ -371,17 +371,17 @@ bool Channel::ChannelImpl::ProcessOutgoi
                               // no connection?
   DCHECK(thread_check_->CalledOnValidThread());
 
   if (output_state_.is_pending) {
     DCHECK(context);
     output_state_.is_pending = false;
     if (!context || bytes_written == 0) {
       DWORD err = GetLastError();
-      LOG(ERROR) << "pipe error: " << err;
+      CHROMIUM_LOG(ERROR) << "pipe error: " << err;
       return false;
     }
     // Message was sent.
     DCHECK(!output_queue_.empty());
     Message* m = output_queue_.front();
     OutputQueuePop();
     delete m;
   }
@@ -406,17 +406,17 @@ bool Channel::ChannelImpl::ProcessOutgoi
 
 #ifdef IPC_MESSAGE_DEBUG_EXTRA
       DLOG(INFO) << "sent pending message @" << m << " on channel @" <<
                     this << " with type " << m->type();
 #endif
 
       return true;
     }
-    LOG(ERROR) << "pipe error: " << err;
+    CHROMIUM_LOG(ERROR) << "pipe error: " << err;
     return false;
   }
 
 #ifdef IPC_MESSAGE_DEBUG_EXTRA
   DLOG(INFO) << "sent message @" << m << " on channel @" << this <<
                 " with type " << m->type();
 #endif
 
--- a/ipc/chromium/src/chrome/common/mach_message_source_mac.cc
+++ b/ipc/chromium/src/chrome/common/mach_message_source_mac.cc
@@ -19,29 +19,29 @@ MachMessageSource::MachMessageSource(mac
   scoped_cftyperef<CFMachPortRef> cf_mach_port_ref(
      CFMachPortCreateWithPort(kCFAllocatorDefault,
                               port,
                               MachMessageSource::OnReceiveMachMessage,
                               &port_context,
                               NULL));
 
   if (cf_mach_port_ref.get() == NULL) {
-   LOG(WARNING) << "CFMachPortCreate failed";
+   CHROMIUM_LOG(WARNING) << "CFMachPortCreate failed";
    *success = false;
    return;
   }
 
   // Create a RL source.
   machport_runloop_ref_.reset(
      CFMachPortCreateRunLoopSource(kCFAllocatorDefault,
                                    cf_mach_port_ref.get(),
                                    0));
 
   if (machport_runloop_ref_.get() == NULL) {
-   LOG(WARNING) << "CFMachPortCreateRunLoopSource failed";
+   CHROMIUM_LOG(WARNING) << "CFMachPortCreateRunLoopSource failed";
    *success = false;
    return;
   }
 
   CFRunLoopAddSource(CFRunLoopGetCurrent(),
                     machport_runloop_ref_.get(),
                     kCFRunLoopCommonModes);
   *success = true;
--- a/ipc/chromium/src/chrome/common/notification_service.cc
+++ b/ipc/chromium/src/chrome/common/notification_service.cc
@@ -120,18 +120,18 @@ NotificationService::~NotificationServic
   lazy_tls_ptr.Pointer()->Set(NULL);
 
 #ifndef NDEBUG
   for (int i = 0; i < NotificationType::NOTIFICATION_TYPE_COUNT; i++) {
     if (observer_counts_[i] > 0) {
       // This may not be completely fixable -- see
       // http://code.google.com/p/chromium/issues/detail?id=11010 .
       // But any new leaks should be fixed.
-      LOG(WARNING) << observer_counts_[i] << " notification observer(s) leaked"
-          << " of notification type " << i;
+      CHROMIUM_LOG(WARNING) << observer_counts_[i] << " notification observer(s) leaked"
+                            << " of notification type " << i;
     }
   }
 #endif
 
   for (int i = 0; i < NotificationType::NOTIFICATION_TYPE_COUNT; i++) {
     NotificationSourceMap omap = observers_[i];
     for (NotificationSourceMap::iterator it = omap.begin();
          it != omap.end(); ++it) {
--- a/ipc/chromium/src/chrome/common/process_watcher_posix_sigchld.cc
+++ b/ipc/chromium/src/chrome/common/process_watcher_posix_sigchld.cc
@@ -110,18 +110,18 @@ private:
 
     if (0 == kill(process_, SIGKILL)) {
       // XXX this will block for whatever amount of time it takes the
       // XXX OS to tear down the process's resources.  might need to
       // XXX rethink this if it proves expensive
       WaitForChildExit();
     }
     else {
-      LOG(ERROR) << "Failed to deliver SIGKILL to " << process_ << "!"
-                 << "("<< errno << ").";
+      CHROMIUM_LOG(ERROR) << "Failed to deliver SIGKILL to " << process_ << "!"
+                          << "("<< errno << ").";
     }
     process_ = 0;
   }
 
   DISALLOW_EVIL_CONSTRUCTORS(ChildGrimReaper);
 };
 
 
--- a/ipc/chromium/src/chrome/common/transport_dib_win.cc
+++ b/ipc/chromium/src/chrome/common/transport_dib_win.cc
@@ -38,19 +38,19 @@ TransportDIB* TransportDIB::Create(size_
 
   return dib;
 }
 
 // static
 TransportDIB* TransportDIB::Map(TransportDIB::Handle handle) {
   TransportDIB* dib = new TransportDIB(handle);
   if (!dib->shared_memory_.Map(0 /* map whole shared memory segment */)) {
-    LOG(ERROR) << "Failed to map transport DIB"
-               << " handle:" << handle
-               << " error:" << GetLastError();
+    CHROMIUM_LOG(ERROR) << "Failed to map transport DIB"
+                        << " handle:" << handle
+                        << " error:" << GetLastError();
     delete dib;
     return NULL;
   }
 
   // There doesn't seem to be any way to find the size of the shared memory
   // region! GetFileSize indicates that the handle is invalid. Thus, we
   // conservatively set the size to the maximum and hope that the renderer
   // isn't about to ask us to read off the end of the array.
--- a/ipc/dbus/DBusThread.cpp
+++ b/ipc/dbus/DBusThread.cpp
@@ -52,23 +52,23 @@
 #include "mozilla/Monitor.h"
 #include "mozilla/FileUtils.h"
 #include "nsThreadUtils.h"
 #include "nsIThread.h"
 #include "nsXULAppAPI.h"
 #include "nsServiceManagerUtils.h"
 #include "nsCOMPtr.h"
 
-#undef LOG
+#undef CHROMIUM_LOG
 #if defined(MOZ_WIDGET_GONK)
 #include <android/log.h>
-#define LOG(args...)  __android_log_print(ANDROID_LOG_INFO, "GonkDBus", args);
+#define CHROMIUM_LOG(args...)  __android_log_print(ANDROID_LOG_INFO, "GonkDBus", args);
 #else
 #define BTDEBUG true
-#define LOG(args...) if (BTDEBUG) printf(args);
+#define CHROMIUM_LOG(args...) if (BTDEBUG) printf(args);
 #endif
 
 namespace mozilla {
 namespace ipc {
 
 class DBusWatcher : public MessageLoopForIO::Watcher
 {
 public:
--- a/ipc/dbus/DBusUtils.cpp
+++ b/ipc/dbus/DBusUtils.cpp
@@ -15,22 +15,22 @@
 ** See the License for the specific language governing permissions and
 ** limitations under the License.
 */
 
 #include <dbus/dbus.h>
 #include "nsAutoPtr.h"
 #include "DBusUtils.h"
 
-#undef LOG
+#undef CHROMIUM_LOG
 #if defined(MOZ_WIDGET_GONK)
 #include <android/log.h>
-#define LOG(args...)  __android_log_print(ANDROID_LOG_INFO, "Gonk", args);
+#define CHROMIUM_LOG(args...)  __android_log_print(ANDROID_LOG_INFO, "Gonk", args);
 #else
-#define LOG(args...)  printf(args);
+#define CHROMIUM_LOG(args...)  printf(args);
 #endif
 
 namespace mozilla {
 namespace ipc {
 
 //
 // DBusMessageRefPtr
 //
@@ -67,21 +67,21 @@ void DBusReplyHandler::Callback(DBusMess
 //
 // Utility functions
 //
 
 void
 log_and_free_dbus_error(DBusError* err, const char* function, DBusMessage* msg)
 {
   if (msg) {
-    LOG("%s: D-Bus error in %s: %s (%s)", function,
-        dbus_message_get_member((msg)), (err)->name, (err)->message);
+    CHROMIUM_LOG("%s: D-Bus error in %s: %s (%s)", function,
+                 dbus_message_get_member((msg)), (err)->name, (err)->message);
   }	else {
-    LOG("%s: D-Bus error: %s (%s)", __FUNCTION__,
-        (err)->name, (err)->message);
+    CHROMIUM_LOG("%s: D-Bus error: %s (%s)", __FUNCTION__,
+                 (err)->name, (err)->message);
   }
   dbus_error_free((err));
 }
 
 int dbus_returns_int32(DBusMessage *reply)
 {
   DBusError err;
   int32_t ret = -1;
--- a/ipc/dbus/RawDBusConnection.cpp
+++ b/ipc/dbus/RawDBusConnection.cpp
@@ -7,25 +7,25 @@
 #include <dbus/dbus.h>
 #include "base/message_loop.h"
 #include "mozilla/Monitor.h"
 #include "nsThreadUtils.h"
 #include "DBusThread.h"
 #include "DBusUtils.h"
 #include "RawDBusConnection.h"
 
-#ifdef LOG
-#undef LOG
+#ifdef CHROMIUM_LOG
+#undef CHROMIUM_LOG
 #endif
 
 #if defined(MOZ_WIDGET_GONK)
 #include <android/log.h>
-#define LOG(args...)  __android_log_print(ANDROID_LOG_INFO, "Gonk", args);
+#define CHROMIUM_LOG(args...)  __android_log_print(ANDROID_LOG_INFO, "Gonk", args);
 #else
-#define LOG(args...)  printf(args);
+#define CHROMIUM_LOG(args...)  printf(args);
 #endif
 
 /* TODO: Remove BlueZ constant */
 #define BLUEZ_DBUS_BASE_IFC "org.bluez"
 
 using namespace mozilla::ipc;
 
 //
@@ -283,21 +283,21 @@ DBusMessage* RawDBusConnection::BuildDBu
                                                  const char* aIntf,
                                                  const char* aFunc,
                                                  int aFirstArgType,
                                                  va_list aArgs)
 {
   DBusMessage* msg = dbus_message_new_method_call(BLUEZ_DBUS_BASE_IFC,
                                                   aPath, aIntf, aFunc);
   if (!msg) {
-    LOG("Could not allocate D-Bus message object!");
+    CHROMIUM_LOG("Could not allocate D-Bus message object!");
     return nullptr;
   }
 
   /* append arguments */
   if (!dbus_message_append_args_valist(msg, aFirstArgType, aArgs)) {
-    LOG("Could not append argument to method call!");
+    CHROMIUM_LOG("Could not append argument to method call!");
     dbus_message_unref(msg);
     return nullptr;
   }
 
   return msg;
 }
--- a/ipc/glue/GeckoChildProcessHost.cpp
+++ b/ipc/glue/GeckoChildProcessHost.cpp
@@ -674,42 +674,42 @@ GeckoChildProcessHost::PerformAsyncLaunc
   // Wait for the child process to send us its 'task_t' data.
   const int kTimeoutMs = 10000;
 
   MachReceiveMessage child_message;
   ReceivePort parent_recv_port(mach_connection_name.c_str());
   kern_return_t err = parent_recv_port.WaitForMessage(&child_message, kTimeoutMs);
   if (err != KERN_SUCCESS) {
     std::string errString = StringPrintf("0x%x %s", err, mach_error_string(err));
-    LOG(ERROR) << "parent WaitForMessage() failed: " << errString;
+    CHROMIUM_LOG(ERROR) << "parent WaitForMessage() failed: " << errString;
     return false;
   }
 
   task_t child_task = child_message.GetTranslatedPort(0);
   if (child_task == MACH_PORT_NULL) {
-    LOG(ERROR) << "parent GetTranslatedPort(0) failed.";
+    CHROMIUM_LOG(ERROR) << "parent GetTranslatedPort(0) failed.";
     return false;
   }
 
   if (child_message.GetTranslatedPort(1) == MACH_PORT_NULL) {
-    LOG(ERROR) << "parent GetTranslatedPort(1) failed.";
+    CHROMIUM_LOG(ERROR) << "parent GetTranslatedPort(1) failed.";
     return false;
   }
   MachPortSender parent_sender(child_message.GetTranslatedPort(1));
 
   MachSendMessage parent_message(/* id= */0);
   if (!parent_message.AddDescriptor(bootstrap_port)) {
-    LOG(ERROR) << "parent AddDescriptor(" << bootstrap_port << ") failed.";
+    CHROMIUM_LOG(ERROR) << "parent AddDescriptor(" << bootstrap_port << ") failed.";
     return false;
   }
 
   err = parent_sender.SendMessage(parent_message, kTimeoutMs);
   if (err != KERN_SUCCESS) {
     std::string errString = StringPrintf("0x%x %s", err, mach_error_string(err));
-    LOG(ERROR) << "parent SendMessage() failed: " << errString;
+    CHROMIUM_LOG(ERROR) << "parent SendMessage() failed: " << errString;
     return false;
   }
 #endif
 
 //--------------------------------------------------
 #elif defined(OS_WIN)
 
   FilePath exePath;
--- a/ipc/keystore/KeyStore.cpp
+++ b/ipc/keystore/KeyStore.cpp
@@ -2,22 +2,22 @@
 /* vim: set sw=4 ts=8 et ft=cpp: */
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #include <fcntl.h>
 #include <sys/stat.h>
 
-#undef LOG
+#undef CHROMIUM_LOG
 #if defined(MOZ_WIDGET_GONK)
 #include <android/log.h>
-#define LOG(args...)  __android_log_print(ANDROID_LOG_INFO, "Gonk", args)
+#define CHROMIUM_LOG(args...)  __android_log_print(ANDROID_LOG_INFO, "Gonk", args)
 #else
-#define LOG(args...)  printf(args);
+#define CHROMIUM_LOG(args...)  printf(args);
 #endif
 
 #include "KeyStore.h"
 #include "jsfriendapi.h"
 #include "MainThreadUtils.h" // For NS_IsMainThread.
 
 #include "plbase64.h"
 #include "certdb.h"
--- a/ipc/netd/Netd.cpp
+++ b/ipc/netd/Netd.cpp
@@ -13,17 +13,17 @@
 
 #include "nsWhitespaceTokenizer.h"
 #include "nsXULAppAPI.h"
 #include "nsAutoPtr.h"
 #include "nsString.h"
 #include "nsThreadUtils.h"
 
 
-#define LOG(args...)  __android_log_print(ANDROID_LOG_INFO, "Gonk", args)
+#define CHROMIUM_LOG(args...)  __android_log_print(ANDROID_LOG_INFO, "Gonk", args)
 #define ICS_SYS_USB_RNDIS_MAC "/sys/class/android_usb/android0/f_rndis/ethaddr"
 #define INVALID_SOCKET -1
 #define MAX_RECONNECT_TIMES 10
 
 namespace {
 
 mozilla::RefPtr<mozilla::ipc::NetdClient> gNetdClient;
 mozilla::RefPtr<mozilla::ipc::NetdConsumer> gNetdConsumer;
@@ -48,17 +48,17 @@ InitRndisAddress()
   char address[kEthernetAddressLength];
   int i = 0;
   int ret = 0;
   int length = 0;
   mozilla::ScopedClose fd;
 
   fd.rwget() = open(ICS_SYS_USB_RNDIS_MAC, O_WRONLY);
   if (fd.rwget() == -1) {
-    LOG("Unable to open file %s.", ICS_SYS_USB_RNDIS_MAC);
+    CHROMIUM_LOG("Unable to open file %s.", ICS_SYS_USB_RNDIS_MAC);
     return false;
   }
 
   property_get("ro.serialno", serialno, "1234567890ABCDEF");
 
   memset(address, 0, sizeof(address));
   // First byte is 0x02 to signify a locally administered address.
   address[0] = 0x02;
@@ -68,17 +68,17 @@ InitRndisAddress()
   }
 
   sprintf(mac, "%02x:%02x:%02x:%02x:%02x:%02x",
           address[0], address[1], address[2],
           address[3], address[4], address[5]);
   length = strlen(mac);
   ret = write(fd.get(), mac, length);
   if (ret != length) {
-    LOG("Fail to write file %s.", ICS_SYS_USB_RNDIS_MAC);
+    CHROMIUM_LOG("Fail to write file %s.", ICS_SYS_USB_RNDIS_MAC);
     return false;
   }
   return true;
 }
 
 } // anonymous namespace
 
 namespace mozilla {
@@ -101,55 +101,55 @@ NetdClient::~NetdClient()
 
 bool
 NetdClient::OpenSocket()
 {
   mSocket.rwget() = socket_local_client("netd",
                                         ANDROID_SOCKET_NAMESPACE_RESERVED,
                                         SOCK_STREAM);
   if (mSocket.rwget() < 0) {
-    LOG("Error connecting to : netd (%s) - will retry", strerror(errno));
+    CHROMIUM_LOG("Error connecting to : netd (%s) - will retry", strerror(errno));
     return false;
   }
   // Add FD_CLOEXEC flag.
   int flags = fcntl(mSocket.get(), F_GETFD);
   if (flags == -1) {
-    LOG("Error doing fcntl with F_GETFD command(%s)", strerror(errno));
+    CHROMIUM_LOG("Error doing fcntl with F_GETFD command(%s)", strerror(errno));
     return false;
   }
   flags |= FD_CLOEXEC;
   if (fcntl(mSocket.get(), F_SETFD, flags) == -1) {
-    LOG("Error doing fcntl with F_SETFD command(%s)", strerror(errno));
+    CHROMIUM_LOG("Error doing fcntl with F_SETFD command(%s)", strerror(errno));
     return false;
   }
   // Set non-blocking.
   if (fcntl(mSocket.get(), F_SETFL, O_NONBLOCK) == -1) {
-    LOG("Error set non-blocking socket(%s)", strerror(errno));
+    CHROMIUM_LOG("Error set non-blocking socket(%s)", strerror(errno));
     return false;
   }
   if (!MessageLoopForIO::current()->
       WatchFileDescriptor(mSocket.get(),
                           true,
                           MessageLoopForIO::WATCH_READ,
                           &mReadWatcher,
                           this)) {
-    LOG("Error set socket read watcher(%s)", strerror(errno));
+    CHROMIUM_LOG("Error set socket read watcher(%s)", strerror(errno));
     return false;
   }
 
   if (!mOutgoingQ.empty()) {
     MessageLoopForIO::current()->
       WatchFileDescriptor(mSocket.get(),
                           false,
                           MessageLoopForIO::WATCH_WRITE,
                           &mWriteWatcher,
                           this);
   }
 
-  LOG("Connected to netd");
+  CHROMIUM_LOG("Connected to netd");
   return true;
 }
 
 void NetdClient::OnLineRead(int aFd, nsDependentCSubstring& aMessage)
 {
   // Set errno to 0 first. For preventing to use the stale version of errno.
   errno = 0;
   // We found a line terminator. Each line is formatted as an
@@ -160,17 +160,17 @@ void NetdClient::OnLineRead(int aFd, nsD
     NetdCommand* response = new NetdCommand();
     // Passing all the response message, including the line terminator.
     response->mSize = aMessage.Length();
     memcpy(response->mData, aMessage.Data(), aMessage.Length());
     gNetdConsumer->MessageReceived(response);
   }
 
   if (!responseCode) {
-    LOG("Can't parse netd's response");
+    CHROMIUM_LOG("Can't parse netd's response");
   }
 }
 
 void
 NetdClient::OnFileCanWriteWithoutBlocking(int aFd)
 {
   MOZ_ASSERT(aFd == mSocket.get());
   WriteNetdCommand();
@@ -196,25 +196,25 @@ NetdClient::OnError()
 
 // static
 void
 NetdClient::Start()
 {
   MOZ_ASSERT(MessageLoop::current() == XRE_GetIOMessageLoop());
 
   if (!gNetdClient) {
-    LOG("Netd Client is not initialized");
+    CHROMIUM_LOG("Netd Client is not initialized");
     return;
   }
 
   if (!gNetdClient->OpenSocket()) {
     // Socket open failed, try again in a second.
-    LOG("Fail to connect to Netd");
+    CHROMIUM_LOG("Fail to connect to Netd");
     if (++gNetdClient->mReConnectTimes > MAX_RECONNECT_TIMES) {
-      LOG("Fail to connect to Netd after retry %d times", MAX_RECONNECT_TIMES);
+      CHROMIUM_LOG("Fail to connect to Netd after retry %d times", MAX_RECONNECT_TIMES);
       return;
     }
 
     MessageLoopForIO::current()->
       PostDelayedTask(FROM_HERE,
                       NewRunnableFunction(NetdClient::Start),
                       1000);
     return;
@@ -225,24 +225,24 @@ NetdClient::Start()
 // static
 void
 NetdClient::SendNetdCommandIOThread(NetdCommand* aMessage)
 {
   MOZ_ASSERT(MessageLoop::current() == XRE_GetIOMessageLoop());
   MOZ_ASSERT(aMessage);
 
   if (!gNetdClient) {
-    LOG("Netd Client is not initialized");
+    CHROMIUM_LOG("Netd Client is not initialized");
     return;
   }
 
   gNetdClient->mOutgoingQ.push(aMessage);
 
   if (gNetdClient->mSocket.get() == INVALID_SOCKET) {
-    LOG("Netd connection is not established, push the message to queue");
+    CHROMIUM_LOG("Netd connection is not established, push the message to queue");
     return;
   }
 
   gNetdClient->WriteNetdCommand();
 }
 
 void
 NetdClient::WriteNetdCommand()
@@ -254,27 +254,27 @@ NetdClient::WriteNetdCommand()
   }
 
   while (mCurrentWriteOffset < mCurrentNetdCommand->mSize) {
     ssize_t write_amount = mCurrentNetdCommand->mSize - mCurrentWriteOffset;
     ssize_t written = write(mSocket.get(),
                             mCurrentNetdCommand->mData + mCurrentWriteOffset,
                             write_amount);
     if (written < 0) {
-      LOG("Cannot write to network, error %d\n", (int) written);
+      CHROMIUM_LOG("Cannot write to network, error %d\n", (int) written);
       OnError();
       return;
     }
 
     if (written > 0) {
       mCurrentWriteOffset += written;
     }
 
     if (written != write_amount) {
-      LOG("WriteNetdCommand fail !!! Write is not completed");
+      CHROMIUM_LOG("WriteNetdCommand fail !!! Write is not completed");
       break;
     }
   }
 
   if (mCurrentWriteOffset != mCurrentNetdCommand->mSize) {
     MessageLoopForIO::current()->
       WatchFileDescriptor(mSocket.get(),
                           false,
@@ -299,17 +299,17 @@ InitNetdIOThread()
   property_get("ro.build.version.sdk", propValue, "0");
   // Assign rndis address for usb tethering in ICS.
   if (atoi(propValue) >= 15) {
     result = InitRndisAddress();
     // We don't return here because InitRnsisAddress() function is related to
     // usb tethering only. Others service such as wifi tethering still need
     // to use ipc to communicate with netd.
     if (!result) {
-      LOG("fail to give rndis interface an address");
+      CHROMIUM_LOG("fail to give rndis interface an address");
     }
   }
   gNetdClient = new NetdClient();
   gNetdClient->Start();
 }
 
 static void
 ShutdownNetdIOThread()
--- a/ipc/nfc/Nfc.cpp
+++ b/ipc/nfc/Nfc.cpp
@@ -7,22 +7,22 @@
 /* Copyright © 2013, Deutsche Telekom, Inc. */
 
 #include "mozilla/ipc/Nfc.h"
 
 #include <fcntl.h>
 #include <sys/socket.h>
 #include <sys/un.h>
 
-#undef LOG
+#undef CHROMIUM_LOG
 #if (defined(MOZ_WIDGET_GONK) && defined(DEBUG))
 #include <android/log.h>
-#define LOG(args...)  __android_log_print(ANDROID_LOG_INFO, "Gonk", args)
+#define CHROMIUM_LOG(args...)  __android_log_print(ANDROID_LOG_INFO, "Gonk", args)
 #else
-#define LOG(args...)
+#define CHROMIUM_LOG(args...)
 #endif
 
 #include "jsfriendapi.h"
 #include "nsThreadUtils.h" // For NS_IsMainThread.
 
 USING_WORKERS_NAMESPACE
 using namespace mozilla::ipc;
 
@@ -323,29 +323,29 @@ NfcConsumer::ReceiveSocketData(nsAutoPtr
     nsRefPtr<DispatchNFCEvent> dre(new DispatchNFCEvent(aMessage.forget()));
     mDispatcher->PostTask(dre);
 }
 
 void
 NfcConsumer::OnConnectSuccess()
 {
     // Nothing to do here.
-    LOG("NFC: %s\n", __FUNCTION__);
+    CHROMIUM_LOG("NFC: %s\n", __FUNCTION__);
 }
 
 void
 NfcConsumer::OnConnectError()
 {
-    LOG("NFC: %s\n", __FUNCTION__);
+    CHROMIUM_LOG("NFC: %s\n", __FUNCTION__);
     CloseSocket();
 }
 
 void
 NfcConsumer::OnDisconnect()
 {
-    LOG("NFC: %s\n", __FUNCTION__);
+    CHROMIUM_LOG("NFC: %s\n", __FUNCTION__);
     if (!mShutdown) {
         ConnectSocket(new NfcConnector(), mAddress.get(), 1000);
     }
 }
 
 } // namespace ipc
 } // namespace mozilla
--- a/ipc/ril/Ril.cpp
+++ b/ipc/ril/Ril.cpp
@@ -6,22 +6,22 @@
 
 #include "mozilla/ipc/Ril.h"
 
 #include <fcntl.h>
 #include <sys/socket.h>
 #include <sys/un.h>
 #include <netdb.h> // For gethostbyname.
 
-#undef LOG
+#undef CHROMIUM_LOG
 #if defined(MOZ_WIDGET_GONK)
 #include <android/log.h>
-#define LOG(args...)  __android_log_print(ANDROID_LOG_INFO, "Gonk", args)
+#define CHROMIUM_LOG(args...)  __android_log_print(ANDROID_LOG_INFO, "Gonk", args)
 #else
-#define LOG(args...)  printf(args);
+#define CHROMIUM_LOG(args...)  printf(args);
 #endif
 
 #include "jsfriendapi.h"
 #include "nsTArray.h"
 #include "nsThreadUtils.h" // For NS_IsMainThread.
 
 USING_WORKERS_NAMESPACE
 using namespace mozilla::ipc;
@@ -356,29 +356,29 @@ RilConsumer::ReceiveSocketData(nsAutoPtr
     nsRefPtr<DispatchRILEvent> dre(new DispatchRILEvent(aMessage.forget()));
     mDispatcher->PostTask(dre);
 }
 
 void
 RilConsumer::OnConnectSuccess()
 {
     // Nothing to do here.
-    LOG("RIL[%lu]: %s\n", mClientId, __FUNCTION__);
+    CHROMIUM_LOG("RIL[%lu]: %s\n", mClientId, __FUNCTION__);
 }
 
 void
 RilConsumer::OnConnectError()
 {
-    LOG("RIL[%lu]: %s\n", mClientId, __FUNCTION__);
+    CHROMIUM_LOG("RIL[%lu]: %s\n", mClientId, __FUNCTION__);
     CloseSocket();
 }
 
 void
 RilConsumer::OnDisconnect()
 {
-    LOG("RIL[%lu]: %s\n", mClientId, __FUNCTION__);
+    CHROMIUM_LOG("RIL[%lu]: %s\n", mClientId, __FUNCTION__);
     if (!mShutdown) {
         ConnectSocket(new RilConnector(mClientId), mAddress.get(), 1000);
     }
 }
 
 } // namespace ipc
 } // namespace mozilla
--- a/ipc/unixsocket/UnixSocket.cpp
+++ b/ipc/unixsocket/UnixSocket.cpp
@@ -19,23 +19,23 @@
 #include "mozilla/Monitor.h"
 #include "mozilla/FileUtils.h"
 #include "nsString.h"
 #include "nsTArray.h"
 #include "nsXULAppAPI.h"
 
 static const size_t MAX_READ_SIZE = 1 << 16;
 
-#undef LOG
+#undef CHROMIUM_LOG
 #if defined(MOZ_WIDGET_GONK)
 #include <android/log.h>
-#define LOG(args...)  __android_log_print(ANDROID_LOG_INFO, "GonkDBus", args);
+#define CHROMIUM_LOG(args...)  __android_log_print(ANDROID_LOG_INFO, "GonkDBus", args);
 #else
 #define BTDEBUG true
-#define LOG(args...) if (BTDEBUG) printf(args);
+#define CHROMIUM_LOG(args...) if (BTDEBUG) printf(args);
 #endif
 
 static const int SOCKET_RETRY_TIME_MS = 1000;
 
 namespace mozilla {
 namespace ipc {
 
 class UnixSocketImpl : public MessageLoopForIO::Watcher
@@ -510,24 +510,24 @@ UnixSocketImpl::Accept()
     }
 
     if (!SetSocketFlags()) {
       return;
     }
 
     if (bind(mFd.get(), (struct sockaddr*)&mAddr, mAddrSize)) {
 #ifdef DEBUG
-      LOG("...bind(%d) gave errno %d", mFd.get(), errno);
+      CHROMIUM_LOG("...bind(%d) gave errno %d", mFd.get(), errno);
 #endif
       return;
     }
 
     if (listen(mFd.get(), 1)) {
 #ifdef DEBUG
-      LOG("...listen(%d) gave errno %d", mFd.get(), errno);
+      CHROMIUM_LOG("...listen(%d) gave errno %d", mFd.get(), errno);
 #endif
       return;
     }
 
     if (!mConnector->SetUpListenSocket(mFd)) {
       NS_WARNING("Could not set up listen socket!");
       nsRefPtr<OnSocketEventTask> t =
         new OnSocketEventTask(this, OnSocketEventTask::CONNECT_ERROR);
@@ -604,22 +604,22 @@ UnixSocketImpl::Connect()
       MessageLoopForIO::current()->WatchFileDescriptor(
         mFd.get(),
         false,
         MessageLoopForIO::WATCH_WRITE,
         &mWriteWatcher,
         this);
 
 #ifdef DEBUG
-      LOG("UnixSocket Connection delayed!");
+      CHROMIUM_LOG("UnixSocket Connection delayed!");
 #endif
       return;
     }
 #if DEBUG
-    LOG("Socket connect errno=%d\n", errno);
+    CHROMIUM_LOG("Socket connect errno=%d\n", errno);
 #endif
     mFd.reset(-1);
     nsRefPtr<OnSocketEventTask> t =
       new OnSocketEventTask(this, OnSocketEventTask::CONNECT_ERROR);
     NS_DispatchToMainThread(t);
     mConnectionStatus = SOCKET_DISCONNECTED;
     return;
   }
--- a/js/jsd/jsd_stak.cpp
+++ b/js/jsd/jsd_stak.cpp
@@ -480,18 +480,18 @@ jsd_ValToStringInStackFrame(JSDContext* 
     JSD_UNLOCK_THREADSTATES(jsdc);
 
     if( ! valid )
         return nullptr;
 
     cx = jsdthreadstate->context;
     JS_ASSERT(cx);
 
+    JS::RootedValue v(cx, val);
     exceptionState = JS_SaveExceptionState(cx);
-    JS::RootedValue v(cx, val);
     retval = JS::ToString(cx, v);
     JS_RestoreExceptionState(cx, exceptionState);
 
     return retval;
 }
 
 bool
 jsd_IsValidThreadState(JSDContext*        jsdc, 
--- a/js/src/Makefile.in
+++ b/js/src/Makefile.in
@@ -119,50 +119,54 @@ jsconfig_FILES = $(export_files)
 jsconfig_DEST = $(DIST)/include
 jsconfig_TARGET := export
 
 # Ensure that this happens before using $(MOZ_PSEUDO_DERECURSE)
 include $(topsrcdir)/config/config.mk
 
 # Ensure that this happens before including rules.mk
 ifdef ENABLE_INTL_API
-ifndef MOZ_NATIVE_ICU
-ifdef MOZ_SHARED_ICU
-ifeq ($(OS_ARCH),WINNT)
+  ifndef MOZ_NATIVE_ICU
   # Library names: On Windows, ICU uses modified library names for static
   # and debug libraries.
-  ifdef MOZ_DEBUG
-    ICU_LIB_SUFFIX=d
-  endif
-  ifdef JS_SHARED_LIBRARY
-    ICU_FILES := $(foreach libname,$(ICU_LIB_NAMES),intl/icu/target/lib/$(libname)$(ICU_LIB_SUFFIX)$(MOZ_ICU_VERSION).dll)
-  else
-    ICU_LIB_RENAME = $(foreach libname,$(ICU_LIB_NAMES),\
-                       cp -p intl/icu/target/lib/s$(libname)$(ICU_LIB_SUFFIX).lib intl/icu/target/lib/$(libname).lib;)
-  endif
-else
-  ifeq ($(OS_ARCH),Darwin)
-    ifdef JS_SHARED_LIBRARY
-      ICU_FILES := $(foreach libname,$(ICU_LIB_NAMES),intl/icu/target/lib/$(DLL_PREFIX)$(libname).$(MOZ_ICU_VERSION)$(DLL_SUFFIX))
-    endif
-  else
-    ifdef JS_SHARED_LIBRARY
-      ICU_FILES := $(foreach libname,$(ICU_LIB_NAMES),intl/icu/target/lib/$(DLL_PREFIX)$(libname)$(DLL_SUFFIX).$(MOZ_ICU_VERSION))
-    endif
-  endif
-endif
-ifdef ICU_FILES
-  ICU_DEST := $(DIST)/bin
-  INSTALL_TARGETS += ICU
-  $(ICU_FILES): buildicu
-  ICU_TARGET := $(if $(MOZ_PSEUDO_DERECURSE),compile,export)
-endif
-endif
-endif
-endif
+    ifeq ($(OS_ARCH),WINNT)
+      ifdef MOZ_DEBUG
+        ICU_LIB_SUFFIX=d
+      endif
+    endif # WINNT
+    ifdef MOZ_SHARED_ICU
+      ifeq ($(OS_ARCH),WINNT)
+        ifdef JS_SHARED_LIBRARY
+          ICU_FILES := $(foreach libname,$(ICU_LIB_NAMES),intl/icu/target/lib/$(libname)$(ICU_LIB_SUFFIX)$(MOZ_ICU_VERSION).dll)
+        endif
+      else # ! WINNT
+        ifeq ($(OS_ARCH),Darwin)
+          ifdef JS_SHARED_LIBRARY
+            ICU_FILES := $(foreach libname,$(ICU_LIB_NAMES),intl/icu/target/lib/$(DLL_PREFIX)$(libname).$(MOZ_ICU_VERSION)$(DLL_SUFFIX))
+          endif
+        else # ! Darwin
+          ifdef JS_SHARED_LIBRARY
+            ICU_FILES := $(foreach libname,$(ICU_LIB_NAMES),intl/icu/target/lib/$(DLL_PREFIX)$(libname)$(DLL_SUFFIX).$(MOZ_ICU_VERSION))
+          endif
+        endif
+      endif # WINNT
+      ifdef ICU_FILES
+        ICU_DEST := $(DIST)/bin
+        INSTALL_TARGETS += ICU
+        $(ICU_FILES): buildicu
+        ICU_TARGET := $(if $(MOZ_PSEUDO_DERECURSE),compile,export)
+      endif
+    else # !MOZ_SHARED_ICU
+      ifeq ($(OS_ARCH),WINNT)
+        ICU_LIB_RENAME = $(foreach libname,$(ICU_LIB_NAMES),\
+                             cp -p intl/icu/target/lib/s$(libname)$(ICU_LIB_SUFFIX).lib intl/icu/target/lib/$(libname).lib;)
+      endif
+    endif # MOZ_SHARED_ICU
+  endif # !MOZ_NATIVE_ICU
+endif # ENABLE_INTL_API
 
 include $(topsrcdir)/config/rules.mk
 
 .PHONY: buildffi buildicu
 buildffi buildicu:
 $(if $(MOZ_PSEUDO_DERECURSE),compile,export):: buildffi buildicu
 
 ifdef JS_HAS_CTYPES
@@ -191,31 +195,33 @@ LOCAL_INCLUDES += \
   -I$(topsrcdir)/../../intl/icu/source/i18n \
   $(NULL)
 endif
 
 ifdef ENABLE_INTL_API
 ifndef MOZ_NATIVE_ICU
 
 ifdef _MSC_VER
+ifdef MOZ_SHARED_ICU
 OS_LIBS += $(call EXPAND_LIBNAME,delayimp)
 ifdef MOZ_DEBUG
 EXTRA_DSO_LDOPTS += \
   -DELAYLOAD:icudtd$(MOZ_ICU_VERSION).dll \
   -DELAYLOAD:icuind$(MOZ_ICU_VERSION).dll \
   -DELAYLOAD:icuucd$(MOZ_ICU_VERSION).dll \
   $(NULL)
 else
 EXTRA_DSO_LDOPTS += \
   -DELAYLOAD:icudt$(MOZ_ICU_VERSION).dll \
   -DELAYLOAD:icuin$(MOZ_ICU_VERSION).dll \
   -DELAYLOAD:icuuc$(MOZ_ICU_VERSION).dll \
   $(NULL)
 endif
 endif
+endif
 
 ifdef .PYMAKE
 ICU_MAKE = $(GMAKE)
 else
 ICU_MAKE = $(MAKE)
 endif
 
 # - ICU requires GNU make according to its readme.html. pymake can't be used
deleted file mode 100644
--- a/js/src/build/ConfigStatus.py
+++ /dev/null
@@ -1,106 +0,0 @@
-# This Source Code Form is subject to the terms of the Mozilla Public
-# License, v. 2.0. If a copy of the MPL was not distributed with this
-# file, You can obtain one at http://mozilla.org/MPL/2.0/.
-
-# Combined with build/autoconf/config.status.m4, ConfigStatus is an almost
-# drop-in replacement for autoconf 2.13's config.status, with features
-# borrowed from autoconf > 2.5, and additional features.
-
-from __future__ import print_function
-
-import logging
-import os
-import sys
-
-from optparse import OptionParser
-
-from mach.logging import LoggingManager
-from mozbuild.backend.configenvironment import ConfigEnvironment
-from mozbuild.backend.recursivemake import RecursiveMakeBackend
-from mozbuild.frontend.emitter import TreeMetadataEmitter
-from mozbuild.frontend.reader import BuildReader
-from mozbuild.mozinfo import write_mozinfo
-
-
-log_manager = LoggingManager()
-
-
-def config_status(topobjdir='.', topsrcdir='.',
-        defines=[], non_global_defines=[], substs=[]):
-    '''Main function, providing config.status functionality.
-
-    Contrary to config.status, it doesn't use CONFIG_FILES or CONFIG_HEADERS
-    variables.
-
-    Without the -n option, this program acts as config.status and considers
-    the current directory as the top object directory, even when config.status
-    is in a different directory. It will, however, treat the directory
-    containing config.status as the top object directory with the -n option.
-
-    The --recheck option, like with the original config.status, runs configure
-    again, with the options given in the "ac_configure_args" subst.
-
-    The options to this function are passed when creating the
-    ConfigEnvironment. These lists, as well as the actual wrapper script
-    around this function, are meant to be generated by configure.
-    See build/autoconf/config.status.m4.
-    '''
-
-    if 'CONFIG_FILES' in os.environ:
-        raise Exception('Using the CONFIG_FILES environment variable is not '
-            'supported.')
-    if 'CONFIG_HEADERS' in os.environ:
-        raise Exception('Using the CONFIG_HEADERS environment variable is not '
-            'supported.')
-
-    if not os.path.isabs(topsrcdir):
-        raise Exception('topsrcdir must be defined as an absolute directory: '
-            '%s' % topsrcdir)
-
-    parser = OptionParser()
-    parser.add_option('--recheck', dest='recheck', action='store_true',
-                      help='update config.status by reconfiguring in the same conditions')
-    parser.add_option('-v', '--verbose', dest='verbose', action='store_true',
-                      help='display verbose output')
-    parser.add_option('-n', dest='not_topobjdir', action='store_true',
-                      help='do not consider current directory as top object directory')
-    parser.add_option('-d', '--diff', action='store_true',
-                      help='print diffs of changed files.')
-    options, args = parser.parse_args()
-
-    # Without -n, the current directory is meant to be the top object directory
-    if not options.not_topobjdir:
-        topobjdir = os.path.abspath('.')
-
-    env = ConfigEnvironment(topsrcdir, topobjdir, defines=defines,
-            non_global_defines=non_global_defines, substs=substs)
-
-    # mozinfo.json only needs written if configure changes and configure always
-    # passes this environment variable.
-    if 'WRITE_MOZINFO' in os.environ:
-        write_mozinfo(os.path.join(topobjdir, 'mozinfo.json'), env, os.environ)
-
-    reader = BuildReader(env)
-    emitter = TreeMetadataEmitter(env)
-    backend = RecursiveMakeBackend(env)
-    # This won't actually do anything because of the magic of generators.
-    definitions = emitter.emit(reader.read_topsrcdir())
-
-    if options.recheck:
-        # Execute configure from the top object directory
-        os.chdir(topobjdir)
-        os.execlp('sh', 'sh', '-c', ' '.join([os.path.join(topsrcdir, 'configure'), env.substs['ac_configure_args'], '--no-create', '--no-recursion']))
-
-    log_level = logging.DEBUG if options.verbose else logging.INFO
-    log_manager.add_terminal_logging(level=log_level)
-    log_manager.enable_unstructured()
-
-    print('Reticulating splines...', file=sys.stderr)
-    summary = backend.consume(definitions)
-
-    for line in summary.summaries():
-        print(line, file=sys.stderr)
-
-    if options.diff:
-        for path, diff in sorted(summary.file_diffs.items()):
-            print(diff)
--- a/js/src/config/config.mk
+++ b/js/src/config/config.mk
@@ -46,16 +46,17 @@ endif
   FORCE_STATIC_LIB \
   FINAL_LIBRARY \
   HOST_CSRCS \
   HOST_CMMSRCS \
   HOST_LIBRARY_NAME \
   HOST_PROGRAM \
   HOST_SIMPLE_PROGRAMS \
   IS_COMPONENT \
+  JAR_MANIFEST \
   JAVA_JAR_TARGETS \
   JS_MODULES_PATH \
   LIBRARY_NAME \
   LIBXUL_LIBRARY \
   MODULE \
   MSVC_ENABLE_PGO \
   NO_DIST_INSTALL \
   PARALLEL_DIRS \
--- a/js/src/config/rules.mk
+++ b/js/src/config/rules.mk
@@ -1279,27 +1279,25 @@ SDK_BINARY_FILES := $(SDK_BINARY)
 SDK_BINARY_DEST := $(SDK_BIN_DIR)
 INSTALL_TARGETS += SDK_BINARY
 endif
 endif # SDK_BINARY
 
 ################################################################################
 # CHROME PACKAGING
 
-JAR_MANIFEST := $(srcdir)/jar.mn
-
 chrome::
 	$(MAKE) realchrome
 	$(LOOP_OVER_PARALLEL_DIRS)
 	$(LOOP_OVER_DIRS)
 	$(LOOP_OVER_TOOL_DIRS)
 
 $(FINAL_TARGET)/chrome: $(call mkdir_deps,$(FINAL_TARGET)/chrome)
 
-ifneq (,$(wildcard $(JAR_MANIFEST)))
+ifneq (,$(JAR_MANIFEST))
 ifndef NO_DIST_INSTALL
 
 ifdef XPI_NAME
 ifdef XPI_ROOT_APPID
 # For add-on packaging we may specify that an application
 # sub-dir should be added to the root chrome manifest with
 # a specific application id.
 MAKE_JARS_FLAGS += --root-manifest-entry-appid='$(XPI_ROOT_APPID)'
@@ -1316,16 +1314,23 @@ endif
 
 libs realchrome:: $(FINAL_TARGET)/chrome
 	$(call py_action,jar_maker,\
 	  $(QUIET) -j $(FINAL_TARGET)/chrome \
 	  $(MAKE_JARS_FLAGS) $(XULPPFLAGS) $(DEFINES) $(ACDEFINES) \
 	  $(JAR_MANIFEST))
 
 endif
+
+# This is a temporary check to ensure patches relying on the old behavior
+# of silently picking up jar.mn files continue to work.
+else # No JAR_MANIFEST
+ifneq (,$(wildcard $(srcdir)/jar.mn))
+$(error $(srcdir) contains a jar.mn file but this file is not declared in a JAR_MANIFESTS variable in a moz.build file)
+endif
 endif
 
 ifneq ($(DIST_FILES),)
 DIST_FILES_PATH := $(FINAL_TARGET)
 DIST_FILES_FLAGS := $(XULAPP_DEFINES)
 PP_TARGETS += DIST_FILES
 endif
 
--- a/js/src/jit-test/tests/proxy/testDirectProxyGet3.js
+++ b/js/src/jit-test/tests/proxy/testDirectProxyGet3.js
@@ -12,8 +12,53 @@ Object.defineProperty(target, 'foo', {
 });
 assertThrowsInstanceOf(function () {
     new Proxy(target, {
         get: function (target, name, receiver) {
             return 'baz';
         }
     })['foo'];
 }, TypeError);
+
+/*
+ * Don't throw a TypeError if the trap reports the same value for a non-writable,
+ * non-configurable property
+ */
+assertEq(new Proxy(target, {
+        get: function (target, name, receiver) {
+            return 'bar';
+        }
+    })['foo'],
+    'bar');
+
+
+/*
+ * Don't throw a TypeError if the trap reports a different value for a writable,
+ * non-configurable property
+ */
+Object.defineProperty(target, 'prop', {
+    value: 'bar',
+    writable: true,
+    configurable: false
+});
+assertEq(new Proxy(target, {
+        get: function (target, name, receiver) {
+            return 'baz';
+        }
+    })['prop'],
+    'baz');
+
+
+/*
+ * Don't throw a TypeError if the trap reports a different value for a non-writable,
+ * configurable property
+ */
+Object.defineProperty(target, 'prop2', {
+    value: 'bar',
+    writable: false,
+    configurable: true
+});
+assertEq(new Proxy(target, {
+        get: function (target, name, receiver) {
+            return 'baz';
+        }
+    })['prop2'],
+    'baz');
--- a/js/src/jit/BaselineIC.cpp
+++ b/js/src/jit/BaselineIC.cpp
@@ -3266,43 +3266,44 @@ EffectlesslyLookupProperty(JSContext *cx
                            MutableHandleObject holder, MutableHandleShape shape,
                            bool *checkDOMProxy=nullptr,
                            DOMProxyShadowsResult *shadowsResult=nullptr,
                            bool *domProxyHasGeneration=nullptr)
 {
     shape.set(nullptr);
     holder.set(nullptr);
 
-    bool isDOMProxy = false;
     if (checkDOMProxy)
         *checkDOMProxy = false;
 
     // Check for list base if asked to.
     RootedObject checkObj(cx, obj);
     if (checkDOMProxy && IsCacheableDOMProxy(obj)) {
         JS_ASSERT(domProxyHasGeneration);
         JS_ASSERT(shadowsResult);
 
-        *checkDOMProxy = isDOMProxy = true;
+        *checkDOMProxy = true;
         if (obj->hasUncacheableProto())
             return true;
 
         RootedId id(cx, NameToId(name));
         *shadowsResult = GetDOMProxyShadowsCheck()(cx, obj, id);
         if (*shadowsResult == ShadowCheckFailed)
             return false;
 
         if (*shadowsResult == Shadows) {
             holder.set(obj);
             return true;
         }
 
         *domProxyHasGeneration = (*shadowsResult == DoesntShadowUnique);
 
         checkObj = GetDOMProxyProto(obj);
+        if (!checkObj)
+            return true;
     } else if (obj->is<TypedArrayObject>() && obj->getProto()) {
         // Typed array objects are non-native, but don't have any named
         // properties. Just forward the lookup to the prototype, to allow
         // inlining common getters like byteOffset.
         checkObj = obj->getProto();
     } else if (!obj->isNative()) {
         return true;
     }
--- a/js/src/jit/CodeGenerator.cpp
+++ b/js/src/jit/CodeGenerator.cpp
@@ -1744,34 +1744,29 @@ CodeGenerator::visitCallNative(LCallNati
     masm.setupUnalignedABICall(3, tempReg);
     masm.passABIArg(argContextReg);
     masm.passABIArg(argUintNReg);
     masm.passABIArg(argVpReg);
 
     switch (executionMode) {
       case SequentialExecution:
         masm.callWithABI(JS_FUNC_TO_DATA_PTR(void *, target->native()));
-
-        // Test for failure.
-        masm.branchIfFalseBool(ReturnReg, masm.failureLabel(executionMode));
         break;
 
       case ParallelExecution:
         masm.callWithABI(JS_FUNC_TO_DATA_PTR(void *, target->parallelNative()));
-
-        // ParallelResult has more nuanced failure, but for now we fail on
-        // anything that's != TP_SUCCESS.
-        masm.branch32(Assembler::NotEqual, ReturnReg, Imm32(TP_SUCCESS),
-                      masm.failureLabel(executionMode));
         break;
 
       default:
         MOZ_ASSUME_UNREACHABLE("No such execution mode");
     }
 
+    // Test for failure.
+    masm.branchIfFalseBool(ReturnReg, masm.failureLabel(executionMode));
+
     // Load the outparam vp[0] into output register(s).
     masm.loadValue(Address(StackPointer, IonNativeExitFrameLayout::offsetOfResult()), JSReturnOperand);
 
     // The next instruction is removing the footer of the exit frame, so there
     // is no need for leaveFakeExitFrame.
 
     // Move the StackPointer back to its original location, unwinding the native exit frame.
     masm.adjustStack(IonNativeExitFrameLayout::Size() - unusedStack);
--- a/js/src/jit/IonFrames.cpp
+++ b/js/src/jit/IonFrames.cpp
@@ -535,17 +535,19 @@ HandleExceptionBaseline(JSContext *cx, c
             }
             break;
 
           case JSTRY_FINALLY:
             if (cx->isExceptionPending()) {
                 rfe->kind = ResumeFromException::RESUME_FINALLY;
                 jsbytecode *finallyPC = script->main() + tn->start + tn->length;
                 rfe->target = script->baselineScript()->nativeCodeForPC(script, finallyPC);
-                rfe->exception = cx->getPendingException();
+                // Drop the exception instead of leaking cross compartment data.
+                if (!cx->getPendingException(MutableHandleValue::fromMarkedLocation(&rfe->exception)))
+                    rfe->exception = UndefinedValue();
                 cx->clearPendingException();
                 return;
             }
             break;
 
           case JSTRY_ITER: {
             Value iterValue(* (Value *) rfe->stackPointer);
             RootedObject iterObject(cx, &iterValue.toObject());
--- a/js/src/jit/ParallelSafetyAnalysis.cpp
+++ b/js/src/jit/ParallelSafetyAnalysis.cpp
@@ -141,17 +141,17 @@ class ParallelSafetyVisitor : public MIn
     UNSAFE_OP(ApplyArgs)
     UNSAFE_OP(Bail)
     UNSAFE_OP(AssertFloat32)
     UNSAFE_OP(GetDynamicName)
     UNSAFE_OP(FilterArgumentsOrEval)
     UNSAFE_OP(CallDirectEval)
     SAFE_OP(BitNot)
     UNSAFE_OP(TypeOf)
-    SAFE_OP(ToId)
+    UNSAFE_OP(ToId)
     SAFE_OP(BitAnd)
     SAFE_OP(BitOr)
     SAFE_OP(BitXor)
     SAFE_OP(Lsh)
     SAFE_OP(Rsh)
     SAFE_OP(Ursh)
     SPECIALIZED_OP(MinMax, PERMIT_NUMERIC)
     SAFE_OP(Abs)
--- a/js/src/jsapi.cpp
+++ b/js/src/jsapi.cpp
@@ -5860,19 +5860,17 @@ JS_IsExceptionPending(JSContext *cx)
 
 JS_PUBLIC_API(bool)
 JS_GetPendingException(JSContext *cx, MutableHandleValue vp)
 {
     AssertHeapIsIdle(cx);
     CHECK_REQUEST(cx);
     if (!cx->isExceptionPending())
         return false;
-    vp.set(cx->getPendingException());
-    assertSameCompartment(cx, vp);
-    return true;
+    return cx->getPendingException(vp);
 }
 
 JS_PUBLIC_API(void)
 JS_SetPendingException(JSContext *cx, HandleValue value)
 {
     AssertHeapIsIdle(cx);
     CHECK_REQUEST(cx);
     assertSameCompartment(cx, value);
--- a/js/src/jscntxt.cpp
+++ b/js/src/jscntxt.cpp
@@ -1068,17 +1068,17 @@ ThreadSafeContext::asForkJoinSlice()
 {
     JS_ASSERT(isForkJoinSlice());
     return reinterpret_cast<ForkJoinSlice *>(this);
 }
 
 JSContext::JSContext(JSRuntime *rt)
   : ExclusiveContext(rt, &rt->mainThread, Context_JS),
     throwing(false),
-    exception(UndefinedValue()),
+    unwrappedException_(UndefinedValue()),
     options_(),
     reportGranularity(JS_DEFAULT_JITREPORT_GRANULARITY),
     resolvingList(nullptr),
     generatingError(false),
     savedFrameChains_(),
     defaultCompartmentObject_(nullptr),
     cycleDetectorSet(MOZ_THIS_IN_INITIALIZER_LIST()),
     errorReporter(nullptr),
@@ -1104,31 +1104,31 @@ JSContext::JSContext(JSRuntime *rt)
 }
 
 JSContext::~JSContext()
 {
     /* Free the stuff hanging off of cx. */
     JS_ASSERT(!resolvingList);
 }
 
-/*
- * Since this function is only called in the context of a pending exception,
- * the caller must subsequently take an error path. If wrapping fails, it will
- * set a new (uncatchable) exception to be used in place of the original.
- */
-void
-JSContext::wrapPendingException()
+bool
+JSContext::getPendingException(MutableHandleValue rval)
 {
-    RootedValue value(this, getPendingException());
+    JS_ASSERT(throwing);
+    rval.set(unwrappedException_);
+    if (IsAtomsCompartment(compartment()))
+        return true;
     clearPendingException();
-    if (!IsAtomsCompartment(compartment()) && compartment()->wrap(this, &value))
-        setPendingException(value);
+    if (!compartment()->wrap(this, rval))
+        return false;
+    assertSameCompartment(this, rval);
+    setPendingException(rval);
+    return true;
 }
 
-
 void
 JSContext::enterGenerator(JSGenerator *gen)
 {
     JS_ASSERT(!gen->prevGenerator);
     gen->prevGenerator = innermostGenerator_;
     innermostGenerator_ = gen;
 }
 
@@ -1166,19 +1166,16 @@ void
 JSContext::restoreFrameChain()
 {
     SavedFrameChain sfc = savedFrameChains_.popCopy();
     setCompartment(sfc.compartment);
     enterCompartmentDepth_ = sfc.enterCompartmentCount;
 
     if (Activation *act = mainThread().activation())
         act->restoreFrameChain();
-
-    if (isExceptionPending())
-        wrapPendingException();
 }
 
 bool
 JSContext::currentlyRunning() const
 {
     for (ActivationIterator iter(runtime()); !iter.done(); ++iter) {
         if (iter.activation()->cx() == this) {
             if (iter.activation()->hasSavedFrameChain())
@@ -1282,17 +1279,17 @@ void
 JSContext::mark(JSTracer *trc)
 {
     /* Stack frames and slots are traced by StackSpace::mark. */
 
     /* Mark other roots-by-definition in the JSContext. */
     if (defaultCompartmentObject_)
         MarkObjectRoot(trc, &defaultCompartmentObject_, "default compartment object");
     if (isExceptionPending())
-        MarkValueRoot(trc, &exception, "exception");
+        MarkValueRoot(trc, &unwrappedException_, "unwrapped exception");
 
     TraceCycleDetectionSet(trc, cycleDetectorSet);
 
     MarkValueRoot(trc, &iterValue, "iterValue");
 }
 
 JSVersion
 JSContext::findVersion() const
--- a/js/src/jscntxt.h
+++ b/js/src/jscntxt.h
@@ -421,17 +421,17 @@ struct JSContext : public js::ExclusiveC
     JSRuntime *runtime() const { return runtime_; }
     js::PerThreadData &mainThread() const { return runtime()->mainThread; }
 
     friend class js::ExclusiveContext;
 
   private:
     /* Exception state -- the exception member is a GC root by definition. */
     bool                throwing;            /* is there a pending exception? */
-    js::Value           exception;           /* most-recently-thrown exception */
+    js::Value           unwrappedException_; /* most-recently-thrown exception */
 
     /* Per-context options. */
     JS::ContextOptions  options_;
 
   public:
     int32_t             reportGranularity;  /* see vm/Probes.h */
 
     js::AutoResolving   *resolvingList;
@@ -463,19 +463,16 @@ struct JSContext : public js::ExclusiveC
   public:
     inline void setDefaultCompartmentObject(JSObject *obj);
     inline void setDefaultCompartmentObjectIfUnset(JSObject *obj);
     JSObject *maybeDefaultCompartmentObject() const {
         JS_ASSERT(!options().noDefaultCompartmentObject());
         return defaultCompartmentObject_;
     }
 
-    /* Wrap cx->exception for the current compartment. */
-    void wrapPendingException();
-
     /* State for object and array toSource conversion. */
     js::ObjectSet       cycleDetectorSet;
 
     /* Per-context optional error reporter. */
     JSErrorReporter     errorReporter;
 
     /* Client opaque pointers. */
     void                *data;
@@ -578,26 +575,23 @@ struct JSContext : public js::ExclusiveC
     void reportAllocationOverflow() {
         js_ReportAllocationOverflow(this);
     }
 
     bool isExceptionPending() {
         return throwing;
     }
 
-    js::Value getPendingException() {
-        JS_ASSERT(throwing);
-        return exception;
-    }
+    bool getPendingException(JS::MutableHandleValue rval);
 
     void setPendingException(js::Value v);
 
     void clearPendingException() {
         throwing = false;
-        exception.setUndefined();
+        unwrappedException_.setUndefined();
     }
 
 #ifdef DEBUG
     /*
      * Controls whether a quadratic-complexity assertion is performed during
      * stack iteration; defaults to true.
      */
     bool stackIterAssertionEnabled;
--- a/js/src/jscntxtinlines.h
+++ b/js/src/jscntxtinlines.h
@@ -353,20 +353,21 @@ inline LifoAlloc &
 ExclusiveContext::typeLifoAlloc()
 {
     return zone()->types.typeLifoAlloc;
 }
 
 }  /* namespace js */
 
 inline void
-JSContext::setPendingException(js::Value v) {
+JSContext::setPendingException(js::Value v)
+{
     JS_ASSERT(!IsPoisonedValue(v));
     this->throwing = true;
-    this->exception = v;
+    this->unwrappedException_ = v;
     js::assertSameCompartment(this, v);
 }
 
 inline void
 JSContext::setDefaultCompartmentObject(JSObject *obj)
 {
     JS_ASSERT(!options().noDefaultCompartmentObject());
     defaultCompartmentObject_ = obj;
@@ -383,39 +384,29 @@ JSContext::setDefaultCompartmentObjectIf
 }
 
 inline void
 js::ExclusiveContext::enterCompartment(JSCompartment *c)
 {
     enterCompartmentDepth_++;
     c->enter();
     setCompartment(c);
-
-    if (JSContext *cx = maybeJSContext()) {
-        if (cx->throwing)
-            cx->wrapPendingException();
-    }
 }
 
 inline void
 js::ExclusiveContext::leaveCompartment(JSCompartment *oldCompartment)
 {
     JS_ASSERT(hasEnteredCompartment());
     enterCompartmentDepth_--;
 
     // Only call leave() after we've setCompartment()-ed away from the current
     // compartment.
     JSCompartment *startingCompartment = compartment_;
     setCompartment(oldCompartment);
     startingCompartment->leave();
-
-    if (JSContext *cx = maybeJSContext()) {
-        if (cx->throwing && oldCompartment)
-            cx->wrapPendingException();
-    }
 }
 
 inline void
 js::ExclusiveContext::setCompartment(JSCompartment *comp)
 {
     // ExclusiveContexts can only be in the atoms zone or in exclusive zones.
     JS_ASSERT_IF(!isJSContext() && !runtime_->isAtomsCompartment(comp),
                  comp->zone()->usedByExclusiveThread);
--- a/js/src/jsexn.cpp
+++ b/js/src/jsexn.cpp
@@ -725,17 +725,20 @@ IsDuckTypedErrorObject(JSContext *cx, Ha
 }
 
 bool
 js_ReportUncaughtException(JSContext *cx)
 {
     if (!cx->isExceptionPending())
         return true;
 
-    RootedValue exn(cx, cx->getPendingException());
+    RootedValue exn(cx);
+    if (!cx->getPendingException(&exn))
+        return false;
+
     AutoValueVector roots(cx);
     roots.resize(6);
 
     /*
      * Because ToString below could error and an exception object could become
      * unrooted, we must root exnObject.  Later, if exnObject is non-null, we
      * need to root other intermediates, so allocate an operand stack segment
      * to protect all of these values.
--- a/js/src/jsiter.cpp
+++ b/js/src/jsiter.cpp
@@ -973,17 +973,18 @@ js::CloseIterator(JSContext *cx, HandleO
         return CloseLegacyGenerator(cx, obj);
     }
     return true;
 }
 
 bool
 js::UnwindIteratorForException(JSContext *cx, HandleObject obj)
 {
-    RootedValue v(cx, cx->getPendingException());
+    RootedValue v(cx);
+    cx->getPendingException(&v);
     cx->clearPendingException();
     if (!CloseIterator(cx, obj))
         return false;
     cx->setPendingException(v);
     return true;
 }
 
 void
@@ -1190,17 +1191,22 @@ js_IteratorMore(JSContext *cx, HandleObj
         if ((ni->flags & JSITER_KEYVALUE) && !NewKeyValuePair(cx, id, rval, rval))
             return false;
     } else {
         /* Call the iterator object's .next method. */
         if (!JSObject::getProperty(cx, iterobj, iterobj, cx->names().next, rval))
             return false;
         if (!Invoke(cx, ObjectValue(*iterobj), rval, 0, nullptr, rval)) {
             /* Check for StopIteration. */
-            if (!cx->isExceptionPending() || !JS_IsStopIteration(cx->getPendingException()))
+            if (!cx->isExceptionPending())
+                return false;
+            RootedValue exception(cx);
+            if (!cx->getPendingException(&exception))
+                return false;
+            if (!JS_IsStopIteration(exception))
                 return false;
 
             cx->clearPendingException();
             cx->iterValue.setMagic(JS_NO_ITER_VALUE);
             rval.setBoolean(false);
             return true;
         }
     }
--- a/js/src/jsproxy.cpp
+++ b/js/src/jsproxy.cpp
@@ -2104,17 +2104,17 @@ ScriptedDirectProxyHandler::get(JSContex
     Rooted<PropertyDescriptor> desc(cx);
     if (!GetOwnPropertyDescriptor(cx, target, id, &desc))
         return false;
 
     // step 7
     if (desc.object()) {
         if (IsDataDescriptor(desc) && desc.isPermanent() && desc.isReadonly()) {
             bool same;
-            if (!SameValue(cx, vp, desc.value(), &same))
+            if (!SameValue(cx, trapResult, desc.value(), &same))
                 return false;
             if (!same) {
                 JS_ReportErrorNumber(cx, js_GetErrorMessage, nullptr, JSMSG_MUST_REPORT_SAME_VALUE);
                 return false;
             }
         }
 
         if (IsAccessorDescriptor(desc) && desc.isPermanent() && !desc.hasGetterObject()) {
--- a/js/src/jswrapper.cpp
+++ b/js/src/jswrapper.cpp
@@ -144,18 +144,18 @@ js::TransparentObjectWrapper(JSContext *
     JS_ASSERT(wrappedProto == TaggedProto::LazyProto);
     return Wrapper::New(cx, obj, parent, &CrossCompartmentWrapper::singleton);
 }
 
 ErrorCopier::~ErrorCopier()
 {
     JSContext *cx = ac.ref().context()->asJSContext();
     if (ac.ref().origin() != cx->compartment() && cx->isExceptionPending()) {
-        RootedValue exc(cx, cx->getPendingException());
-        if (exc.isObject() && exc.toObject().is<ErrorObject>()) {
+        RootedValue exc(cx);
+        if (cx->getPendingException(&exc) && exc.isObject() && exc.toObject().is<ErrorObject>()) {
             cx->clearPendingException();
             ac.destroy();
             Rooted<ErrorObject*> errObj(cx, &exc.toObject().as<ErrorObject>());
             JSObject *copyobj = js_CopyErrorObject(cx, errObj, scope);
             if (copyobj)
                 cx->setPendingException(ObjectValue(*copyobj));
         }
     }
--- a/js/src/vm/Debugger.cpp
+++ b/js/src/vm/Debugger.cpp
@@ -778,21 +778,23 @@ Debugger::unwrapDebuggeeValue(JSContext 
 
 JSTrapStatus
 Debugger::handleUncaughtExceptionHelper(Maybe<AutoCompartment> &ac,
                                         MutableHandleValue *vp, bool callHook)
 {
     JSContext *cx = ac.ref().context()->asJSContext();
     if (cx->isExceptionPending()) {
         if (callHook && uncaughtExceptionHook) {
-            Value fval = ObjectValue(*uncaughtExceptionHook);
-            Value exc = cx->getPendingException();
+            RootedValue exc(cx);
+            if (!cx->getPendingException(&exc))
+                return JSTRAP_ERROR;
+            cx->clearPendingException();
+            RootedValue fval(cx, ObjectValue(*uncaughtExceptionHook));
             RootedValue rv(cx);
-            cx->clearPendingException();
-            if (Invoke(cx, ObjectValue(*object), fval, 1, &exc, &rv))
+            if (Invoke(cx, ObjectValue(*object), fval, 1, exc.address(), &rv))
                 return vp ? parseResumptionValue(ac, true, rv, *vp, false) : JSTRAP_CONTINUE;
         }
 
         if (cx->isExceptionPending()) {
             JS_ReportPendingException(cx);
             cx->clearPendingException();
         }
     }
@@ -818,17 +820,18 @@ Debugger::resultToCompletion(JSContext *
 {
     JS_ASSERT_IF(ok, !cx->isExceptionPending());
 
     if (ok) {
         *status = JSTRAP_RETURN;
         value.set(rv);
     } else if (cx->isExceptionPending()) {
         *status = JSTRAP_THROW;
-        value.set(cx->getPendingException());
+        if (!cx->getPendingException(value))
+            *status = JSTRAP_ERROR;
         cx->clearPendingException();
     } else {
         *status = JSTRAP_ERROR;
         value.setUndefined();
     }
 }
 
 bool
@@ -979,17 +982,19 @@ Debugger::fireDebuggerStatement(JSContex
 
 JSTrapStatus
 Debugger::fireExceptionUnwind(JSContext *cx, MutableHandleValue vp)
 {
     RootedObject hook(cx, getHook(OnExceptionUnwind));
     JS_ASSERT(hook);
     JS_ASSERT(hook->isCallable());
 
-    RootedValue exc(cx, cx->getPendingException());
+    RootedValue exc(cx);
+    if (!cx->getPendingException(&exc))
+        return JSTRAP_ERROR;
     cx->clearPendingException();
 
     Maybe<AutoCompartment> ac;
     ac.construct(cx, object);
 
     Value argvData[] = { JSVAL_VOID, exc };
     AutoValueArray argv(cx, argvData, 2);
     ScriptFrameIter iter(cx);
@@ -1226,17 +1231,18 @@ Debugger::onSingleStep(JSContext *cx, Mu
      * We may be stepping over a JSOP_EXCEPTION, that pushes the context's
      * pending exception for a 'catch' clause to handle. Don't let the
      * onStep handlers mess with that (other than by returning a resumption
      * value).
      */
     RootedValue exception(cx, UndefinedValue());
     bool exceptionPending = cx->isExceptionPending();
     if (exceptionPending) {
-        exception = cx->getPendingException();
+        if (!cx->getPendingException(&exception))
+            return JSTRAP_ERROR;
         cx->clearPendingException();
     }
 
     /*
      * Build list of Debugger.Frame instances referring to this frame with
      * onStep handlers.
      */
     AutoObjectVector frames(cx);
--- a/js/src/vm/Interpreter.cpp
+++ b/js/src/vm/Interpreter.cpp
@@ -988,40 +988,37 @@ HandleError(JSContext *cx, FrameRegs &re
                 ForcedReturn(cx, si, regs);
                 return SuccessfulReturnContinuation;
 
               default:
                 MOZ_ASSUME_UNREACHABLE("Invalid trap status");
             }
         }
 
+        RootedValue exception(cx);
         for (TryNoteIter tni(cx, regs); !tni.done(); ++tni) {
             JSTryNote *tn = *tni;
 
             UnwindScope(cx, si, tn->stackDepth);
 
             /*
              * Set pc to the first bytecode after the the try note to point
              * to the beginning of catch or finally or to [enditer] closing
              * the for-in loop.
              */
             regs.pc = regs.fp()->script()->main() + tn->start + tn->length;
             regs.sp = regs.spForStackDepth(tn->stackDepth);
 
             switch (tn->kind) {
               case JSTRY_CATCH:
                 /* Catch cannot intercept the closing of a generator. */
-                if (JS_UNLIKELY(cx->getPendingException().isMagic(JS_GENERATOR_CLOSING)))
+                if (!cx->getPendingException(&exception))
+                    return ErrorReturnContinuation;
+                if (exception.isMagic(JS_GENERATOR_CLOSING))
                     break;
-
-                /*
-                 * Don't clear exceptions to save cx->exception from GC
-                 * until it is pushed to the stack via [exception] in the
-                 * catch block.
-                 */
                 return CatchContinuation;
 
               case JSTRY_FINALLY:
                 return FinallyContinuation;
 
               case JSTRY_ITER: {
                 /* This is similar to JSOP_ENDITER in the interpreter loop. */
                 JS_ASSERT(JSOp(*regs.pc) == JSOP_ENDITER);
@@ -1037,21 +1034,26 @@ HandleError(JSContext *cx, FrameRegs &re
                 break;
             }
         }
 
         /*
          * Propagate the exception or error to the caller unless the exception
          * is an asynchronous return from a generator.
          */
-        if (JS_UNLIKELY(cx->isExceptionPending() &&
-                        cx->getPendingException().isMagic(JS_GENERATOR_CLOSING))) {
-            cx->clearPendingException();
-            ok = true;
-            regs.fp()->clearReturnValue();
+        if (cx->isExceptionPending()) {
+            RootedValue exception(cx);
+            if (!cx->getPendingException(&exception))
+                return ErrorReturnContinuation;
+
+            if (exception.isMagic(JS_GENERATOR_CLOSING)) {
+                cx->clearPendingException();
+                ok = true;
+                regs.fp()->clearReturnValue();
+            }
         }
     } else {
         UnwindForUncatchableException(cx, regs);
     }
 
     ForcedReturn(cx, si, regs);
     return ok ? SuccessfulReturnContinuation : ErrorReturnContinuation;
 }
@@ -3428,18 +3430,23 @@ DEFAULT()
       case CatchContinuation:
         ADVANCE_AND_DISPATCH(0);
 
       case FinallyContinuation:
         /*
          * Push (true, exception) pair for finally to indicate that [retsub]
          * should rethrow the exception.
          */
+        RootedValue &exception = rootValue0;
+        if (!cx->getPendingException(&exception)) {
+            interpReturnOK = false;
+            goto return_continuation;
+        }
         PUSH_BOOLEAN(true);
-        PUSH_COPY(cx->getPendingException());
+        PUSH_COPY(exception);
         cx->clearPendingException();
         ADVANCE_AND_DISPATCH(0);
     }
     MOZ_ASSUME_UNREACHABLE("Invalid HandleError continuation");
 
   exit:
     if (JS_UNLIKELY(cx->compartment()->debugMode()))
         interpReturnOK = ScriptDebugEpilogue(cx, REGS.fp(), REGS.pc, interpReturnOK);
@@ -3678,19 +3685,19 @@ js::SetCallOperation(JSContext *cx)
 bool
 js::GetAndClearException(JSContext *cx, MutableHandleValue res)
 {
     // Check the interrupt flag to allow interrupting deeply nested exception
     // handling.
     if (cx->runtime()->interrupt && !js_HandleExecutionInterrupt(cx))
         return false;
 
-    res.set(cx->getPendingException());
+    bool status = cx->getPendingException(res);
     cx->clearPendingException();
-    return true;
+    return status;
 }
 
 template <bool strict>
 bool
 js::SetProperty(JSContext *cx, HandleObject obj, HandleId id, const Value &value)
 {
     RootedValue v(cx, value);
     return JSObject::setGeneric(cx, obj, obj, id, &v, strict);
--- a/js/src/vm/OldDebugAPI.cpp
+++ b/js/src/vm/OldDebugAPI.cpp
@@ -627,29 +627,33 @@ GetPropertyDesc(JSContext *cx, JSObject 
 {
     assertSameCompartment(cx, obj_);
     pd->id = IdToJsval(shape->propid());
 
     RootedObject obj(cx, obj_);
 
     bool wasThrowing = cx->isExceptionPending();
     RootedValue lastException(cx, UndefinedValue());
-    if (wasThrowing)
-        lastException = cx->getPendingException();
+    if (wasThrowing) {
+        if (!cx->getPendingException(&lastException))
+            return false;
+    }
     cx->clearPendingException();
 
     Rooted<jsid> id(cx, shape->propid());
     RootedValue value(cx);
     if (!baseops::GetProperty(cx, obj, id, &value)) {
         if (!cx->isExceptionPending()) {
             pd->flags = JSPD_ERROR;
             pd->value = JSVAL_VOID;
         } else {
             pd->flags = JSPD_EXCEPTION;
-            pd->value = cx->getPendingException();
+            if (!cx->getPendingException(&value))
+                return false;
+            pd->value = value;
         }
     } else {
         pd->flags = 0;
         pd->value = value;
     }
 
     if (wasThrowing)
         cx->setPendingException(lastException);
--- a/layout/generic/moz.build
+++ b/layout/generic/moz.build
@@ -116,8 +116,10 @@ LOCAL_INCLUDES += [
     '../../dom/plugins/base',
     '../base',
     '../forms',
     '../style',
     '../svg',
     '../tables',
     '../xul',
 ]
+
+JAR_MANIFESTS += ['jar.mn']
\ No newline at end of file
--- a/layout/ipc/moz.build
+++ b/layout/ipc/moz.build
@@ -26,8 +26,10 @@ include('/ipc/chromium/chromium-config.m
 FINAL_LIBRARY = 'gklayout'
 
 LOCAL_INCLUDES += [
     '/content/base/src',
     '/layout/base',
     '/layout/generic',
     '/layout/xul',
 ]
+
+JAR_MANIFESTS += ['jar.mn']
\ No newline at end of file
--- a/layout/mathml/moz.build
+++ b/layout/mathml/moz.build
@@ -41,8 +41,10 @@ LOCAL_INCLUDES += [
     '/content/base/src',
     '/content/mathml/content/src',
 ]
 
 if CONFIG['ENABLE_TESTS']:
     PARALLEL_DIRS += [
         'tests',
     ]
+
+JAR_MANIFESTS += ['jar.mn']
\ No newline at end of file
--- a/layout/style/moz.build
+++ b/layout/style/moz.build
@@ -149,8 +149,10 @@ LOCAL_INCLUDES += [
     '../../content/html/content/src',
     '../../content/xbl/src',
     '../../content/xul/document/src',
     '../base',
     '../generic',
     '../xul',
     '/dom/base',
 ]
+
+JAR_MANIFESTS += ['jar.mn']
\ No newline at end of file
--- a/layout/style/xbl-marquee/moz.build
+++ b/layout/style/xbl-marquee/moz.build
@@ -1,6 +1,7 @@
 # -*- Mode: python; c-basic-offset: 4; indent-tabs-mode: nil; tab-width: 40 -*-
 # vim: set filetype=python:
 # This Source Code Form is subject to the terms of the Mozilla Public
 # License, v. 2.0. If a copy of the MPL was not distributed with this
 # file, You can obtain one at http://mozilla.org/MPL/2.0/.
 
+JAR_MANIFESTS += ['jar.mn']
\ No newline at end of file
--- a/layout/tools/layout-debug/ui/moz.build
+++ b/layout/tools/layout-debug/ui/moz.build
@@ -1,6 +1,7 @@
 # -*- Mode: python; c-basic-offset: 4; indent-tabs-mode: nil; tab-width: 40 -*-
 # vim: set filetype=python:
 # This Source Code Form is subject to the terms of the Mozilla Public
 # License, v. 2.0. If a copy of the MPL was not distributed with this
 # file, You can obtain one at http://mozilla.org/MPL/2.0/.
 
+JAR_MANIFESTS += ['jar.mn']
\ No newline at end of file
--- a/layout/tools/recording/moz.build
+++ b/layout/tools/recording/moz.build
@@ -3,8 +3,10 @@
 # This Source Code Form is subject to the terms of the Mozilla Public
 # License, v. 2.0. If a copy of the MPL was not distributed with this
 # file, You can obtain one at http://mozilla.org/MPL/2.0/.
 
 EXTRA_COMPONENTS += [
     'recording-cmdline.js',
     'recording-cmdline.manifest',
 ]
+
+JAR_MANIFESTS += ['jar.mn']
\ No newline at end of file
--- a/layout/tools/reftest/moz.build
+++ b/layout/tools/reftest/moz.build
@@ -3,8 +3,9 @@
 # This Source Code Form is subject to the terms of the Mozilla Public
 # License, v. 2.0. If a copy of the MPL was not distributed with this
 # file, You can obtain one at http://mozilla.org/MPL/2.0/.
 
 EXTRA_COMPONENTS += [
     'reftest-cmdline.js',
 ]
 
+JAR_MANIFESTS += ['jar.mn']
\ No newline at end of file
--- a/layout/tools/reftest/reftest.js
+++ b/layout/tools/reftest/reftest.js
@@ -1868,17 +1868,17 @@ function RegisterMessageListenersAndLoad
         "reftest:ExpectProcessCrash",
         function (m) { RecvExpectProcessCrash(); }
     );
     gBrowserMessageManager.addMessageListener(
         "reftest:EnableAsyncScroll",
         function (m) { SetAsyncScroll(true); }
     );
 
-    gBrowserMessageManager.loadFrameScript("chrome://reftest/content/reftest-content.js", true);
+    gBrowserMessageManager.loadFrameScript("chrome://reftest/content/reftest-content.js", true, true);
 }
 
 function SetAsyncScroll(enabled)
 {
     gBrowser.QueryInterface(CI.nsIFrameLoaderOwner).frameLoader.renderMode =
         enabled ? CI.nsIFrameLoader.RENDER_MODE_ASYNC_SCROLL :
                   CI.nsIFrameLoader.RENDER_MODE_DEFAULT;
 }
--- a/mobile/android/branding/aurora/content/moz.build
+++ b/mobile/android/branding/aurora/content/moz.build
@@ -1,6 +1,7 @@
 # -*- Mode: python; c-basic-offset: 4; indent-tabs-mode: nil; tab-width: 40 -*-
 # vim: set filetype=python:
 # This Source Code Form is subject to the terms of the Mozilla Public
 # License, v. 2.0. If a copy of the MPL was not distributed with this
 # file, You can obtain one at http://mozilla.org/MPL/2.0/.
 
+JAR_MANIFESTS += ['jar.mn']
\ No newline at end of file
--- a/mobile/android/branding/aurora/locales/moz.build
+++ b/mobile/android/branding/aurora/locales/moz.build
@@ -1,6 +1,7 @@
 # -*- Mode: python; c-basic-offset: 4; indent-tabs-mode: nil; tab-width: 40 -*-
 # vim: set filetype=python:
 # This Source Code Form is subject to the terms of the Mozilla Public
 # License, v. 2.0. If a copy of the MPL was not distributed with this
 # file, You can obtain one at http://mozilla.org/MPL/2.0/.
 
+JAR_MANIFESTS += ['jar.mn']
\ No newline at end of file
--- a/mobile/android/branding/beta/content/moz.build
+++ b/mobile/android/branding/beta/content/moz.build
@@ -1,6 +1,7 @@
 # -*- Mode: python; c-basic-offset: 4; indent-tabs-mode: nil; tab-width: 40 -*-
 # vim: set filetype=python:
 # This Source Code Form is subject to the terms of the Mozilla Public
 # License, v. 2.0. If a copy of the MPL was not distributed with this
 # file, You can obtain one at http://mozilla.org/MPL/2.0/.
 
+JAR_MANIFESTS += ['jar.mn']
\ No newline at end of file
--- a/mobile/android/branding/beta/locales/moz.build
+++ b/mobile/android/branding/beta/locales/moz.build
@@ -1,6 +1,7 @@
 # -*- Mode: python; c-basic-offset: 4; indent-tabs-mode: nil; tab-width: 40 -*-
 # vim: set filetype=python:
 # This Source Code Form is subject to the terms of the Mozilla Public
 # License, v. 2.0. If a copy of the MPL was not distributed with this
 # file, You can obtain one at http://mozilla.org/MPL/2.0/.
 
+JAR_MANIFESTS += ['jar.mn']
\ No newline at end of file
--- a/mobile/android/branding/nightly/content/moz.build
+++ b/mobile/android/branding/nightly/content/moz.build
@@ -1,6 +1,7 @@
 # -*- Mode: python; c-basic-offset: 4; indent-tabs-mode: nil; tab-width: 40 -*-
 # vim: set filetype=python:
 # This Source Code Form is subject to the terms of the Mozilla Public
 # License, v. 2.0. If a copy of the MPL was not distributed with this
 # file, You can obtain one at http://mozilla.org/MPL/2.0/.
 
+JAR_MANIFESTS += ['jar.mn']
\ No newline at end of file
--- a/mobile/android/branding/nightly/locales/moz.build
+++ b/mobile/android/branding/nightly/locales/moz.build
@@ -1,6 +1,7 @@
 # -*- Mode: python; c-basic-offset: 4; indent-tabs-mode: nil; tab-width: 40 -*-
 # vim: set filetype=python:
 # This Source Code Form is subject to the terms of the Mozilla Public
 # License, v. 2.0. If a copy of the MPL was not distributed with this
 # file, You can obtain one at http://mozilla.org/MPL/2.0/.
 
+JAR_MANIFESTS += ['jar.mn']
\ No newline at end of file
--- a/mobile/android/branding/official/content/moz.build
+++ b/mobile/android/branding/official/content/moz.build
@@ -1,6 +1,7 @@
 # -*- Mode: python; c-basic-offset: 4; indent-tabs-mode: nil; tab-width: 40 -*-
 # vim: set filetype=python:
 # This Source Code Form is subject to the terms of the Mozilla Public
 # License, v. 2.0. If a copy of the MPL was not distributed with this
 # file, You can obtain one at http://mozilla.org/MPL/2.0/.
 
+JAR_MANIFESTS += ['jar.mn']
\ No newline at end of file
--- a/mobile/android/branding/official/locales/moz.build
+++ b/mobile/android/branding/official/locales/moz.build
@@ -1,6 +1,7 @@
 # -*- Mode: python; c-basic-offset: 4; indent-tabs-mode: nil; tab-width: 40 -*-
 # vim: set filetype=python:
 # This Source Code Form is subject to the terms of the Mozilla Public
 # License, v. 2.0. If a copy of the MPL was not distributed with this
 # file, You can obtain one at http://mozilla.org/MPL/2.0/.
 
+JAR_MANIFESTS += ['jar.mn']
\ No newline at end of file
--- a/mobile/android/branding/unofficial/content/moz.build
+++ b/mobile/android/branding/unofficial/content/moz.build
@@ -1,6 +1,7 @@
 # -*- Mode: python; c-basic-offset: 4; indent-tabs-mode: nil; tab-width: 40 -*-
 # vim: set filetype=python:
 # This Source Code Form is subject to the terms of the Mozilla Public
 # License, v. 2.0. If a copy of the MPL was not distributed with this
 # file, You can obtain one at http://mozilla.org/MPL/2.0/.
 
+JAR_MANIFESTS += ['jar.mn']
\ No newline at end of file
--- a/mobile/android/branding/unofficial/locales/moz.build
+++ b/mobile/android/branding/unofficial/locales/moz.build
@@ -1,6 +1,7 @@
 # -*- Mode: python; c-basic-offset: 4; indent-tabs-mode: nil; tab-width: 40 -*-
 # vim: set filetype=python:
 # This Source Code Form is subject to the terms of the Mozilla Public
 # License, v. 2.0. If a copy of the MPL was not distributed with this
 # file, You can obtain one at http://mozilla.org/MPL/2.0/.
 
+JAR_MANIFESTS += ['jar.mn']
\ No newline at end of file
--- a/mobile/android/chrome/moz.build
+++ b/mobile/android/chrome/moz.build
@@ -3,8 +3,10 @@
 # This Source Code Form is subject to the terms of the Mozilla Public
 # License, v. 2.0. If a copy of the MPL was not distributed with this
 # file, You can obtain one at http://mozilla.org/MPL/2.0/.
 
 DEFINES['AB_CD'] = CONFIG['MOZ_UI_LOCALE']
 DEFINES['PACKAGE'] = 'browser'
 DEFINES['MOZ_APP_VERSION'] = CONFIG['MOZ_APP_VERSION']
 DEFINES['ANDROID_PACKAGE_NAME'] = CONFIG['ANDROID_PACKAGE_NAME']
+
+JAR_MANIFESTS += ['jar.mn']
\ No newline at end of file
--- a/mobile/android/installer/package-manifest.in
+++ b/mobile/android/installer/package-manifest.in
@@ -29,16 +29,19 @@
 #endif
 @BINPATH@/dictionaries/*
 @BINPATH@/hyphenation/*
 
 [assets destdir="assets"]
 #ifndef MOZ_STATIC_JS
 @BINPATH@/@DLL_PREFIX@mozjs@DLL_SUFFIX@
 #endif
+#ifdef MOZ_DMD
+@BINPATH@/@DLL_PREFIX@dmd@DLL_SUFFIX@
+#endif
 #ifndef MOZ_FOLD_LIBS
 @BINPATH@/@DLL_PREFIX@plc4@DLL_SUFFIX@
 @BINPATH@/@DLL_PREFIX@plds4@DLL_SUFFIX@
 @BINPATH@/@DLL_PREFIX@nspr4@DLL_SUFFIX@
 #endif
 @BINPATH@/@DLL_PREFIX@mozalloc@DLL_SUFFIX@
 @BINPATH@/@DLL_PREFIX@omxplugin@DLL_SUFFIX@
 @BINPATH@/@DLL_PREFIX@omxplugingb@DLL_SUFFIX@
--- a/mobile/android/locales/moz.build
+++ b/mobile/android/locales/moz.build
@@ -1,6 +1,7 @@
 # -*- Mode: python; c-basic-offset: 4; indent-tabs-mode: nil; tab-width: 40 -*-
 # vim: set filetype=python:
 # This Source Code Form is subject to the terms of the Mozilla Public
 # License, v. 2.0. If a copy of the MPL was not distributed with this
 # file, You can obtain one at http://mozilla.org/MPL/2.0/.
 
+JAR_MANIFESTS += ['jar.mn']
\ No newline at end of file
--- a/mobile/android/themes/core/moz.build
+++ b/mobile/android/themes/core/moz.build
@@ -1,6 +1,7 @@
 # -*- Mode: python; c-basic-offset: 4; indent-tabs-mode: nil; tab-width: 40 -*-
 # vim: set filetype=python:
 # This Source Code Form is subject to the terms of the Mozilla Public
 # License, v. 2.0. If a copy of the MPL was not distributed with this
 # file, You can obtain one at http://mozilla.org/MPL/2.0/.
 
+JAR_MANIFESTS += ['jar.mn']
\ No newline at end of file
--- a/mobile/locales/moz.build
+++ b/mobile/locales/moz.build
@@ -1,6 +1,7 @@
 # -*- Mode: python; c-basic-offset: 4; indent-tabs-mode: nil; tab-width: 40 -*-
 # vim: set filetype=python:
 # This Source Code Form is subject to the terms of the Mozilla Public
 # License, v. 2.0. If a copy of the MPL was not distributed with this
 # file, You can obtain one at http://mozilla.org/MPL/2.0/.
 
+JAR_MANIFESTS += ['jar.mn']
\ No newline at end of file
--- a/moz.build
+++ b/moz.build
@@ -7,19 +7,21 @@
 CONFIGURE_SUBST_FILES += [
     'mozilla-config.h',
     'tools/update-packaging/Makefile',
 ]
 
 if CONFIG['ENABLE_CLANG_PLUGIN']:
   add_tier_dir('base', 'build/clang-plugin', external=True)
 
-add_tier_dir('base', ['config', 'build', 'probes', 'mfbt', 'python'])
+add_tier_dir('base', ['config', 'build', 'probes', 'python'])
 
 if not CONFIG['LIBXUL_SDK']:
+    add_tier_dir('base', ['mfbt'])
+
     if CONFIG['MOZ_WIDGET_TOOLKIT'] in ('android', 'gonk'):
         add_tier_dir('base', ['other-licenses/android'])
 
     if CONFIG['MOZ_MEMORY']:
         add_tier_dir('base', ['memory'])
 
     if not CONFIG['MOZ_NATIVE_ZLIB']:
         add_tier_dir('base', ['modules/zlib'])
--- a/netwerk/base/src/Seer.cpp
+++ b/netwerk/base/src/Seer.cpp
@@ -898,17 +898,17 @@ Seer::PredictForLink(nsIURI *targetURI, 
     sourceURI->SchemeIs("https", &isSSL);
     if (isSSL) {
       // We don't want to predict from an HTTPS page, to avoid info leakage
       SEER_LOG(("Not predicting for link hover - on an SSL page"));
       return;
     }
   }
 
-  mSpeculativeService->SpeculativeConnect(targetURI, this);
+  mSpeculativeService->SpeculativeConnect(targetURI, nullptr);
   if (verifier) {
     verifier->OnPredictPreconnect(targetURI);
   }
 }
 
 // This runnable runs on the main thread, and is responsible for actually
 // firing off predictive actions (such as TCP/TLS preconnects and DNS lookups)
 class SeerPredictionRunner : public nsRunnable
--- a/netwerk/locales/moz.build
+++ b/netwerk/locales/moz.build
@@ -1,6 +1,7 @@
 # -*- Mode: python; c-basic-offset: 4; indent-tabs-mode: nil; tab-width: 40 -*-
 # vim: set filetype=python:
 # This Source Code Form is subject to the terms of the Mozilla Public
 # License, v. 2.0. If a copy of the MPL was not distributed with this
 # file, You can obtain one at http://mozilla.org/MPL/2.0/.
 
+JAR_MANIFESTS += ['jar.mn']
\ No newline at end of file
--- a/netwerk/test/httpserver/moz.build
+++ b/netwerk/test/httpserver/moz.build
@@ -11,8 +11,9 @@ XPIDL_SOURCES += [
 XPIDL_MODULE = 'test_necko'
 
 XPCSHELL_TESTS_MANIFESTS += ['test/xpcshell.ini']
 
 EXTRA_COMPONENTS += [
     'httpd.js',
 ]
 
+JAR_MANIFESTS += ['jar.mn']
\ No newline at end of file
--- a/python/mozbuild/mozbuild/backend/recursivemake.py
+++ b/python/mozbuild/mozbuild/backend/recursivemake.py
@@ -27,16 +27,17 @@ from ..frontend.data import (
     Defines,
     DirectoryTraversal,
     Exports,
     GeneratedInclude,
     HostProgram,
     HostSimpleProgram,
     InstallationTarget,
     IPDLFile,
+    JARManifest,
     JavaJarData,
     LibraryDefinition,
     LocalInclude,
     Program,
     SandboxDerived,
     SandboxWrapped,
     SimpleProgram,
     TestManifest,
@@ -400,16 +401,19 @@ class RecursiveMakeBackend(CommonBackend
                 backend_file.write('DEFINES +=')
                 for define in defines:
                     backend_file.write(' %s' % define)
                 backend_file.write('\n')
 
         elif isinstance(obj, Exports):
             self._process_exports(obj, obj.exports, backend_file)
 
+        elif isinstance(obj, JARManifest):
+            backend_file.write('JAR_MANIFEST := %s\n' % obj.path)
+
         elif isinstance(obj, IPDLFile):
             self._ipdl_sources.add(mozpath.join(obj.srcdir, obj.basename))
 
         elif isinstance(obj, Program):
             self._process_program(obj.program, backend_file)
 
         elif isinstance(obj, HostProgram):
             self._process_host_program(obj.program, backend_file)
@@ -678,21 +682,16 @@ class RecursiveMakeBackend(CommonBackend
                         if tier in ('compile', 'binaries'):
                             continue
                         if bf.relobjdir in skiplist:
                             skiplist.remove(bf.relobjdir)
                 else:
                     self.log(logging.DEBUG, 'stub_makefile',
                         {'path': makefile}, 'Creating stub Makefile: {path}')
 
-                # Can't skip directories with a jar.mn for the 'libs' tier.
-                if bf.relobjdir in self._may_skip['libs'] and \
-                        os.path.exists(mozpath.join(srcdir, 'jar.mn')):
-                    self._may_skip['libs'].remove(bf.relobjdir)
-
                 obj = self.Substitution()
                 obj.output_path = makefile
                 obj.input_path = makefile_in
                 obj.topsrcdir = bf.environment.topsrcdir
                 obj.topobjdir = bf.environment.topobjdir
                 self._create_makefile(obj, stub=stub)
 
         # Write out a master list of all IPDL source files.
rename from build/ConfigStatus.py
rename to python/mozbuild/mozbuild/config_status.py
--- a/python/mozbuild/mozbuild/frontend/data.py
+++ b/python/mozbuild/mozbuild/frontend/data.py
@@ -442,16 +442,33 @@ class GeneratedInclude(SandboxDerived):
     )
 
     def __init__(self, sandbox, path):
         SandboxDerived.__init__(self, sandbox)
 
         self.path = path
 
 
+class JARManifest(SandboxDerived):
+    """Describes an individual JAR manifest file and how to process it.
+
+    This class isn't very useful for optimizing backends yet because we don't
+    capture defines. We can't capture defines safely until all of them are
+    defined in moz.build and not Makefile.in files.
+    """
+    __slots__ = (
+        'path',
+    )
+
+    def __init__(self, sandbox, path):
+        SandboxDerived.__init__(self, sandbox)
+
+        self.path = path
+
+
 class SandboxWrapped(SandboxDerived):
     """Generic sandbox container object for a wrapped rich object.
 
     Use this wrapper class to shuttle a rich build system object
     completely defined in moz.build files through the tree metadata
     emitter to the build backend for processing as-is.
     """
 
--- a/python/mozbuild/mozbuild/frontend/emitter.py
+++ b/python/mozbuild/mozbuild/frontend/emitter.py
@@ -25,16 +25,17 @@ from .data import (
     GeneratedInclude,
     GeneratedWebIDLFile,
     ExampleWebIDLInterface,
     HeaderFileSubstitution,
     HostProgram,
     HostSimpleProgram,
     InstallationTarget,
     IPDLFile,
+    JARManifest,
     LibraryDefinition,
     LocalInclude,
     PreprocessedTestWebIDLFile,
     PreprocessedWebIDLFile,
     Program,
     ReaderSummary,
     SandboxWrapped,
     SimpleProgram,
@@ -376,16 +377,35 @@ class TreeMetadataEmitter(LoggingMixin):
             XPCSHELL_TESTS=('xpcshell', 'xpcshell', False),
         )
 
         for prefix, info in test_manifests.items():
             for path in sandbox.get('%s_MANIFESTS' % prefix, []):
                 for obj in self._process_test_manifest(sandbox, info, path):
                     yield obj
 
+        jar_manifests = sandbox.get('JAR_MANIFESTS', [])
+        if len(jar_manifests) > 1:
+            raise SandboxValidationError('While JAR_MANIFESTS is a list, '
+                'it is currently limited to one value.')
+
+        for path in jar_manifests:
+            yield JARManifest(sandbox, mozpath.join(sandbox['SRCDIR'], path))
+
+        # Temporary test to look for jar.mn files that creep in without using
+        # the new declaration. Before, we didn't require jar.mn files to
+        # declared anywhere (they were discovered). This will detect people
+        # relying on the old behavior.
+        if os.path.exists(os.path.join(sandbox['SRCDIR'], 'jar.mn')):
+            if 'jar.mn' not in jar_manifests:
+                raise SandboxValidationError('A jar.mn exists in %s but it '
+                    'is not referenced in the corresponding moz.build file. '
+                    'Please define JAR_MANIFESTS in the moz.build file.' %
+                    sandbox['SRCDIR'])
+
         for name, jar in sandbox.get('JAVA_JAR_TARGETS', {}).items():
             yield SandboxWrapped(sandbox, jar)
 
         if passthru.variables:
             yield passthru
 
     def _create_substitution(self, cls, sandbox, path):
         if os.path.isabs(path):
--- a/python/mozbuild/mozbuild/frontend/sandbox_symbols.py
+++ b/python/mozbuild/mozbuild/frontend/sandbox_symbols.py
@@ -435,16 +435,24 @@ VARIABLES = {
 
     'NO_DIST_INSTALL': (bool, bool,
         """Disable installing certain files into the distribution directory.
 
         If present, some files defined by other variables won't be
         distributed/shipped with the produced build.
         """, None),
 
+    'JAR_MANIFESTS': (StrictOrderingOnAppendList, list,
+        """JAR manifest files that should be processed as part of the build.
+
+        JAR manifests are files in the tree that define how to package files
+        into JARs and how chrome registration is performed. For more info,
+        see :ref:`jar_manifests`.
+        """, 'libs'),
+
     # IDL Generation.
     'XPIDL_SOURCES': (StrictOrderingOnAppendList, list,
         """XPCOM Interface Definition Files (xpidl).
 
         This is a list of files that define XPCOM interface definitions.
         Entries must be files that exist. Entries are almost certainly ``.idl``
         files.
         """, 'libs'),
--- a/python/mozbuild/mozbuild/test/backend/common.py
+++ b/python/mozbuild/mozbuild/test/backend/common.py
@@ -10,29 +10,30 @@ import unittest
 from shutil import rmtree
 from tempfile import mkdtemp
 
 from mach.logging import LoggingManager
 
 from mozbuild.backend.configenvironment import ConfigEnvironment
 from mozbuild.frontend.emitter import TreeMetadataEmitter
 from mozbuild.frontend.reader import BuildReader
+from mozbuild.util import DefaultOnReadDict
 
 import mozpack.path as mozpath
 
 
 log_manager = LoggingManager()
 log_manager.add_terminal_logging()
 
 
 test_data_path = mozpath.abspath(mozpath.dirname(__file__))
 test_data_path = mozpath.join(test_data_path, 'data')
 
 
-CONFIGS = {
+CONFIGS = DefaultOnReadDict({
     'stub0': {
         'defines': [
             ('MOZ_TRUE_1', '1'),
             ('MOZ_TRUE_2', '1'),
         ],
         'non_global_defines': [
             ('MOZ_NONGLOBAL_1', '1'),
             ('MOZ_NONGLOBAL_2', '1'),
@@ -45,72 +46,31 @@ CONFIGS = {
     'substitute_config_files': {
         'defines': [],
         'non_global_defines': [],
         'substs': [
             ('MOZ_FOO', 'foo'),
             ('MOZ_BAR', 'bar'),
         ],
     },
-    'variable_passthru': {
-        'defines': [],
-        'non_global_defines': [],
-        'substs': [],
-    },
-    'defines': {
-        'defines': [],
-        'non_global_defines': [],
-        'substs': [],
-    },
-    'exports': {
-        'defines': [],
-        'non_global_defines': [],
-        'substs': [],
-    },
-    'test-manifests-written': {
-        'defines': [],
-        'non_global_defines': [],
-        'substs': [],
-    },
-    'ipdl_sources': {
-        'defines': [],
-        'non_global_defines': [],
-        'substs': [],
-    },
-    'xpidl': {
-        'defines': [],
-        'non_global_defines': [],
-        'substs': [],
-    },
-    'local_includes': {
-        'defines': [],
-        'non_global_defines': [],
-        'substs': [],
-    },
-    'generated_includes': {
-        'defines': [],
-        'non_global_defines': [],
-        'substs': [],
-    },
-    'final_target': {
-        'defines': [],
-        'non_global_defines': [],
-        'substs': [],
-    },
     'test_config': {
         'defines': [
             ('foo', 'baz qux'),
             ('baz', 1)
         ],
         'non_global_defines': [],
         'substs': [
             ('foo', 'bar baz'),
         ],
     },
-}
+}, global_default={
+    'defines': [],
+    'non_global_defines': [],
+    'substs': [],
+})
 
 
 class BackendTester(unittest.TestCase):
     def _get_environment(self, name):
         """Obtain a new instance of a ConfigEnvironment for a known profile.
 
         A new temporary object directory is created for the environment. The
         environment is cleaned up automatically when the test finishes.
new file mode 100644
--- /dev/null
+++ b/python/mozbuild/mozbuild/test/backend/data/jar-manifests/moz.build
@@ -0,0 +1,8 @@
+# -*- Mode: python; c-basic-offset: 4; indent-tabs-mode: nil; tab-width: 40 -*-
+# vim: set filetype=python:
+# This Source Code Form is subject to the terms of the Mozilla Public
+# License, v. 2.0. If a copy of the MPL was not distributed with this
+# file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+JAR_MANIFESTS += ['jar.mn']
+
--- a/python/mozbuild/mozbuild/test/backend/test_recursivemake.py
+++ b/python/mozbuild/mozbuild/test/backend/test_recursivemake.py
@@ -509,17 +509,16 @@ class TestRecursiveMakeBackend(BackendTe
         found = [str for str in lines if str.startswith('LOCAL_INCLUDES')]
         self.assertEqual(found, expected)
 
     def test_final_target(self):
         """Test that FINAL_TARGET is written to backend.mk correctly."""
         env = self._consume('final_target', RecursiveMakeBackend)
 
         final_target_rule = "FINAL_TARGET = $(if $(XPI_NAME),$(DIST)/xpi-stage/$(XPI_NAME),$(DIST)/bin)$(DIST_SUBDIR:%=/%)"
-        print([x for x in os.walk(env.topobjdir)])
         expected = dict()
         expected[env.topobjdir] = []
         expected[mozpath.join(env.topobjdir, 'both')] = [
             'XPI_NAME = mycrazyxpi',
             'DIST_SUBDIR = asubdir',
             final_target_rule
         ]
         expected[mozpath.join(env.topobjdir, 'dist-subdir')] = [
@@ -567,10 +566,21 @@ class TestRecursiveMakeBackend(BackendTe
                 '\n',
                 '#ifdef foo\n',
                 '#   define   foo baz qux\n',
                 '#  define foo    baz qux\n',
                 '  #     define   foo   baz qux   \n',
                 '#endif\n',
             ])
 
+    def test_jar_manifests(self):
+        env = self._consume('jar-manifests', RecursiveMakeBackend)
+
+        with open(os.path.join(env.topobjdir, 'backend.mk'), 'rb') as fh:
+            lines = fh.readlines()
+
+        lines = [line.rstrip() for line in lines]
+
+        self.assertIn('JAR_MANIFEST := %s/jar.mn' % env.topsrcdir, lines)
+
+
 if __name__ == '__main__':
     main()
new file mode 100644
--- /dev/null
+++ b/python/mozbuild/mozbuild/test/frontend/data/jar-manifests-multiple-files/moz.build
@@ -0,0 +1,8 @@
+# -*- Mode: python; c-basic-offset: 4; indent-tabs-mode: nil; tab-width: 40 -*-
+# vim: set filetype=python:
+# This Source Code Form is subject to the terms of the Mozilla Public
+# License, v. 2.0. If a copy of the MPL was not distributed with this
+# file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+JAR_MANIFESTS += ['jar.mn', 'other.jar']
+
new file mode 100644
--- /dev/null
+++ b/python/mozbuild/mozbuild/test/frontend/data/jar-manifests/moz.build
@@ -0,0 +1,7 @@
+# -*- Mode: python; c-basic-offset: 4; indent-tabs-mode: nil; tab-width: 40 -*-
+# vim: set filetype=python:
+# This Source Code Form is subject to the terms of the Mozilla Public
+# License, v. 2.0. If a copy of the MPL was not distributed with this
+# file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+JAR_MANIFESTS += ['jar.mn']
--- a/python/mozbuild/mozbuild/test/frontend/test_emitter.py
+++ b/python/mozbuild/mozbuild/test/frontend/test_emitter.py
@@ -11,16 +11,17 @@ from mozunit import main
 
 from mozbuild.frontend.data import (
     ConfigFileSubstitution,
     Defines,
     DirectoryTraversal,
     Exports,
     GeneratedInclude,
     IPDLFile,
+    JARManifest,
     LocalInclude,
     Program,
     ReaderSummary,
     SimpleProgram,
     TestManifest,
     VariablePassthru,
 )
 from mozbuild.frontend.emitter import TreeMetadataEmitter
@@ -42,31 +43,42 @@ class TestEmitterBasic(unittest.TestCase
     def reader(self, name):
         config = MockConfig(mozpath.join(data_path, name), extra_substs=dict(
             ENABLE_TESTS='1',
             BIN_SUFFIX='.prog',
         ))
 
         return BuildReader(config)
 
-    def read_topsrcdir(self, reader):
+    def read_topsrcdir(self, reader, filter_common=True):
         emitter = TreeMetadataEmitter(reader.config)
         def ack(obj):
             obj.ack()
             return obj
 
         objs = list(ack(o) for o in emitter.emit(reader.read_topsrcdir()))
         self.assertGreater(len(objs), 0)
         self.assertIsInstance(objs[-1], ReaderSummary)
 
-        return objs[:-1]
+        filtered = []
+        for obj in objs:
+            if filter_common and isinstance(obj, DirectoryTraversal):
+                continue
+
+            # Always filter ReaderSummary because it's asserted above.
+            if isinstance(obj, ReaderSummary):
+                continue
+
+            filtered.append(obj)
+
+        return filtered
 
     def test_dirs_traversal_simple(self):
         reader = self.reader('traversal-simple')
-        objs = self.read_topsrcdir(reader)
+        objs = self.read_topsrcdir(reader, filter_common=False)
         self.assertEqual(len(objs), 4)
 
         for o in objs:
             self.assertIsInstance(o, DirectoryTraversal)
             self.assertEqual(o.parallel_dirs, [])
             self.assertEqual(o.tool_dirs, [])
             self.assertEqual(o.test_dirs, [])
             self.assertEqual(o.test_tool_dirs, [])
@@ -78,17 +90,17 @@ class TestEmitterBasic(unittest.TestCase
         reldirs = [o.relativedir for o in objs]
         self.assertEqual(reldirs, ['', 'foo', 'foo/biz', 'bar'])
 
         dirs = [o.dirs for o in objs]
         self.assertEqual(dirs, [['foo', 'bar'], ['biz'], [], []])
 
     def test_traversal_all_vars(self):
         reader = self.reader('traversal-all-vars')
-        objs = self.read_topsrcdir(reader)
+        objs = self.read_topsrcdir(reader, filter_common=False)
         self.assertEqual(len(objs), 6)
 
         for o in objs:
             self.assertIsInstance(o, DirectoryTraversal)
 
         reldirs = set([o.relativedir for o in objs])
         self.assertEqual(reldirs, set(['', 'parallel', 'regular', 'test',
             'test_tool', 'tool']))
@@ -100,45 +112,43 @@ class TestEmitterBasic(unittest.TestCase
                 self.assertEqual(o.dirs, ['regular'])
                 self.assertEqual(o.parallel_dirs, ['parallel'])
                 self.assertEqual(o.test_dirs, ['test'])
                 self.assertEqual(o.test_tool_dirs, ['test_tool'])
                 self.assertEqual(o.tool_dirs, ['tool'])
 
     def test_tier_simple(self):
         reader = self.reader('traversal-tier-simple')
-        objs = self.read_topsrcdir(reader)
+        objs = self.read_topsrcdir(reader, filter_common=False)
         self.assertEqual(len(objs), 4)
 
         reldirs = [o.relativedir for o in objs]
         self.assertEqual(reldirs, ['', 'foo', 'foo/biz', 'bar'])
 
     def test_config_file_substitution(self):
         reader = self.reader('config-file-substitution')
         objs = self.read_topsrcdir(reader)
-        self.assertEqual(len(objs), 3)
+        self.assertEqual(len(objs), 2)
 
-        self.assertIsInstance(objs[0], DirectoryTraversal)
+        self.assertIsInstance(objs[0], ConfigFileSubstitution)
         self.assertIsInstance(objs[1], ConfigFileSubstitution)
-        self.assertIsInstance(objs[2], ConfigFileSubstitution)
 
         topobjdir = mozpath.abspath(reader.config.topobjdir)
-        self.assertEqual(objs[1].relpath, 'foo')
+        self.assertEqual(objs[0].relpath, 'foo')
+        self.assertEqual(mozpath.normpath(objs[0].output_path),
+            mozpath.normpath(mozpath.join(topobjdir, 'foo')))
         self.assertEqual(mozpath.normpath(objs[1].output_path),
-            mozpath.normpath(mozpath.join(topobjdir, 'foo')))
-        self.assertEqual(mozpath.normpath(objs[2].output_path),
             mozpath.normpath(mozpath.join(topobjdir, 'bar')))
 
     def test_variable_passthru(self):
         reader = self.reader('variable-passthru')
         objs = self.read_topsrcdir(reader)
 
-        self.assertEqual(len(objs), 2)
-        self.assertIsInstance(objs[0], DirectoryTraversal)
-        self.assertIsInstance(objs[1], VariablePassthru)
+        self.assertEqual(len(objs), 1)
+        self.assertIsInstance(objs[0], VariablePassthru)
 
         wanted = dict(
             ASFILES=['fans.asm', 'tans.s'],
             CMMSRCS=['fans.mm', 'tans.mm'],
             CSRCS=['fans.c', 'tans.c'],
             CPP_UNIT_TESTS=['foo.cpp'],
             EXPORT_LIBRARY=True,
             EXTRA_COMPONENTS=['fans.js', 'tans.js'],
@@ -156,31 +166,30 @@ class TestEmitterBasic(unittest.TestCase
             MSVC_ENABLE_PGO=True,
             NO_DIST_INSTALL=True,
             OS_LIBS=['foo.so', '-l123', 'aaa.a'],
             SDK_LIBRARY=['fans.sdk', 'tans.sdk'],
             SSRCS=['bans.S', 'fans.S'],
             VISIBILITY_FLAGS='',
         )
 
-        variables = objs[1].variables
+        variables = objs[0].variables
         maxDiff = self.maxDiff
         self.maxDiff = None
         self.assertEqual(wanted, variables)
         self.maxDiff = maxDiff
 
     def test_exports(self):
         reader = self.reader('exports')
         objs = self.read_topsrcdir(reader)
 
-        self.assertEqual(len(objs), 2)
-        self.assertIsInstance(objs[0], DirectoryTraversal)
-        self.assertIsInstance(objs[1], Exports)
+        self.assertEqual(len(objs), 1)
+        self.assertIsInstance(objs[0], Exports)
 
-        exports = objs[1].exports
+        exports = objs[0].exports
         self.assertEqual(exports.get_strings(), ['foo.h', 'bar.h', 'baz.h'])
 
         self.assertIn('mozilla', exports._children)
         mozilla = exports._children['mozilla']
         self.assertEqual(mozilla.get_strings(), ['mozilla1.h', 'mozilla2.h'])
 
         self.assertIn('dom', mozilla._children)
         dom = mozilla._children['dom']
@@ -203,25 +212,24 @@ class TestEmitterBasic(unittest.TestCase
         self.assertIn('overwrite', exports._children)
         overwrite = exports._children['overwrite']
         self.assertEqual(overwrite.get_strings(), ['new.h'])
 
     def test_program(self):
         reader = self.reader('program')
         objs = self.read_topsrcdir(reader)
 
-        self.assertEqual(len(objs), 4)
-        self.assertIsInstance(objs[0], DirectoryTraversal)
-        self.assertIsInstance(objs[1], Program)
+        self.assertEqual(len(objs), 3)
+        self.assertIsInstance(objs[0], Program)
+        self.assertIsInstance(objs[1], SimpleProgram)
         self.assertIsInstance(objs[2], SimpleProgram)
-        self.assertIsInstance(objs[3], SimpleProgram)
 
-        self.assertEqual(objs[1].program, 'test_program.prog')
-        self.assertEqual(objs[2].program, 'test_program1.prog')
-        self.assertEqual(objs[3].program, 'test_program2.prog')
+        self.assertEqual(objs[0].program, 'test_program.prog')
+        self.assertEqual(objs[1].program, 'test_program1.prog')
+        self.assertEqual(objs[2].program, 'test_program2.prog')
 
     def test_test_manifest_missing_manifest(self):
         """A missing manifest file should result in an error."""
         reader = self.reader('test-manifest-missing-manifest')
 
         with self.assertRaisesRegexp(SandboxValidationError, 'IOError: Missing files'):
             self.read_topsrcdir(reader)
 
@@ -400,10 +408,25 @@ class TestEmitterBasic(unittest.TestCase
             'BAR': 7,
             'BAZ': '"abcd"',
             'FOO': True,
             'VALUE': 'xyz',
         }
 
         self.assertEqual(defines, expected)
 
+    def test_jar_manifests(self):
+        reader = self.reader('jar-manifests')
+        objs = self.read_topsrcdir(reader)
+
+        self.assertEqual(len(objs), 1)
+        for obj in objs:
+            self.assertIsInstance(obj, JARManifest)
+            self.assertTrue(os.path.isabs(obj.path))
+
+    def test_jar_manifests_multiple_files(self):
+        with self.assertRaisesRegexp(SandboxValidationError, 'limited to one value'):
+            reader = self.reader('jar-manifests-multiple-files')
+            self.read_topsrcdir(reader)
+
+
 if __name__ == '__main__':
     main()
--- a/security/manager/locales/moz.build
+++ b/security/manager/locales/moz.build
@@ -1,6 +1,7 @@
 # -*- Mode: python; c-basic-offset: 4; indent-tabs-mode: nil; tab-width: 40 -*-
 # vim: set filetype=python:
 # This Source Code Form is subject to the terms of the Mozilla Public
 # License, v. 2.0. If a copy of the MPL was not distributed with this
 # file, You can obtain one at http://mozilla.org/MPL/2.0/.
 
+JAR_MANIFESTS += ['jar.mn']
\ No newline at end of file
--- a/security/manager/pki/resources/moz.build
+++ b/security/manager/pki/resources/moz.build
@@ -1,6 +1,7 @@
 # -*- Mode: python; c-basic-offset: 4; indent-tabs-mode: nil; tab-width: 40 -*-
 # vim: set filetype=python:
 # This Source Code Form is subject to the terms of the Mozilla Public
 # License, v. 2.0. If a copy of the MPL was not distributed with this
 # file, You can obtain one at http://mozilla.org/MPL/2.0/.
 
+JAR_MANIFESTS += ['jar.mn']
\ No newline at end of file
--- a/services/sync/locales/moz.build
+++ b/services/sync/locales/moz.build
@@ -1,6 +1,7 @@
 # -*- Mode: python; c-basic-offset: 4; indent-tabs-mode: nil; tab-width: 40 -*-
 # vim: set filetype=python:
 # This Source Code Form is subject to the terms of the Mozilla Public
 # License, v. 2.0. If a copy of the MPL was not distributed with this
 # file, You can obtain one at http://mozilla.org/MPL/2.0/.
 
+JAR_MANIFESTS += ['jar.mn']
--- a/testing/marionette/atoms/moz.build
+++ b/testing/marionette/atoms/moz.build
@@ -1,6 +1,7 @@
 # -*- Mode: python; c-basic-offset: 4; indent-tabs-mode: nil; tab-width: 40 -*-
 # vim: set filetype=python:
 # This Source Code Form is subject to the terms of the Mozilla Public
 # License, v. 2.0. If a copy of the MPL was not distributed with this
 # file, You can obtain one at http://mozilla.org/MPL/2.0/.
 
+JAR_MANIFESTS += ['jar.mn']
\ No newline at end of file
--- a/testing/marionette/client/marionette/runner/base.py
+++ b/testing/marionette/client/marionette/runner/base.py
@@ -529,17 +529,17 @@ class BaseMarionetteTestRunner(object):
         self._appName = None
         self.es_servers = es_servers
         self.shuffle = shuffle
         self.sdcard = sdcard
         self.mixin_run_tests = []
 
         if testvars:
             if not os.path.exists(testvars):
-                raise Exception('--testvars file does not exist')
+                raise IOError('--testvars file does not exist')
 
             import json
             with open(testvars) as f:
                 self.testvars = json.loads(f.read())
 
         # set up test handlers
         self.test_handlers = []
 
@@ -811,16 +811,18 @@ class BaseMarionetteTestRunner(object):
                                   self.device,
                                   self.appName))
                 self.todo += 1
 
             target_tests = manifest.get(tests=manifest_tests, **testargs)
             if self.shuffle:
                 random.shuffle(target_tests)
             for i in target_tests:
+                if not os.path.exists(i["path"]):
+                    raise IOError("test file: %s does not exist" % i["path"])
                 self.run_test(i["path"], i["expected"])
                 if self.marionette.check_for_crash():
                     return
             return
 
             self.logger.info('TEST-START %s' % os.path.basename(test))
 
         self.test_kwargs['expected'] = expected
--- a/testing/marionette/marionette-frame-manager.js
+++ b/testing/marionette/marionette-frame-manager.js
@@ -121,17 +121,17 @@ FrameManager.prototype = {
         return;
       }
     }
 
     // If we get here, then we need to load the frame script in this frame, 
     // and set the frame's ChromeMessageSender as the active message manager the server will listen to
     this.addMessageManagerListeners(mm);
     logger.info("frame-manager load script: " + mm.toString());
-    mm.loadFrameScript(FRAME_SCRIPT, true);
+    mm.loadFrameScript(FRAME_SCRIPT, true, true);
     let aFrame = new MarionetteRemoteFrame(message.json.win, message.json.frame);
     aFrame.messageManager = Cu.getWeakReference(mm);
     remoteFrames.push(aFrame);
     this.currentRemoteFrame = aFrame;
   },
 
   /*
    * This function handles switching back to the frame that was interrupted by the modal dialog.
--- a/testing/marionette/marionette-listener.js
+++ b/testing/marionette/marionette-listener.js
@@ -256,17 +256,17 @@ function deleteSession(msg) {
   removeMessageListenerId("Marionette:screenShot", screenShot);
   removeMessageListenerId("Marionette:addCookie", addCookie);
   removeMessageListenerId("Marionette:getAllCookies", getAllCookies);
   removeMessageListenerId("Marionette:deleteAllCookies", deleteAllCookies);
   removeMessageListenerId("Marionette:deleteCookie", deleteCookie);
   if (isB2G) {
     content.removeEventListener("mozbrowsershowmodalprompt", modalHandler, false);
   }
-  this.elementManager.reset();
+  elementManager.reset();
   // reset frame to the top-most frame
   curFrame = content;
   curFrame.focus();
   touchIds = {};
 }
 
 /*
  * Helper methods 
--- a/testing/marionette/marionette-server.js
+++ b/testing/marionette/marionette-server.js
@@ -2492,17 +2492,17 @@ BrowserObj.prototype = {
    * Loads content listeners if we don't already have them
    *
    * @param string script
    *        path of script to load
    * @param nsIDOMWindow frame
    *        frame to load the script in
    */
   loadFrameScript: function BO_loadFrameScript(script, frame) {
-    frame.window.messageManager.loadFrameScript(script, true);
+    frame.window.messageManager.loadFrameScript(script, true, true);
     Services.prefs.setBoolPref("marionette.contentListener", true);
   },
 
   /**
    * Registers a new frame, and sets its current frame id to this frame
    * if it is not already assigned, and if a) we already have a session 
    * or b) we're starting a new session and it is the right start frame.
    *
--- a/testing/marionette/moz.build
+++ b/testing/marionette/moz.build
@@ -3,8 +3,10 @@
 # This Source Code Form is subject to the terms of the Mozilla Public
 # License, v. 2.0. If a copy of the MPL was not distributed with this
 # file, You can obtain one at http://mozilla.org/MPL/2.0/.
 
 DIRS += ['components', 'atoms']
 
 if CONFIG['ENABLE_TESTS']:
     DEFINES['ENABLE_TESTS'] = True
+
+JAR_MANIFESTS += ['jar.mn']
\ No newline at end of file
--- a/testing/mochitest/moz.build
+++ b/testing/mochitest/moz.build
@@ -12,8 +12,10 @@ DIRS += [
     'chrome',
     'ssltunnel',
 ]
 
 if CONFIG['MOZ_BUILD_APP'] == 'mobile/android':
     DIRS += ['roboextender']
 
 XPI_NAME = 'mochijar'
+
+JAR_MANIFESTS += ['jar.mn']
\ No newline at end of file
--- a/testing/specialpowers/content/MozillaLogger.js
+++ b/testing/specialpowers/content/MozillaLogger.js
@@ -111,8 +111,11 @@ MozillaFileLogger.prototype = {
     if(this._foStream)
       this._foStream.close();
   
     this._foStream = null;
     this._file = null;
   }
 };
 
+this.MozillaLogger = MozillaLogger;
+this.SpecialPowersLogger = SpecialPowersLogger;
+this.MozillaFileLogger = MozillaFileLogger;
--- a/testing/specialpowers/content/specialpowers.js
+++ b/testing/specialpowers/content/specialpowers.js
@@ -134,8 +134,11 @@ function SpecialPowersManager() {
 SpecialPowersManager.prototype = {
   handleEvent: function handleEvent(aEvent) {
     var window = aEvent.target.defaultView;
     attachSpecialPowersToWindow(window);
   }
 };
 
 var specialpowersmanager = new SpecialPowersManager();
+
+this.SpecialPowers = SpecialPowers;
+this.attachSpecialPowersToWindow = attachSpecialPowersToWindow;
--- a/testing/specialpowers/content/specialpowersAPI.js
+++ b/testing/specialpowers/content/specialpowersAPI.js
@@ -1646,8 +1646,12 @@ SpecialPowersAPI.prototype = {
     var msg = {
       'op': 'notify',
       'observerTopic': topic,
       'observerData': data
     };
     this._sendSyncMessage('SPObserverService', msg);
   },
 };
+
+this.SpecialPowersAPI = SpecialPowersAPI;
+this.bindDOMWindowUtils = bindDOMWindowUtils;
+this.getRawComponents = getRawComponents;
--- a/testing/specialpowers/moz.build
+++ b/testing/specialpowers/moz.build
@@ -4,8 +4,10 @@
 # License, v. 2.0. If a copy of the MPL was not distributed with this
 # file, You can obtain one at http://mozilla.org/MPL/2.0/.
 
 EXTRA_COMPONENTS += [
     'components/SpecialPowersObserver.js',
 ]
 
 XPI_NAME = 'specialpowers'
+
+JAR_MANIFESTS += ['jar.mn']
\ No newline at end of file
--- a/toolkit/components/aboutmemory/moz.build
+++ b/toolkit/components/aboutmemory/moz.build
@@ -1,7 +1,9 @@
 # -*- Mode: python; c-basic-offset: 4; indent-tabs-mode: nil; tab-width: 40 -*-
 # vim: set filetype=python:
 # This Source Code Form is subject to the terms of the Mozilla Public
 # License, v. 2.0. If a copy of the MPL was not distributed with this
 # file, You can obtain one at http://mozilla.org/MPL/2.0/.
 
 TEST_DIRS += ['tests']
+
+JAR_MANIFESTS += ['jar.mn']
\ No newline at end of file
--- a/toolkit/components/alerts/moz.build
+++ b/toolkit/components/alerts/moz.build
@@ -15,8 +15,10 @@ XPIDL_MODULE = 'alerts'
 UNIFIED_SOURCES += [
     'nsAlertsService.cpp',
     'nsXULAlerts.cpp',
 ]
 
 include('/ipc/chromium/chromium-config.mozbuild')
 
 FINAL_LIBRARY = 'toolkitcomps'
+
+JAR_MANIFESTS += ['jar.mn']
\ No newline at end of file
--- a/toolkit/components/apppicker/moz.build
+++ b/toolkit/components/apppicker/moz.build
@@ -1,6 +1,7 @@
 # -*- Mode: python; c-basic-offset: 4; indent-tabs-mode: nil; tab-width: 40 -*-
 # vim: set filetype=python:
 # This Source Code Form is subject to the terms of the Mozilla Public
 # License, v. 2.0. If a copy of the MPL was not distributed with this
 # file, You can obtain one at http://mozilla.org/MPL/2.0/.
 
+JAR_MANIFESTS += ['jar.mn']
\ No newline at end of file
--- a/toolkit/components/console/moz.build
+++ b/toolkit/components/console/moz.build
@@ -5,8 +5,10 @@
 # file, You can obtain one at http://mozilla.org/MPL/2.0/.
 
 TEST_DIRS += ['tests']
 
 EXTRA_COMPONENTS += [
     'jsconsole-clhandler.js',
     'jsconsole-clhandler.manifest',
 ]
+
+JAR_MANIFESTS += ['jar.mn']
\ No newline at end of file
--- a/toolkit/components/cookie/moz.build
+++ b/toolkit/components/cookie/moz.build
@@ -1,6 +1,7 @@
 # -*- Mode: python; c-basic-offset: 4; indent-tabs-mode: nil; tab-width: 40 -*-
 # vim: set filetype=python:
 # This Source Code Form is subject to the terms of the Mozilla Public
 # License, v. 2.0. If a copy of the MPL was not distributed with this
 # file, You can obtain one at http://mozilla.org/MPL/2.0/.
 
+JAR_MANIFESTS += ['jar.mn']
\ No newline at end of file
--- a/toolkit/components/filepicker/moz.build
+++ b/toolkit/components/filepicker/moz.build
@@ -18,8 +18,10 @@ if CONFIG['MOZ_XUL'] and \
         ]
         EXTRA_PP_COMPONENTS += [
             'nsFilePicker.manifest',
         ]
         DIRS += [
             'test',
         ]
         FINAL_LIBRARY = 'xul'
+
+JAR_MANIFESTS += ['jar.mn']
\ No newline at end of file
--- a/toolkit/components/help/moz.build
+++ b/toolkit/components/help/moz.build
@@ -1,6 +1,7 @@
 # -*- Mode: python; c-basic-offset: 4; indent-tabs-mode: nil; tab-width: 40 -*-
 # vim: set filetype=python:
 # This Source Code Form is subject to the terms of the Mozilla Public
 # License, v. 2.0. If a copy of the MPL was not distributed with this
 # file, You can obtain one at http://mozilla.org/MPL/2.0/.
 
+JAR_MANIFESTS += ['jar.mn']
\ No newline at end of file
--- a/toolkit/components/osfile/modules/osfile_shared_allthreads.jsm
+++ b/toolkit/components/osfile/modules/osfile_shared_allthreads.jsm
@@ -963,17 +963,18 @@ function declareLazyFFI(object, field, .
     get: function() {
       delete this[field];
       let ffi = declareFFI(...declareFFIArgs);
       if (ffi) {
         return this[field] = ffi;
       }
       return undefined;
     },
-    configurable: true
+    configurable: true,
+    enumerable: true
   });
 }
 exports.declareLazyFFI = declareLazyFFI;
 
 /**
  * Define a lazy getter to a js-ctypes function using ctypes method declare.
  *
  * @param {object} The object containing the function as a field.
--- a/toolkit/components/passwordmgr/moz.build
+++ b/toolkit/components/passwordmgr/moz.build
@@ -28,8 +28,10 @@ EXTRA_COMPONENTS += [
 EXTRA_PP_COMPONENTS += [
     'storage-mozStorage.js',
 ]
 
 EXTRA_JS_MODULES += [
     'InsecurePasswordUtils.jsm',
     'LoginManagerContent.jsm',
 ]
+
+JAR_MANIFESTS += ['jar.mn']
\ No newline at end of file
--- a/toolkit/components/printing/moz.build
+++ b/toolkit/components/printing/moz.build
@@ -1,6 +1,7 @@
 # -*- Mode: python; c-basic-offset: 4; indent-tabs-mode: nil; tab-width: 40 -*-
 # vim: set filetype=python:
 # This Source Code Form is subject to the terms of the Mozilla Public
 # License, v. 2.0. If a copy of the MPL was not distributed with this
 # file, You can obtain one at http://mozilla.org/MPL/2.0/.
 
+JAR_MANIFESTS += ['jar.mn']
\ No newline at end of file
--- a/toolkit/components/prompts/moz.build
+++ b/toolkit/components/prompts/moz.build
@@ -1,8 +1,10 @@
 # -*- Mode: python; c-basic-offset: 4; indent-tabs-mode: nil; tab-width: 40 -*-
 # vim: set filetype=python:
 # This Source Code Form is subject to the terms of the Mozilla Public
 # License, v. 2.0. If a copy of the MPL was not distributed with this
 # file, You can obtain one at http://mozilla.org/MPL/2.0/.
 
 DIRS += ['src']
 TEST_DIRS += ['test']
+
+JAR_MANIFESTS += ['jar.mn']
\ No newline at end of file
--- a/toolkit/components/satchel/moz.build
+++ b/toolkit/components/satchel/moz.build
@@ -39,8 +39,10 @@ EXTRA_JS_MODULES += [
     'nsFormAutoCompleteResult.jsm',
 ]
 
 EXTRA_PP_JS_MODULES += [
     'FormHistory.jsm',
 ]
 
 FINAL_LIBRARY = 'xul'
+
+JAR_MANIFESTS += ['jar.mn']
\ No newline at end of file
--- a/toolkit/components/telemetry/Telemetry.cpp
+++ b/toolkit/components/telemetry/Telemetry.cpp
@@ -934,18 +934,18 @@ mCachedTelemetryData(false),
 mLastShutdownTime(0),
 mFailedLockCount(0)
 {
   // A whitelist to prevent Telemetry reporting on Addon & Thunderbird DBs
   const char *trackedDBs[] = {
     "addons.sqlite", "content-prefs.sqlite", "cookies.sqlite",
     "downloads.sqlite", "extensions.sqlite", "formhistory.sqlite",
     "index.sqlite", "healthreport.sqlite", "permissions.sqlite",
-    "places.sqlite", "search.sqlite", "signons.sqlite", "urlclassifier3.sqlite",
-    "webappsstore.sqlite"
+    "places.sqlite", "search.sqlite", "seer.sqlite", "signons.sqlite",
+    "urlclassifier3.sqlite", "webappsstore.sqlite"
   };
 
   for (size_t i = 0; i < ArrayLength(trackedDBs); i++)
     mTrackedDBs.PutEntry(nsDependentCString(trackedDBs[i]));
 
 #ifdef DEBUG
   // Mark immutable to prevent asserts on simultaneous access from multiple threads
   mTrackedDBs.MarkImmutable();
@@ -2178,38 +2178,38 @@ const uint32_t kMaxSlowStatementLength =
 
 void
 TelemetryImpl::RecordSlowStatement(const nsACString &sql,
                                    const nsACString &dbName,
                                    uint32_t delay)
 {
   if (!sTelemetry || !sTelemetry->mCanRecord)
     return;
-  
-  nsAutoCString dbNameComment;
-  dbNameComment.AppendPrintf(" /* %s */", dbName.BeginReading());
-  
+
   bool isFirefoxDB = sTelemetry->mTrackedDBs.Contains(dbName);
   if (isFirefoxDB) {
     nsAutoCString sanitizedSQL(SanitizeSQL(sql));
     if (sanitizedSQL.Length() > kMaxSlowStatementLength) {
       sanitizedSQL.SetLength(kMaxSlowStatementLength);
       sanitizedSQL += "...";
-      sanitizedSQL += dbNameComment;
     }
+    sanitizedSQL.AppendPrintf(" /* %s */", nsPromiseFlatCString(dbName).get());
     StoreSlowSQL(sanitizedSQL, delay, Sanitized);
   } else {
     // Report aggregate DB-level statistics for addon DBs
     nsAutoCString aggregate;
-    aggregate.AppendPrintf("Untracked SQL for %s", dbName.BeginReading());
+    aggregate.AppendPrintf("Untracked SQL for %s",
+                           nsPromiseFlatCString(dbName).get());
     StoreSlowSQL(aggregate, delay, Sanitized);
   }
 
-  nsAutoCString fullSQL(sql);
-  fullSQL += dbNameComment;
+  nsAutoCString fullSQL;
+  fullSQL.AppendPrintf("%s /* %s */",
+                       nsPromiseFlatCString(sql).get(),
+                       nsPromiseFlatCString(dbName).get());
   StoreSlowSQL(fullSQL, delay, Unsanitized);
 }
 
 #if defined(MOZ_ENABLE_PROFILER_SPS)
 void
 TelemetryImpl::RecordChromeHang(uint32_t duration,
                                 Telemetry::ProcessedStack &aStack)
 {
--- a/toolkit/components/thumbnails/moz.build
+++ b/toolkit/components/thumbnails/moz.build
@@ -11,8 +11,10 @@ EXTRA_COMPONENTS += [
     'PageThumbsProtocol.js',
 ]
 
 EXTRA_JS_MODULES += [
     'BackgroundPageThumbs.jsm',
     'PageThumbs.jsm',
     'PageThumbsWorker.js',
 ]
+
+JAR_MANIFESTS += ['jar.mn']
\ No newline at end of file
--- a/toolkit/components/thumbnails/test/thumbnails_crash_content_helper.js
+++ b/toolkit/components/thumbnails/test/thumbnails_crash_content_helper.js
@@ -1,11 +1,13 @@
 /* Any copyright is dedicated to the Public Domain.
 * http://creativecommons.org/publicdomain/zero/1.0/ */
 
+let Cu = Components.utils;
+
 // Ideally we would use CrashTestUtils.jsm, but that's only available for
 // xpcshell tests - so we just copy a ctypes crasher from it.
 Cu.import("resource://gre/modules/ctypes.jsm");
 let crash = function() { // this will crash when called.
   let zero = new ctypes.intptr_t(8);
   let badptr = ctypes.cast(zero, ctypes.PointerType(ctypes.int32_t));
   badptr.contents
 };
--- a/toolkit/components/typeaheadfind/moz.build
+++ b/toolkit/components/typeaheadfind/moz.build
@@ -10,8 +10,10 @@ XPIDL_SOURCES += [
 
 XPIDL_MODULE = 'fastfind'
 
 SOURCES += [
     'nsTypeAheadFind.cpp',
 ]
 
 FINAL_LIBRARY = 'toolkitcomps'
+
+JAR_MANIFESTS += ['jar.mn']
\ No newline at end of file
--- a/toolkit/components/url-classifier/tests/moz.build
+++ b/toolkit/components/url-classifier/tests/moz.build
@@ -2,8 +2,10 @@
 # vim: set filetype=python:
 # This Source Code Form is subject to the terms of the Mozilla Public
 # License, v. 2.0. If a copy of the MPL was not distributed with this
 # file, You can obtain one at http://mozilla.org/MPL/2.0/.
 
 TEST_TOOL_DIRS += ['mochitest']
 
 XPCSHELL_TESTS_MANIFESTS += ['unit/xpcshell.ini']
+
+JAR_MANIFESTS += ['jar.mn']
\ No newline at end of file
--- a/toolkit/components/viewconfig/moz.build
+++ b/toolkit/components/viewconfig/moz.build
@@ -1,6 +1,7 @@
 # -*- Mode: python; c-basic-offset: 4; indent-tabs-mode: nil; tab-width: 40 -*-
 # vim: set filetype=python:
 # This Source Code Form is subject to the terms of the Mozilla Public
 # License, v. 2.0. If a copy of the MPL was not distributed with this
 # file, You can obtain one at http://mozilla.org/MPL/2.0/.
 
+JAR_MANIFESTS += ['jar.mn']
\ No newline at end of file
--- a/toolkit/components/viewsource/moz.build
+++ b/toolkit/components/viewsource/moz.build
@@ -1,7 +1,9 @@
 # -*- Mode: python; c-basic-offset: 4; indent-tabs-mode: nil; tab-width: 40 -*-
 # vim: set filetype=python:
 # This Source Code Form is subject to the terms of the Mozilla Public
 # License, v. 2.0. If a copy of the MPL was not distributed with this
 # file, You can obtain one at http://mozilla.org/MPL/2.0/.
 
 TEST_DIRS += ['test']
+
+JAR_MANIFESTS += ['jar.mn']
\ No newline at end of file
--- a/toolkit/content/moz.build
+++ b/toolkit/content/moz.build
@@ -10,8 +10,10 @@ for var in ('target', 'ac_configure_args
             'CXX', 'CXX_VERSION'):
     DEFINES[var] = CONFIG[var]
 
 if CONFIG['OS_TARGET'] == 'Android':
     DEFINES['ANDROID_PACKAGE_NAME'] = CONFIG['ANDROID_PACKAGE_NAME']
 
 if 'stlport' in CONFIG['STLPORT_LIBS']:
     DEFINES['USE_STLPORT'] = True
+
+JAR_MANIFESTS += ['jar.mn']
\ No newline at end of file
--- a/toolkit/crashreporter/moz.build
+++ b/toolkit/crashreporter/moz.build
@@ -89,8 +89,10 @@ if CONFIG['OS_TARGET'] == 'Android':
     DEFINES['_STLP_NO_MEMBER_TEMPLATES'] = True
 
 if CONFIG['OS_ARCH'] == 'SunOS':
     # there's no define for this normally
     DEFINES['XP_SOLARIS'] = True
 
 DEFINES['UNICODE'] = True
 DEFINES['_UNICODE'] = True
+
+JAR_MANIFESTS += ['jar.mn']
\ No newline at end of file
--- a/toolkit/locales/moz.build
+++ b/toolkit/locales/moz.build
@@ -1,6 +1,7 @@
 # -*- Mode: python; c-basic-offset: 4; indent-tabs-mode: nil; tab-width: 40 -*-
 # vim: set filetype=python:
 # This Source Code Form is subject to the terms of the Mozilla Public
 # License, v. 2.0. If a copy of the MPL was not distributed with this
 # file, You can obtain one at http://mozilla.org/MPL/2.0/.
 
+JAR_MANIFESTS += ['jar.mn']
\ No newline at end of file
--- a/toolkit/mozapps/downloads/moz.build
+++ b/toolkit/mozapps/downloads/moz.build
@@ -19,8 +19,9 @@ EXTRA_JS_MODULES += [
     'DownloadPaths.jsm',
     'DownloadUtils.jsm',
 ]
 
 EXTRA_PP_JS_MODULES += [
     'DownloadTaskbarProgress.jsm',
 ]
 
+JAR_MANIFESTS += ['jar.mn']
\ No newline at end of file
--- a/toolkit/mozapps/extensions/addonManager.js
+++ b/toolkit/mozapps/extensions/addonManager.js
@@ -39,17 +39,17 @@ var gSingleton = null;
 function amManager() {
   Components.utils.import("resource://gre/modules/AddonManager.jsm");
 
   var messageManager = Cc["@mozilla.org/globalmessagemanager;1"].
                        getService(Ci.nsIMessageListenerManager);
 
   messageManager.addMessageListener(MSG_INSTALL_ENABLED, this);
   messageManager.addMessageListener(MSG_INSTALL_ADDONS, this);
-  messageManager.loadFrameScript(CHILD_SCRIPT, true, true);
+  messageManager.loadFrameScript(CHILD_SCRIPT, true);
 }
 
 amManager.prototype = {
   observe: function AMC_observe(aSubject, aTopic, aData) {
     if (aTopic == "addons-startup")
       AddonManagerPrivate.startup();
   },
 
--- a/toolkit/mozapps/extensions/moz.build
+++ b/toolkit/mozapps/extensions/moz.build
@@ -50,8 +50,10 @@ if CONFIG['MOZ_UPDATE_CHANNEL'] not in (
 
 # This is used in multiple places, so is defined here to avoid it getting
 # out of sync.
 DEFINES['MOZ_EXTENSIONS_DB_SCHEMA'] = 15
 
 # Additional debugging info is exposed in debug builds
 if CONFIG['MOZ_DEBUG']:
     DEFINES['MOZ_EM_DEBUG'] = 1
+
+JAR_MANIFESTS += ['jar.mn']
\ No newline at end of file
--- a/toolkit/mozapps/handling/moz.build
+++ b/toolkit/mozapps/handling/moz.build
@@ -3,8 +3,10 @@
 # This Source Code Form is subject to the terms of the Mozilla Public
 # License, v. 2.0. If a copy of the MPL was not distributed with this
 # file, You can obtain one at http://mozilla.org/MPL/2.0/.
 
 EXTRA_COMPONENTS += [
     'nsContentDispatchChooser.js',
     'nsContentDispatchChooser.manifest',
 ]
+
+JAR_MANIFESTS += ['jar.mn']
\ No newline at end of file
--- a/toolkit/mozapps/plugins/moz.build
+++ b/toolkit/mozapps/plugins/moz.build
@@ -4,8 +4,10 @@
 # License, v. 2.0. If a copy of the MPL was not distributed with this
 # file, You can obtain one at http://mozilla.org/MPL/2.0/.
 
 TEST_DIRS += ['tests']
 
 EXTRA_COMPONENTS += [
     'pluginGlue.manifest',
 ]
+
+JAR_MANIFESTS += ['jar.mn']
\ No newline at end of file
--- a/toolkit/mozapps/preferences/moz.build
+++ b/toolkit/mozapps/preferences/moz.build
@@ -1,6 +1,7 @@
 # -*- Mode: python; c-basic-offset: 4; indent-tabs-mode: nil; tab-width: 40 -*-
 # vim: set filetype=python:
 # This Source Code Form is subject to the terms of the Mozilla Public
 # License, v. 2.0. If a copy of the MPL was not distributed with this
 # file, You can obtain one at http://mozilla.org/MPL/2.0/.
 
+JAR_MANIFESTS += ['jar.mn']
\ No newline at end of file
--- a/toolkit/mozapps/update/moz.build
+++ b/toolkit/mozapps/update/moz.build
@@ -40,8 +40,10 @@ if CONFIG['MOZ_UPDATER']:
     EXTRA_COMPONENTS += [
         'nsUpdateService.manifest',
     ]
 
     EXTRA_PP_COMPONENTS += [
         'nsUpdateService.js',
         'nsUpdateServiceStub.js',
     ]
+
+JAR_MANIFESTS += ['jar.mn']
\ No newline at end of file
--- a/toolkit/obsolete/moz.build
+++ b/toolkit/obsolete/moz.build
@@ -1,6 +1,7 @@
 # -*- Mode: python; c-basic-offset: 4; indent-tabs-mode: nil; tab-width: 40 -*-
 # vim: set filetype=python:
 # This Source Code Form is subject to the terms of the Mozilla Public
 # License, v. 2.0. If a copy of the MPL was not distributed with this
 # file, You can obtain one at http://mozilla.org/MPL/2.0/.
 
+JAR_MANIFESTS += ['jar.mn']
\ No newline at end of file
--- a/toolkit/profile/moz.build
+++ b/toolkit/profile/moz.build
@@ -23,8 +23,10 @@ UNIFIED_SOURCES += [
 LOCAL_INCLUDES += [
     '../xre',
     '/profile/dirserviceprovider/src',
 ]
 
 FAIL_ON_WARNINGS = True
 
 FINAL_LIBRARY = 'xulapp_s'
+
+JAR_MANIFESTS += ['jar.mn']
\ No newline at end of file
--- a/toolkit/themes/faststripe/global/moz.build
+++ b/toolkit/themes/faststripe/global/moz.build
@@ -1,6 +1,7 @@
 # -*- Mode: python; c-basic-offset: 4; indent-tabs-mode: nil; tab-width: 40 -*-
 # vim: set filetype=python:
 # This Source Code Form is subject to the terms of the Mozilla Public
 # License, v. 2.0. If a copy of the MPL was not distributed with this
 # file, You can obtain one at http://mozilla.org/MPL/2.0/.
 
+JAR_MANIFESTS += ['jar.mn']
\ No newline at end of file
--- a/toolkit/themes/linux/global/moz.build
+++ b/toolkit/themes/linux/global/moz.build
@@ -1,6 +1,7 @@
 # -*- Mode: python; c-basic-offset: 4; indent-tabs-mode: nil; tab-width: 40 -*-
 # vim: set filetype=python:
 # This Source Code Form is subject to the terms of the Mozilla Public
 # License, v. 2.0. If a copy of the MPL was not distributed with this
 # file, You can obtain one at http://mozilla.org/MPL/2.0/.
 
+JAR_MANIFESTS += ['jar.mn']
\ No newline at end of file
--- a/toolkit/themes/linux/help/moz.build
+++ b/toolkit/themes/linux/help/moz.build
@@ -1,6 +1,7 @@
 # -*- Mode: python; c-basic-offset: 4; indent-tabs-mode: nil; tab-width: 40 -*-
 # vim: set filetype=python:
 # This Source Code Form is subject to the terms of the Mozilla Public
 # License, v. 2.0. If a copy of the MPL was not distributed with this
 # file, You can obtain one at http://mozilla.org/MPL/2.0/.
 
+JAR_MANIFESTS += ['jar.mn']
\ No newline at end of file
--- a/toolkit/themes/linux/mozapps/moz.build
+++ b/toolkit/themes/linux/mozapps/moz.build
@@ -1,6 +1,7 @@
 # -*- Mode: python; c-basic-offset: 4; indent-tabs-mode: nil; tab-width: 40 -*-
 # vim: set filetype=python:
 # This Source Code Form is subject to the terms of the Mozilla Public
 # License, v. 2.0. If a copy of the MPL was not distributed with this
 # file, You can obtain one at http://mozilla.org/MPL/2.0/.
 
+JAR_MANIFESTS += ['jar.mn']
\ No newline at end of file
--- a/toolkit/themes/os2/global/moz.build
+++ b/toolkit/themes/os2/global/moz.build
@@ -1,6 +1,7 @@
 # -*- Mode: python; c-basic-offset: 4; indent-tabs-mode: nil; tab-width: 40 -*-
 # vim: set filetype=python:
 # This Source Code Form is subject to the terms of the Mozilla Public
 # License, v. 2.0. If a copy of the MPL was not distributed with this
 # file, You can obtain one at http://mozilla.org/MPL/2.0/.
 
+JAR_MANIFESTS += ['jar.mn']
\ No newline at end of file
--- a/toolkit/themes/osx/global/moz.build
+++ b/toolkit/themes/osx/global/moz.build
@@ -1,6 +1,7 @@
 # -*- Mode: python; c-basic-offset: 4; indent-tabs-mode: nil; tab-width: 40 -*-
 # vim: set filetype=python:
 # This Source Code Form is subject to the terms of the Mozilla Public
 # License, v. 2.0. If a copy of the MPL was not distributed with this
 # file, You can obtain one at http://mozilla.org/MPL/2.0/.
 
+JAR_MANIFESTS += ['jar.mn']
\ No newline at end of file
--- a/toolkit/themes/osx/help/moz.build
+++ b/toolkit/themes/osx/help/moz.build
@@ -1,6 +1,7 @@
 # -*- Mode: python; c-basic-offset: 4; indent-tabs-mode: nil; tab-width: 40 -*-
 # vim: set filetype=python:
 # This Source Code Form is subject to the terms of the Mozilla Public
 # License, v. 2.0. If a copy of the MPL was not distributed with this
 # file, You can obtain one at http://mozilla.org/MPL/2.0/.
 
+JAR_MANIFESTS += ['jar.mn']
\ No newline at end of file
--- a/toolkit/themes/osx/mozapps/moz.build
+++ b/toolkit/themes/osx/mozapps/moz.build
@@ -1,6 +1,7 @@
 # -*- Mode: python; c-basic-offset: 4; indent-tabs-mode: nil; tab-width: 40 -*-
 # vim: set filetype=python:
 # This Source Code Form is subject to the terms of the Mozilla Public
 # License, v. 2.0. If a copy of the MPL was not distributed with this
 # file, You can obtain one at http://mozilla.org/MPL/2.0/.
 
+JAR_MANIFESTS += ['jar.mn']
\ No newline at end of file
--- a/toolkit/themes/windows/global/moz.build
+++ b/toolkit/themes/windows/global/moz.build
@@ -1,6 +1,7 @@
 # -*- Mode: python; c-basic-offset: 4; indent-tabs-mode: nil; tab-width: 40 -*-
 # vim: set filetype=python:
 # This Source Code Form is subject to the terms of the Mozilla Public
 # License, v. 2.0. If a copy of the MPL was not distributed with this
 # file, You can obtain one at http://mozilla.org/MPL/2.0/.
 
+JAR_MANIFESTS += ['jar.mn']
\ No newline at end of file
--- a/toolkit/themes/windows/help/moz.build
+++ b/toolkit/themes/windows/help/moz.build
@@ -1,6 +1,7 @@
 # -*- Mode: python; c-basic-offset: 4; indent-tabs-mode: nil; tab-width: 40 -*-
 # vim: set filetype=python:
 # This Source Code Form is subject to the terms of the Mozilla Public
 # License, v. 2.0. If a copy of the MPL was not distributed with this
 # file, You can obtain one at http://mozilla.org/MPL/2.0/.
 
+JAR_MANIFESTS += ['jar.mn']
\ No newline at end of file
--- a/toolkit/themes/windows/mozapps/moz.build
+++ b/toolkit/themes/windows/mozapps/moz.build
@@ -1,6 +1,7 @@
 # -*- Mode: python; c-basic-offset: 4; indent-tabs-mode: nil; tab-width: 40 -*-
 # vim: set filetype=python:
 # This Source Code Form is subject to the terms of the Mozilla Public
 # License, v. 2.0. If a copy of the MPL was not distributed with this
 # file, You can obtain one at http://mozilla.org/MPL/2.0/.
 
+JAR_MANIFESTS += ['jar.mn']
\ No newline at end of file
--- a/tools/quitter/moz.build
+++ b/tools/quitter/moz.build
@@ -4,8 +4,10 @@
 # License, v. 2.0. If a copy of the MPL was not distributed with this
 # file, You can obtain one at http://mozilla.org/MPL/2.0/.
 
 EXTRA_COMPONENTS += [
     'QuitterObserver.js',
 ]
 
 XPI_NAME = 'quitter'
+
+JAR_MANIFESTS += ['jar.mn']
\ No newline at end of file
--- a/webapprt/locales/moz.build
+++ b/webapprt/locales/moz.build
@@ -1,4 +1,6 @@
 # vim: set filetype=python:
 # This Source Code Form is subject to the terms of the Mozilla Public
 # License, v. 2.0. If a copy of the MPL was not distributed with this
 # file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+JAR_MANIFESTS += ['jar.mn']
\ No newline at end of file
--- a/webapprt/moz.build
+++ b/webapprt/moz.build
@@ -39,8 +39,10 @@ export('DIST_SUBDIR')
 if CONFIG['MOZ_DEBUG']:
     DEFINES['MOZ_DEBUG'] = 1
 
 if CONFIG['MOZILLA_OFFICIAL']:
     DEFINES['MOZILLA_OFFICIAL'] = True
 
 DEFINES['GRE_MILESTONE'] = CONFIG['GRE_MILESTONE']
 DEFINES['MOZ_APP_BASENAME'] = CONFIG['MOZ_APP_BASENAME']
+
+JAR_MANIFESTS += ['jar.mn']
\ No newline at end of file
--- a/xpfe/components/autocomplete/moz.build
+++ b/xpfe/components/autocomplete/moz.build
@@ -1,5 +1,7 @@
 # -*- Mode: python; c-basic-offset: 4; indent-tabs-mode: nil; tab-width: 40 -*-
 # vim: set filetype=python:
 # This Source Code Form is subject to the terms of the Mozilla Public
 # License, v. 2.0. If a copy of the MPL was not distributed with this
 # file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+JAR_MANIFESTS += ['jar.mn']
\ No newline at end of file
--- a/xulrunner/examples/simple/moz.build
+++ b/xulrunner/examples/simple/moz.build
@@ -2,8 +2,10 @@
 # vim: set filetype=python:
 # This Source Code Form is subject to the terms of the Mozilla Public
 # License, v. 2.0. If a copy of the MPL was not distributed with this
 # file, You can obtain one at http://mozilla.org/MPL/2.0/.
 
 DIRS += ['components']
 
 XPI_NAME = 'simple'
+
+JAR_MANIFESTS += ['jar.mn']
\ No newline at end of file