Merge mozilla-central to autoland
authorCarsten "Tomcat" Book <cbook@mozilla.com>
Fri, 13 Jan 2017 10:24:01 +0100
changeset 374276 6033d916b268c2c22cf6a0d69e611ada2d073d1f
parent 374275 b8970b27c10e6bc068724959a454f713afbe5fbc (current diff)
parent 374253 91f5293e9a89056565493ed5073c3842b0ee9fdc (diff)
child 374277 997b7726f2e4cc93a4234b533ffa8a482cbea157
push id6996
push userjlorenzo@mozilla.com
push dateMon, 06 Mar 2017 20:48:21 +0000
treeherdermozilla-beta@d89512dab048 [default view] [failures only]
perfherder[talos] [build metrics] [platform microbench] (compared to previous push)
milestone53.0a1
first release with
nightly linux32
nightly linux64
nightly mac
nightly win32
nightly win64
last release without
nightly linux32
nightly linux64
nightly mac
nightly win32
nightly win64
Merge mozilla-central to autoland
browser/extensions/pocket/content/panels/img/signup_or@1x.png
browser/extensions/pocket/content/panels/img/signup_or@2x.png
browser/themes/shared/newtab/whimsycorn.png
browser/themes/shared/social/gear_clicked.png
browser/themes/shared/social/gear_default.png
browser/themes/windows/keyhole-forward-mask.svg
embedding/browser/build/moz.build
embedding/browser/build/nsWebBrowserModule.cpp
embedding/browser/moz.build
embedding/browser/nsCTooltipTextProvider.h
embedding/browser/nsCWebBrowser.idl
embedding/browser/nsCommandHandler.cpp
embedding/browser/nsCommandHandler.h
embedding/browser/nsContextMenuInfo.cpp
embedding/browser/nsContextMenuInfo.h
embedding/browser/nsDocShellTreeOwner.cpp
embedding/browser/nsDocShellTreeOwner.h
embedding/browser/nsEmbedStream.cpp
embedding/browser/nsEmbedStream.h
embedding/browser/nsICommandHandler.idl
embedding/browser/nsIContextMenuListener.idl
embedding/browser/nsIContextMenuListener2.idl
embedding/browser/nsIEmbeddingSiteWindow.idl
embedding/browser/nsIPrintPreviewNavigation.idl
embedding/browser/nsIPrintingPromptService.idl
embedding/browser/nsITooltipListener.idl
embedding/browser/nsITooltipTextProvider.idl
embedding/browser/nsIWebBrowser.idl
embedding/browser/nsIWebBrowserChrome.idl
embedding/browser/nsIWebBrowserChrome2.idl
embedding/browser/nsIWebBrowserChrome3.idl
embedding/browser/nsIWebBrowserChromeFocus.idl
embedding/browser/nsIWebBrowserFocus.idl
embedding/browser/nsIWebBrowserPrint.idl
embedding/browser/nsIWebBrowserSetup.idl
embedding/browser/nsIWebBrowserStream.idl
embedding/browser/nsWebBrowser.cpp
embedding/browser/nsWebBrowser.h
embedding/browser/nsWebBrowserContentPolicy.cpp
embedding/browser/nsWebBrowserContentPolicy.h
embedding/components/appstartup/moz.build
embedding/components/appstartup/nsAppStartupNotifier.cpp
embedding/components/appstartup/nsAppStartupNotifier.h
embedding/components/appstartup/nsIAppStartupNotifier.h
embedding/components/build/moz.build
embedding/components/build/nsEmbeddingModule.cpp
embedding/components/commandhandler/moz.build
embedding/components/commandhandler/nsBaseCommandController.cpp
embedding/components/commandhandler/nsBaseCommandController.h
embedding/components/commandhandler/nsCommandGroup.cpp
embedding/components/commandhandler/nsCommandGroup.h
embedding/components/commandhandler/nsCommandManager.cpp
embedding/components/commandhandler/nsCommandManager.h
embedding/components/commandhandler/nsCommandParams.cpp
embedding/components/commandhandler/nsCommandParams.h
embedding/components/commandhandler/nsControllerCommandTable.cpp
embedding/components/commandhandler/nsControllerCommandTable.h
embedding/components/commandhandler/nsICommandManager.idl
embedding/components/commandhandler/nsICommandParams.idl
embedding/components/commandhandler/nsIControllerCommand.idl
embedding/components/commandhandler/nsIControllerCommandTable.idl
embedding/components/commandhandler/nsIControllerContext.idl
embedding/components/commandhandler/nsPICommandUpdater.idl
embedding/components/find/moz.build
embedding/components/find/nsFind.cpp
embedding/components/find/nsFind.h
embedding/components/find/nsIFind.idl
embedding/components/find/nsIWebBrowserFind.idl
embedding/components/find/nsWebBrowserFind.cpp
embedding/components/find/nsWebBrowserFind.h
embedding/components/moz.build
embedding/components/printingui/ipc/PPrintProgressDialog.ipdl
embedding/components/printingui/ipc/PPrintSettingsDialog.ipdl
embedding/components/printingui/ipc/PPrinting.ipdl
embedding/components/printingui/ipc/PPrintingTypes.ipdlh
embedding/components/printingui/ipc/PrintDataUtils.cpp
embedding/components/printingui/ipc/PrintDataUtils.h
embedding/components/printingui/ipc/PrintProgressDialogChild.cpp
embedding/components/printingui/ipc/PrintProgressDialogChild.h
embedding/components/printingui/ipc/PrintProgressDialogParent.cpp
embedding/components/printingui/ipc/PrintProgressDialogParent.h
embedding/components/printingui/ipc/PrintSettingsDialogChild.cpp
embedding/components/printingui/ipc/PrintSettingsDialogChild.h
embedding/components/printingui/ipc/PrintSettingsDialogParent.cpp
embedding/components/printingui/ipc/PrintSettingsDialogParent.h
embedding/components/printingui/ipc/PrintingParent.cpp
embedding/components/printingui/ipc/PrintingParent.h
embedding/components/printingui/ipc/moz.build
embedding/components/printingui/ipc/nsPrintingProxy.cpp
embedding/components/printingui/ipc/nsPrintingProxy.h
embedding/components/printingui/mac/moz.build
embedding/components/printingui/mac/nsPrintProgress.cpp
embedding/components/printingui/mac/nsPrintProgress.h
embedding/components/printingui/mac/nsPrintProgressParams.cpp
embedding/components/printingui/mac/nsPrintProgressParams.h
embedding/components/printingui/mac/nsPrintingPromptService.h
embedding/components/printingui/mac/nsPrintingPromptServiceX.mm
embedding/components/printingui/moz.build
embedding/components/printingui/unixshared/moz.build
embedding/components/printingui/unixshared/nsPrintProgress.cpp
embedding/components/printingui/unixshared/nsPrintProgress.h
embedding/components/printingui/unixshared/nsPrintProgressParams.cpp
embedding/components/printingui/unixshared/nsPrintProgressParams.h
embedding/components/printingui/unixshared/nsPrintingPromptService.cpp
embedding/components/printingui/unixshared/nsPrintingPromptService.h
embedding/components/printingui/win/moz.build
embedding/components/printingui/win/nsPrintDialogUtil.cpp
embedding/components/printingui/win/nsPrintDialogUtil.h
embedding/components/printingui/win/nsPrintProgress.cpp
embedding/components/printingui/win/nsPrintProgress.h
embedding/components/printingui/win/nsPrintProgressParams.cpp
embedding/components/printingui/win/nsPrintProgressParams.h
embedding/components/printingui/win/nsPrintingPromptService.cpp
embedding/components/printingui/win/nsPrintingPromptService.h
embedding/components/webbrowserpersist/PWebBrowserPersistDocument.ipdl
embedding/components/webbrowserpersist/PWebBrowserPersistResources.ipdl
embedding/components/webbrowserpersist/PWebBrowserPersistSerialize.ipdl
embedding/components/webbrowserpersist/WebBrowserPersistDocumentChild.cpp
embedding/components/webbrowserpersist/WebBrowserPersistDocumentChild.h
embedding/components/webbrowserpersist/WebBrowserPersistDocumentParent.cpp
embedding/components/webbrowserpersist/WebBrowserPersistDocumentParent.h
embedding/components/webbrowserpersist/WebBrowserPersistLocalDocument.cpp
embedding/components/webbrowserpersist/WebBrowserPersistLocalDocument.h
embedding/components/webbrowserpersist/WebBrowserPersistRemoteDocument.cpp
embedding/components/webbrowserpersist/WebBrowserPersistRemoteDocument.h
embedding/components/webbrowserpersist/WebBrowserPersistResourcesChild.cpp
embedding/components/webbrowserpersist/WebBrowserPersistResourcesChild.h
embedding/components/webbrowserpersist/WebBrowserPersistResourcesParent.cpp
embedding/components/webbrowserpersist/WebBrowserPersistResourcesParent.h
embedding/components/webbrowserpersist/WebBrowserPersistSerializeChild.cpp
embedding/components/webbrowserpersist/WebBrowserPersistSerializeChild.h
embedding/components/webbrowserpersist/WebBrowserPersistSerializeParent.cpp
embedding/components/webbrowserpersist/WebBrowserPersistSerializeParent.h
embedding/components/webbrowserpersist/moz.build
embedding/components/webbrowserpersist/nsCWebBrowserPersist.idl
embedding/components/webbrowserpersist/nsIWebBrowserPersist.idl
embedding/components/webbrowserpersist/nsIWebBrowserPersistDocument.idl
embedding/components/webbrowserpersist/nsIWebBrowserPersistable.idl
embedding/components/webbrowserpersist/nsWebBrowserPersist.cpp
embedding/components/webbrowserpersist/nsWebBrowserPersist.h
embedding/components/windowwatcher/moz.build
embedding/components/windowwatcher/nsAutoWindowStateHelper.cpp
embedding/components/windowwatcher/nsAutoWindowStateHelper.h
embedding/components/windowwatcher/nsDialogParamBlock.cpp
embedding/components/windowwatcher/nsDialogParamBlock.h
embedding/components/windowwatcher/nsIDialogParamBlock.idl
embedding/components/windowwatcher/nsIPromptFactory.idl
embedding/components/windowwatcher/nsIPromptService.idl
embedding/components/windowwatcher/nsIPromptService2.idl
embedding/components/windowwatcher/nsIWindowWatcher.idl
embedding/components/windowwatcher/nsPIPromptService.idl
embedding/components/windowwatcher/nsPIWindowWatcher.idl
embedding/components/windowwatcher/nsPromptUtils.h
embedding/components/windowwatcher/nsWindowWatcher.cpp
embedding/components/windowwatcher/nsWindowWatcher.h
embedding/components/windowwatcher/test/browser.ini
embedding/components/windowwatcher/test/browser_new_content_window_chromeflags.js
embedding/components/windowwatcher/test/browser_new_content_window_from_chrome_principal.js
embedding/components/windowwatcher/test/browser_new_remote_window_flags.js
embedding/components/windowwatcher/test/browser_new_sized_window.js
embedding/components/windowwatcher/test/chrome.ini
embedding/components/windowwatcher/test/file_storage_copied.html
embedding/components/windowwatcher/test/file_test_dialog.html
embedding/components/windowwatcher/test/mochitest.ini
embedding/components/windowwatcher/test/moz.build
embedding/components/windowwatcher/test/test_blank_named_window.html
embedding/components/windowwatcher/test/test_dialog_arguments.html
embedding/components/windowwatcher/test/test_modal_windows.html
embedding/components/windowwatcher/test/test_named_window.html
embedding/components/windowwatcher/test/test_storage_copied.html
embedding/moz.build
embedding/nsEmbedCID.h
embedding/nsIWindowCreator.idl
embedding/nsIWindowCreator2.idl
embedding/nsIWindowProvider.idl
embedding/test/320x240.ogv
embedding/test/browser.ini
embedding/test/browser_bug1204626.js
embedding/test/bug1170334_iframe.xml
embedding/test/bug1170334_style.css
embedding/test/bug1204626_doc0.html
embedding/test/bug1204626_doc1.html
embedding/test/bug293834_form.html
embedding/test/bug449141_page.html
embedding/test/chrome.ini
embedding/test/mochitest.ini
embedding/test/moz.build
embedding/test/test_bug1170334_wbp_xmlstyle.html
embedding/test/test_bug1192654.html
embedding/test/test_bug293834.html
embedding/test/test_bug449141.html
embedding/test/test_bug499115.html
embedding/test/test_nsFind.html
embedding/test/test_private_window_from_content.html
embedding/test/test_window_open_position_constraint.html
embedding/test/test_window_open_units.html
embedding/tests/unit/test_wwauthpromptfactory.js
embedding/tests/unit/test_wwpromptfactory.js
embedding/tests/unit/xpcshell.ini
--- a/b2g/installer/package-manifest.in
+++ b/b2g/installer/package-manifest.in
@@ -194,26 +194,24 @@
 @RESPATH@/components/dom_xbl.xpt
 @RESPATH@/components/dom_xhr.xpt
 @RESPATH@/components/dom_xpath.xpt
 @RESPATH@/components/dom_xul.xpt
 @RESPATH@/components/dom_time.xpt
 @RESPATH@/components/dom_presentation.xpt
 @RESPATH@/components/downloads.xpt
 @RESPATH@/components/editor.xpt
-@RESPATH@/components/embed_base.xpt
 @RESPATH@/components/extensions.xpt
 @RESPATH@/components/exthandler.xpt
 @RESPATH@/components/exthelper.xpt
 @RESPATH@/components/fastfind.xpt
 @RESPATH@/components/feeds.xpt
 #ifdef MOZ_GTK
 @RESPATH@/components/filepicker.xpt
 #endif
-@RESPATH@/components/find.xpt
 @RESPATH@/components/gfx.xpt
 @RESPATH@/components/gaia_chrome.xpt
 @RESPATH@/components/hal.xpt
 @RESPATH@/components/html5.xpt
 @RESPATH@/components/htmlparser.xpt
 @RESPATH@/components/identity.xpt
 @RESPATH@/components/imglib2.xpt
 @RESPATH@/components/inspector.xpt
@@ -304,16 +302,17 @@
 @RESPATH@/components/webshell_idls.xpt
 @RESPATH@/components/widget.xpt
 #ifdef XP_MACOSX
 @RESPATH@/components/widget_cocoa.xpt
 #endif
 #ifdef ANDROID
 @RESPATH@/components/widget_android.xpt
 #endif
+@RESPATH@/components/windowcreator.xpt
 @RESPATH@/components/windowds.xpt
 @RESPATH@/components/windowwatcher.xpt
 @RESPATH@/components/xpcom_base.xpt
 @RESPATH@/components/xpcom_system.xpt
 @RESPATH@/components/xpcom_components.xpt
 @RESPATH@/components/xpcom_ds.xpt
 @RESPATH@/components/xpcom_io.xpt
 @RESPATH@/components/xpcom_threads.xpt
--- a/browser/base/content/tabbrowser.xml
+++ b/browser/base/content/tabbrowser.xml
@@ -2177,16 +2177,23 @@
               // This can go away when bug 672618 or bug 55696 are fixed.
               t.setAttribute("label", aURI);
             }
 
             if (aIsPrerendered) {
               t.setAttribute("hidden", "true");
             }
 
+            // Related tab inherits current tab's user context unless a different
+            // usercontextid is specified
+            if (aUserContextId == null &&
+                (aRelatedToCurrent == null ? aReferrerURI : aRelatedToCurrent)) {
+              aUserContextId = this.mCurrentTab.getAttribute("usercontextid") || 0;
+            }
+
             if (aUserContextId) {
               t.setAttribute("usercontextid", aUserContextId);
               ContextualIdentityService.setTabStyle(t);
             }
 
             t.setAttribute("onerror", "this.removeAttribute('image');");
             t.className = "tabbrowser-tab";
 
--- a/browser/components/contextualidentity/test/browser/browser.ini
+++ b/browser/components/contextualidentity/test/browser/browser.ini
@@ -23,8 +23,9 @@ tags = openwindow
 [browser_windowOpen.js]
 tags = openwindow
 [browser_serviceworkers.js]
 [browser_broadcastchannel.js]
 [browser_blobUrl.js]
 [browser_middleClick.js]
 [browser_imageCache.js]
 [browser_count_and_remove.js]
+[browser_relatedTab.js]
new file mode 100644
--- /dev/null
+++ b/browser/components/contextualidentity/test/browser/browser_relatedTab.js
@@ -0,0 +1,31 @@
+"use strict";
+
+/*
+ * Bug 1325014 - Adding tab related to current tab inherits current tab's container usercontextid unless otherwise specified
+ */
+
+add_task(function* () {
+  let tab = gBrowser.addTab("about:blank", {userContextId: 1});
+
+  gBrowser.selectedTab = tab;
+  let relatedTab = gBrowser.addTab("about:blank", {relatedToCurrent: true});
+  is(relatedTab.getAttribute('usercontextid'), 1, "Related tab (relatedToCurrent) inherits current tab's usercontextid");
+  yield BrowserTestUtils.removeTab(relatedTab);
+
+  gBrowser.selectedTab = tab;
+  relatedTab = gBrowser.addTab("about:blank", {relatedToCurrent: true, userContextId: 2});
+  is(relatedTab.getAttribute('usercontextid'), 2, "Related tab (relatedToCurrent) with overridden usercontextid");
+  yield BrowserTestUtils.removeTab(relatedTab);
+
+  gBrowser.selectedTab = tab;
+  relatedTab = gBrowser.addTab("about:blank", {referrerURI: gBrowser.currentURI});
+  is(relatedTab.getAttribute('usercontextid'), 1, "Related tab (referrer) inherits current tab's usercontextid");
+  yield BrowserTestUtils.removeTab(relatedTab);
+
+  gBrowser.selectedTab = tab;
+  relatedTab = gBrowser.addTab("about:blank", {referrerURI: gBrowser.currentURI, userContextId: 2});
+  is(relatedTab.getAttribute('usercontextid'), 2, "Related tab (referrer) with overridden usercontextid");
+  yield BrowserTestUtils.removeTab(relatedTab);
+
+  yield BrowserTestUtils.removeTab(tab);
+});
--- a/browser/extensions/pdfjs/README.mozilla
+++ b/browser/extensions/pdfjs/README.mozilla
@@ -1,3 +1,3 @@
 This is the pdf.js project output, https://github.com/mozilla/pdf.js
 
-Current extension version is: 1.6.418
+Current extension version is: 1.6.454
--- a/browser/extensions/pdfjs/content/PdfJs.jsm
+++ b/browser/extensions/pdfjs/content/PdfJs.jsm
@@ -192,21 +192,21 @@ var PdfJs = {
       this._ensureRegistered();
     } else {
       this._ensureUnregistered();
     }
   },
 
   uninit: function uninit() {
     if (this._initialized) {
-      Services.prefs.removeObserver(PREF_DISABLED, this);
-      Services.prefs.removeObserver(PREF_DISABLED_PLUGIN_TYPES, this);
-      Services.obs.removeObserver(this, TOPIC_PDFJS_HANDLER_CHANGED);
-      Services.obs.removeObserver(this, TOPIC_PLUGINS_LIST_UPDATED);
-      Services.obs.removeObserver(this, TOPIC_PLUGIN_INFO_UPDATED);
+      Services.prefs.removeObserver(PREF_DISABLED, this, false);
+      Services.prefs.removeObserver(PREF_DISABLED_PLUGIN_TYPES, this, false);
+      Services.obs.removeObserver(this, TOPIC_PDFJS_HANDLER_CHANGED, false);
+      Services.obs.removeObserver(this, TOPIC_PLUGINS_LIST_UPDATED, false);
+      Services.obs.removeObserver(this, TOPIC_PLUGIN_INFO_UPDATED, false);
       this._initialized = false;
     }
     this._ensureUnregistered();
   },
 
   _migrate: function migrate() {
     const VERSION = 2;
     var currentVersion = getIntPref(PREF_MIGRATION_VERSION, 0);
--- a/browser/extensions/pdfjs/content/PdfStreamConverter.jsm
+++ b/browser/extensions/pdfjs/content/PdfStreamConverter.jsm
@@ -142,31 +142,16 @@ function getLocalizedStrings(path) {
 function getLocalizedString(strings, id, property) {
   property = property || 'textContent';
   if (id in strings) {
     return strings[id][property];
   }
   return id;
 }
 
-function createNewChannel(uri, node) {
-  return NetUtil.newChannel({
-    uri: uri,
-    loadUsingSystemPrincipal: true,
-  });
-}
-
-function asyncOpenChannel(channel, listener, context) {
-  return channel.asyncOpen2(listener);
-}
-
-function asyncFetchChannel(channel, callback) {
-  return NetUtil.asyncFetch(channel, callback);
-}
-
 // PDF data storage
 function PdfDataListener(length) {
   this.length = length; // less than 0, if length is unknown
   this.buffer = null;
   this.loaded = 0;
 }
 
 PdfDataListener.prototype = {
@@ -250,22 +235,25 @@ ChromeActions.prototype = {
       filename = 'document.pdf';
     }
     var blobUri = NetUtil.newURI(blobUrl);
     var extHelperAppSvc =
           Cc['@mozilla.org/uriloader/external-helper-app-service;1'].
              getService(Ci.nsIExternalHelperAppService);
 
     var docIsPrivate = this.isInPrivateBrowsing();
-    var netChannel = createNewChannel(blobUri, this.domWindow.document);
+    var netChannel = NetUtil.newChannel({
+      uri: blobUri,
+      loadUsingSystemPrincipal: true,
+    });
     if ('nsIPrivateBrowsingChannel' in Ci &&
         netChannel instanceof Ci.nsIPrivateBrowsingChannel) {
       netChannel.setPrivate(docIsPrivate);
     }
-    asyncFetchChannel(netChannel, function(aInputStream, aResult) {
+    NetUtil.asyncFetch(netChannel, function(aInputStream, aResult) {
       if (!Components.isSuccessCode(aResult)) {
         if (sendResponse) {
           sendResponse(true);
         }
         return;
       }
       // Create a nsIInputStreamChannel so we can set the url on the channel
       // so the filename will be correct.
@@ -313,17 +301,17 @@ ChromeActions.prototype = {
         },
         onDataAvailable: function(aRequest, aContext, aInputStream, aOffset,
                                   aCount) {
           this.extListener.onDataAvailable(aRequest, aContext, aInputStream,
                                            aOffset, aCount);
         }
       };
 
-      asyncOpenChannel(channel, listener, null);
+      channel.asyncOpen2(listener);
     });
   },
   getLocale: function() {
     return getStringPref('general.useragent.locale', 'en-US');
   },
   getStrings: function(data) {
     try {
       // Lazy initialization of localizedStrings
@@ -955,17 +943,20 @@ PdfStreamConverter.prototype = {
 
     // Creating storage for PDF data
     var contentLength = aRequest.contentLength;
     this.dataListener = new PdfDataListener(contentLength);
     this.binaryStream = Cc['@mozilla.org/binaryinputstream;1']
                         .createInstance(Ci.nsIBinaryInputStream);
 
     // Create a new channel that is viewer loaded as a resource.
-    var channel = createNewChannel(PDF_VIEWER_WEB_PAGE, null);
+    var channel = NetUtil.newChannel({
+      uri: PDF_VIEWER_WEB_PAGE,
+      loadUsingSystemPrincipal: true,
+    });
 
     var listener = this.listener;
     var dataListener = this.dataListener;
     // Proxy all the request observer calls, when it gets to onStopRequest
     // we can get the dom window.  We also intentionally pass on the original
     // request(aRequest) below so we don't overwrite the original channel and
     // trigger an assertion.
     var proxy = {
@@ -1013,21 +1004,21 @@ PdfStreamConverter.prototype = {
     channel.loadInfo.originAttributes = aRequest.loadInfo.originAttributes;
 
     // We can use the resource principal when data is fetched by the chrome,
     // e.g. useful for NoScript. Make make sure we reuse the origin attributes
     // from the request channel to keep isolation consistent.
     var ssm = Cc['@mozilla.org/scriptsecuritymanager;1']
                 .getService(Ci.nsIScriptSecurityManager);
     var uri = NetUtil.newURI(PDF_VIEWER_WEB_PAGE);
-    var resourcePrincipal;
-    resourcePrincipal =
+    var resourcePrincipal =
       ssm.createCodebasePrincipal(uri, aRequest.loadInfo.originAttributes);
     aRequest.owner = resourcePrincipal;
-    asyncOpenChannel(channel, proxy, aContext);
+
+    channel.asyncOpen2(proxy);
   },
 
   // nsIRequestObserver::onStopRequest
   onStopRequest: function(aRequest, aContext, aStatusCode) {
     if (!this.dataListener) {
       // Do nothing
       return;
     }
--- a/browser/extensions/pdfjs/content/PdfjsChromeUtils.jsm
+++ b/browser/extensions/pdfjs/content/PdfjsChromeUtils.jsm
@@ -105,17 +105,17 @@ var PdfjsChromeUtils = {
                                        this);
 
       this._mmg.removeMessageListener('PDFJS:Parent:displayWarning', this);
 
       this._mmg.removeMessageListener('PDFJS:Parent:addEventListener', this);
       this._mmg.removeMessageListener('PDFJS:Parent:removeEventListener', this);
       this._mmg.removeMessageListener('PDFJS:Parent:updateControlState', this);
 
-      Services.obs.removeObserver(this, 'quit-application');
+      Services.obs.removeObserver(this, 'quit-application', false);
 
       this._mmg = null;
       this._ppmm = null;
     }
   },
 
   /*
    * Called by the main module when preference changes are picked up
--- a/browser/extensions/pdfjs/content/build/pdf.js
+++ b/browser/extensions/pdfjs/content/build/pdf.js
@@ -18,18 +18,18 @@
   define('pdfjs-dist/build/pdf', ['exports'], factory);
  } else if (typeof exports !== 'undefined') {
   factory(exports);
  } else {
   factory(root['pdfjsDistBuildPdf'] = {});
  }
 }(this, function (exports) {
  'use strict';
- var pdfjsVersion = '1.6.418';
- var pdfjsBuild = '59afb4b9';
+ var pdfjsVersion = '1.6.454';
+ var pdfjsBuild = 'b8cd1433';
  var pdfjsFilePath = typeof document !== 'undefined' && document.currentScript ? document.currentScript.src : null;
  var pdfjsLibs = {};
  (function pdfjsWrapper() {
   (function (root, factory) {
    factory(root.pdfjsSharedUtil = {});
   }(this, function (exports) {
    var globalScope = typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : this;
    var FONT_IDENTITY_MATRIX = [
@@ -1808,19 +1808,18 @@
       switch (fieldType) {
       case 'Tx':
        return new TextWidgetAnnotationElement(parameters);
       case 'Btn':
        if (parameters.data.radioButton) {
         return new RadioButtonWidgetAnnotationElement(parameters);
        } else if (parameters.data.checkBox) {
         return new CheckboxWidgetAnnotationElement(parameters);
-       } else {
-        warn('Unimplemented button widget annotation: pushbutton');
        }
+       warn('Unimplemented button widget annotation: pushbutton');
        break;
       case 'Ch':
        return new ChoiceWidgetAnnotationElement(parameters);
       }
       return new WidgetAnnotationElement(parameters);
      case AnnotationType.POPUP:
       return new PopupAnnotationElement(parameters);
      case AnnotationType.HIGHLIGHT:
@@ -6325,28 +6324,32 @@
     function WorkerTransport(messageHandler, loadingTask, pdfDataRangeTransport) {
      this.messageHandler = messageHandler;
      this.loadingTask = loadingTask;
      this.pdfDataRangeTransport = pdfDataRangeTransport;
      this.commonObjs = new PDFObjects();
      this.fontLoader = new FontLoader(loadingTask.docId);
      this.destroyed = false;
      this.destroyCapability = null;
+     this._passwordCapability = null;
      this.pageCache = [];
      this.pagePromises = [];
      this.downloadInfoCapability = createPromiseCapability();
      this.setupMessageHandler();
     }
     WorkerTransport.prototype = {
      destroy: function WorkerTransport_destroy() {
       if (this.destroyCapability) {
        return this.destroyCapability.promise;
       }
       this.destroyed = true;
       this.destroyCapability = createPromiseCapability();
+      if (this._passwordCapability) {
+       this._passwordCapability.reject(new Error('Worker was destroyed during onPassword callback'));
+      }
       var waitOn = [];
       this.pageCache.forEach(function (page) {
        if (page) {
         waitOn.push(page._destroy());
        }
       });
       this.pageCache = [];
       this.pagePromises = [];
@@ -6364,19 +6367,17 @@
         self.messageHandler = null;
        }
        self.destroyCapability.resolve();
       }, this.destroyCapability.reject);
       return this.destroyCapability.promise;
      },
      setupMessageHandler: function WorkerTransport_setupMessageHandler() {
       var messageHandler = this.messageHandler;
-      function updatePassword(password) {
-       messageHandler.send('UpdatePassword', password);
-      }
+      var loadingTask = this.loadingTask;
       var pdfDataRangeTransport = this.pdfDataRangeTransport;
       if (pdfDataRangeTransport) {
        pdfDataRangeTransport.addRangeListener(function (begin, chunk) {
         messageHandler.send('OnDataRange', {
          begin: begin,
          chunk: chunk
         });
        });
@@ -6393,28 +6394,29 @@
       messageHandler.on('GetDoc', function transportDoc(data) {
        var pdfInfo = data.pdfInfo;
        this.numPages = data.pdfInfo.numPages;
        var loadingTask = this.loadingTask;
        var pdfDocument = new PDFDocumentProxy(pdfInfo, this, loadingTask);
        this.pdfDocument = pdfDocument;
        loadingTask._capability.resolve(pdfDocument);
       }, this);
-      messageHandler.on('NeedPassword', function transportNeedPassword(exception) {
-       var loadingTask = this.loadingTask;
+      messageHandler.on('PasswordRequest', function transportPasswordRequest(exception) {
+       this._passwordCapability = createPromiseCapability();
        if (loadingTask.onPassword) {
-        return loadingTask.onPassword(updatePassword, PasswordResponses.NEED_PASSWORD);
+        var updatePassword = function (password) {
+         this._passwordCapability.resolve({ password: password });
+        }.bind(this);
+        loadingTask.onPassword(updatePassword, exception.code);
+       } else {
+        this._passwordCapability.reject(new PasswordException(exception.message, exception.code));
        }
-       loadingTask._capability.reject(new PasswordException(exception.message, exception.code));
+       return this._passwordCapability.promise;
       }, this);
-      messageHandler.on('IncorrectPassword', function transportIncorrectPassword(exception) {
-       var loadingTask = this.loadingTask;
-       if (loadingTask.onPassword) {
-        return loadingTask.onPassword(updatePassword, PasswordResponses.INCORRECT_PASSWORD);
-       }
+      messageHandler.on('PasswordException', function transportPasswordException(exception) {
        loadingTask._capability.reject(new PasswordException(exception.message, exception.code));
       }, this);
       messageHandler.on('InvalidPDF', function transportInvalidPDF(exception) {
        this.loadingTask._capability.reject(new InvalidPDFException(exception.message));
       }, this);
       messageHandler.on('MissingPDF', function transportMissingPDF(exception) {
        this.loadingTask._capability.reject(new MissingPDFException(exception.message));
       }, this);
@@ -6715,30 +6717,28 @@
       obj.resolved = true;
       obj.data = data;
       obj.capability.resolve(data);
      },
      isResolved: function PDFObjects_isResolved(objId) {
       var objs = this.objs;
       if (!objs[objId]) {
        return false;
-      } else {
-       return objs[objId].resolved;
-      }
+      }
+      return objs[objId].resolved;
      },
      hasData: function PDFObjects_hasData(objId) {
       return this.isResolved(objId);
      },
      getData: function PDFObjects_getData(objId) {
       var objs = this.objs;
       if (!objs[objId] || !objs[objId].resolved) {
        return null;
-      } else {
-       return objs[objId].data;
-      }
+      }
+      return objs[objId].data;
      },
      clear: function PDFObjects_clear() {
       this.objs = Object.create(null);
      }
     };
     return PDFObjects;
    }();
    var RenderTask = function RenderTaskClosure() {
--- a/browser/extensions/pdfjs/content/build/pdf.worker.js
+++ b/browser/extensions/pdfjs/content/build/pdf.worker.js
@@ -18,18 +18,18 @@
   define('pdfjs-dist/build/pdf.worker', ['exports'], factory);
  } else if (typeof exports !== 'undefined') {
   factory(exports);
  } else {
   factory(root['pdfjsDistBuildPdfWorker'] = {});
  }
 }(this, function (exports) {
  'use strict';
- var pdfjsVersion = '1.6.418';
- var pdfjsBuild = '59afb4b9';
+ var pdfjsVersion = '1.6.454';
+ var pdfjsBuild = 'b8cd1433';
  var pdfjsFilePath = typeof document !== 'undefined' && document.currentScript ? document.currentScript.src : null;
  var pdfjsLibs = {};
  (function pdfjsWrapper() {
   (function (root, factory) {
    factory(root.pdfjsCoreArithmeticDecoder = {});
   }(this, function (exports) {
    var ArithmeticDecoder = function ArithmeticDecoderClosure() {
     var QeTable = [
@@ -4712,17 +4712,17 @@
      }
      types[i] = charType;
     }
     if (numBidi === 0) {
      isLTR = true;
      return createBidiText(str, isLTR);
     }
     if (startLevel === -1) {
-     if (strLength / numBidi < 0.3) {
+     if (numBidi / strLength < 0.3) {
       isLTR = true;
       startLevel = 0;
      } else {
       isLTR = false;
       startLevel = 1;
      }
     }
     var levels = [];
@@ -5669,20 +5669,19 @@
         value = value << 8 | dict[pos++];
         return value;
        } else if (value >= 32 && value <= 246) {
         return value - 139;
        } else if (value >= 247 && value <= 250) {
         return (value - 247) * 256 + dict[pos++] + 108;
        } else if (value >= 251 && value <= 254) {
         return -((value - 251) * 256) - dict[pos++] - 108;
-       } else {
-        warn('CFFParser_parseDict: "' + value + '" is a reserved command.');
-        return NaN;
-       }
+       }
+       warn('CFFParser_parseDict: "' + value + '" is a reserved command.');
+       return NaN;
       }
       function parseFloatOperand() {
        var str = '';
        var eof = 15;
        var lookup = [
         '0',
         '1',
         '2',
@@ -6954,19 +6953,18 @@
       }
       this.compilePrivateDicts([cff.topDict], [topDictTracker], output);
       output.add([0]);
       return output.data;
      },
      encodeNumber: function CFFCompiler_encodeNumber(value) {
       if (parseFloat(value) === parseInt(value, 10) && !isNaN(value)) {
        return this.encodeInteger(value);
-      } else {
-       return this.encodeFloat(value);
-      }
+      }
+      return this.encodeFloat(value);
      },
      encodeFloat: function CFFCompiler_encodeFloat(num) {
       var value = num.toString();
       var m = /\.(\d*?)(?:9{5,20}|0{5,20})\d{0,2}(?:e(.+)|$)/.exec(value);
       if (m) {
        var epsilon = parseFloat('1e' + ((m[2] ? +m[2] : 0) + m[1].length));
        value = (Math.round(num * epsilon) / epsilon).toString();
       }
@@ -14244,22 +14242,21 @@
      _isColorConversionNeeded: function isColorConversionNeeded() {
       if (this.adobe && this.adobe.transformCode) {
        return true;
       } else if (this.numComponents === 3) {
        if (!this.adobe && this.colorTransform === 0) {
         return false;
        }
        return true;
-      } else {
-       if (!this.adobe && this.colorTransform === 1) {
-        return true;
-       }
-       return false;
-      }
+      }
+      if (!this.adobe && this.colorTransform === 1) {
+       return true;
+      }
+      return false;
      },
      _convertYccToRgb: function convertYccToRgb(data) {
       var Y, Cb, Cr;
       for (var i = 0, length = data.length; i < length; i += 3) {
        Y = data[i];
        Cb = data[i + 1];
        Cr = data[i + 2];
        data[i] = clamp0to255(Y - 179.456 + 1.402 * Cr);
@@ -14333,19 +14330,18 @@
        }
        return rgbData;
       } else if (this.numComponents === 3 && this._isColorConversionNeeded()) {
        return this._convertYccToRgb(data);
       } else if (this.numComponents === 4) {
        if (this._isColorConversionNeeded()) {
         if (forceRGBoutput) {
          return this._convertYcckToRgb(data);
-        } else {
-         return this._convertYcckToCmyk(data);
-        }
+        }
+        return this._convertYcckToCmyk(data);
        } else if (forceRGBoutput) {
         return this._convertCmykToRgb(data);
        }
       }
       return data;
      }
     };
     return JpegImage;
@@ -23524,22 +23520,24 @@
      this.eof = !rawBytes.length;
      if (this.eof) {
       return;
      }
      var inbuf = 0, outbuf = 0;
      var inbits = 0, outbits = 0;
      var pos = bufferLength;
      var i;
-     if (bits === 1) {
+     if (bits === 1 && colors === 1) {
       for (i = 0; i < rowBytes; ++i) {
-       var c = rawBytes[i];
-       inbuf = inbuf << 8 | c;
-       buffer[pos++] = (c ^ inbuf >> colors) & 0xFF;
-       inbuf &= 0xFFFF;
+       var c = rawBytes[i] ^ inbuf;
+       c ^= c >> 1;
+       c ^= c >> 2;
+       c ^= c >> 4;
+       inbuf = (c & 1) << 7;
+       buffer[pos++] = c;
       }
      } else if (bits === 8) {
       for (i = 0; i < colors; ++i) {
        buffer[pos++] = rawBytes[i];
       }
       for (; i < rowBytes; ++i) {
        buffer[pos] = buffer[pos - colors] + rawBytes[i];
        pos++;
@@ -33584,19 +33582,18 @@
         1 / unitsPerEm,
         0,
         0,
         1 / unitsPerEm,
         0,
         0
        ];
        return new TrueTypeCompiled(parseGlyfTable(glyf, loca, indexToLocFormat), cmap, fontMatrix);
-      } else {
-       return new Type2Compiled(cff, cmap, font.fontMatrix, font.glyphNameMap);
-      }
+      }
+      return new Type2Compiled(cff, cmap, font.fontMatrix, font.glyphNameMap);
      }
     };
    }();
    exports.FontRendererFactory = FontRendererFactory;
   }));
   (function (root, factory) {
    factory(root.pdfjsCoreParser = {}, root.pdfjsSharedUtil, root.pdfjsCorePrimitives, root.pdfjsCoreStream);
   }(this, function (exports, sharedUtil, corePrimitives, coreStream) {
@@ -38329,17 +38326,17 @@
        }
        if (table.length === 0) {
         continue;
        }
        tables[table.tag] = table;
       }
       var isTrueType = !tables['CFF '];
       if (!isTrueType) {
-       if (header.version === 'OTTO' && properties.type !== 'CIDFontType2' || !tables['head'] || !tables['hhea'] || !tables['maxp'] || !tables['post']) {
+       if (header.version === 'OTTO' && !properties.composite || !tables['head'] || !tables['hhea'] || !tables['maxp'] || !tables['post']) {
         cffFile = new Stream(tables['CFF '].data);
         cff = new CFFFont(cffFile, properties);
         adjustWidths(properties);
         return this.convert(name, cff, properties);
        }
        delete tables['glyf'];
        delete tables['loca'];
        delete tables['fpgm'];
@@ -38431,17 +38428,17 @@
        if (!skipToUnicode && charCode >= 0 && toUnicode.has(charCode)) {
         return true;
        }
        if (widths && widthCode >= 0 && isNum(widths[widthCode])) {
         return true;
        }
        return false;
       }
-      if (properties.type === 'CIDFontType2') {
+      if (properties.composite) {
        var cidToGidMap = properties.cidToGidMap || [];
        var isCidToGidMapEmpty = cidToGidMap.length === 0;
        properties.cMap.forEach(function (charCode, cid) {
         assert(cid <= 0xffff, 'Max size of CID is 65,535');
         var glyphId = -1;
         if (isCidToGidMapEmpty) {
          glyphId = cid;
         } else if (cidToGidMap[cid] !== undefined) {
@@ -41333,21 +41330,23 @@
       info('Invalid Range, falling back to defaults');
       this.amin = -100;
       this.amax = 100;
       this.bmin = -100;
       this.bmax = 100;
      }
     }
     function fn_g(x) {
+     var result;
      if (x >= 6 / 29) {
-      return x * x * x;
+      result = x * x * x;
      } else {
-      return 108 / 841 * (x - 4 / 29);
-     }
+      result = 108 / 841 * (x - 4 / 29);
+     }
+     return result;
     }
     function decode(value, high1, low2, high2) {
      return low2 + value * (high2 - low2) / high1;
     }
     function convertToRgb(cs, src, srcOffset, maxVal, dest, destOffset) {
      var Ls = src[srcOffset];
      var as = src[srcOffset + 1];
      var bs = src[srcOffset + 2];
@@ -41419,19 +41418,18 @@
    var ColorSpace = coreColorSpace.ColorSpace;
    var DecodeStream = coreStream.DecodeStream;
    var JpegStream = coreStream.JpegStream;
    var JpxImage = coreJpx.JpxImage;
    var PDFImage = function PDFImageClosure() {
     function handleImageData(image, nativeDecoder) {
      if (nativeDecoder && nativeDecoder.canDecode(image)) {
       return nativeDecoder.decode(image);
-     } else {
-      return Promise.resolve(image);
-     }
+     }
+     return Promise.resolve(image);
     }
     function decodeAndClamp(value, addend, coefficient, max) {
      value = addend + value * coefficient;
      return value < 0 ? 0 : value > max ? max : value;
     }
     function resizeImageMask(src, bpc, w1, h1, w2, h2) {
      var length = w2 * h2;
      var dest = bpc <= 8 ? new Uint8Array(length) : bpc <= 16 ? new Uint16Array(length) : new Uint32Array(length);
@@ -42493,22 +42491,22 @@
       if (isString(dest) || isArray(dest)) {
        resultObj.dest = dest;
       }
      }
     };
     return Catalog;
    }();
    var XRef = function XRefClosure() {
-    function XRef(stream, password) {
+    function XRef(stream, pdfManager) {
      this.stream = stream;
+     this.pdfManager = pdfManager;
      this.entries = [];
      this.xrefstms = Object.create(null);
      this.cache = [];
-     this.password = password;
      this.stats = {
       streamTypes: [],
       fontTypes: []
      };
     }
     XRef.prototype = {
      setStartXRef: function XRef_setStartXRef(startXRef) {
       this.startXRefQueue = [startXRef];
@@ -42519,21 +42517,21 @@
        trailerDict = this.readXRef();
       } else {
        warn('Indexing all PDF objects');
        trailerDict = this.indexObjects();
       }
       trailerDict.assignXref(this);
       this.trailer = trailerDict;
       var encrypt = trailerDict.get('Encrypt');
-      if (encrypt) {
+      if (isDict(encrypt)) {
        var ids = trailerDict.get('ID');
        var fileId = ids && ids.length ? ids[0] : '';
        encrypt.suppressEncryption = true;
-       this.encrypt = new CipherTransformFactory(encrypt, fileId, this.password);
+       this.encrypt = new CipherTransformFactory(encrypt, fileId, this.pdfManager.password);
       }
       if (!(this.root = trailerDict.get('Root'))) {
        error('Invalid root reference');
       }
      },
      processXRefTable: function XRef_processXRefTable(parser) {
       if (!('tableState' in this)) {
        this.tableState = {
@@ -43173,19 +43171,18 @@
      } else if (dict.has('F')) {
       return dict.get('F');
      } else if (dict.has('Unix')) {
       return dict.get('Unix');
      } else if (dict.has('Mac')) {
       return dict.get('Mac');
      } else if (dict.has('DOS')) {
       return dict.get('DOS');
-     } else {
-      return null;
-     }
+     }
+     return null;
     }
     FileSpec.prototype = {
      get filename() {
       if (!this._filename && this.root) {
        var filename = pickPlatformItem(this.root) || 'unnamed';
        this._filename = stringToPDFString(filename).replace(/\\\\/g, '\\').replace(/\\\//g, '/').replace(/\\/g, '/');
       }
       return this._filename;
@@ -44278,23 +44275,22 @@
     NativeImageDecoder.isDecodable = function NativeImageDecoder_isDecodable(image, xref, res) {
      var dict = image.dict;
      if (dict.has('DecodeParms') || dict.has('DP')) {
       return false;
      }
      var cs = ColorSpace.parse(dict.get('ColorSpace', 'CS'), xref, res);
      return (cs.numComps === 1 || cs.numComps === 3) && cs.isDefaultDecode(dict.getArray('Decode', 'D'));
     };
-    function PartialEvaluator(pdfManager, xref, handler, pageIndex, uniquePrefix, idCounters, fontCache, options) {
+    function PartialEvaluator(pdfManager, xref, handler, pageIndex, idFactory, fontCache, options) {
      this.pdfManager = pdfManager;
      this.xref = xref;
      this.handler = handler;
      this.pageIndex = pageIndex;
-     this.uniquePrefix = uniquePrefix;
-     this.idCounters = idCounters;
+     this.idFactory = idFactory;
      this.fontCache = fontCache;
      this.options = options || DefaultPartialEvaluatorOptions;
     }
     var TIME_SLOT_DURATION_MS = 20;
     var CHECK_TIME_EVERY = 100;
     function TimeSlotManager() {
      this.reset();
     }
@@ -44447,18 +44443,17 @@
       var mask = dict.get('Mask') || false;
       var SMALL_IMAGE_DIMENSIONS = 200;
       if (inline && !softMask && !mask && !(image instanceof JpegStream) && w + h < SMALL_IMAGE_DIMENSIONS) {
        var imageObj = new PDFImage(this.xref, resources, image, inline, null, null);
        imgData = imageObj.createImageData(true);
        operatorList.addOp(OPS.paintInlineImageXObject, [imgData]);
        return;
       }
-      var uniquePrefix = this.uniquePrefix || '';
-      var objId = 'img_' + uniquePrefix + ++this.idCounters.obj;
+      var objId = 'img_' + this.idFactory.createObjId();
       operatorList.addDependency(objId);
       args = [
        objId,
        w,
        h
       ];
       if (!softMask && !mask && image instanceof JpegStream && NativeImageDecoder.isSupported(image, this.xref, resources)) {
        operatorList.addOp(OPS.paintJpegXObject, args);
@@ -44732,17 +44727,17 @@
         fontAliases[hash].aliasRef = fontRef;
        }
        fontID = fontAliases[hash].fontID;
       }
       if (fontRefIsRef) {
        this.fontCache.put(fontRef, fontCapability.promise);
       } else {
        if (!fontID) {
-        fontID = (this.uniquePrefix || 'F_') + ++this.idCounters.obj;
+        fontID = this.idFactory.createObjId();
        }
        this.fontCache.put('id_' + fontID, fontCapability.promise);
       }
       assert(fontID, 'The "fontID" must be defined.');
       font.loadedName = 'g_' + this.pdfManager.docId + '_f' + fontID;
       font.translated = fontCapability.promise;
       var translatedPromise;
       try {
@@ -44798,19 +44793,18 @@
         var color = cs.base ? cs.base.getRgb(args, 0) : null;
         return this.handleTilingType(fn, color, resources, pattern, dict, operatorList, task);
        } else if (typeNum === SHADING_PATTERN) {
         var shading = dict.get('Shading');
         var matrix = dict.getArray('Matrix');
         pattern = Pattern.parseShading(shading, matrix, xref, resources, this.handler);
         operatorList.addOp(fn, pattern.getIR());
         return Promise.resolve();
-       } else {
-        return Promise.reject('Unknown PatternType: ' + typeNum);
-       }
+       }
+       return Promise.reject('Unknown PatternType: ' + typeNum);
       }
       operatorList.addOp(fn, args);
       return Promise.resolve();
      },
      getOperatorList: function PartialEvaluator_getOperatorList(stream, task, resources, operatorList, initialState) {
       var self = this;
       var xref = this.xref;
       var imageCache = Object.create(null);
@@ -46754,27 +46748,26 @@
          }
         } else if (argsLength > numArgs) {
          info('Command ' + fn + ': expected [0,' + numArgs + '] args, but received ' + argsLength + ' args.');
         }
         this.preprocessCommand(fn, args);
         operation.fn = fn;
         operation.args = args;
         return true;
-       } else {
-        if (isEOF(obj)) {
-         return false;
-        }
-        if (obj !== null) {
-         if (args === null) {
-          args = [];
-         }
-         args.push(obj);
-         assert(args.length <= 33, 'Too many arguments');
-        }
+       }
+       if (isEOF(obj)) {
+        return false;
+       }
+       if (obj !== null) {
+        if (args === null) {
+         args = [];
+        }
+        args.push(obj);
+        assert(args.length <= 33, 'Too many arguments');
        }
       }
      },
      preprocessCommand: function EvaluatorPreprocessor_preprocessCommand(fn, args) {
       switch (fn | 0) {
       case OPS.save:
        this.stateManager.save();
        break;
@@ -47139,22 +47132,22 @@
    var ColorSpace = coreColorSpace.ColorSpace;
    var Catalog = coreObj.Catalog;
    var ObjectLoader = coreObj.ObjectLoader;
    var FileSpec = coreObj.FileSpec;
    var OperatorList = coreEvaluator.OperatorList;
    function AnnotationFactory() {
    }
    AnnotationFactory.prototype = {
-    create: function AnnotationFactory_create(xref, ref, pdfManager, uniquePrefix, idCounters) {
+    create: function AnnotationFactory_create(xref, ref, pdfManager, idFactory) {
      var dict = xref.fetchIfRef(ref);
      if (!isDict(dict)) {
       return;
      }
-     var id = isRef(ref) ? ref.toString() : 'annot_' + (uniquePrefix || '') + ++idCounters.obj;
+     var id = isRef(ref) ? ref.toString() : 'annot_' + idFactory.createObjId();
      var subtype = dict.get('Subtype');
      subtype = isName(subtype) ? subtype.name : null;
      var parameters = {
       xref: xref,
       dict: dict,
       ref: isRef(ref) ? ref : null,
       subtype: subtype,
       id: id,
@@ -47844,20 +47837,25 @@
     ];
     function Page(pdfManager, xref, pageIndex, pageDict, ref, fontCache) {
      this.pdfManager = pdfManager;
      this.pageIndex = pageIndex;
      this.pageDict = pageDict;
      this.xref = xref;
      this.ref = ref;
      this.fontCache = fontCache;
-     this.uniquePrefix = 'p' + this.pageIndex + '_';
-     this.idCounters = { obj: 0 };
      this.evaluatorOptions = pdfManager.evaluatorOptions;
      this.resourcesPromise = null;
+     var uniquePrefix = 'p' + this.pageIndex + '_';
+     var idCounters = { obj: 0 };
+     this.idFactory = {
+      createObjId: function () {
+       return uniquePrefix + ++idCounters.obj;
+      }
+     };
     }
     Page.prototype = {
      getPageProp: function Page_getPageProp(key) {
       return this.pageDict.get(key);
      },
      getInheritedPageProp: function Page_getInheritedPageProp(key, getArray) {
       var dict = this.pageDict, valueArray = null, loopCount = 0;
       var MAX_LOOP_COUNT = 100;
@@ -47964,17 +47962,17 @@
       var resourcesPromise = this.loadResources([
        'ExtGState',
        'ColorSpace',
        'Pattern',
        'Shading',
        'XObject',
        'Font'
       ]);
-      var partialEvaluator = new PartialEvaluator(pdfManager, this.xref, handler, this.pageIndex, this.uniquePrefix, this.idCounters, this.fontCache, this.evaluatorOptions);
+      var partialEvaluator = new PartialEvaluator(pdfManager, this.xref, handler, this.pageIndex, this.idFactory, this.fontCache, this.evaluatorOptions);
       var dataPromises = Promise.all([
        contentStreamPromise,
        resourcesPromise
       ]);
       var pageListPromise = dataPromises.then(function (data) {
        var contentStream = data[0];
        var opList = new OperatorList(intent, handler, self.pageIndex);
        handler.send('StartRenderPage', {
@@ -48020,17 +48018,17 @@
        'Font'
       ]);
       var dataPromises = Promise.all([
        contentStreamPromise,
        resourcesPromise
       ]);
       return dataPromises.then(function (data) {
        var contentStream = data[0];
-       var partialEvaluator = new PartialEvaluator(pdfManager, self.xref, handler, self.pageIndex, self.uniquePrefix, self.idCounters, self.fontCache, self.evaluatorOptions);
+       var partialEvaluator = new PartialEvaluator(pdfManager, self.xref, handler, self.pageIndex, self.idFactory, self.fontCache, self.evaluatorOptions);
        return partialEvaluator.getTextContent(contentStream, task, self.resources, null, normalizeWhitespace, combineTextItems);
       });
      },
      getAnnotationsData: function Page_getAnnotationsData(intent) {
       var annotations = this.annotations;
       var annotationsData = [];
       for (var i = 0, n = annotations.length; i < n; ++i) {
        if (intent) {
@@ -48043,44 +48041,42 @@
       return annotationsData;
      },
      get annotations() {
       var annotations = [];
       var annotationRefs = this.getInheritedPageProp('Annots') || [];
       var annotationFactory = new AnnotationFactory();
       for (var i = 0, n = annotationRefs.length; i < n; ++i) {
        var annotationRef = annotationRefs[i];
-       var annotation = annotationFactory.create(this.xref, annotationRef, this.pdfManager, this.uniquePrefix, this.idCounters);
+       var annotation = annotationFactory.create(this.xref, annotationRef, this.pdfManager, this.idFactory);
        if (annotation) {
         annotations.push(annotation);
        }
       }
       return shadow(this, 'annotations', annotations);
      }
     };
     return Page;
    }();
    var PDFDocument = function PDFDocumentClosure() {
     var FINGERPRINT_FIRST_BYTES = 1024;
     var EMPTY_FINGERPRINT = '\x00\x00\x00\x00\x00\x00\x00' + '\x00\x00\x00\x00\x00\x00\x00\x00\x00';
-    function PDFDocument(pdfManager, arg, password) {
+    function PDFDocument(pdfManager, arg) {
+     var stream;
      if (isStream(arg)) {
-      init.call(this, pdfManager, arg, password);
+      stream = arg;
      } else if (isArrayBuffer(arg)) {
-      init.call(this, pdfManager, new Stream(arg), password);
+      stream = new Stream(arg);
      } else {
       error('PDFDocument: Unknown argument type');
      }
-    }
-    function init(pdfManager, stream, password) {
      assert(stream.length > 0, 'stream must have data');
      this.pdfManager = pdfManager;
      this.stream = stream;
-     var xref = new XRef(this.stream, password, pdfManager);
-     this.xref = xref;
+     this.xref = new XRef(stream, pdfManager);
     }
     function find(stream, needle, limit, backwards) {
      var pos = stream.pos;
      var end = stream.end;
      var strBuf = [];
      if (pos + limit > end) {
       limit = end - pos;
      }
@@ -48303,16 +48299,19 @@
    var BasePdfManager = function BasePdfManagerClosure() {
     function BasePdfManager() {
      throw new Error('Cannot initialize BaseManagerManager');
     }
     BasePdfManager.prototype = {
      get docId() {
       return this._docId;
      },
+     get password() {
+      return this._password;
+     },
      get docBaseUrl() {
       var docBaseUrl = null;
       if (this._docBaseUrl) {
        var absoluteUrl = createValidAbsoluteUrl(this._docBaseUrl);
        if (absoluteUrl) {
         docBaseUrl = absoluteUrl.href;
        } else {
         warn('Invalid absolute docBaseUrl: "' + this._docBaseUrl + '".');
@@ -48346,38 +48345,32 @@
      },
      requestLoadedStream: function BasePdfManager_requestLoadedStream() {
       return new NotImplementedException();
      },
      sendProgressiveData: function BasePdfManager_sendProgressiveData(chunk) {
       return new NotImplementedException();
      },
      updatePassword: function BasePdfManager_updatePassword(password) {
-      this.pdfDocument.xref.password = this.password = password;
-      if (this._passwordChangedCapability) {
-       this._passwordChangedCapability.resolve();
-      }
-     },
-     passwordChanged: function BasePdfManager_passwordChanged() {
-      this._passwordChangedCapability = createPromiseCapability();
-      return this._passwordChangedCapability.promise;
+      this._password = password;
      },
      terminate: function BasePdfManager_terminate() {
       return new NotImplementedException();
      }
     };
     return BasePdfManager;
    }();
    var LocalPdfManager = function LocalPdfManagerClosure() {
     function LocalPdfManager(docId, data, password, evaluatorOptions, docBaseUrl) {
      this._docId = docId;
+     this._password = password;
      this._docBaseUrl = docBaseUrl;
      this.evaluatorOptions = evaluatorOptions;
      var stream = new Stream(data);
-     this.pdfDocument = new PDFDocument(this, stream, password);
+     this.pdfDocument = new PDFDocument(this, stream);
      this._loadedStreamCapability = createPromiseCapability();
      this._loadedStreamCapability.resolve(stream);
     }
     Util.inherit(LocalPdfManager, BasePdfManager, {
      ensure: function LocalPdfManager_ensure(obj, prop, args) {
       return new Promise(function (resolve, reject) {
        try {
         var value = obj[prop];
@@ -48392,42 +48385,41 @@
         reject(e);
        }
       });
      },
      requestRange: function LocalPdfManager_requestRange(begin, end) {
       return Promise.resolve();
      },
      requestLoadedStream: function LocalPdfManager_requestLoadedStream() {
-      return;
      },
      onLoadedStream: function LocalPdfManager_onLoadedStream() {
       return this._loadedStreamCapability.promise;
      },
      terminate: function LocalPdfManager_terminate() {
-      return;
      }
     });
     return LocalPdfManager;
    }();
    var NetworkPdfManager = function NetworkPdfManagerClosure() {
     function NetworkPdfManager(docId, pdfNetworkStream, args, evaluatorOptions, docBaseUrl) {
      this._docId = docId;
+     this._password = args.password;
      this._docBaseUrl = docBaseUrl;
      this.msgHandler = args.msgHandler;
      this.evaluatorOptions = evaluatorOptions;
      var params = {
       msgHandler: args.msgHandler,
       url: args.url,
       length: args.length,
       disableAutoFetch: args.disableAutoFetch,
       rangeChunkSize: args.rangeChunkSize
      };
      this.streamManager = new ChunkedStreamManager(pdfNetworkStream, params);
-     this.pdfDocument = new PDFDocument(this, this.streamManager.getStream(), args.password);
+     this.pdfDocument = new PDFDocument(this, this.streamManager.getStream());
     }
     Util.inherit(NetworkPdfManager, BasePdfManager, {
      ensure: function NetworkPdfManager_ensure(obj, prop, args) {
       var pdfManager = this;
       return new Promise(function (resolve, reject) {
        function ensureHelper() {
         try {
          var result;
@@ -48919,38 +48911,58 @@
        pdfManagerCapability.reject(e);
        cancelXHRs = null;
       });
       cancelXHRs = function () {
        pdfStream.cancelAllRequests('abort');
       };
       return pdfManagerCapability.promise;
      }
-     var setupDoc = function (data) {
-      var onSuccess = function (doc) {
+     function setupDoc(data) {
+      function onSuccess(doc) {
        ensureNotTerminated();
        handler.send('GetDoc', { pdfInfo: doc });
-      };
-      var onFailure = function (e) {
+      }
+      function onFailure(e) {
        if (e instanceof PasswordException) {
-        if (e.code === PasswordResponses.NEED_PASSWORD) {
-         handler.send('NeedPassword', e);
-        } else if (e.code === PasswordResponses.INCORRECT_PASSWORD) {
-         handler.send('IncorrectPassword', e);
-        }
+        var task = new WorkerTask('PasswordException: response ' + e.code);
+        startWorkerTask(task);
+        handler.sendWithPromise('PasswordRequest', e).then(function (data) {
+         finishWorkerTask(task);
+         pdfManager.updatePassword(data.password);
+         pdfManagerReady();
+        }).catch(function (ex) {
+         finishWorkerTask(task);
+         handler.send('PasswordException', ex);
+        }.bind(null, e));
        } else if (e instanceof InvalidPDFException) {
         handler.send('InvalidPDF', e);
        } else if (e instanceof MissingPDFException) {
         handler.send('MissingPDF', e);
        } else if (e instanceof UnexpectedResponseException) {
         handler.send('UnexpectedResponse', e);
        } else {
         handler.send('UnknownError', new UnknownErrorException(e.message, e.toString()));
        }
-      };
+      }
+      function pdfManagerReady() {
+       ensureNotTerminated();
+       loadDocument(false).then(onSuccess, function loadFailure(ex) {
+        ensureNotTerminated();
+        if (!(ex instanceof XRefParseException)) {
+         onFailure(ex);
+         return;
+        }
+        pdfManager.requestLoadedStream();
+        pdfManager.onLoadedStream().then(function () {
+         ensureNotTerminated();
+         loadDocument(true).then(onSuccess, onFailure);
+        });
+       }, onFailure);
+      }
       ensureNotTerminated();
       var cMapOptions = {
        url: data.cMapUrl === undefined ? null : data.cMapUrl,
        packed: data.cMapPacked === true
       };
       var evaluatorOptions = {
        forceDataSchema: data.disableCreateObjectURL,
        maxImageSize: data.maxImageSize === undefined ? -1 : data.maxImageSize,
@@ -48962,35 +48974,18 @@
         newPdfManager.terminate();
         throw new Error('Worker was terminated');
        }
        pdfManager = newPdfManager;
        handler.send('PDFManagerReady', null);
        pdfManager.onLoadedStream().then(function (stream) {
         handler.send('DataLoaded', { length: stream.bytes.byteLength });
        });
-      }).then(function pdfManagerReady() {
-       ensureNotTerminated();
-       loadDocument(false).then(onSuccess, function loadFailure(ex) {
-        ensureNotTerminated();
-        if (!(ex instanceof XRefParseException)) {
-         if (ex instanceof PasswordException) {
-          pdfManager.passwordChanged().then(pdfManagerReady);
-         }
-         onFailure(ex);
-         return;
-        }
-        pdfManager.requestLoadedStream();
-        pdfManager.onLoadedStream().then(function () {
-         ensureNotTerminated();
-         loadDocument(true).then(onSuccess, onFailure);
-        });
-       }, onFailure);
-      }, onFailure);
-     };
+      }).then(pdfManagerReady, onFailure);
+     }
      handler.on('GetPage', function wphSetupGetPage(data) {
       return pdfManager.getPage(data.pageIndex).then(function (page) {
        var rotatePromise = pdfManager.ensure(page, 'rotate');
        var refPromise = pdfManager.ensure(page, 'ref');
        var userUnitPromise = pdfManager.ensure(page, 'userUnit');
        var viewPromise = pdfManager.ensure(page, 'view');
        return Promise.all([
         rotatePromise,
@@ -49040,19 +49035,16 @@
       pdfManager.requestLoadedStream();
       return pdfManager.onLoadedStream().then(function (stream) {
        return stream.bytes;
       });
      });
      handler.on('GetStats', function wphSetupGetStats(data) {
       return pdfManager.pdfDocument.xref.stats;
      });
-     handler.on('UpdatePassword', function wphSetupUpdatePassword(data) {
-      pdfManager.updatePassword(data);
-     });
      handler.on('GetAnnotations', function wphSetupGetAnnotations(data) {
       return pdfManager.getPage(data.pageIndex).then(function (page) {
        return pdfManager.ensure(page, 'getAnnotationsData', [data.intent]);
       });
      });
      handler.on('RenderPageRequest', function wphSetupRenderPage(data) {
       var pageIndex = data.pageIndex;
       pdfManager.getPage(pageIndex).then(function (page) {
--- a/browser/extensions/pdfjs/content/web/viewer.html
+++ b/browser/extensions/pdfjs/content/web/viewer.html
@@ -33,17 +33,16 @@ See https://github.com/adobe-type-tools/
 
 
     <link rel="stylesheet" href="viewer.css">
 
 
 
 
 
-
     <script src="viewer.js"></script>
 
   </head>
 
   <body tabindex="1" class="loadingInProgress">
     <div id="outerContainer">
 
       <div id="sidebarContainer">
--- a/browser/extensions/pdfjs/content/web/viewer.js
+++ b/browser/extensions/pdfjs/content/web/viewer.js
@@ -353,51 +353,56 @@ var pdfjsWebLibs;
     return PDFRenderingQueue;
    }();
    exports.RenderingStates = RenderingStates;
    exports.PDFRenderingQueue = PDFRenderingQueue;
   }));
   (function (root, factory) {
    factory(root.pdfjsWebPreferences = {});
   }(this, function (exports) {
-   var defaultPreferences;
-   defaultPreferences = Promise.resolve({
-    "showPreviousViewOnLoad": true,
-    "defaultZoomValue": "",
-    "sidebarViewOnLoad": 0,
-    "enableHandToolOnLoad": false,
-    "enableWebGL": false,
-    "pdfBugEnabled": false,
-    "disableRange": false,
-    "disableStream": false,
-    "disableAutoFetch": false,
-    "disableFontFace": false,
-    "disableTextLayer": false,
-    "useOnlyCssZoom": false,
-    "externalLinkTarget": 0,
-    "enhanceTextSelection": false,
-    "renderer": "canvas",
-    "renderInteractiveForms": false,
-    "disablePageLabels": false
-   });
+   var defaultPreferences = null;
+   function getDefaultPreferences() {
+    if (!defaultPreferences) {
+     defaultPreferences = Promise.resolve({
+      "showPreviousViewOnLoad": true,
+      "defaultZoomValue": "",
+      "sidebarViewOnLoad": 0,
+      "enableHandToolOnLoad": false,
+      "enableWebGL": false,
+      "pdfBugEnabled": false,
+      "disableRange": false,
+      "disableStream": false,
+      "disableAutoFetch": false,
+      "disableFontFace": false,
+      "disableTextLayer": false,
+      "useOnlyCssZoom": false,
+      "externalLinkTarget": 0,
+      "enhanceTextSelection": false,
+      "renderer": "canvas",
+      "renderInteractiveForms": false,
+      "disablePageLabels": false
+     });
+    }
+    return defaultPreferences;
+   }
    function cloneObj(obj) {
     var result = {};
     for (var i in obj) {
      if (Object.prototype.hasOwnProperty.call(obj, i)) {
       result[i] = obj[i];
      }
     }
     return result;
    }
    var Preferences = {
     prefs: null,
     isInitializedPromiseResolved: false,
     initializedPromise: null,
     initialize: function preferencesInitialize() {
-     return this.initializedPromise = defaultPreferences.then(function (defaults) {
+     return this.initializedPromise = getDefaultPreferences().then(function (defaults) {
       Object.defineProperty(this, 'defaults', {
        value: Object.freeze(defaults),
        writable: false,
        enumerable: true,
        configurable: false
       });
       this.prefs = cloneObj(defaults);
       return this._readFromStorage(defaults);
@@ -1127,33 +1132,35 @@ var pdfjsWebLibs;
      if (x_ <= p / q) {
       c = p;
       d = q;
      } else {
       a = p;
       b = q;
      }
     }
+    var result;
     if (x_ - a / b < c / d - x_) {
-     return x_ === x ? [
+     result = x_ === x ? [
       a,
       b
      ] : [
       b,
       a
      ];
     } else {
-     return x_ === x ? [
+     result = x_ === x ? [
       c,
       d
      ] : [
       d,
       c
      ];
     }
+    return result;
    }
    function roundToDivide(x, div) {
     var r = x % div;
     return r === 0 ? x : Math.round(x - r + div);
    }
    function getVisibleElements(scrollEl, views, sortByVisibility) {
     var top = scrollEl.scrollTop, bottom = top + scrollEl.clientHeight;
     var left = scrollEl.scrollLeft, right = left + scrollEl.clientWidth;
@@ -1696,22 +1703,21 @@ var pdfjsWebLibs;
       var fileSize = this.rawFileSize, kb = fileSize / 1024;
       if (!kb) {
        return;
       } else if (kb < 1024) {
        return mozL10n.get('document_properties_kb', {
         size_kb: (+kb.toPrecision(3)).toLocaleString(),
         size_b: fileSize.toLocaleString()
        }, '{{size_kb}} KB ({{size_b}} bytes)');
-      } else {
-       return mozL10n.get('document_properties_mb', {
-        size_mb: (+(kb / 1024).toPrecision(3)).toLocaleString(),
-        size_b: fileSize.toLocaleString()
-       }, '{{size_mb}} MB ({{size_b}} bytes)');
-      }
+      }
+      return mozL10n.get('document_properties_mb', {
+       size_mb: (+(kb / 1024).toPrecision(3)).toLocaleString(),
+       size_b: fileSize.toLocaleString()
+      }, '{{size_mb}} MB ({{size_b}} bytes)');
      },
      _parseDate: function PDFDocumentProperties_parseDate(inputDate) {
       var dateToParse = inputDate;
       if (dateToParse === undefined) {
        return '';
       }
       if (dateToParse.substring(0, 2) === 'D:') {
        dateToParse = dateToParse.substring(2);
@@ -2022,27 +2028,26 @@ var pdfjsWebLibs;
       var offset = this.offset;
       var numMatches = matches.length;
       var previous = this.state.findPrevious;
       if (numMatches) {
        this.hadMatch = true;
        offset.matchIdx = previous ? numMatches - 1 : 0;
        this.updateMatch(true);
        return true;
-      } else {
-       this.advanceOffsetPage(previous);
-       if (offset.wrapped) {
-        offset.matchIdx = null;
-        if (this.pagesToSearch < 0) {
-         this.updateMatch(false);
-         return true;
-        }
-       }
-       return false;
-      }
+      }
+      this.advanceOffsetPage(previous);
+      if (offset.wrapped) {
+       offset.matchIdx = null;
+       if (this.pagesToSearch < 0) {
+        this.updateMatch(false);
+        return true;
+       }
+      }
+      return false;
      },
      updateMatchPosition: function PDFFindController_updateMatchPosition(pageIndex, index, elements, beginIdx) {
       if (this.selected.matchIdx === index && this.selected.pageIdx === pageIndex) {
        var spot = {
         top: FIND_SCROLL_OFFSET_TOP,
         left: FIND_SCROLL_OFFSET_LEFT
        };
        scrollIntoView(elements[beginIdx], spot, true);
@@ -3369,19 +3374,18 @@ var pdfjsWebLibs;
       }
       return;
      }
      if (this.nextHashParam) {
       if (this.nextHashParam === params.hash) {
        this.nextHashParam = null;
        this.updatePreviousBookmark = true;
        return;
-      } else {
-       this.nextHashParam = null;
-      }
+      }
+      this.nextHashParam = null;
      }
      if (params.hash) {
       if (this.current.hash) {
        if (this.current.hash !== params.hash) {
         this._pushToHistory(params, true);
        } else {
         if (!this.current.page && params.page) {
          this._pushToHistory(params, false, true);
@@ -3571,17 +3575,16 @@ var pdfjsWebLibs;
          });
         }
        } else {
         self.pdfDocument.getPageIndex(destRef).then(function (pageIndex) {
          self.cachePageRef(pageIndex + 1, destRef);
          goToDestination(destRef);
         }).catch(function () {
          console.error('PDFLinkService_navigateTo: "' + destRef + '" is not a valid page reference.');
-         return;
         });
        }
       };
       var destinationPromise;
       if (typeof dest === 'string') {
        destString = dest;
        destinationPromise = this.pdfDocument.getDestination(dest);
       } else {
@@ -5331,29 +5334,28 @@ var pdfjsWebLibs;
       return this.presentationModeState === PresentationModeState.CHANGING;
      },
      get isHorizontalScrollbarEnabled() {
       return this.isInPresentationMode ? false : this.container.scrollWidth > this.container.clientWidth;
      },
      _getVisiblePages: function () {
       if (!this.isInPresentationMode) {
        return getVisibleElements(this.container, this._pages, true);
-      } else {
-       var visible = [];
-       var currentPage = this._pages[this._currentPageNumber - 1];
-       visible.push({
-        id: currentPage.id,
-        view: currentPage
-       });
-       return {
-        first: currentPage,
-        last: currentPage,
-        views: visible
-       };
-      }
+      }
+      var visible = [];
+      var currentPage = this._pages[this._currentPageNumber - 1];
+      visible.push({
+       id: currentPage.id,
+       view: currentPage
+      });
+      return {
+       first: currentPage,
+       last: currentPage,
+       views: visible
+      };
      },
      cleanup: function () {
       for (var i = 0, ii = this._pages.length; i < ii; i++) {
        if (this._pages[i] && this._pages[i].renderingState !== RenderingStates.FINISHED) {
         this._pages[i].reset();
        }
       }
      },
@@ -7357,9 +7359,13 @@ function getViewerConfiguration() {
   debuggerScriptPath: './debugger.js'
  };
 }
 function webViewerLoad() {
  var config = getViewerConfiguration();
  window.PDFViewerApplication = pdfjsWebLibs.pdfjsWebApp.PDFViewerApplication;
  pdfjsWebLibs.pdfjsWebApp.PDFViewerApplication.run(config);
 }
-document.addEventListener('DOMContentLoaded', webViewerLoad, true);
\ No newline at end of file
+if (document.readyState === 'interactive' || document.readyState === 'complete') {
+ webViewerLoad();
+} else {
+ document.addEventListener('DOMContentLoaded', webViewerLoad, true);
+}
\ No newline at end of file
deleted file mode 100644
index 318cea0f6f7f652dc93bebddb66794b844fd6ec8..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
GIT binary patch
literal 0
Hc$@<O00001
deleted file mode 100644
index 837f1814a335a1013481c79f6cde1ed0bcfbb7e4..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
GIT binary patch
literal 0
Hc$@<O00001
--- a/browser/installer/package-manifest.in
+++ b/browser/installer/package-manifest.in
@@ -218,26 +218,24 @@
 @RESPATH@/components/dom_workers.xpt
 @RESPATH@/components/dom_xbl.xpt
 @RESPATH@/components/dom_xhr.xpt
 @RESPATH@/components/dom_xpath.xpt
 @RESPATH@/components/dom_xul.xpt
 @RESPATH@/components/dom_presentation.xpt
 @RESPATH@/components/downloads.xpt
 @RESPATH@/components/editor.xpt
-@RESPATH@/components/embed_base.xpt
 @RESPATH@/components/extensions.xpt
 @RESPATH@/components/exthandler.xpt
 @RESPATH@/components/exthelper.xpt
 @RESPATH@/components/fastfind.xpt
 @RESPATH@/components/feeds.xpt
 #ifdef MOZ_GTK
 @RESPATH@/components/filepicker.xpt
 #endif
-@RESPATH@/components/find.xpt
 @RESPATH@/components/gfx.xpt
 @RESPATH@/components/html5.xpt
 @RESPATH@/components/htmlparser.xpt
 @RESPATH@/components/identity.xpt
 @RESPATH@/components/imglib2.xpt
 @RESPATH@/components/inspector.xpt
 @RESPATH@/components/intl.xpt
 @RESPATH@/components/jar.xpt
@@ -322,16 +320,17 @@
 @RESPATH@/components/uriloader.xpt
 @RESPATH@/components/urlformatter.xpt
 @RESPATH@/components/webBrowser_core.xpt
 @RESPATH@/components/webbrowserpersist.xpt
 @RESPATH@/components/widget.xpt
 #ifdef XP_MACOSX
 @RESPATH@/components/widget_cocoa.xpt
 #endif
+@RESPATH@/components/windowcreator.xpt
 @RESPATH@/components/windowds.xpt
 @RESPATH@/components/windowwatcher.xpt
 @RESPATH@/components/xpcom_base.xpt
 @RESPATH@/components/xpcom_system.xpt
 @RESPATH@/components/xpcom_components.xpt
 @RESPATH@/components/xpcom_ds.xpt
 @RESPATH@/components/xpcom_io.xpt
 @RESPATH@/components/xpcom_threads.xpt
--- a/browser/themes/shared/jar.inc.mn
+++ b/browser/themes/shared/jar.inc.mn
@@ -65,17 +65,16 @@
 * skin/classic/browser/identity-icon.svg                       (../shared/identity-block/identity-icon.svg)
   skin/classic/browser/info.svg                                (../shared/info.svg)
 * skin/classic/browser/menuPanel.svg                           (../shared/menuPanel.svg)
 * skin/classic/browser/menuPanel-small.svg                     (../shared/menuPanel-small.svg)
 * skin/classic/browser/notification-icons.svg                  (../shared/notification-icons.svg)
 * skin/classic/browser/tracking-protection-16.svg              (../shared/identity-block/tracking-protection-16.svg)
   skin/classic/browser/newtab/close.png                        (../shared/newtab/close.png)
   skin/classic/browser/newtab/controls.svg                     (../shared/newtab/controls.svg)
-  skin/classic/browser/newtab/whimsycorn.png                   (../shared/newtab/whimsycorn.png)
   skin/classic/browser/panel-icons.svg                         (../shared/panel-icons.svg)
   skin/classic/browser/preferences/in-content/favicon.ico      (../shared/incontentprefs/favicon.ico)
   skin/classic/browser/preferences/in-content/icons.svg        (../shared/incontentprefs/icons.svg)
   skin/classic/browser/preferences/in-content/search.css       (../shared/incontentprefs/search.css)
 * skin/classic/browser/preferences/in-content/containers.css   (../shared/incontentprefs/containers.css)
 * skin/classic/browser/preferences/containers.css              (../shared/preferences/containers.css)
   skin/classic/browser/fxa/default-avatar.svg                  (../shared/fxa/default-avatar.svg)
   skin/classic/browser/fxa/logo.png                            (../shared/fxa/logo.png)
@@ -95,18 +94,16 @@
   skin/classic/browser/badge-add-engine.png                    (../shared/search/badge-add-engine.png)
   skin/classic/browser/badge-add-engine@2x.png                 (../shared/search/badge-add-engine@2x.png)
   skin/classic/browser/search-indicator-badge-add.png          (../shared/search/search-indicator-badge-add.png)
   skin/classic/browser/search-indicator-badge-add@2x.png       (../shared/search/search-indicator-badge-add@2x.png)
   skin/classic/browser/search-history-icon.svg                 (../shared/search/history-icon.svg)
   skin/classic/browser/search-indicator-magnifying-glass.svg   (../shared/search/search-indicator-magnifying-glass.svg)
   skin/classic/browser/search-arrow-go.svg                     (../shared/search/search-arrow-go.svg)
   skin/classic/browser/gear.svg                                (../shared/search/gear.svg)
-  skin/classic/browser/social/gear_default.png                 (../shared/social/gear_default.png)
-  skin/classic/browser/social/gear_clicked.png                 (../shared/social/gear_clicked.png)
   skin/classic/browser/tabbrowser/connecting.png               (../shared/tabbrowser/connecting.png)
   skin/classic/browser/tabbrowser/connecting@2x.png            (../shared/tabbrowser/connecting@2x.png)
   skin/classic/browser/tabbrowser/crashed.svg                  (../shared/tabbrowser/crashed.svg)
   skin/classic/browser/tabbrowser/pendingpaint.png             (../shared/tabbrowser/pendingpaint.png)
   skin/classic/browser/tabbrowser/tab-audio.svg                (../shared/tabbrowser/tab-audio.svg)
   skin/classic/browser/tabbrowser/tab-audio-small.svg          (../shared/tabbrowser/tab-audio-small.svg)
   skin/classic/browser/tabbrowser/tab-overflow-indicator.png   (../shared/tabbrowser/tab-overflow-indicator.png)
   skin/classic/browser/toolbarbutton-dropdown-arrow.png        (../shared/toolbarbutton-dropdown-arrow.png)
deleted file mode 100644
index 5c5c2f4989fdb128cae9fa39a8b6063d84276398..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
GIT binary patch
literal 0
Hc$@<O00001
deleted file mode 100644
index 7c93aa767e4b9542ab143f6bf7062514761f7304..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
GIT binary patch
literal 0
Hc$@<O00001
deleted file mode 100644
index 2a9c8e19895a44c153fb6cc953d7373778befd3a..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
GIT binary patch
literal 0
Hc$@<O00001
--- a/browser/themes/windows/jar.mn
+++ b/browser/themes/windows/jar.mn
@@ -10,17 +10,16 @@ browser.jar:
   skin/classic/browser/aboutSyncTabs.css
 * skin/classic/browser/syncedtabs/sidebar.css     (syncedtabs/sidebar.css)
 * skin/classic/browser/browser.css
 * skin/classic/browser/devedition.css
 * skin/classic/browser/browser-lightweightTheme.css
   skin/classic/browser/caption-buttons.svg
   skin/classic/browser/click-to-play-warning-stripes.png
   skin/classic/browser/Info.png
-  skin/classic/browser/keyhole-forward-mask.svg
   skin/classic/browser/livemark-folder.png
   skin/classic/browser/menu-back.png
   skin/classic/browser/menu-forward.png
   skin/classic/browser/menuPanel-customize.png
   skin/classic/browser/menuPanel-customize@2x.png
   skin/classic/browser/menuPanel-exit.png
   skin/classic/browser/menuPanel-exit@2x.png
   skin/classic/browser/menuPanel-help.png
deleted file mode 100644
--- a/browser/themes/windows/keyhole-forward-mask.svg
+++ /dev/null
@@ -1,14 +0,0 @@
-<?xml version="1.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/. -->
-<svg xmlns="http://www.w3.org/2000/svg">
-  <mask id="mask" maskContentUnits="objectBoundingBox">
-    <rect x="0" y="0" width="1" height="1" fill="#fff"/>
-    <circle cx="-0.46" cy="0.5" r="0.63"/>
-  </mask>
-  <mask id="mask-hover" maskContentUnits="objectBoundingBox">
-    <rect x="0" y="0" width="1" height="1" fill="#fff"/>
-    <circle cx="-0.35" cy="0.5" r="0.58"/>
-  </mask>
-</svg>
--- a/devtools/client/debugger/test/mochitest/browser2.ini
+++ b/devtools/client/debugger/test/mochitest/browser2.ini
@@ -268,17 +268,17 @@ skip-if = e10s && debug
 skip-if = e10s && debug
 [browser_dbg_search-symbols.js]
 skip-if = (e10s && debug) || os == "linux" # Bug 1132375
 [browser_dbg_searchbox-help-popup-01.js]
 skip-if = e10s && debug
 [browser_dbg_searchbox-help-popup-02.js]
 skip-if = e10s && debug
 [browser_dbg_searchbox-parse.js]
-skip-if = e10s && debug
+skip-if = (e10s && debug) || (os == 'linux' && asan) # asan, bug 1313861
 [browser_dbg_source-maps-01.js]
 skip-if = e10s && debug
 [browser_dbg_source-maps-02.js]
 skip-if = e10s && debug
 [browser_dbg_source-maps-03.js]
 skip-if = e10s && debug
 [browser_dbg_source-maps-04.js]
 skip-if = e10s # Bug 1093535
--- a/devtools/client/webconsole/test/browser_console_history_persist.js
+++ b/devtools/client/webconsole/test/browser_console_history_persist.js
@@ -3,16 +3,18 @@
 /* Any copyright is dedicated to the Public Domain.
  * http://creativecommons.org/publicdomain/zero/1.0/ */
 
 // Test that console command input is persisted across toolbox loads.
 // See Bug 943306.
 
 "use strict";
 
+requestLongerTimeout(2);
+
 const TEST_URI = "data:text/html;charset=utf-8,Web Console test for " +
                  "persisting history - bug 943306";
 const INPUT_HISTORY_COUNT = 10;
 
 add_task(function* () {
   info("Setting custom input history pref to " + INPUT_HISTORY_COUNT);
   Services.prefs.setIntPref("devtools.webconsole.inputHistoryCount",
                             INPUT_HISTORY_COUNT);
--- a/devtools/client/webconsole/test/browser_webconsole_bug_614793_jsterm_scroll.js
+++ b/devtools/client/webconsole/test/browser_webconsole_bug_614793_jsterm_scroll.js
@@ -3,16 +3,18 @@
 /* Any copyright is dedicated to the Public Domain.
  * http://creativecommons.org/publicdomain/zero/1.0/ */
 
 "use strict";
 
 const TEST_URI = "data:text/html;charset=utf-8,Web Console test for " +
                  "bug 614793: jsterm result scroll";
 
+requestLongerTimeout(2);
+
 add_task(function* () {
   yield loadTab(TEST_URI);
   let hud = yield openConsole();
 
   yield testScrollPosition(hud);
 });
 
 function* testScrollPosition(hud) {
--- a/docshell/base/moz.build
+++ b/docshell/base/moz.build
@@ -10,76 +10,86 @@ DIRS += [
 
 XPIDL_SOURCES += [
     'nsCDefaultURIFixup.idl',
     'nsIClipboardCommands.idl',
     'nsIContentViewer.idl',
     'nsIContentViewerContainer.idl',
     'nsIContentViewerEdit.idl',
     'nsIContentViewerFile.idl',
+    'nsIContextMenuListener.idl',
+    'nsIContextMenuListener2.idl',
     'nsIDocCharset.idl',
     'nsIDocShell.idl',
     'nsIDocShellLoadInfo.idl',
     'nsIDocShellTreeItem.idl',
     'nsIDocShellTreeOwner.idl',
     'nsIDocumentLoaderFactory.idl',
     'nsIDownloadHistory.idl',
     'nsIGlobalHistory2.idl',
     'nsILoadContext.idl',
     'nsIPrivacyTransitionObserver.idl',
     'nsIReflowObserver.idl',
     'nsIRefreshURI.idl',
     'nsIScrollable.idl',
     'nsITextScroll.idl',
+    'nsITooltipListener.idl',
+    'nsITooltipTextProvider.idl',
     'nsIURIFixup.idl',
     'nsIWebNavigation.idl',
     'nsIWebNavigationInfo.idl',
     'nsIWebPageDescriptor.idl',
 ]
 
 XPIDL_MODULE = 'docshell'
 
 EXPORTS += [
+    'nsCTooltipTextProvider.h',
     'nsDocShellLoadTypes.h',
+    'nsDocShellTreeOwner.h',
     'nsILinkHandler.h',
     'nsIScrollObserver.h',
     'nsIWebShellServices.h',
     'SerializedLoadContext.h',
 ]
 
 EXPORTS.mozilla += [
     'IHistory.h',
     'LoadContext.h',
 ]
 
 UNIFIED_SOURCES += [
     'LoadContext.cpp',
     'nsAboutRedirector.cpp',
+    'nsContextMenuInfo.cpp',
     'nsDefaultURIFixup.cpp',
     'nsDocShell.cpp',
     'nsDocShellEditorData.cpp',
     'nsDocShellEnumerator.cpp',
     'nsDocShellLoadInfo.cpp',
     'nsDocShellTransferableHooks.cpp',
+    'nsDocShellTreeOwner.cpp',
     'nsDownloadHistory.cpp',
     'nsDSURIContentListener.cpp',
     'nsWebNavigationInfo.cpp',
     'SerializedLoadContext.cpp',
 ]
 
 include('/ipc/chromium/chromium-config.mozbuild')
 
 FINAL_LIBRARY = 'xul'
 LOCAL_INCLUDES += [
     '/docshell/shistory',
     '/dom/base',
     '/layout/base',
     '/layout/generic',
+    '/layout/style',
     '/layout/xul',
     '/netwerk/protocol/viewsource',
+    '/toolkit/components/browser',
     '/tools/profiler',
 ]
 
 if CONFIG['MOZ_TOOLKIT_SEARCH']:
     DEFINES['MOZ_TOOLKIT_SEARCH'] = True
 
 if CONFIG['MOZ_DEVTOOLS'] == 'all':
     DEFINES['MOZ_DEVTOOLS_ALL'] = True
rename from embedding/browser/nsCTooltipTextProvider.h
rename to docshell/base/nsCTooltipTextProvider.h
rename from embedding/browser/nsContextMenuInfo.cpp
rename to docshell/base/nsContextMenuInfo.cpp
rename from embedding/browser/nsContextMenuInfo.h
rename to docshell/base/nsContextMenuInfo.h
rename from embedding/browser/nsDocShellTreeOwner.cpp
rename to docshell/base/nsDocShellTreeOwner.cpp
rename from embedding/browser/nsDocShellTreeOwner.h
rename to docshell/base/nsDocShellTreeOwner.h
rename from embedding/browser/nsIContextMenuListener.idl
rename to docshell/base/nsIContextMenuListener.idl
rename from embedding/browser/nsIContextMenuListener2.idl
rename to docshell/base/nsIContextMenuListener2.idl
rename from embedding/browser/nsITooltipListener.idl
rename to docshell/base/nsITooltipListener.idl
rename from embedding/browser/nsITooltipTextProvider.idl
rename to docshell/base/nsITooltipTextProvider.idl
--- a/dom/base/ElementInlines.h
+++ b/dom/base/ElementInlines.h
@@ -53,16 +53,21 @@ inline bool
 Element::ShouldTraverseForServo()
 {
   return HasDirtyDescendantsForServo() || Servo_Element_ShouldTraverse(this);
 }
 
 inline void
 Element::NoteDirtyDescendantsForServo()
 {
+  if (!HasServoData()) {
+    // The dirty descendants bit only applies to styled elements.
+    return;
+  }
+
   Element* curr = this;
   while (curr && !curr->HasDirtyDescendantsForServo()) {
     curr->SetHasDirtyDescendantsForServo();
     curr = curr->GetFlattenedTreeParentElementForStyle();
   }
 
   MOZ_ASSERT(DirtyDescendantsBitIsPropagatedForServo());
 }
--- a/dom/base/nsDOMClassInfo.cpp
+++ b/dom/base/nsDOMClassInfo.cpp
@@ -788,16 +788,23 @@ nsDOMClassInfo::GetScriptableFlags()
 
 // virtual
 const js::Class*
 nsDOMClassInfo::GetClass()
 {
     return &mData->mClass;
 }
 
+// virtual
+const JSClass*
+nsDOMClassInfo::GetJSClass()
+{
+    return Jsvalify(&mData->mClass);
+}
+
 NS_IMETHODIMP
 nsDOMClassInfo::PreCreate(nsISupports *nativeObj, JSContext *cx,
                           JSObject *globalObj, JSObject **parentObj)
 {
   *parentObj = globalObj;
   return NS_OK;
 }
 
rename from embedding/components/commandhandler/moz.build
rename to dom/commandhandler/moz.build
rename from embedding/components/commandhandler/nsBaseCommandController.cpp
rename to dom/commandhandler/nsBaseCommandController.cpp
rename from embedding/components/commandhandler/nsBaseCommandController.h
rename to dom/commandhandler/nsBaseCommandController.h
rename from embedding/components/commandhandler/nsCommandGroup.cpp
rename to dom/commandhandler/nsCommandGroup.cpp
rename from embedding/components/commandhandler/nsCommandGroup.h
rename to dom/commandhandler/nsCommandGroup.h
rename from embedding/components/commandhandler/nsCommandManager.cpp
rename to dom/commandhandler/nsCommandManager.cpp
rename from embedding/components/commandhandler/nsCommandManager.h
rename to dom/commandhandler/nsCommandManager.h
rename from embedding/components/commandhandler/nsCommandParams.cpp
rename to dom/commandhandler/nsCommandParams.cpp
rename from embedding/components/commandhandler/nsCommandParams.h
rename to dom/commandhandler/nsCommandParams.h
rename from embedding/components/commandhandler/nsControllerCommandTable.cpp
rename to dom/commandhandler/nsControllerCommandTable.cpp
rename from embedding/components/commandhandler/nsControllerCommandTable.h
rename to dom/commandhandler/nsControllerCommandTable.h
rename from embedding/components/commandhandler/nsICommandManager.idl
rename to dom/commandhandler/nsICommandManager.idl
rename from embedding/components/commandhandler/nsICommandParams.idl
rename to dom/commandhandler/nsICommandParams.idl
rename from embedding/components/commandhandler/nsIControllerCommand.idl
rename to dom/commandhandler/nsIControllerCommand.idl
rename from embedding/components/commandhandler/nsIControllerCommandTable.idl
rename to dom/commandhandler/nsIControllerCommandTable.idl
rename from embedding/components/commandhandler/nsIControllerContext.idl
rename to dom/commandhandler/nsIControllerContext.idl
rename from embedding/components/commandhandler/nsPICommandUpdater.idl
rename to dom/commandhandler/nsPICommandUpdater.idl
--- a/dom/html/crashtests/crashtests.list
+++ b/dom/html/crashtests/crashtests.list
@@ -12,17 +12,17 @@ load 382568-1.html
 asserts-if(stylo,1) load 383137.xhtml # bug 1324704
 load 388183-1.html
 skip-if(stylo) load 395340-1.html # bug 1323652
 load 399694-1.html
 load 407053.html
 load 423371-1.html
 load 448564.html
 load 451123-1.html
-skip-if(stylo) load 453406-1.html # bug 1323654
+load 453406-1.html
 load 464197-1.html
 load 465466-1.xhtml
 load 468562-1.html
 load 468562-2.html
 load 494225.html
 load 495543.svg
 load 495546-1.html
 load 504183-1.html
--- a/dom/ipc/ContentChild.cpp
+++ b/dom/ipc/ContentChild.cpp
@@ -2442,17 +2442,20 @@ ContentChild::GetRemoteType() const
 {
   return mRemoteType;
 }
 
 mozilla::ipc::IPCResult
 ContentChild::RecvInitServiceWorkers(const ServiceWorkerConfiguration& aConfig)
 {
   RefPtr<ServiceWorkerManager> swm = ServiceWorkerManager::GetInstance();
-  MOZ_ASSERT(swm);
+  if (!swm) {
+    // browser shutdown began
+    return IPC_OK();
+  }
   swm->LoadRegistrations(aConfig.serviceWorkerRegistrations());
   return IPC_OK();
 }
 
 mozilla::ipc::IPCResult
 ContentChild::RecvInitBlobURLs(nsTArray<BlobURLRegistrationData>&& aRegistrations)
 {
   for (uint32_t i = 0; i < aRegistrations.Length(); ++i) {
--- a/dom/ipc/moz.build
+++ b/dom/ipc/moz.build
@@ -121,24 +121,24 @@ LOCAL_INCLUDES += [
     '/dom/devicestorage',
     '/dom/events',
     '/dom/filesystem',
     '/dom/geolocation',
     '/dom/media/webspeech/synth/ipc',
     '/dom/security',
     '/dom/storage',
     '/dom/workers',
-    '/embedding/components/printingui/ipc',
     '/extensions/cookie',
     '/extensions/spellcheck/src',
     '/gfx/2d',
     '/hal/sandbox',
     '/layout/base',
     '/media/webrtc',
     '/netwerk/base',
+    '/toolkit/components/printingui/ipc',
     '/toolkit/crashreporter',
     '/toolkit/xre',
     '/uriloader/exthandler',
     '/widget',
     '/xpcom/base',
     '/xpcom/threads',
 ]
 
--- a/dom/moz.build
+++ b/dom/moz.build
@@ -38,16 +38,17 @@ DIRS += [
     'animation',
     'base',
     'archivereader',
     'bindings',
     'battery',
     'browser-element',
     'cache',
     'canvas',
+    'commandhandler',
     'crypto',
     'devicestorage',
     'encoding',
     'events',
     'fetch',
     'file',
     'filehandle',
     'filesystem',
@@ -91,16 +92,17 @@ DIRS += [
     'xml',
     'xslt',
     'xul',
     'manifest',
     'vr',
     'u2f',
     'console',
     'performance',
+    'webbrowserpersist',
     'xhr',
     'worklet',
 ]
 
 if CONFIG['OS_ARCH'] == 'WINNT':
     DIRS += ['plugins/ipc/hangui']
 
 if CONFIG['MOZ_SECUREELEMENT']:
--- a/dom/notification/Notification.cpp
+++ b/dom/notification/Notification.cpp
@@ -2553,16 +2553,22 @@ public:
     nsIPrincipal* principal = mWorkerPrivate->GetPrincipal();
     mRv = CheckScope(principal, mScope);
 
     if (NS_FAILED(mRv)) {
       return true;
     }
 
     RefPtr<ServiceWorkerManager> swm = ServiceWorkerManager::GetInstance();
+    if (!swm) {
+      // browser shutdown began
+      mRv = NS_ERROR_FAILURE;
+      return true;
+    }
+
     RefPtr<ServiceWorkerRegistrationInfo> registration =
       swm->GetRegistration(principal, mScope);
 
     // This is coming from a ServiceWorkerRegistration.
     MOZ_ASSERT(registration);
 
     if (!registration->GetActive() ||
         registration->GetActive()->ID() != mWorkerPrivate->ServiceWorkerID()) {
rename from embedding/components/webbrowserpersist/PWebBrowserPersistDocument.ipdl
rename to dom/webbrowserpersist/PWebBrowserPersistDocument.ipdl
rename from embedding/components/webbrowserpersist/PWebBrowserPersistResources.ipdl
rename to dom/webbrowserpersist/PWebBrowserPersistResources.ipdl
rename from embedding/components/webbrowserpersist/PWebBrowserPersistSerialize.ipdl
rename to dom/webbrowserpersist/PWebBrowserPersistSerialize.ipdl
rename from embedding/components/webbrowserpersist/WebBrowserPersistDocumentChild.cpp
rename to dom/webbrowserpersist/WebBrowserPersistDocumentChild.cpp
rename from embedding/components/webbrowserpersist/WebBrowserPersistDocumentChild.h
rename to dom/webbrowserpersist/WebBrowserPersistDocumentChild.h
rename from embedding/components/webbrowserpersist/WebBrowserPersistDocumentParent.cpp
rename to dom/webbrowserpersist/WebBrowserPersistDocumentParent.cpp
rename from embedding/components/webbrowserpersist/WebBrowserPersistDocumentParent.h
rename to dom/webbrowserpersist/WebBrowserPersistDocumentParent.h
rename from embedding/components/webbrowserpersist/WebBrowserPersistLocalDocument.cpp
rename to dom/webbrowserpersist/WebBrowserPersistLocalDocument.cpp
rename from embedding/components/webbrowserpersist/WebBrowserPersistLocalDocument.h
rename to dom/webbrowserpersist/WebBrowserPersistLocalDocument.h
rename from embedding/components/webbrowserpersist/WebBrowserPersistRemoteDocument.cpp
rename to dom/webbrowserpersist/WebBrowserPersistRemoteDocument.cpp
rename from embedding/components/webbrowserpersist/WebBrowserPersistRemoteDocument.h
rename to dom/webbrowserpersist/WebBrowserPersistRemoteDocument.h
rename from embedding/components/webbrowserpersist/WebBrowserPersistResourcesChild.cpp
rename to dom/webbrowserpersist/WebBrowserPersistResourcesChild.cpp
rename from embedding/components/webbrowserpersist/WebBrowserPersistResourcesChild.h
rename to dom/webbrowserpersist/WebBrowserPersistResourcesChild.h
rename from embedding/components/webbrowserpersist/WebBrowserPersistResourcesParent.cpp
rename to dom/webbrowserpersist/WebBrowserPersistResourcesParent.cpp
rename from embedding/components/webbrowserpersist/WebBrowserPersistResourcesParent.h
rename to dom/webbrowserpersist/WebBrowserPersistResourcesParent.h
rename from embedding/components/webbrowserpersist/WebBrowserPersistSerializeChild.cpp
rename to dom/webbrowserpersist/WebBrowserPersistSerializeChild.cpp
rename from embedding/components/webbrowserpersist/WebBrowserPersistSerializeChild.h
rename to dom/webbrowserpersist/WebBrowserPersistSerializeChild.h
rename from embedding/components/webbrowserpersist/WebBrowserPersistSerializeParent.cpp
rename to dom/webbrowserpersist/WebBrowserPersistSerializeParent.cpp
rename from embedding/components/webbrowserpersist/WebBrowserPersistSerializeParent.h
rename to dom/webbrowserpersist/WebBrowserPersistSerializeParent.h
rename from embedding/components/webbrowserpersist/moz.build
rename to dom/webbrowserpersist/moz.build
rename from embedding/components/webbrowserpersist/nsCWebBrowserPersist.idl
rename to dom/webbrowserpersist/nsCWebBrowserPersist.idl
rename from embedding/components/webbrowserpersist/nsIWebBrowserPersist.idl
rename to dom/webbrowserpersist/nsIWebBrowserPersist.idl
rename from embedding/components/webbrowserpersist/nsIWebBrowserPersistDocument.idl
rename to dom/webbrowserpersist/nsIWebBrowserPersistDocument.idl
rename from embedding/components/webbrowserpersist/nsIWebBrowserPersistable.idl
rename to dom/webbrowserpersist/nsIWebBrowserPersistable.idl
rename from embedding/components/webbrowserpersist/nsWebBrowserPersist.cpp
rename to dom/webbrowserpersist/nsWebBrowserPersist.cpp
rename from embedding/components/webbrowserpersist/nsWebBrowserPersist.h
rename to dom/webbrowserpersist/nsWebBrowserPersist.h
--- a/dom/workers/ServiceWorkerClients.cpp
+++ b/dom/workers/ServiceWorkerClients.cpp
@@ -126,20 +126,26 @@ public:
     MutexAutoLock lock(mPromiseProxy->Lock());
     if (mPromiseProxy->CleanedUp()) {
       return NS_OK;
     }
 
     WorkerPrivate* workerPrivate = mPromiseProxy->GetWorkerPrivate();
     MOZ_ASSERT(workerPrivate);
 
-    RefPtr<ServiceWorkerManager> swm = ServiceWorkerManager::GetInstance();
+    UniquePtr<ServiceWorkerClientInfo> result;
     ErrorResult rv;
-    UniquePtr<ServiceWorkerClientInfo> result = swm->GetClient(workerPrivate->GetPrincipal(),
-                                                               mClientId, rv);
+
+    RefPtr<ServiceWorkerManager> swm = ServiceWorkerManager::GetInstance();
+    if (!swm) {
+      rv = NS_ERROR_FAILURE;
+    } else {
+      result = swm->GetClient(workerPrivate->GetPrincipal(), mClientId, rv);
+    }
+
     RefPtr<ResolvePromiseWorkerRunnable> r =
       new ResolvePromiseWorkerRunnable(mPromiseProxy->GetWorkerPrivate(),
                                        mPromiseProxy, Move(result),
                                        rv.StealNSResult());
     rv.SuppressException();
 
     r->Dispatch();
     return NS_OK;
@@ -205,21 +211,22 @@ public:
   {
     AssertIsOnMainThread();
 
     MutexAutoLock lock(mPromiseProxy->Lock());
     if (mPromiseProxy->CleanedUp()) {
       return NS_OK;
     }
 
+    nsTArray<ServiceWorkerClientInfo> result;
     RefPtr<ServiceWorkerManager> swm = ServiceWorkerManager::GetInstance();
-    nsTArray<ServiceWorkerClientInfo> result;
-
-    swm->GetAllClients(mPromiseProxy->GetWorkerPrivate()->GetPrincipal(), mScope,
-                       mIncludeUncontrolled, result);
+    if (swm) {
+      swm->GetAllClients(mPromiseProxy->GetWorkerPrivate()->GetPrincipal(),
+                         mScope, mIncludeUncontrolled, result);
+    }
     RefPtr<ResolvePromiseWorkerRunnable> r =
       new ResolvePromiseWorkerRunnable(mPromiseProxy->GetWorkerPrivate(),
                                        mPromiseProxy, result);
 
     r->Dispatch();
     return NS_OK;
   }
 };
@@ -283,21 +290,25 @@ public:
     MutexAutoLock lock(mPromiseProxy->Lock());
     if (mPromiseProxy->CleanedUp()) {
       return NS_OK;
     }
 
     WorkerPrivate* workerPrivate = mPromiseProxy->GetWorkerPrivate();
     MOZ_ASSERT(workerPrivate);
 
+    nsresult rv = NS_OK;
     RefPtr<ServiceWorkerManager> swm = ServiceWorkerManager::GetInstance();
-    MOZ_ASSERT(swm);
-
-    nsresult rv = swm->ClaimClients(workerPrivate->GetPrincipal(),
-                                    mScope, mServiceWorkerID);
+    if (!swm) {
+      // browser shutdown
+      rv = NS_ERROR_FAILURE;
+    } else {
+      rv = swm->ClaimClients(workerPrivate->GetPrincipal(), mScope,
+                             mServiceWorkerID);
+    }
 
     RefPtr<ResolveClaimRunnable> r =
       new ResolveClaimRunnable(workerPrivate, mPromiseProxy, rv);
 
     r->Dispatch();
     return NS_OK;
   }
 };
@@ -531,17 +542,20 @@ public:
       nsCOMPtr<nsIDocShell> docShell = window->GetDocShell();
       nsCOMPtr<nsIWebProgress> webProgress = do_GetInterface(docShell);
 
       if (!webProgress) {
         return NS_ERROR_FAILURE;
       }
 
       RefPtr<ServiceWorkerManager> swm = ServiceWorkerManager::GetInstance();
-      MOZ_ASSERT(swm);
+      if (!swm) {
+        // browser shutdown
+        return NS_ERROR_FAILURE;
+      }
 
       nsCOMPtr<nsIPrincipal> principal = workerPrivate->GetPrincipal();
       MOZ_ASSERT(principal);
       RefPtr<ServiceWorkerRegistrationInfo> registration =
         swm->GetRegistration(principal, NS_ConvertUTF16toUTF8(mScope));
       if (NS_WARN_IF(!registration)) {
         return NS_ERROR_FAILURE;
       }
@@ -567,17 +581,20 @@ public:
       // to try opening a window again.
       nsCOMPtr<nsIObserverService> os = services::GetObserverService();
       NS_ENSURE_STATE(os);
 
       WorkerPrivate* workerPrivate = mPromiseProxy->GetWorkerPrivate();
       MOZ_ASSERT(workerPrivate);
 
       RefPtr<ServiceWorkerManager> swm = ServiceWorkerManager::GetInstance();
-      MOZ_ASSERT(swm);
+      if (!swm) {
+        // browser shutdown
+        return NS_ERROR_FAILURE;
+      }
 
       nsCOMPtr<nsIPrincipal> principal = workerPrivate->GetPrincipal();
       MOZ_ASSERT(principal);
 
       RefPtr<ServiceWorkerRegistrationInfo> registration =
         swm->GetRegistration(principal, NS_ConvertUTF16toUTF8(mScope));
       if (NS_WARN_IF(!registration)) {
         return NS_ERROR_FAILURE;
--- a/dom/workers/ServiceWorkerEvents.cpp
+++ b/dom/workers/ServiceWorkerEvents.cpp
@@ -869,16 +869,20 @@ public:
         NewRunnableMethod(this, &WaitUntilHandler::ReportOnMainThread)));
   }
 
   void
   ReportOnMainThread()
   {
     AssertIsOnMainThread();
     RefPtr<ServiceWorkerManager> swm = ServiceWorkerManager::GetInstance();
+    if (!swm) {
+      // browser shutdown
+      return;
+    }
 
     // TODO: Make the error message a localized string. (bug 1222720)
     nsString message;
     message.AppendLiteral("Service worker event waitUntil() was passed a "
                           "promise that rejected with '");
     message.Append(mRejectValue);
     message.AppendLiteral("'.");
 
--- a/dom/workers/ServiceWorkerJob.cpp
+++ b/dom/workers/ServiceWorkerJob.cpp
@@ -96,17 +96,22 @@ ServiceWorkerJob::Start(Callback* aFinal
 
   nsCOMPtr<nsIRunnable> runnable =
     NewRunnableMethod(this, &ServiceWorkerJob::AsyncExecute);
 
   // We may have to wait for the PBackground actor to be initialized
   // before proceeding.  We should always be able to get a ServiceWorkerManager,
   // however, since Start() should not be called during shutdown.
   RefPtr<ServiceWorkerManager> swm = ServiceWorkerManager::GetInstance();
+  if (!swm) {
+    // browser shutdown
+    return;
+  }
   if (!swm->HasBackgroundActor()) {
+    // waiting to initialize
     swm->AppendPendingOperation(runnable);
     return;
   }
 
   // Otherwise start asynchronously.  We should never run a job synchronously.
   MOZ_ALWAYS_TRUE(NS_SUCCEEDED(
     NS_DispatchToMainThread(runnable.forget())));
 }
--- a/dom/workers/ServiceWorkerManager.cpp
+++ b/dom/workers/ServiceWorkerManager.cpp
@@ -327,19 +327,20 @@ public:
     , mScope(aScope)
   {}
 
   NS_IMETHOD Run() override
   {
     AssertIsOnMainThread();
 
     RefPtr<ServiceWorkerManager> swm = ServiceWorkerManager::GetInstance();
-    MOZ_ASSERT(swm);
-
-    swm->PropagateSoftUpdate(mOriginAttributes, mScope);
+    if (swm) {
+      swm->PropagateSoftUpdate(mOriginAttributes, mScope);
+    }
+
     return NS_OK;
   }
 
 private:
   ~PropagateSoftUpdateRunnable()
   {}
 
   const OriginAttributes mOriginAttributes;
@@ -359,21 +360,18 @@ public:
     MOZ_ASSERT(aPrincipal);
   }
 
   NS_IMETHOD Run() override
   {
     AssertIsOnMainThread();
 
     RefPtr<ServiceWorkerManager> swm = ServiceWorkerManager::GetInstance();
-    MOZ_ASSERT(swm);
-
-    nsresult rv = swm->PropagateUnregister(mPrincipal, mCallback, mScope);
-    if (NS_WARN_IF(NS_FAILED(rv))) {
-      return rv;
+    if (swm) {
+      swm->PropagateUnregister(mPrincipal, mCallback, mScope);
     }
 
     return NS_OK;
   }
 
 private:
   ~PropagateUnregisterRunnable()
   {}
@@ -389,19 +387,20 @@ public:
   explicit RemoveRunnable(const nsACString& aHost)
   {}
 
   NS_IMETHOD Run() override
   {
     AssertIsOnMainThread();
 
     RefPtr<ServiceWorkerManager> swm = ServiceWorkerManager::GetInstance();
-    MOZ_ASSERT(swm);
-
-    swm->Remove(mHost);
+    if (swm) {
+      swm->Remove(mHost);
+    }
+
     return NS_OK;
   }
 
 private:
   ~RemoveRunnable()
   {}
 
   const nsCString mHost;
@@ -413,19 +412,20 @@ public:
   explicit PropagateRemoveRunnable(const nsACString& aHost)
   {}
 
   NS_IMETHOD Run() override
   {
     AssertIsOnMainThread();
 
     RefPtr<ServiceWorkerManager> swm = ServiceWorkerManager::GetInstance();
-    MOZ_ASSERT(swm);
-
-    swm->PropagateRemove(mHost);
+    if (swm) {
+      swm->PropagateRemove(mHost);
+    }
+
     return NS_OK;
   }
 
 private:
   ~PropagateRemoveRunnable()
   {}
 
   const nsCString mHost;
@@ -437,19 +437,20 @@ public:
   PropagateRemoveAllRunnable()
   {}
 
   NS_IMETHOD Run() override
   {
     AssertIsOnMainThread();
 
     RefPtr<ServiceWorkerManager> swm = ServiceWorkerManager::GetInstance();
-    MOZ_ASSERT(swm);
-
-    swm->PropagateRemoveAll();
+    if (swm) {
+      swm->PropagateRemoveAll();
+    }
+
     return NS_OK;
   }
 
 private:
   ~PropagateRemoveAllRunnable()
   {}
 };
 
@@ -654,16 +655,20 @@ public:
   GetRegistrationsRunnable(nsPIDOMWindowInner* aWindow, Promise* aPromise)
     : mWindow(aWindow), mPromise(aPromise)
   {}
 
   NS_IMETHOD
   Run() override
   {
     RefPtr<ServiceWorkerManager> swm = ServiceWorkerManager::GetInstance();
+    if (!swm) {
+      mPromise->MaybeReject(NS_ERROR_UNEXPECTED);
+      return NS_OK;
+    }
 
     nsIDocument* doc = mWindow->GetExtantDoc();
     if (!doc) {
       mPromise->MaybeReject(NS_ERROR_UNEXPECTED);
       return NS_OK;
     }
 
     nsCOMPtr<nsIURI> docURI = doc->GetDocumentURI();
@@ -778,16 +783,20 @@ public:
                           const nsAString& aDocumentURL)
     : mWindow(aWindow), mPromise(aPromise), mDocumentURL(aDocumentURL)
   {}
 
   NS_IMETHOD
   Run() override
   {
     RefPtr<ServiceWorkerManager> swm = ServiceWorkerManager::GetInstance();
+    if (!swm) {
+      mPromise->MaybeReject(NS_ERROR_UNEXPECTED);
+      return NS_OK;
+    }
 
     nsIDocument* doc = mWindow->GetExtantDoc();
     if (!doc) {
       mPromise->MaybeReject(NS_ERROR_UNEXPECTED);
       return NS_OK;
     }
 
     nsCOMPtr<nsIURI> docURI = doc->GetDocumentURI();
@@ -878,16 +887,20 @@ public:
   GetReadyPromiseRunnable(nsPIDOMWindowInner* aWindow, Promise* aPromise)
     : mWindow(aWindow), mPromise(aPromise)
   {}
 
   NS_IMETHOD
   Run() override
   {
     RefPtr<ServiceWorkerManager> swm = ServiceWorkerManager::GetInstance();
+    if (!swm) {
+      mPromise->MaybeReject(NS_ERROR_UNEXPECTED);
+      return NS_OK;
+    }
 
     nsIDocument* doc = mWindow->GetExtantDoc();
     if (!doc) {
       mPromise->MaybeReject(NS_ERROR_UNEXPECTED);
       return NS_OK;
     }
 
     nsCOMPtr<nsIURI> docURI = doc->GetDocumentURI();
@@ -1885,17 +1898,20 @@ ServiceWorkerManager::PrincipalToScopeKe
 /* static */ void
 ServiceWorkerManager::AddScopeAndRegistration(const nsACString& aScope,
                                               ServiceWorkerRegistrationInfo* aInfo)
 {
   MOZ_ASSERT(aInfo);
   MOZ_ASSERT(aInfo->mPrincipal);
 
   RefPtr<ServiceWorkerManager> swm = ServiceWorkerManager::GetInstance();
-  MOZ_ASSERT(swm);
+  if (!swm) {
+    // browser shutdown
+    return;
+  }
 
   nsAutoCString scopeKey;
   nsresult rv = swm->PrincipalToScopeKey(aInfo->mPrincipal, scopeKey);
   if (NS_WARN_IF(NS_FAILED(rv))) {
     return;
   }
 
   MOZ_ASSERT(!scopeKey.IsEmpty());
@@ -1936,19 +1952,18 @@ ServiceWorkerManager::AddScopeAndRegistr
 ServiceWorkerManager::FindScopeForPath(const nsACString& aScopeKey,
                                        const nsACString& aPath,
                                        RegistrationDataPerPrincipal** aData,
                                        nsACString& aMatch)
 {
   MOZ_ASSERT(aData);
 
   RefPtr<ServiceWorkerManager> swm = ServiceWorkerManager::GetInstance();
-  MOZ_ASSERT(swm);
-
-  if (!swm->mRegistrationInfos.Get(aScopeKey, aData)) {
+
+  if (!swm || !swm->mRegistrationInfos.Get(aScopeKey, aData)) {
     return false;
   }
 
   for (uint32_t i = 0; i < (*aData)->mOrderedScopes.Length(); ++i) {
     const nsCString& current = (*aData)->mOrderedScopes[i];
     if (StringBeginsWith(aPath, current)) {
       aMatch = current;
       return true;
@@ -1958,17 +1973,19 @@ ServiceWorkerManager::FindScopeForPath(c
   return false;
 }
 
 /* static */ bool
 ServiceWorkerManager::HasScope(nsIPrincipal* aPrincipal,
                                const nsACString& aScope)
 {
   RefPtr<ServiceWorkerManager> swm = ServiceWorkerManager::GetInstance();
-  MOZ_ASSERT(swm);
+  if (!swm) {
+    return false;
+  }
 
   nsAutoCString scopeKey;
   nsresult rv = PrincipalToScopeKey(aPrincipal, scopeKey);
   if (NS_WARN_IF(NS_FAILED(rv))) {
     return false;
   }
 
   RegistrationDataPerPrincipal* data;
@@ -1978,17 +1995,19 @@ ServiceWorkerManager::HasScope(nsIPrinci
 
   return data->mOrderedScopes.Contains(aScope);
 }
 
 /* static */ void
 ServiceWorkerManager::RemoveScopeAndRegistration(ServiceWorkerRegistrationInfo* aRegistration)
 {
   RefPtr<ServiceWorkerManager> swm = ServiceWorkerManager::GetInstance();
-  MOZ_ASSERT(swm);
+  if (!swm) {
+    return;
+  }
 
   nsAutoCString scopeKey;
   nsresult rv = swm->PrincipalToScopeKey(aRegistration->mPrincipal, scopeKey);
   if (NS_WARN_IF(NS_FAILED(rv))) {
     return;
   }
 
   RegistrationDataPerPrincipal* data;
@@ -3271,27 +3290,26 @@ ServiceWorkerManager::Remove(const nsACS
   // We need to postpone this operation in case we don't have an actor because
   // this is needed by the ForceUnregister.
   if (!mActor) {
     RefPtr<nsIRunnable> runnable = new RemoveRunnable(aHost);
     AppendPendingOperation(runnable);
     return;
   }
 
-  RefPtr<ServiceWorkerManager> swm = ServiceWorkerManager::GetInstance();
   for (auto it1 = mRegistrationInfos.Iter(); !it1.Done(); it1.Next()) {
     ServiceWorkerManager::RegistrationDataPerPrincipal* data = it1.UserData();
     for (auto it2 = data->mInfos.Iter(); !it2.Done(); it2.Next()) {
       ServiceWorkerRegistrationInfo* reg = it2.UserData();
       nsCOMPtr<nsIURI> scopeURI;
       nsresult rv = NS_NewURI(getter_AddRefs(scopeURI), it2.Key(),
                               nullptr, nullptr);
       // This way subdomains are also cleared.
       if (NS_SUCCEEDED(rv) && HasRootDomain(scopeURI, aHost)) {
-        swm->ForceUnregister(data, reg);
+        ForceUnregister(data, reg);
       }
     }
   }
 }
 
 void
 ServiceWorkerManager::PropagateRemove(const nsACString& aHost)
 {
@@ -3306,22 +3324,21 @@ ServiceWorkerManager::PropagateRemove(co
   mActor->SendPropagateRemove(nsCString(aHost));
 }
 
 void
 ServiceWorkerManager::RemoveAll()
 {
   AssertIsOnMainThread();
 
-  RefPtr<ServiceWorkerManager> swm = ServiceWorkerManager::GetInstance();
   for (auto it1 = mRegistrationInfos.Iter(); !it1.Done(); it1.Next()) {
     ServiceWorkerManager::RegistrationDataPerPrincipal* data = it1.UserData();
     for (auto it2 = data->mInfos.Iter(); !it2.Done(); it2.Next()) {
       ServiceWorkerRegistrationInfo* reg = it2.UserData();
-      swm->ForceUnregister(data, reg);
+      ForceUnregister(data, reg);
     }
   }
 }
 
 void
 ServiceWorkerManager::PropagateRemoveAll()
 {
   AssertIsOnMainThread();
@@ -3356,18 +3373,17 @@ ServiceWorkerManager::RemoveAllRegistrat
       MOZ_ASSERT(reg->mPrincipal);
 
       bool matches =
         aPattern->Matches(reg->mPrincipal->OriginAttributesRef());
       if (!matches) {
         continue;
       }
 
-      RefPtr<ServiceWorkerManager> swm = ServiceWorkerManager::GetInstance();
-      swm->ForceUnregister(data, reg);
+      ForceUnregister(data, reg);
     }
   }
 }
 
 NS_IMETHODIMP
 ServiceWorkerManager::AddListener(nsIServiceWorkerManagerListener* aListener)
 {
   AssertIsOnMainThread();
@@ -3702,17 +3718,19 @@ class ServiceWorkerManager::Interception
   // Weak reference to channel is safe, because the channel holds a
   // reference to this object.  Also, the pointer is only used for
   // comparison purposes.
   nsIInterceptedChannel* mChannel;
 
   ~InterceptionReleaseHandle()
   {
     RefPtr<ServiceWorkerManager> swm = ServiceWorkerManager::GetInstance();
-    swm->RemoveNavigationInterception(mScope, mChannel);
+    if (swm) {
+      swm->RemoveNavigationInterception(mScope, mChannel);
+    }
   }
 
 public:
   InterceptionReleaseHandle(const nsACString& aScope,
                             nsIInterceptedChannel* aChannel)
     : mScope(aScope)
     , mChannel(aChannel)
   {
--- a/dom/workers/ServiceWorkerManagerChild.cpp
+++ b/dom/workers/ServiceWorkerManagerChild.cpp
@@ -19,48 +19,53 @@ mozilla::ipc::IPCResult
 ServiceWorkerManagerChild::RecvNotifyRegister(
                                      const ServiceWorkerRegistrationData& aData)
 {
   if (mShuttingDown) {
     return IPC_OK();
   }
 
   RefPtr<ServiceWorkerManager> swm = ServiceWorkerManager::GetInstance();
-  MOZ_ASSERT(swm);
+  if (swm) {
+    swm->LoadRegistration(aData);
+  }
 
-  swm->LoadRegistration(aData);
   return IPC_OK();
 }
 
 mozilla::ipc::IPCResult
 ServiceWorkerManagerChild::RecvNotifySoftUpdate(
                                       const OriginAttributes& aOriginAttributes,
                                       const nsString& aScope)
 {
   if (mShuttingDown) {
     return IPC_OK();
   }
 
   RefPtr<ServiceWorkerManager> swm = ServiceWorkerManager::GetInstance();
-  MOZ_ASSERT(swm);
+  if (swm) {
+    swm->SoftUpdate(aOriginAttributes, NS_ConvertUTF16toUTF8(aScope));
+  }
 
-  swm->SoftUpdate(aOriginAttributes, NS_ConvertUTF16toUTF8(aScope));
   return IPC_OK();
 }
 
 mozilla::ipc::IPCResult
 ServiceWorkerManagerChild::RecvNotifyUnregister(const PrincipalInfo& aPrincipalInfo,
                                                 const nsString& aScope)
 {
   if (mShuttingDown) {
     return IPC_OK();
   }
 
   RefPtr<ServiceWorkerManager> swm = ServiceWorkerManager::GetInstance();
-  MOZ_ASSERT(swm);
+  if (!swm) {
+    // browser shutdown
+    return IPC_OK();
+  }
 
   nsCOMPtr<nsIPrincipal> principal = PrincipalInfoToPrincipal(aPrincipalInfo);
   if (NS_WARN_IF(!principal)) {
     return IPC_OK();
   }
 
   nsresult rv = swm->NotifyUnregister(principal, aScope);
   Unused << NS_WARN_IF(NS_FAILED(rv));
@@ -70,31 +75,33 @@ ServiceWorkerManagerChild::RecvNotifyUnr
 mozilla::ipc::IPCResult
 ServiceWorkerManagerChild::RecvNotifyRemove(const nsCString& aHost)
 {
   if (mShuttingDown) {
     return IPC_OK();
   }
 
   RefPtr<ServiceWorkerManager> swm = ServiceWorkerManager::GetInstance();
-  MOZ_ASSERT(swm);
+  if (swm) {
+    swm->Remove(aHost);
+  }
 
-  swm->Remove(aHost);
   return IPC_OK();
 }
 
 mozilla::ipc::IPCResult
 ServiceWorkerManagerChild::RecvNotifyRemoveAll()
 {
   if (mShuttingDown) {
     return IPC_OK();
   }
 
   RefPtr<ServiceWorkerManager> swm = ServiceWorkerManager::GetInstance();
-  MOZ_ASSERT(swm);
+  if (swm) {
+    swm->RemoveAll();
+  }
 
-  swm->RemoveAll();
   return IPC_OK();
 }
 
 } // namespace workers
 } // namespace dom
 } // namespace mozilla
--- a/dom/workers/ServiceWorkerPrivate.cpp
+++ b/dom/workers/ServiceWorkerPrivate.cpp
@@ -1697,23 +1697,21 @@ NS_IMPL_ISUPPORTS_INHERITED(FetchEventRu
 nsresult
 ServiceWorkerPrivate::SendFetchEvent(nsIInterceptedChannel* aChannel,
                                      nsILoadGroup* aLoadGroup,
                                      const nsAString& aDocumentId,
                                      bool aIsReload)
 {
   AssertIsOnMainThread();
 
-  if (NS_WARN_IF(!mInfo)) {
+  RefPtr<ServiceWorkerManager> swm = ServiceWorkerManager::GetInstance();
+  if (NS_WARN_IF(!mInfo || !swm)) {
     return NS_ERROR_FAILURE;
   }
 
-  RefPtr<ServiceWorkerManager> swm = ServiceWorkerManager::GetInstance();
-  MOZ_ASSERT(swm);
-
   RefPtr<ServiceWorkerRegistrationInfo> registration =
     swm->GetRegistration(mInfo->GetPrincipal(), mInfo->Scope());
 
   // Its possible the registration is removed between starting the interception
   // and actually dispatching the fetch event.  In these cases we simply
   // want to restart the original network request.  Since this is a normal
   // condition we handle the reset here instead of returning an error which
   // would in turn trigger a console report.
--- a/dom/workers/ServiceWorkerRegisterJob.cpp
+++ b/dom/workers/ServiceWorkerRegisterJob.cpp
@@ -22,22 +22,22 @@ ServiceWorkerRegisterJob::ServiceWorkerR
 {
 }
 
 void
 ServiceWorkerRegisterJob::AsyncExecute()
 {
   AssertIsOnMainThread();
 
-  if (Canceled()) {
+  RefPtr<ServiceWorkerManager> swm = ServiceWorkerManager::GetInstance();
+  if (Canceled() || !swm) {
     FailUpdateJob(NS_ERROR_DOM_ABORT_ERR);
     return;
   }
 
-  RefPtr<ServiceWorkerManager> swm = ServiceWorkerManager::GetInstance();
   RefPtr<ServiceWorkerRegistrationInfo> registration =
     swm->GetRegistration(mPrincipal, mScope);
 
   if (registration) {
     bool isSameLoadFlags = registration->GetLoadFlags() == GetLoadFlags();
     registration->SetLoadFlags(GetLoadFlags());
 
     // If we are resurrecting an uninstalling registration, then persist
--- a/dom/workers/ServiceWorkerRegistration.cpp
+++ b/dom/workers/ServiceWorkerRegistration.cpp
@@ -361,17 +361,20 @@ UpdateInternal(nsIPrincipal* aPrincipal,
                const nsAString& aScope,
                ServiceWorkerUpdateFinishCallback* aCallback)
 {
   AssertIsOnMainThread();
   MOZ_ASSERT(aPrincipal);
   MOZ_ASSERT(aCallback);
 
   RefPtr<ServiceWorkerManager> swm = ServiceWorkerManager::GetInstance();
-  MOZ_ASSERT(swm);
+  if (!swm) {
+    // browser shutdown
+    return;
+  }
 
   swm->Update(aPrincipal, NS_ConvertUTF16toUTF8(aScope), aCallback);
 }
 
 class MainThreadUpdateCallback final : public ServiceWorkerUpdateFinishCallback
 {
   RefPtr<Promise> mPromise;
 
@@ -915,29 +918,23 @@ public:
 
   bool
   Notify(Status aStatus) override;
 
   already_AddRefed<PushManager>
   GetPushManager(JSContext* aCx, ErrorResult& aRv) override;
 
 private:
-  enum Reason
-  {
-    RegistrationIsGoingAway = 0,
-    WorkerIsGoingAway,
-  };
-
   ~ServiceWorkerRegistrationWorkerThread();
 
   void
   InitListener();
 
   void
-  ReleaseListener(Reason aReason);
+  ReleaseListener();
 
   WorkerPrivate* mWorkerPrivate;
   RefPtr<WorkerListener> mListener;
 
   RefPtr<PushManager> mPushManager;
 };
 
 class WorkerListener final : public ServiceWorkerRegistrationListener
@@ -1068,30 +1065,30 @@ NS_IMPL_CYCLE_COLLECTION_TRAVERSE_BEGIN_
                                                   ServiceWorkerRegistration)
   NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mPushManager)
 
 NS_IMPL_CYCLE_COLLECTION_TRAVERSE_END
 
 NS_IMPL_CYCLE_COLLECTION_UNLINK_BEGIN_INHERITED(ServiceWorkerRegistrationWorkerThread,
                                                 ServiceWorkerRegistration)
   NS_IMPL_CYCLE_COLLECTION_UNLINK(mPushManager)
-  tmp->ReleaseListener(RegistrationIsGoingAway);
+  tmp->ReleaseListener();
 NS_IMPL_CYCLE_COLLECTION_UNLINK_END
 
 ServiceWorkerRegistrationWorkerThread::ServiceWorkerRegistrationWorkerThread(WorkerPrivate* aWorkerPrivate,
                                                                              const nsAString& aScope)
   : ServiceWorkerRegistration(nullptr, aScope)
   , mWorkerPrivate(aWorkerPrivate)
 {
   InitListener();
 }
 
 ServiceWorkerRegistrationWorkerThread::~ServiceWorkerRegistrationWorkerThread()
 {
-  ReleaseListener(RegistrationIsGoingAway);
+  ReleaseListener();
   MOZ_ASSERT(!mListener);
 }
 
 already_AddRefed<workers::ServiceWorker>
 ServiceWorkerRegistrationWorkerThread::GetInstalling()
 {
   // FIXME(nsm): Will be implemented after Bug 1113522.
   return nullptr;
@@ -1170,129 +1167,65 @@ ServiceWorkerRegistrationWorkerThread::U
   }
 
   RefPtr<StartUnregisterRunnable> r = new StartUnregisterRunnable(proxy, mScope);
   MOZ_ALWAYS_SUCCEEDS(worker->DispatchToMainThread(r.forget()));
 
   return promise.forget();
 }
 
-class StartListeningRunnable final : public Runnable
-{
-  RefPtr<WorkerListener> mListener;
-public:
-  explicit StartListeningRunnable(WorkerListener* aListener)
-    : mListener(aListener)
-  {}
-
-  NS_IMETHOD
-  Run() override
-  {
-    mListener->StartListeningForEvents();
-    return NS_OK;
-  }
-};
-
 void
 ServiceWorkerRegistrationWorkerThread::InitListener()
 {
   MOZ_ASSERT(!mListener);
   WorkerPrivate* worker = GetCurrentThreadWorkerPrivate();
   MOZ_ASSERT(worker);
   worker->AssertIsOnWorkerThread();
 
   mListener = new WorkerListener(worker, this);
   if (!HoldWorker(worker, Closing)) {
     mListener = nullptr;
     NS_WARNING("Could not add feature");
     return;
   }
 
-  RefPtr<StartListeningRunnable> r =
-    new StartListeningRunnable(mListener);
+  nsCOMPtr<nsIRunnable> r =
+    NewRunnableMethod(mListener, &WorkerListener::StartListeningForEvents);
   MOZ_ALWAYS_SUCCEEDS(worker->DispatchToMainThread(r.forget()));
 }
 
-class AsyncStopListeningRunnable final : public Runnable
-{
-  RefPtr<WorkerListener> mListener;
-public:
-  explicit AsyncStopListeningRunnable(WorkerListener* aListener)
-    : mListener(aListener)
-  {}
-
-  NS_IMETHOD
-  Run() override
-  {
-    mListener->StopListeningForEvents();
-    return NS_OK;
-  }
-};
-
-class SyncStopListeningRunnable final : public WorkerMainThreadRunnable
-{
-  RefPtr<WorkerListener> mListener;
-public:
-  SyncStopListeningRunnable(WorkerPrivate* aWorkerPrivate,
-                            WorkerListener* aListener)
-    : WorkerMainThreadRunnable(aWorkerPrivate,
-                               NS_LITERAL_CSTRING("ServiceWorkerRegistration :: StopListening"))
-    , mListener(aListener)
-  {}
-
-  bool
-  MainThreadRun() override
-  {
-    mListener->StopListeningForEvents();
-    return true;
-  }
-};
-
 void
-ServiceWorkerRegistrationWorkerThread::ReleaseListener(Reason aReason)
+ServiceWorkerRegistrationWorkerThread::ReleaseListener()
 {
   if (!mListener) {
     return;
   }
 
   // We can assert worker here, because:
   // 1) We always HoldWorker, so if the worker has shutdown already, we'll
   //    have received Notify and removed it. If HoldWorker had failed,
   //    mListener will be null and we won't reach here.
   // 2) Otherwise, worker is still around even if we are going away.
   mWorkerPrivate->AssertIsOnWorkerThread();
   ReleaseWorker();
 
   mListener->ClearRegistration();
 
-  if (aReason == RegistrationIsGoingAway) {
-    RefPtr<AsyncStopListeningRunnable> r =
-      new AsyncStopListeningRunnable(mListener);
-    MOZ_ALWAYS_SUCCEEDS(mWorkerPrivate->DispatchToMainThread(r.forget()));
-  } else if (aReason == WorkerIsGoingAway) {
-    RefPtr<SyncStopListeningRunnable> r =
-      new SyncStopListeningRunnable(mWorkerPrivate, mListener);
-    ErrorResult rv;
-    r->Dispatch(Killing, rv);
-    if (rv.Failed()) {
-      NS_ERROR("Failed to dispatch stop listening runnable!");
-      // And now what?
-      rv.SuppressException();
-    }
-  } else {
-    MOZ_CRASH("Bad reason");
-  }
+  nsCOMPtr<nsIRunnable> r =
+    NewRunnableMethod(mListener, &WorkerListener::StopListeningForEvents);
+  MOZ_ALWAYS_SUCCEEDS(mWorkerPrivate->DispatchToMainThread(r.forget()));
+
   mListener = nullptr;
   mWorkerPrivate = nullptr;
 }
 
 bool
 ServiceWorkerRegistrationWorkerThread::Notify(Status aStatus)
 {
-  ReleaseListener(WorkerIsGoingAway);
+  ReleaseListener();
   return true;
 }
 
 class FireUpdateFoundRunnable final : public WorkerRunnable
 {
   RefPtr<WorkerListener> mListener;
 public:
   FireUpdateFoundRunnable(WorkerPrivate* aWorkerPrivate,
--- a/dom/workers/ServiceWorkerRegistrationInfo.cpp
+++ b/dom/workers/ServiceWorkerRegistrationInfo.cpp
@@ -233,22 +233,27 @@ ServiceWorkerRegistrationInfo::TryToActi
 
 void
 ServiceWorkerRegistrationInfo::Activate()
 {
   if (!mWaitingWorker) {
     return;
   }
 
+  RefPtr<ServiceWorkerManager> swm = ServiceWorkerManager::GetInstance();
+  if (!swm) {
+    // browser shutdown began during async activation step
+    return;
+  }
+
   TransitionWaitingToActive();
 
   // FIXME(nsm): Unlink appcache if there is one.
 
   // "Queue a task to fire a simple event named controllerchange..."
-  RefPtr<ServiceWorkerManager> swm = ServiceWorkerManager::GetInstance();
   nsCOMPtr<nsIRunnable> controllerChangeRunnable =
     NewRunnableMethod<RefPtr<ServiceWorkerRegistrationInfo>>(
       swm, &ServiceWorkerManager::FireControllerChange, this);
   NS_DispatchToMainThread(controllerChangeRunnable);
 
   nsCOMPtr<nsIRunnable> failRunnable =
     NewRunnableMethod<bool>(this,
                             &ServiceWorkerRegistrationInfo::FinishActivate,
@@ -274,16 +279,20 @@ ServiceWorkerRegistrationInfo::FinishAct
   if (mPendingUninstall || !mActiveWorker ||
       mActiveWorker->State() != ServiceWorkerState::Activating) {
     return;
   }
 
   // Activation never fails, so aSuccess is ignored.
   mActiveWorker->UpdateState(ServiceWorkerState::Activated);
   RefPtr<ServiceWorkerManager> swm = ServiceWorkerManager::GetInstance();
+  if (!swm) {
+    // browser shutdown started during async activation completion step
+    return;
+  }
   swm->StoreRegistration(mPrincipal, this);
 }
 
 void
 ServiceWorkerRegistrationInfo::RefreshLastUpdateCheckTime()
 {
   AssertIsOnMainThread();
   mLastUpdateCheckTime = PR_IntervalNow() / PR_MSEC_PER_SEC;
@@ -309,16 +318,21 @@ ServiceWorkerRegistrationInfo::IsLastUpd
 }
 
 void
 ServiceWorkerRegistrationInfo::AsyncUpdateRegistrationStateProperties(WhichServiceWorker aWorker,
                                                                       TransitionType aTransition)
 {
   AssertIsOnMainThread();
   RefPtr<ServiceWorkerManager> swm = ServiceWorkerManager::GetInstance();
+  if (!swm) {
+    // browser shutdown started during this async step
+    return;
+  }
+
   if (aTransition == Invalidate) {
     swm->InvalidateServiceWorkerRegistrationWorker(this, aWorker);
   } else {
     MOZ_ASSERT(aTransition == TransitionToNextState);
     swm->TransitionServiceWorkerRegistrationWorker(this, aWorker);
 
     if (aWorker == WhichServiceWorker::WAITING_WORKER) {
       swm->CheckPendingReadyPromises();
@@ -490,16 +504,20 @@ ServiceWorkerRegistrationInfo::Transitio
   }
 
   mWaitingWorker = mInstallingWorker.forget();
   UpdateRegistrationStateProperties(WhichServiceWorker::INSTALLING_WORKER,
                                     TransitionToNextState);
   mWaitingWorker->UpdateState(ServiceWorkerState::Installed);
 
   RefPtr<ServiceWorkerManager> swm = ServiceWorkerManager::GetInstance();
+  if (!swm) {
+    // browser shutdown began
+    return;
+  }
   swm->StoreRegistration(mPrincipal, this);
 }
 
 void
 ServiceWorkerRegistrationInfo::SetActive(ServiceWorkerInfo* aServiceWorker)
 {
   AssertIsOnMainThread();
   MOZ_ASSERT(aServiceWorker);
--- a/dom/workers/ServiceWorkerUnregisterJob.cpp
+++ b/dom/workers/ServiceWorkerUnregisterJob.cpp
@@ -94,28 +94,27 @@ ServiceWorkerUnregisterJob::AsyncExecute
   }
 }
 
 void
 ServiceWorkerUnregisterJob::Unregister()
 {
   AssertIsOnMainThread();
 
-  if (Canceled()) {
+  RefPtr<ServiceWorkerManager> swm = ServiceWorkerManager::GetInstance();
+  if (Canceled() || !swm) {
     Finish(NS_ERROR_DOM_ABORT_ERR);
     return;
   }
 
   // Step 1 of the Unregister algorithm requires checking that the
   // client origin matches the scope's origin.  We perform this in
   // registration->update() method directly since we don't have that
   // client information available here.
 
-  RefPtr<ServiceWorkerManager> swm = ServiceWorkerManager::GetInstance();
-
   // "Let registration be the result of running [[Get Registration]]
   // algorithm passing scope as the argument."
   RefPtr<ServiceWorkerRegistrationInfo> registration =
     swm->GetRegistration(mPrincipal, mScope);
   if (!registration) {
     // "If registration is null, then, resolve promise with false."
     Finish(NS_OK);
     return;
--- a/dom/workers/ServiceWorkerUpdateJob.cpp
+++ b/dom/workers/ServiceWorkerUpdateJob.cpp
@@ -242,26 +242,26 @@ ServiceWorkerUpdateJob::FailUpdateJob(ns
 }
 
 void
 ServiceWorkerUpdateJob::AsyncExecute()
 {
   AssertIsOnMainThread();
   MOZ_ASSERT(GetType() == Type::Update);
 
-  if (Canceled()) {
+  RefPtr<ServiceWorkerManager> swm = ServiceWorkerManager::GetInstance();
+  if (Canceled() || !swm) {
     FailUpdateJob(NS_ERROR_DOM_ABORT_ERR);
     return;
   }
 
   // Begin step 1 of the Update algorithm.
   //
   //  https://slightlyoff.github.io/ServiceWorker/spec/service_worker/index.html#update-algorithm
 
-  RefPtr<ServiceWorkerManager> swm = ServiceWorkerManager::GetInstance();
   RefPtr<ServiceWorkerRegistrationInfo> registration =
     swm->GetRegistration(mPrincipal, mScope);
 
   if (!registration || registration->mPendingUninstall) {
     ErrorResult rv;
     rv.ThrowTypeError<MSG_SW_UPDATE_BAD_REGISTRATION>(NS_ConvertUTF8toUTF16(mScope),
                                                       NS_LITERAL_STRING("uninstalled"));
     FailUpdateJob(rv);
@@ -343,17 +343,18 @@ ServiceWorkerUpdateJob::SetLoadFlags(nsL
 void
 ServiceWorkerUpdateJob::ComparisonResult(nsresult aStatus,
                                          bool aInCacheAndEqual,
                                          const nsAString& aNewCacheName,
                                          const nsACString& aMaxScope)
 {
   AssertIsOnMainThread();
 
-  if (NS_WARN_IF(Canceled())) {
+  RefPtr<ServiceWorkerManager> swm = ServiceWorkerManager::GetInstance();
+  if (NS_WARN_IF(Canceled() || !swm)) {
     FailUpdateJob(NS_ERROR_DOM_ABORT_ERR);
     return;
   }
 
   // Handle failure of the download or comparison.  This is part of Update
   // step 5 as "If the algorithm asynchronously completes with null, then:".
   if (NS_WARN_IF(NS_FAILED(aStatus))) {
     FailUpdateJob(aStatus);
@@ -408,17 +409,16 @@ ServiceWorkerUpdateJob::ComparisonResult
     NS_ConvertUTF8toUTF16 reportScope(mRegistration->mScope);
     NS_ConvertUTF8toUTF16 reportMaxPrefix(maxPrefix);
     const char16_t* params[] = { reportScope.get(), reportMaxPrefix.get() };
 
     rv = nsContentUtils::FormatLocalizedString(nsContentUtils::eDOM_PROPERTIES,
                                                "ServiceWorkerScopePathMismatch",
                                                params, message);
     NS_WARNING_ASSERTION(NS_SUCCEEDED(rv), "Failed to format localized string");
-    RefPtr<ServiceWorkerManager> swm = ServiceWorkerManager::GetInstance();
     swm->ReportToAllClients(mScope,
                             message,
                             EmptyString(),
                             EmptyString(), 0, 0,
                             nsIScriptError::errorFlag);
     FailUpdateJob(NS_ERROR_DOM_SECURITY_ERR);
     return;
   }
@@ -457,17 +457,18 @@ ServiceWorkerUpdateJob::ComparisonResult
   }
 }
 
 void
 ServiceWorkerUpdateJob::ContinueUpdateAfterScriptEval(bool aScriptEvaluationResult)
 {
   AssertIsOnMainThread();
 
-  if (Canceled()) {
+  RefPtr<ServiceWorkerManager> swm = ServiceWorkerManager::GetInstance();
+  if (Canceled() || !swm) {
     FailUpdateJob(NS_ERROR_DOM_ABORT_ERR);
     return;
   }
 
   // Step 7.5 of the Update algorithm verifying that the script evaluated
   // successfully.
 
   if (NS_WARN_IF(!aScriptEvaluationResult)) {
@@ -475,45 +476,44 @@ ServiceWorkerUpdateJob::ContinueUpdateAf
 
     NS_ConvertUTF8toUTF16 scriptSpec(mScriptSpec);
     NS_ConvertUTF8toUTF16 scope(mRegistration->mScope);
     error.ThrowTypeError<MSG_SW_SCRIPT_THREW>(scriptSpec, scope);
     FailUpdateJob(error);
     return;
   }
 
-  Install();
+  Install(swm);
 }
 
 void
-ServiceWorkerUpdateJob::Install()
+ServiceWorkerUpdateJob::Install(ServiceWorkerManager* aSWM)
 {
   AssertIsOnMainThread();
-  MOZ_ASSERT(!Canceled());
+  MOZ_DIAGNOSTIC_ASSERT(!Canceled());
+  MOZ_DIAGNOSTIC_ASSERT(aSWM);
 
   MOZ_ASSERT(!mRegistration->GetInstalling());
 
   // Begin step 2 of the Install algorithm.
   //
   //  https://slightlyoff.github.io/ServiceWorker/spec/service_worker/index.html#installation-algorithm
 
   mRegistration->TransitionEvaluatingToInstalling();
 
   // Step 6 of the Install algorithm resolving the job promise.
   InvokeResultCallbacks(NS_OK);
 
   // The job promise cannot be rejected after this point, but the job can
   // still fail; e.g. if the install event handler throws, etc.
 
-  RefPtr<ServiceWorkerManager> swm = ServiceWorkerManager::GetInstance();
-
   // fire the updatefound event
   nsCOMPtr<nsIRunnable> upr =
     NewRunnableMethod<RefPtr<ServiceWorkerRegistrationInfo>>(
-      swm,
+      aSWM,
       &ServiceWorkerManager::FireUpdateFoundOnServiceWorkerRegistrations,
       mRegistration);
   NS_DispatchToMainThread(upr);
 
   // Call ContinueAfterInstallEvent(false) on main thread if the SW
   // script fails to load.
   nsCOMPtr<nsIRunnable> failRunnable = NewRunnableMethod<bool>
     (this, &ServiceWorkerUpdateJob::ContinueAfterInstallEvent, false);
--- a/dom/workers/ServiceWorkerUpdateJob.h
+++ b/dom/workers/ServiceWorkerUpdateJob.h
@@ -8,16 +8,18 @@
 #define mozilla_dom_workers_serviceworkerupdatejob_h
 
 #include "ServiceWorkerJob.h"
 
 namespace mozilla {
 namespace dom {
 namespace workers {
 
+class ServiceWorkerManager;
+
 // A job class that performs the Update and Install algorithms from the
 // service worker spec.  This class is designed to be inherited and customized
 // as a different job type.  This is necessary because the register job
 // performs largely the same operations as the update job, but has a few
 // different starting steps.
 class ServiceWorkerUpdateJob : public ServiceWorkerJob
 {
 public:
@@ -88,17 +90,17 @@ private:
                    const nsACString& aMaxScope);
 
   // Utility method called after evaluating the worker script.
   void
   ContinueUpdateAfterScriptEval(bool aScriptEvaluationResult);
 
   // Utility method corresponding to the spec Install algorithm.
   void
-  Install();
+  Install(ServiceWorkerManager* aSWM);
 
   // Utility method called after the install event is handled.
   void
   ContinueAfterInstallEvent(bool aInstallEventSuccess);
 
   nsCOMPtr<nsILoadGroup> mLoadGroup;
   nsLoadFlags mLoadFlags;
 
--- a/dom/workers/WorkerPrivate.cpp
+++ b/dom/workers/WorkerPrivate.cpp
@@ -1121,23 +1121,24 @@ private:
         return true;
       }
 
       // Service workers do not have a main thread parent global, so normal
       // worker error reporting will crash.  Instead, pass the error to
       // the ServiceWorkerManager to report on any controlled documents.
       if (aWorkerPrivate->IsServiceWorker()) {
         RefPtr<ServiceWorkerManager> swm = ServiceWorkerManager::GetInstance();
-        MOZ_ASSERT(swm);
-        swm->HandleError(aCx, aWorkerPrivate->GetPrincipal(),
-                         aWorkerPrivate->WorkerName(),
-                         aWorkerPrivate->ScriptURL(),
-                         mMessage,
-                         mFilename, mLine, mLineNumber,
-                         mColumnNumber, mFlags, mExnType);
+        if (swm) {
+          swm->HandleError(aCx, aWorkerPrivate->GetPrincipal(),
+                           aWorkerPrivate->WorkerName(),
+                           aWorkerPrivate->ScriptURL(),
+                           mMessage,
+                           mFilename, mLine, mLineNumber,
+                           mColumnNumber, mFlags, mExnType);
+        }
         return true;
       }
 
       // The innerWindowId is only required if we are going to ReportError
       // below, which is gated on this condition. The inner window correctness
       // check is only going to succeed when the worker is accepting events.
       if (workerIsAcceptingEvents) {
         aWorkerPrivate->AssertInnerWindowIsCorrect();
--- a/dom/workers/WorkerScope.cpp
+++ b/dom/workers/WorkerScope.cpp
@@ -744,27 +744,30 @@ public:
   {
     MOZ_ASSERT(aPromiseProxy);
   }
 
   NS_IMETHOD
   Run() override
   {
     AssertIsOnMainThread();
-    RefPtr<ServiceWorkerManager> swm = ServiceWorkerManager::GetInstance();
-    MOZ_ASSERT(swm);
 
     MutexAutoLock lock(mPromiseProxy->Lock());
     if (mPromiseProxy->CleanedUp()) {
       return NS_OK;
     }
 
     WorkerPrivate* workerPrivate = mPromiseProxy->GetWorkerPrivate();
-    swm->SetSkipWaitingFlag(workerPrivate->GetPrincipal(), mScope,
-                            workerPrivate->ServiceWorkerID());
+    MOZ_DIAGNOSTIC_ASSERT(workerPrivate);
+
+    RefPtr<ServiceWorkerManager> swm = ServiceWorkerManager::GetInstance();
+    if (swm) {
+      swm->SetSkipWaitingFlag(workerPrivate->GetPrincipal(), mScope,
+                              workerPrivate->ServiceWorkerID());
+    }
 
     RefPtr<SkipWaitingResultRunnable> runnable =
       new SkipWaitingResultRunnable(workerPrivate, mPromiseProxy);
 
     if (!runnable->Dispatch()) {
       NS_WARNING("Failed to dispatch SkipWaitingResultRunnable to the worker.");
     }
     return NS_OK;
--- a/editor/libeditor/crashtests/crashtests.list
+++ b/editor/libeditor/crashtests/crashtests.list
@@ -20,17 +20,17 @@ load 448329-2.html
 load 448329-3.html
 load 456727-1.html
 load 456727-2.html
 load 459613.html
 needs-focus load 467647-1.html
 load 475132-1.xhtml
 load 499844-1.html
 load 503709-1.xhtml
-skip-if(stylo) load 513375-1.xhtml # bug 1323654
+load 513375-1.xhtml
 load 535632-1.xhtml
 load 574558-1.xhtml
 load 580151-1.xhtml
 load 582138-1.xhtml
 load 612565-1.html
 load 615015-1.html
 load 615450-1.html
 load 633709.xhtml
deleted file mode 100644
--- a/embedding/browser/moz.build
+++ /dev/null
@@ -1,57 +0,0 @@
-# -*- Mode: python; 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 += ['build']
-
-XPIDL_SOURCES += [
-    'nsCWebBrowser.idl',
-    'nsICommandHandler.idl',
-    'nsIContextMenuListener.idl',
-    'nsIContextMenuListener2.idl',
-    'nsIEmbeddingSiteWindow.idl',
-    'nsITooltipListener.idl',
-    'nsITooltipTextProvider.idl',
-    'nsIWebBrowser.idl',
-    'nsIWebBrowserChrome.idl',
-    'nsIWebBrowserChrome2.idl',
-    'nsIWebBrowserChrome3.idl',
-    'nsIWebBrowserChromeFocus.idl',
-    'nsIWebBrowserFocus.idl',
-    'nsIWebBrowserSetup.idl',
-    'nsIWebBrowserStream.idl',
-]
-
-if CONFIG['NS_PRINTING']:
-    XPIDL_SOURCES += [
-        'nsIPrintingPromptService.idl',
-        'nsIWebBrowserPrint.idl',
-    ]
-
-XPIDL_MODULE = 'webBrowser_core'
-
-EXPORTS += [
-    'nsCTooltipTextProvider.h',
-]
-
-UNIFIED_SOURCES += [
-    'nsCommandHandler.cpp',
-    'nsContextMenuInfo.cpp',
-    'nsDocShellTreeOwner.cpp',
-    'nsEmbedStream.cpp',
-    'nsWebBrowser.cpp',
-    'nsWebBrowserContentPolicy.cpp',
-]
-
-FINAL_LIBRARY = 'xul'
-LOCAL_INCLUDES += [
-    '/docshell/base',
-    '/dom/base',
-    '/dom/svg',
-    '/layout/style',
-]
-
-if CONFIG['GNU_CXX']:
-    CXXFLAGS += ['-Wno-error=shadow']
deleted file mode 100644
--- a/embedding/browser/nsIPrintingPromptService.idl
+++ /dev/null
@@ -1,165 +0,0 @@
-/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-/* Doc interface here */
-
-#include "nsISupports.idl"
-#include "nsIWebBrowserPrint.idl"
-#include "nsIWebProgressListener.idl"
-#include "nsIPrintProgressParams.idl"
-#include "nsIPrintSettings.idl"
-#include "nsIObserver.idl"
-
-interface nsIDOMWindow;
-
-[scriptable, uuid(328daa3e-09e4-455f-bb6f-0a921766042f)]
-interface nsIPrintingPromptService : nsISupports
-{
-   /**
-   *  This service enables embedders to implement their own Print and Progress Dialogs.
-   *  Each platform has a "base" or "basckstop" implementation of the service. The 
-   *  service is automatically registered at start up.
-   *
-   *  Historically, platform toolkits with native dialogs have implemented them in the GFX layer
-   *  Usually they were displayed when a new DeviceContextSpec specific to that platform
-   *  was created.
-   *
-   *  Windows: The GFX layer no longers supports default toolkit behavior for displaying the 
-   *           native Print Dialog.
-   *           If an embedder implemented service returns any error code (other than NS_ERROR_ABORT)
-   *           printing will terminate.
-   *
-   *           Returning NS_OK assumes that the PrintSettings object was correctly filled in and
-   *           if it does not have valid fields for printer name, etc. it may also terminate.
-   *
-   *           Defaults for platform service:           
-   *             showPrintDialog       - displays a native dialog
-   *             showPageSetup         - displays a XUL dialog
-   *             showProgress          - displays a XUL dialog
-   *             showPrinterProperties - n/a
-   *
-   *           Summary for Windows Embedders:
-   *             Stated once again: There is no "fallback" native platform support in GFX for the
-   *             displaying of the native print dialog. The current default implementation for Windows
-   *             display a native print dialog but a XUL-based progress dialog.
-   *             If you wish to have a native progress dialog on Windows you will have to create and 
-   *             register your own service.
-   *  
-   *             Note: The Windows version Mozilla implements this service which is 
-   *                   automatically built and registered for you. You can use it as an example.
-   *                   It is located at "mozilla/embedding/components/printingui/win". That service
-   *                   is capable of displaying a native print dialog and a XUL progress dialog.
-   *
-   *             To fly your own dialog you may:
-   *
-   *              1) Implement this service to display at least the Print Dialog and a Print Progress Dialog
-   *                 or you may implement just one of the dialogs and pass back NS_ERROR_NOT_IMPLEMENTED
-   *                 for any of the others.
-   *
-   *              2) For the Print Dialog:
-   *                 You may stub out this service by having all the methods return NS_ERROR_NOT_IMPLEMENTED.
-   *                 You can then fly you own dialog and then properly fill in the PrintSettings object
-   *                 before calling nsIWebBrowserPrint's Print method. If you stub out this service  
-   *                 you MUST set "printSilent" to true, if you do not, Printing will terminate and an 
-   *                 error dialog will be displayed.
-   *
-   *  Mac: The GFX layer still supports default toolkit behavior for displaying the Print Dialog.
-   *       If an embedder implemented service returns NS_ERROR_NOT_IMPLEMENTED for "showPrintDialog"
-   *       The toolkit will display the native print dialog.
-   *
-   *       Defaults for platform service:           
-   *       Mac OS9: showPrintDialog       - displays a native dialog
-   *                showPageSetup         - displays a native dialog
-   *                showProgress          - displays a XUL dialog
-   *                showPrinterProperties - n/a
-   *                
-   *       Mac OSX: showPrintDialog       - displays a native dialog
-   *                showPageSetup         - displays a native dialog
-   *                showProgress          - not implemented (provided by OS)
-   *                showPrinterProperties - n/a
-   *                
-   *  GTK: There are no native dialog for GTK.
-   *
-   *       Defaults for platform service:           
-   *         showPrintDialog       - displays a XUL dialog
-   *         showPageSetup         - displays a XUL dialog
-   *         showProgress          - displays a XUL dialog
-   *         showPrinterProperties - displays a XUL dialog
-   *
-   */
- 
-
-
-  /**
-   *  Show the Print Dialog 
-   *
-   *  @param parent - a DOM windows the dialog will be parented to (required)
-   *  @param webBrowserPrint - represents the document to be printed (required)
-   *  @param printSettings - PrintSettings for print "job" (required)
-   *
-   */
-  void showPrintDialog(in mozIDOMWindowProxy parent,
-                       in nsIWebBrowserPrint webBrowserPrint,
-                       in nsIPrintSettings printSettings);
-
-  /**
-   *  Shows the print progress dialog
-   *
-   *  @param parent - a DOM windows the dialog will be parented to
-   *  @param webBrowserPrint - represents the document to be printed
-   *  @param printSettings - PrintSettings for print "job"
-   *  @param openDialogObserver - an observer that will be notifed when the dialog is opened
-   *  @param isForPrinting - true - for printing, false for print preview
-   *  @param webProgressListener - additional listener can be registered for progress notifications
-   *  @param printProgressParams - parameter object for passing progress state
-   *  @param notifyOnOpen - this indicates that the observer will be notified when the progress
-   *                        dialog has been opened. If false is returned it means the observer
-   *                        (usually the caller) shouldn't wait
-   *                        For Print Preview Progress there is intermediate progress
-   */
-  void showProgress(in mozIDOMWindowProxy parent,
-                    in nsIWebBrowserPrint webBrowserPrint,
-                    in nsIPrintSettings printSettings,
-                    in nsIObserver openDialogObserver,
-                    in boolean isForPrinting,
-                    out nsIWebProgressListener webProgressListener,
-                    out nsIPrintProgressParams printProgressParams,
-                    out boolean notifyOnOpen);
-
-  /**
-   *  Shows the print progress dialog
-   *
-   *  @param parent - a DOM windows the dialog will be parented to (required)
-   *  @param printSettings - PrintSettings for page setup (required)
-   *  @param aObs - An observer to know if the contents of the Print Settings 
-   *                object has changed while the dialog is being shown. 
-   *                For example, some platforms may implement an "Apply" button (not required)
-   */
-  void showPageSetup(in mozIDOMWindowProxy parent,
-                     in nsIPrintSettings printSettings,
-                     in nsIObserver aObs);
-
-  /**
-   *  Sometimes platforms need to bring up a special properties dialog for showing
-   *  print specific properties. Although the PrintSettings has a place to set the 
-   *  printer name, here is is an argument to be clear as to what printer is being
-   *  asked to have the properties set for it. The Printer name in the PS is ignored.
-   *
-   *  @param parent - a DOM windows the dialog will be parented to (required)
-   *  @param printerName - name of printer (required)
-   *  @param printSettings - PrintSettings for page setup (required)
-   */
-  void showPrinterProperties(in mozIDOMWindowProxy parent,
-                             in wstring printerName,
-                             in nsIPrintSettings printSettings);
-
-};
-
-%{C++
-// {260FEDC5-524D-4aa6-9A41-E829F4C78B92}
-#define NS_PRINTINGPROMPTSERVICE_IID \
- {0x260fedc5, 0x524d, 0x4aa6, { 0x9a, 0x41, 0xe8, 0x29, 0xf4, 0xc7, 0x8b, 0x92}}
-%}
-
deleted file mode 100644
--- a/embedding/components/appstartup/moz.build
+++ /dev/null
@@ -1,15 +0,0 @@
-# -*- Mode: python; 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/.
-
-EXPORTS += [
-    'nsIAppStartupNotifier.h',
-]
-
-SOURCES += [
-    'nsAppStartupNotifier.cpp',
-]
-
-FINAL_LIBRARY = 'xul'
deleted file mode 100644
--- a/embedding/components/build/moz.build
+++ /dev/null
@@ -1,38 +0,0 @@
-# -*- Mode: python; 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/.
-
-SOURCES += [
-    'nsEmbeddingModule.cpp',
-]
-
-FINAL_LIBRARY = 'xul'
-LOCAL_INCLUDES += [
-    '../appstartup',
-    '../commandhandler',
-    '../find',
-    '../printingui/ipc',
-    '../webbrowserpersist',
-    '../windowwatcher',
-]
-
-if CONFIG['MOZ_WIDGET_TOOLKIT'] == 'windows':
-    DEFINES['PROXY_PRINTING'] = 1
-    LOCAL_INCLUDES += [
-        '../printingui/win',
-    ]
-elif CONFIG['MOZ_WIDGET_TOOLKIT'] == 'cocoa':
-    DEFINES['PROXY_PRINTING'] = 1
-    LOCAL_INCLUDES += [
-        '../printingui/mac',
-    ]
-
-if CONFIG['MOZ_PDF_PRINTING']:
-    DEFINES['PROXY_PRINTING'] = 1
-    LOCAL_INCLUDES += [
-        '../printingui/unixshared',
-    ]
-
-include('/ipc/chromium/chromium-config.mozbuild')
deleted file mode 100644
--- a/embedding/components/find/moz.build
+++ /dev/null
@@ -1,19 +0,0 @@
-# -*- Mode: python; indent-tabs-mode: nil; tab-width: 40 -*-
-# vim: set filetype=python:
-# This Source Code Form is subject to the terms of the Mozilla Public
-# License, v. 2.0. If a copy of the MPL was not distributed with this
-# file, You can obtain one at http://mozilla.org/MPL/2.0/.
-
-XPIDL_SOURCES += [
-    'nsIFind.idl',
-    'nsIWebBrowserFind.idl',
-]
-
-XPIDL_MODULE = 'find'
-
-UNIFIED_SOURCES += [
-    'nsFind.cpp',
-    'nsWebBrowserFind.cpp',
-]
-
-FINAL_LIBRARY = 'xul'
deleted file mode 100644
--- a/embedding/components/moz.build
+++ /dev/null
@@ -1,20 +0,0 @@
-# -*- Mode: python; 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/.
-
-# You'd think we could skip building ui if XUL is disabled,
-# but we need to export interface headers from those directories.
-DIRS += [
-    'windowwatcher',
-    'appstartup',
-    'find',
-    'webbrowserpersist',
-    'commandhandler',
-]
-
-if CONFIG['MOZ_XUL']:
-    DIRS += ['printingui']
-
-DIRS += ['build']
deleted file mode 100644
--- a/embedding/moz.build
+++ /dev/null
@@ -1,24 +0,0 @@
-# -*- Mode: python; 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 += ['components', 'browser']
-
-TEST_DIRS += ['test']
-
-if CONFIG['ENABLE_TESTS']:
-    XPCSHELL_TESTS_MANIFESTS += ['tests/unit/xpcshell.ini']
-
-XPIDL_SOURCES += [
-    'nsIWindowCreator.idl',
-    'nsIWindowCreator2.idl',
-    'nsIWindowProvider.idl',
-]
-
-XPIDL_MODULE = 'embed_base'
-
-EXPORTS += [
-    'nsEmbedCID.h',
-]
--- a/extensions/spellcheck/hunspell/src/README.mozilla
+++ b/extensions/spellcheck/hunspell/src/README.mozilla
@@ -1,2 +1,2 @@
-Hunspell Version:   1.5.4
+Hunspell Version:   1.6.0
 Additional Patches: See patches directory.
--- a/gfx/layers/composite/ContainerLayerComposite.h
+++ b/gfx/layers/composite/ContainerLayerComposite.h
@@ -65,21 +65,16 @@ public:
   // LayerComposite Implementation
   virtual Layer* GetLayer() override { return this; }
 
   virtual void SetLayerManager(HostLayerManager* aManager) override
   {
     LayerComposite::SetLayerManager(aManager);
     mManager = aManager;
     mLastIntermediateSurface = nullptr;
-
-    for (Layer* l = GetFirstChild(); l; l = l->GetNextSibling()) {
-      HostLayer* child = l->AsHostLayer();
-      child->SetLayerManager(aManager);
-    }
   }
 
   virtual void Destroy() override;
 
   LayerComposite* GetFirstChildComposite() override;
 
   virtual void Cleanup() override;
 
@@ -162,16 +157,23 @@ public:
 
 protected:
   ~RefLayerComposite();
 
 public:
   /** LayerOGL implementation */
   Layer* GetLayer() override { return this; }
 
+  virtual void SetLayerManager(HostLayerManager* aManager) override
+  {
+    LayerComposite::SetLayerManager(aManager);
+    mManager = aManager;
+    mLastIntermediateSurface = nullptr;
+  }
+
   void Destroy() override;
 
   LayerComposite* GetFirstChildComposite() override;
 
   virtual void RenderLayer(const gfx::IntRect& aClipRect,
                            const Maybe<gfx::Polygon>& aGeometry) override;
 
   virtual void Prepare(const RenderTargetIntRect& aClipRect) override;
--- a/gfx/layers/ipc/CompositorBridgeParent.cpp
+++ b/gfx/layers/ipc/CompositorBridgeParent.cpp
@@ -1521,20 +1521,17 @@ CompositorBridgeParent::NotifyChildCreat
 mozilla::ipc::IPCResult
 CompositorBridgeParent::RecvAdoptChild(const uint64_t& child)
 {
   APZCTreeManagerParent* parent;
   {
     MonitorAutoLock lock(*sIndirectLayerTreesLock);
     NotifyChildCreated(child);
     if (sIndirectLayerTrees[child].mLayerTree) {
-      sIndirectLayerTrees[child].mLayerTree->mLayerManager = mLayerManager;
-    }
-    if (sIndirectLayerTrees[child].mRoot) {
-      sIndirectLayerTrees[child].mRoot->AsHostLayer()->SetLayerManager(static_cast<HostLayerManager*>(mLayerManager.get()));
+      sIndirectLayerTrees[child].mLayerTree->SetLayerManager(mLayerManager);
     }
     parent = sIndirectLayerTrees[child].mApzcTreeManagerParent;
   }
 
   if (mApzcTreeManager && parent) {
     parent->ChildAdopted(mApzcTreeManager);
   }
   return IPC_OK();
--- a/gfx/layers/ipc/LayerTransactionParent.cpp
+++ b/gfx/layers/ipc/LayerTransactionParent.cpp
@@ -65,16 +65,26 @@ LayerTransactionParent::LayerTransaction
   , mIPCOpen(false)
 {
 }
 
 LayerTransactionParent::~LayerTransactionParent()
 {
 }
 
+void
+LayerTransactionParent::SetLayerManager(HostLayerManager* aLayerManager)
+{
+  mLayerManager = aLayerManager;
+  for (auto iter = mLayerMap.Iter(); !iter.Done(); iter.Next()) {
+    auto layer = iter.Data();
+    layer->AsHostLayer()->SetLayerManager(aLayerManager);
+  }
+}
+
 mozilla::ipc::IPCResult
 LayerTransactionParent::RecvShutdown()
 {
   Destroy();
   IProtocol* mgr = Manager();
   if (!Send__delete__(this)) {
     return IPC_FAIL_NO_REASON(mgr);
   }
--- a/gfx/layers/ipc/LayerTransactionParent.h
+++ b/gfx/layers/ipc/LayerTransactionParent.h
@@ -53,16 +53,18 @@ public:
 protected:
   ~LayerTransactionParent();
 
 public:
   void Destroy();
 
   HostLayerManager* layer_manager() const { return mLayerManager; }
 
+  void SetLayerManager(HostLayerManager* aLayerManager);
+
   uint64_t GetId() const { return mId; }
   Layer* GetRoot() const { return mRoot; }
 
   uint64_t GetChildEpoch() const { return mChildEpoch; }
   bool ShouldParentObserveEpoch();
 
   virtual ShmemAllocator* AsShmemAllocator() override { return this; }
 
--- a/gfx/layers/ipc/ShadowLayers.cpp
+++ b/gfx/layers/ipc/ShadowLayers.cpp
@@ -46,17 +46,17 @@ namespace layers {
 
 using namespace mozilla::gfx;
 using namespace mozilla::gl;
 using namespace mozilla::ipc;
 
 class ClientTiledLayerBuffer;
 
 typedef nsTArray<SurfaceDescriptor> BufferArray;
-typedef std::vector<Edit> EditVector;
+typedef nsTArray<Edit> EditVector;
 typedef nsTHashtable<nsPtrHashKey<ShadowableLayer>> ShadowableLayerSet;
 typedef nsTArray<OpDestroy> OpDestroyVector;
 
 class Transaction
 {
 public:
   Transaction()
     : mTargetRotation(ROTATION_0)
@@ -82,17 +82,17 @@ public:
   }
   void MarkSyncTransaction()
   {
     mSwapRequired = true;
   }
   void AddEdit(const Edit& aEdit)
   {
     MOZ_ASSERT(!Finished(), "forgot BeginTransaction?");
-    mCset.push_back(aEdit);
+    mCset.AppendElement(aEdit);
   }
   void AddEdit(const CompositableOperation& aEdit)
   {
     AddEdit(Edit(aEdit));
   }
   void AddPaint(const Edit& aPaint)
   {
     AddNoSwapPaint(aPaint);
@@ -102,41 +102,41 @@ public:
   {
     AddNoSwapPaint(Edit(aPaint));
     mSwapRequired = true;
   }
 
   void AddNoSwapPaint(const Edit& aPaint)
   {
     MOZ_ASSERT(!Finished(), "forgot BeginTransaction?");
-    mPaints.push_back(aPaint);
+    mPaints.AppendElement(aPaint);
   }
   void AddNoSwapPaint(const CompositableOperation& aPaint)
   {
     MOZ_ASSERT(!Finished(), "forgot BeginTransaction?");
-    mPaints.push_back(Edit(aPaint));
+    mPaints.AppendElement(Edit(aPaint));
   }
   void AddMutant(ShadowableLayer* aLayer)
   {
     MOZ_ASSERT(!Finished(), "forgot BeginTransaction?");
     mMutants.PutEntry(aLayer);
   }
   void End()
   {
-    mCset.clear();
-    mPaints.clear();
+    mCset.Clear();
+    mPaints.Clear();
     mMutants.Clear();
     mDestroyedActors.Clear();
     mOpen = false;
     mSwapRequired = false;
     mRotationChanged = false;
   }
 
   bool Empty() const {
-    return mCset.empty() && mPaints.empty() && mMutants.IsEmpty()
+    return mCset.IsEmpty() && mPaints.IsEmpty() && mMutants.IsEmpty()
            && mDestroyedActors.IsEmpty();
   }
   bool RotationChanged() const {
     return mRotationChanged;
   }
   bool Finished() const { return !mOpen && Empty(); }
 
   bool Opened() const { return mOpen; }
@@ -598,17 +598,17 @@ ShadowLayerForwarder::EndTransaction(Inf
 
   AutoTxnEnd _(mTxn);
 
   if (mTxn->Empty() && !mTxn->RotationChanged()) {
     MOZ_LAYERS_LOG(("[LayersForwarder] 0-length cset (?) and no rotation event, skipping Update()"));
     return true;
   }
 
-  if (!mTxn->mPaints.empty()) {
+  if (!mTxn->mPaints.IsEmpty()) {
     // With some platforms, telling the drawing backend that there will be no more
     // drawing for this frame helps with preventing command queues from spanning
     // across multiple frames.
     gfxPlatform::GetPlatform()->FlushContentDrawing();
   }
 
   MOZ_LAYERS_LOG(("[LayersForwarder] destroying buffers..."));
 
@@ -689,34 +689,32 @@ ShadowLayerForwarder::EndTransaction(Inf
     attrs.specific() = null_t();
     mutant->FillSpecificAttributes(attrs.specific());
 
     MOZ_LAYERS_LOG(("[LayersForwarder] OpSetLayerAttributes(%p)\n", mutant));
 
     mTxn->AddEdit(OpSetLayerAttributes(Shadow(shadow), attrs));
   }
 
-  size_t nCsets = mTxn->mCset.size() + mTxn->mPaints.size();
-  if (nCsets == 0 && !mTxn->RotationChanged()) {
+  if (mTxn->mCset.IsEmpty() &&
+      mTxn->mPaints.IsEmpty() &&
+      !mTxn->RotationChanged())
+  {
     return true;
   }
 
-  auto& cset = info.cset();
-  cset.SetCapacity(nCsets);
-  if (!mTxn->mCset.empty()) {
-    cset.AppendElements(&mTxn->mCset.front(), mTxn->mCset.size());
-  }
   // Paints after non-paint ops, including attribute changes.  See
   // above.
-  if (!mTxn->mPaints.empty()) {
-    cset.AppendElements(&mTxn->mPaints.front(), mTxn->mPaints.size());
+  if (!mTxn->mPaints.IsEmpty()) {
+    mTxn->mCset.AppendElements(mTxn->mPaints);
   }
 
   mWindowOverlayChanged = false;
 
+  info.cset() = Move(mTxn->mCset);
   info.toDestroy() = mTxn->mDestroyedActors;
   info.fwdTransactionId() = GetFwdTransactionId();
   info.id() = aId;
   info.plugins() = mPluginWindowData;
   info.isFirstPaint() = mIsFirstPaint;
   info.scheduleComposite() = aScheduleComposite;
   info.paintSequenceNumber() = aPaintSequenceNumber;
   info.isRepeatTransaction() = aIsRepeatTransaction;
--- a/gfx/tests/crashtests/crashtests.list
+++ b/gfx/tests/crashtests/crashtests.list
@@ -85,17 +85,17 @@ load 563740-1.html
 load 580100-1.html
 load 580212-1.html
 load 580233-1.html
 load 580719-1.html
 load 593526.html
 load 593526.xul
 load 594654-1.xhtml
 load 595042-1.html
-skip-if(stylo) load 595727-1.html # bug 1323671
+load 595727-1.html
 load 624198.xhtml
 load 633322-1.html
 load 633453-1.html
 load 662467-1.html
 load 665218.html
 load 675550-1.html
 load 686190-1.html
 load 691581-1.html
--- a/gfx/thebes/gfxFcPlatformFontList.cpp
+++ b/gfx/thebes/gfxFcPlatformFontList.cpp
@@ -639,16 +639,17 @@ PrepareFontOptions(FcPattern* aPattern,
     } else {
         antialias = CAIRO_ANTIALIAS_SUBPIXEL;
     }
     cairo_font_options_set_antialias(aFontOptions, antialias);
 }
 
 cairo_scaled_font_t*
 gfxFontconfigFontEntry::CreateScaledFont(FcPattern* aRenderPattern,
+                                         gfxFloat aAdjustedSize,
                                          const gfxFontStyle *aStyle,
                                          bool aNeedsBold)
 {
     if (aNeedsBold) {
         FcPatternAddBool(aRenderPattern, FC_EMBOLDEN, FcTrue);
     }
 
     // synthetic oblique by skewing via the font matrix
@@ -676,21 +677,17 @@ gfxFontconfigFontEntry::CreateScaledFont
                                       FTUserFontDataRef::Destroy);
     }
 
     cairo_scaled_font_t *scaledFont = nullptr;
 
     cairo_matrix_t sizeMatrix;
     cairo_matrix_t identityMatrix;
 
-    double adjustedSize = aStyle->size;
-    if (aStyle->sizeAdjust >= 0.0) {
-        adjustedSize = aStyle->GetAdjustedSize(GetAspect());
-    }
-    cairo_matrix_init_scale(&sizeMatrix, adjustedSize, adjustedSize);
+    cairo_matrix_init_scale(&sizeMatrix, aAdjustedSize, aAdjustedSize);
     cairo_matrix_init_identity(&identityMatrix);
 
     if (needsOblique) {
         const double kSkewFactor = OBLIQUE_SKEW_FACTOR;
 
         cairo_matrix_t style;
         cairo_matrix_init(&style,
                           1,                //xx
@@ -804,20 +801,26 @@ gfxFontconfigFontEntry::CreateFontInstan
     PreparePattern(pattern, aFontStyle->printerFont);
     nsAutoRef<FcPattern> renderPattern
         (FcFontRenderPrepare(nullptr, pattern, mFontPattern));
     if (!renderPattern) {
         NS_WARNING("Failed to prepare Fontconfig pattern for font instance");
         return nullptr;
     }
 
+    double adjustedSize = aFontStyle->size;
+    if (aFontStyle->sizeAdjust >= 0.0) {
+        adjustedSize = aFontStyle->GetAdjustedSize(GetAspect());
+    }
+
     cairo_scaled_font_t* scaledFont =
-        CreateScaledFont(renderPattern, aFontStyle, aNeedsBold);
+        CreateScaledFont(renderPattern, adjustedSize, aFontStyle, aNeedsBold);
     gfxFont* newFont =
-        new gfxFontconfigFont(scaledFont, renderPattern, this, aFontStyle, aNeedsBold);
+        new gfxFontconfigFont(scaledFont, renderPattern, adjustedSize,
+                              this, aFontStyle, aNeedsBold);
     cairo_scaled_font_destroy(scaledFont);
 
     return newFont;
 }
 
 nsresult
 gfxFontconfigFontEntry::CopyFontTable(uint32_t aTableTag,
                                       nsTArray<uint8_t>& aBuffer)
@@ -920,21 +923,23 @@ gfxFontconfigFontFamily::AddFontPattern(
                  "font patterns must not be added to already enumerated families");
 
     nsCountedRef<FcPattern> pattern(aFontPattern);
     mFontPatterns.AppendElement(pattern);
 }
 
 gfxFontconfigFont::gfxFontconfigFont(cairo_scaled_font_t *aScaledFont,
                                      FcPattern *aPattern,
+                                     gfxFloat aAdjustedSize,
                                      gfxFontEntry *aFontEntry,
                                      const gfxFontStyle *aFontStyle,
                                      bool aNeedsBold) :
     gfxFontconfigFontBase(aScaledFont, aPattern, aFontEntry, aFontStyle)
 {
+    mAdjustedSize = aAdjustedSize;
 }
 
 gfxFontconfigFont::~gfxFontconfigFont()
 {
 }
 
 gfxFcPlatformFontList::gfxFcPlatformFontList()
     : mLocalNames(64)
--- a/gfx/thebes/gfxFcPlatformFontList.h
+++ b/gfx/thebes/gfxFcPlatformFontList.h
@@ -128,16 +128,17 @@ protected:
     virtual ~gfxFontconfigFontEntry();
 
     gfxFont *CreateFontInstance(const gfxFontStyle *aFontStyle,
                                 bool aNeedsBold) override;
 
     // helper method for creating cairo font from pattern
     cairo_scaled_font_t*
     CreateScaledFont(FcPattern* aRenderPattern,
+                     gfxFloat aAdjustedSize,
                      const gfxFontStyle *aStyle,
                      bool aNeedsBold);
 
     // override to pull data from FTFace
     virtual nsresult
     CopyFontTable(uint32_t aTableTag,
                   nsTArray<uint8_t>& aBuffer) override;
 
@@ -194,16 +195,17 @@ protected:
 
     bool      mContainsAppFonts;
 };
 
 class gfxFontconfigFont : public gfxFontconfigFontBase {
 public:
     gfxFontconfigFont(cairo_scaled_font_t *aScaledFont,
                       FcPattern *aPattern,
+                      gfxFloat aAdjustedSize,
                       gfxFontEntry *aFontEntry,
                       const gfxFontStyle *aFontStyle,
                       bool aNeedsBold);
 
 protected:
     virtual ~gfxFontconfigFont();
 };
 
--- a/js/xpconnect/idl/nsIXPCScriptable.idl
+++ b/js/xpconnect/idl/nsIXPCScriptable.idl
@@ -24,16 +24,17 @@ interface nsIXPConnectWrappedNative;
 
 [ptr] native JSContextPtr(JSContext);
 [ptr] native JSObjectPtr(JSObject);
 [ptr] native JSValPtr(JS::Value);
 [ptr] native JSFreeOpPtr(JSFreeOp);
 [ref] native JSCallArgsRef(const JS::CallArgs);
 [ref] native JSAutoIdVector(JS::AutoIdVector);
 [ptr] native jsClassPtr(const js::Class);
+[ptr] native JSClassPtr(const JSClass);
 
 /**
  * Note: This is not really an XPCOM interface.  For example, callers must
  * guarantee that they set the *_retval of the various methods that return a
  * boolean to PR_TRUE before making the call.  Implementations may skip writing
  * to *_retval unless they want to return PR_FALSE.
  */
 [uuid(19b70b26-7c3f-437f-a04a-2a8f9e28b617)]
@@ -60,16 +61,17 @@ interface nsIXPCScriptable : nsISupports
     const uint32_t ALLOW_PROP_MODS_DURING_RESOLVE   = 1 << 16;
     const uint32_t ALLOW_PROP_MODS_TO_PROTOTYPE     = 1 << 17;
     const uint32_t IS_GLOBAL_OBJECT                 = 1 << 18;
     const uint32_t DONT_REFLECT_INTERFACE_NAMES     = 1 << 19;
 
     readonly attribute string className;
     [notxpcom,nostdcall] uint32_t getScriptableFlags();
     [notxpcom,nostdcall] jsClassPtr getClass();
+    [notxpcom,nostdcall] JSClassPtr getJSClass();
 
     void   preCreate(in nsISupports nativeObj, in JSContextPtr cx,
                      in JSObjectPtr globalObj, out JSObjectPtr parentObj);
 
     boolean getProperty(in nsIXPConnectWrappedNative wrapper,
                        in JSContextPtr cx, in JSObjectPtr obj, in jsid id,
                        in JSValPtr vp);
 
--- a/js/xpconnect/public/xpc_map_end.h
+++ b/js/xpconnect/public/xpc_map_end.h
@@ -80,16 +80,23 @@ XPC_MAP_CLASSNAME::GetClass()
     static const js::ClassOps classOps =
         XPC_MAKE_CLASS_OPS(GetScriptableFlags());
     static const js::Class klass =
         XPC_MAKE_CLASS(XPC_MAP_QUOTED_CLASSNAME, GetScriptableFlags(),
                        &classOps);
     return &klass;
 }
 
+// virtual
+const JSClass*
+XPC_MAP_CLASSNAME::GetJSClass()
+{
+    return Jsvalify(GetClass());
+}
+
 /**************************************************************/
 
 #ifndef XPC_MAP_WANT_PRECREATE
 NS_IMETHODIMP XPC_MAP_CLASSNAME::PreCreate(nsISupports* nativeObj, JSContext * cx, JSObject * globalObj, JSObject * *parentObj)
     {NS_ERROR("never called"); return NS_ERROR_NOT_IMPLEMENTED;}
 #endif
 
 #ifndef XPC_MAP_WANT_GETPROPERTY
--- a/js/xpconnect/src/XPCCallContext.cpp
+++ b/js/xpconnect/src/XPCCallContext.cpp
@@ -65,21 +65,18 @@ XPCCallContext::XPCCallContext(JSContext
     if (IS_WN_CLASS(clasp)) {
         mWrapper = XPCWrappedNative::Get(unwrapped);
     } else if (IS_TEAROFF_CLASS(clasp)) {
         mTearOff = (XPCWrappedNativeTearOff*)js::GetObjectPrivate(unwrapped);
         mWrapper = XPCWrappedNative::Get(
           &js::GetReservedSlot(unwrapped,
                                XPC_WN_TEAROFF_FLAT_OBJECT_SLOT).toObject());
     }
-    if (mWrapper) {
-        if (mTearOff)
-            mScriptableInfo = nullptr;
-        else
-            mScriptableInfo = mWrapper->GetScriptableInfo();
+    if (mWrapper && !mTearOff) {
+        mScriptable = mWrapper->GetScriptable();
     }
 
     if (!JSID_IS_VOID(name))
         SetName(name);
 
     if (argc != NO_ARGS)
         SetArgsAndResultPtr(argc, argv, rval);
 
--- a/js/xpconnect/src/XPCForwards.h
+++ b/js/xpconnect/src/XPCForwards.h
@@ -23,17 +23,16 @@ class nsXPCWrappedJSClass;
 
 class XPCNativeMember;
 class XPCNativeInterface;
 class XPCNativeSet;
 
 class XPCWrappedNative;
 class XPCWrappedNativeProto;
 class XPCWrappedNativeTearOff;
-class XPCNativeScriptableInfo;
 class XPCNativeScriptableCreateInfo;
 
 class XPCTraceableVariant;
 class XPCJSObjectHolder;
 
 class JSObject2WrappedJSMap;
 class Native2WrappedNativeMap;
 class IID2WrappedJSClassMap;
--- a/js/xpconnect/src/XPCInlines.h
+++ b/js/xpconnect/src/XPCInlines.h
@@ -94,21 +94,21 @@ XPCCallContext::CanGetTearOff() const
 
 inline XPCWrappedNativeTearOff*
 XPCCallContext::GetTearOff() const
 {
     CHECK_STATE(HAVE_OBJECT);
     return mTearOff;
 }
 
-inline XPCNativeScriptableInfo*
-XPCCallContext::GetScriptableInfo() const
+inline nsIXPCScriptable*
+XPCCallContext::GetScriptable() const
 {
     CHECK_STATE(HAVE_OBJECT);
-    return mScriptableInfo;
+    return mScriptable;
 }
 
 inline bool
 XPCCallContext::CanGetSet() const
 {
     return mState >= HAVE_NAME;
 }
 
--- a/js/xpconnect/src/XPCJSContext.cpp
+++ b/js/xpconnect/src/XPCJSContext.cpp
@@ -3526,31 +3526,30 @@ XPCJSContext::JSContextInitialized(JSCon
 
     return true;
 }
 
 bool
 XPCJSContext::DescribeCustomObjects(JSObject* obj, const js::Class* clasp,
                                     char (&name)[72]) const
 {
-    XPCNativeScriptableInfo* si = nullptr;
 
     if (!IS_PROTO_CLASS(clasp)) {
         return false;
     }
 
     XPCWrappedNativeProto* p =
         static_cast<XPCWrappedNativeProto*>(xpc_GetJSPrivate(obj));
-    si = p->GetScriptableInfo();
-
-    if (!si) {
+    nsCOMPtr<nsIXPCScriptable> scr = p->GetScriptable();
+    if (!scr) {
         return false;
     }
 
-    SprintfLiteral(name, "JS Object (%s - %s)", clasp->name, si->GetJSClass()->name);
+    SprintfLiteral(name, "JS Object (%s - %s)",
+                   clasp->name, scr->GetJSClass()->name);
     return true;
 }
 
 bool
 XPCJSContext::NoteCustomGCThingXPCOMChildren(const js::Class* clasp, JSObject* obj,
                                              nsCycleCollectionTraversalCallback& cb) const
 {
     if (clasp != &XPC_WN_Tearoff_JSClass) {
--- a/js/xpconnect/src/XPCWrappedNative.cpp
+++ b/js/xpconnect/src/XPCWrappedNative.cpp
@@ -45,19 +45,20 @@ NS_IMPL_CYCLE_COLLECTION_UNLINK_BEGIN(XP
 NS_IMPL_CYCLE_COLLECTION_UNLINK_END
 
 NS_IMPL_CYCLE_COLLECTION_TRAVERSE_BEGIN_INTERNAL(XPCWrappedNative)
     if (!tmp->IsValid())
         return NS_OK;
 
     if (MOZ_UNLIKELY(cb.WantDebugInfo())) {
         char name[72];
-        XPCNativeScriptableInfo* si = tmp->GetScriptableInfo();
-        if (si)
-            SprintfLiteral(name, "XPCWrappedNative (%s)", si->GetJSClass()->name);
+        nsCOMPtr<nsIXPCScriptable> scr = tmp->GetScriptable();
+        if (scr)
+            SprintfLiteral(name, "XPCWrappedNative (%s)",
+                           scr->GetJSClass()->name);
         else
             SprintfLiteral(name, "XPCWrappedNative");
 
         cb.DescribeRefCountedNode(tmp->mRefCnt.get(), name);
     } else {
         NS_IMPL_CYCLE_COLLECTION_DESCRIBE(XPCWrappedNative, tmp->mRefCnt.get())
     }
 
@@ -165,23 +166,23 @@ XPCWrappedNative::WrapNewGlobal(xpcObjec
 
     // Put together the ScriptableCreateInfo...
     XPCNativeScriptableCreateInfo sciProto;
     XPCNativeScriptableCreateInfo sciMaybe;
     const XPCNativeScriptableCreateInfo& sciWrapper =
         GatherScriptableCreateInfo(identity, nativeHelper.GetClassInfo(),
                                    sciProto, sciMaybe);
 
-    // ...and then ScriptableInfo. We need all this stuff now because it's going
-    // to tell us the JSClass of the object we're going to create.
-    XPCNativeScriptableInfo* si = XPCNativeScriptableInfo::Construct(&sciWrapper);
-    MOZ_ASSERT(si);
+    // ...and then get the nsIXPCScriptable. This will tell us the JSClass of
+    // the object we're going to create.
+    nsCOMPtr<nsIXPCScriptable> scr = sciWrapper.GetCallback();
+    MOZ_ASSERT(scr);
 
     // Finally, we get to the JSClass.
-    const JSClass* clasp = si->GetJSClass();
+    const JSClass* clasp = scr->GetJSClass();
     MOZ_ASSERT(clasp->flags & JSCLASS_IS_GLOBAL);
 
     // Create the global.
     aOptions.creationOptions().setTrace(XPCWrappedNative::Trace);
     if (xpc::SharedMemoryEnabled())
         aOptions.creationOptions().setSharedMemoryAndAtomicsEnabled(true);
     RootedObject global(cx, xpc::CreateGlobalObject(cx, clasp, principal, aOptions));
     if (!global)
@@ -216,33 +217,17 @@ XPCWrappedNative::WrapNewGlobal(xpcObjec
     RefPtr<XPCWrappedNative> wrapper =
         new XPCWrappedNative(nativeHelper.forgetCanonical(), proto);
 
     //
     // We don't call ::Init() on this wrapper, because our setup requirements
     // are different for globals. We do our setup inline here, instead.
     //
 
-    // Share mScriptableInfo with the proto.
-    //
-    // This is probably more trouble than it's worth, since we've already
-    // created an XPCNativeScriptableInfo for ourselves. Nevertheless, this is
-    // what ::Init() does, and we want to be as consistent as possible with
-    // that code.
-    XPCNativeScriptableInfo* siProto = proto->GetScriptableInfo();
-    if (siProto && siProto->GetCallback() == sciWrapper.GetCallback()) {
-        wrapper->mScriptableInfo = siProto;
-        // XPCNativeScriptableInfo uses manual memory management. If we're
-        // switching over to that of the proto, we need to destroy the one
-        // we've allocated.
-        delete si;
-        si = nullptr;
-    } else {
-        wrapper->mScriptableInfo = si;
-    }
+    wrapper->mScriptable = scr;
 
     // Set the JS object to the global we already created.
     wrapper->mFlatJSObject = global;
     wrapper->mFlatJSObject.setFlags(FLAT_JS_OBJECT_VALID);
 
     // Set the private to the XPCWrappedNative.
     JS_SetPrivate(global, wrapper);
 
@@ -545,36 +530,34 @@ XPCWrappedNative::GetUsedOnly(nsISupport
     wrapper.forget(resultWrapper);
     return NS_OK;
 }
 
 // This ctor is used if this object will have a proto.
 XPCWrappedNative::XPCWrappedNative(already_AddRefed<nsISupports>&& aIdentity,
                                    XPCWrappedNativeProto* aProto)
     : mMaybeProto(aProto),
-      mSet(aProto->GetSet()),
-      mScriptableInfo(nullptr)
+      mSet(aProto->GetSet())
 {
     MOZ_ASSERT(NS_IsMainThread());
 
     mIdentity = aIdentity;
     mFlatJSObject.setFlags(FLAT_JS_OBJECT_VALID);
 
     MOZ_ASSERT(mMaybeProto, "bad ctor param");
     MOZ_ASSERT(mSet, "bad ctor param");
 }
 
 // This ctor is used if this object will NOT have a proto.
 XPCWrappedNative::XPCWrappedNative(already_AddRefed<nsISupports>&& aIdentity,
                                    XPCWrappedNativeScope* aScope,
                                    already_AddRefed<XPCNativeSet>&& aSet)
 
     : mMaybeScope(TagScope(aScope)),
-      mSet(aSet),
-      mScriptableInfo(nullptr)
+      mSet(aSet)
 {
     MOZ_ASSERT(NS_IsMainThread());
 
     mIdentity = aIdentity;
     mFlatJSObject.setFlags(FLAT_JS_OBJECT_VALID);
 
     MOZ_ASSERT(aScope, "bad ctor param");
     MOZ_ASSERT(mSet, "bad ctor param");
@@ -583,24 +566,17 @@ XPCWrappedNative::XPCWrappedNative(alrea
 XPCWrappedNative::~XPCWrappedNative()
 {
     Destroy();
 }
 
 void
 XPCWrappedNative::Destroy()
 {
-    XPCWrappedNativeProto* proto = GetProto();
-
-    if (mScriptableInfo &&
-        (!HasProto() ||
-         (proto && proto->GetScriptableInfo() != mScriptableInfo))) {
-        delete mScriptableInfo;
-        mScriptableInfo = nullptr;
-    }
+    mScriptable = nullptr;
 
     XPCWrappedNativeScope* scope = GetScope();
     if (scope) {
         Native2WrappedNativeMap* map = scope->GetWrappedNativeMap();
 
         // Post-1.9 we should not remove this wrapper from the map if it is
         // uninitialized.
         map->Remove(this);
@@ -724,40 +700,30 @@ XPCWrappedNative::GatherScriptableCreate
 
     return sciProto;
 }
 
 bool
 XPCWrappedNative::Init(const XPCNativeScriptableCreateInfo* sci)
 {
     AutoJSContext cx;
-    // setup our scriptable info...
 
-    if (sci->GetCallback()) {
-        if (HasProto()) {
-            XPCNativeScriptableInfo* siProto = GetProto()->GetScriptableInfo();
-            if (siProto && siProto->GetCallback() == sci->GetCallback())
-                mScriptableInfo = siProto;
-        }
-        if (!mScriptableInfo) {
-            mScriptableInfo = XPCNativeScriptableInfo::Construct(sci);
-
-            if (!mScriptableInfo)
-                return false;
-        }
-    }
-    XPCNativeScriptableInfo* si = mScriptableInfo;
+    // Setup our scriptable...
+    MOZ_ASSERT(!mScriptable);
+    mScriptable = sci->GetCallback();
 
     // create our flatJSObject
 
-    const JSClass* jsclazz = si ? si->GetJSClass() : Jsvalify(&XPC_WN_NoHelper_JSClass);
+    const JSClass* jsclazz = mScriptable
+                           ? mScriptable->GetJSClass()
+                           : Jsvalify(&XPC_WN_NoHelper_JSClass);
 
     // We should have the global jsclass flag if and only if we're a global.
-    MOZ_ASSERT_IF(si, !!si->GetCallback()->IsGlobalObject() ==
-                      !!(jsclazz->flags & JSCLASS_IS_GLOBAL));
+    MOZ_ASSERT_IF(mScriptable, !!mScriptable->IsGlobalObject() ==
+                               !!(jsclazz->flags & JSCLASS_IS_GLOBAL));
 
     MOZ_ASSERT(jsclazz &&
                jsclazz->name &&
                jsclazz->flags &&
                jsclazz->getResolve() &&
                jsclazz->hasFinalize(), "bad class");
 
     // XXXbz JS_GetObjectPrototype wants an object, even though it then asserts
@@ -954,17 +920,17 @@ XPCWrappedNative::SystemIsBeingShutDown(
     mFlatJSObject = nullptr;
     mFlatJSObject.unsetFlags(FLAT_JS_OBJECT_VALID);
 
     XPCWrappedNativeProto* proto = GetProto();
 
     if (HasProto())
         proto->SystemIsBeingShutDown();
 
-    // We don't destroy mScriptableInfo here. The destructor will do it.
+    // We don't clear mScriptable here. The destructor will do it.
 
     // Cleanup the tearoffs.
     for (XPCWrappedNativeTearOff* to = &mFirstTearOff; to; to = to->GetNextTearOff()) {
         if (JSObject* jso = to->GetJSObjectPreserveColor()) {
             JS_SetPrivate(jso, nullptr);
             to->SetJSObject(nullptr);
         }
         // We leak the tearoff mNative
@@ -1090,18 +1056,18 @@ XPCWrappedNative::InitTearOff(XPCWrapped
     nsISupports* identity = GetIdentityObject();
 
     // This is an nsRefPtr instead of an nsCOMPtr because it may not be the
     // canonical nsISupports for this object.
     RefPtr<nsISupports> qiResult;
 
     // If the scriptable helper forbids us from reflecting additional
     // interfaces, then don't even try the QI, just fail.
-    if (mScriptableInfo &&
-        mScriptableInfo->GetCallback()->ClassInfoInterfacesOnly() &&
+    if (mScriptable &&
+        mScriptable->ClassInfoInterfacesOnly() &&
         !mSet->HasInterface(aInterface) &&
         !mSet->HasInterfaceWithAncestor(aInterface)) {
         return NS_ERROR_NO_INTERFACE;
     }
 
     // We are about to call out to other code.
     // So protect our intended tearoff.
 
@@ -2147,24 +2113,22 @@ NS_IMETHODIMP XPCWrappedNative::DebugDum
 
         if (depth && mSet)
             mSet->DebugDump(depth);
         else
             XPC_LOG_ALWAYS(("mSet @ %x", mSet.get()));
 
         XPC_LOG_ALWAYS(("mFlatJSObject of %x", mFlatJSObject.unbarrieredGetPtr()));
         XPC_LOG_ALWAYS(("mIdentity of %x", mIdentity.get()));
-        XPC_LOG_ALWAYS(("mScriptableInfo @ %x", mScriptableInfo));
+        XPC_LOG_ALWAYS(("mScriptable @ %x", mScriptable.get()));
 
-        if (depth && mScriptableInfo) {
-            nsCOMPtr<nsIXPCScriptable> scr = mScriptableInfo->GetCallback();
+        if (depth && mScriptable) {
             XPC_LOG_INDENT();
-            XPC_LOG_ALWAYS(("mScriptable @ %x", scr.get()));
-            XPC_LOG_ALWAYS(("mFlags of %x", scr->GetScriptableFlags()));
-            XPC_LOG_ALWAYS(("mJSClass @ %x", mScriptableInfo->GetJSClass()));
+            XPC_LOG_ALWAYS(("mFlags of %x", mScriptable->GetScriptableFlags()));
+            XPC_LOG_ALWAYS(("mJSClass @ %x", mScriptable->GetJSClass()));
             XPC_LOG_OUTDENT();
         }
     XPC_LOG_OUTDENT();
 #endif
     return NS_OK;
 }
 
 /***************************************************************************/
@@ -2180,19 +2144,19 @@ XPCWrappedNative::ToString(XPCWrappedNat
 #  define FMT_ADDR ""
 #  define FMT_STR(str)
 #  define PARAM_ADDR(w)
 #endif
 
     char* sz = nullptr;
     char* name = nullptr;
 
-    XPCNativeScriptableInfo* si = GetScriptableInfo();
-    if (si)
-        name = JS_smprintf("%s", si->GetJSClass()->name);
+    nsCOMPtr<nsIXPCScriptable> scr = GetScriptable();
+    if (scr)
+        name = JS_smprintf("%s", scr->GetJSClass()->name);
     if (to) {
         const char* fmt = name ? " (%s)" : "%s";
         name = JS_sprintf_append(name, fmt,
                                  to->GetInterface()->GetNameString());
     } else if (!name) {
         XPCNativeSet* set = GetSet();
         XPCNativeInterface** array = set->GetInterfaceArray();
         RefPtr<XPCNativeInterface> isupp = XPCNativeInterface::GetISupports();
@@ -2213,17 +2177,17 @@ XPCWrappedNative::ToString(XPCWrappedNat
         }
     }
 
     if (!name) {
         return nullptr;
     }
     const char* fmt = "[xpconnect wrapped %s" FMT_ADDR FMT_STR(" (native")
         FMT_ADDR FMT_STR(")") "]";
-    if (si) {
+    if (scr) {
         fmt = "[object %s" FMT_ADDR FMT_STR(" (native") FMT_ADDR FMT_STR(")") "]";
     }
     sz = JS_smprintf(fmt, name PARAM_ADDR(this) PARAM_ADDR(mIdentity.get()));
 
     JS_smprintf_free(name);
 
 
     return sz;
@@ -2262,22 +2226,20 @@ static void DEBUG_CheckClassInfoClaims(X
         // Houston, We have a problem...
 
         char* className = nullptr;
         char* contractID = nullptr;
         const char* interfaceName;
 
         info->GetNameShared(&interfaceName);
         clsInfo->GetContractID(&contractID);
-        if (wrapper->GetScriptableInfo()) {
-            wrapper->GetScriptableInfo()->GetCallback()->
-                GetClassName(&className);
+        if (wrapper->GetScriptable()) {
+            wrapper->GetScriptable()->GetClassName(&className);
         }
 
-
         printf("\n!!! Object's nsIClassInfo lies about its interfaces!!!\n"
                "   classname: %s \n"
                "   contractid: %s \n"
                "   unimplemented interface name: %s\n\n",
                className ? className : "<unknown>",
                contractID ? contractID : "<unknown>",
                interfaceName);
 
--- a/js/xpconnect/src/XPCWrappedNativeJSOps.cpp
+++ b/js/xpconnect/src/XPCWrappedNativeJSOps.cpp
@@ -224,17 +224,17 @@ DefinePropertyIfFound(XPCCallContext& cc
                       HandleId idArg,
                       XPCNativeSet* set,
                       XPCNativeInterface* ifaceArg,
                       XPCNativeMember* member,
                       XPCWrappedNativeScope* scope,
                       bool reflectToStringAndToSource,
                       XPCWrappedNative* wrapperToReflectInterfaceNames,
                       XPCWrappedNative* wrapperToReflectDoubleWrap,
-                      XPCNativeScriptableInfo* scriptableInfo,
+                      nsIXPCScriptable* scr,
                       unsigned propFlags,
                       bool* resolved)
 {
     RootedId id(ccx, idArg);
     RefPtr<XPCNativeInterface> iface = ifaceArg;
     XPCJSContext* xpccx = ccx.GetContext();
     bool found;
     const char* name;
@@ -249,19 +249,18 @@ DefinePropertyIfFound(XPCCallContext& cc
     } else
         found = (nullptr != (member = iface->FindMember(id)));
 
     if (!found) {
         if (reflectToStringAndToSource) {
             JSNative call;
             uint32_t flags = 0;
 
-            if (scriptableInfo) {
-                nsCOMPtr<nsIClassInfo> classInfo = do_QueryInterface(
-                    scriptableInfo->GetCallback());
+            if (scr) {
+                nsCOMPtr<nsIClassInfo> classInfo = do_QueryInterface(scr);
 
                 if (classInfo) {
                     nsresult rv = classInfo->GetFlags(&flags);
                     if (NS_FAILED(rv))
                         return Throw(rv, ccx);
                 }
             }
 
@@ -410,18 +409,18 @@ DefinePropertyIfFound(XPCCallContext& cc
                 *resolved = true;
             desc.attributesRef() |= JSPROP_RESOLVING;
             return JS_DefinePropertyById(ccx, obj, id, desc);
         }
     }
 
     if (id == xpccx->GetStringID(XPCJSContext::IDX_TO_STRING) ||
         id == xpccx->GetStringID(XPCJSContext::IDX_TO_SOURCE) ||
-        (scriptableInfo &&
-         scriptableInfo->GetCallback()->DontEnumQueryInterface() &&
+        (scr &&
+         scr->DontEnumQueryInterface() &&
          id == xpccx->GetStringID(XPCJSContext::IDX_QUERY_INTERFACE)))
         propFlags &= ~JSPROP_ENUMERATE;
 
     RootedValue funval(ccx);
     if (!member->NewFunctionObject(ccx, iface, obj, funval.address()))
         return false;
 
     if (member->IsMethod()) {
@@ -544,17 +543,17 @@ WrappedNativeFinalize(js::FreeOp* fop, J
         mozilla::dom::DestroyProtoAndIfaceCache(obj);
     }
     nsISupports* p = static_cast<nsISupports*>(xpc_GetJSPrivate(obj));
     if (!p)
         return;
 
     XPCWrappedNative* wrapper = static_cast<XPCWrappedNative*>(p);
     if (helperType == WN_HELPER)
-        wrapper->GetScriptableCallback()->Finalize(wrapper, js::CastToJSFreeOp(fop), obj);
+        wrapper->GetScriptable()->Finalize(wrapper, js::CastToJSFreeOp(fop), obj);
     wrapper->FlatJSObjectFinalized();
 }
 
 static void
 WrappedNativeObjectMoved(JSObject* obj, const JSObject* old)
 {
     nsISupports* p = static_cast<nsISupports*>(xpc_GetJSPrivate(obj));
     if (!p)
@@ -699,17 +698,17 @@ XPC_WN_MaybeResolvingDeletePropertyStub(
         return false;                                                         \
     }                                                                         \
     if (!IS_WN_REFLECTOR(unwrapped)) {                                        \
         return Throw(NS_ERROR_XPC_BAD_OP_ON_WN_PROTO, cx);                    \
     }                                                                         \
     XPCWrappedNative* wrapper = XPCWrappedNative::Get(unwrapped);             \
     THROW_AND_RETURN_IF_BAD_WRAPPER(cx, wrapper);                             \
     bool retval = true;                                                       \
-    nsresult rv = wrapper->GetScriptableCallback()->
+    nsresult rv = wrapper->GetScriptable()->
 
 #define POST_HELPER_STUB                                                      \
     if (NS_FAILED(rv))                                                        \
         return Throw(rv, cx);                                                 \
     return retval;
 
 #define POST_HELPER_STUB_WITH_OBJECTOPRESULT(failMethod)                      \
     if (NS_FAILED(rv))                                                        \
@@ -792,25 +791,25 @@ XPC_WN_Helper_Resolve(JSContext* cx, Han
     bool retval = true;
     bool resolved = false;
     XPCCallContext ccx(cx, obj);
     XPCWrappedNative* wrapper = ccx.GetWrapper();
     THROW_AND_RETURN_IF_BAD_WRAPPER(cx, wrapper);
 
     RootedId old(cx, ccx.SetResolveName(id));
 
-    XPCNativeScriptableInfo* si = wrapper->GetScriptableInfo();
-    if (si && si->GetCallback()->WantResolve()) {
+    nsCOMPtr<nsIXPCScriptable> scr = wrapper->GetScriptable();
+    if (scr && scr->WantResolve()) {
         XPCWrappedNative* oldResolvingWrapper;
-        bool allowPropMods = si->GetCallback()->AllowPropModsDuringResolve();
+        bool allowPropMods = scr->AllowPropModsDuringResolve();
 
         if (allowPropMods)
             oldResolvingWrapper = ccx.SetResolvingWrapper(wrapper);
 
-        rv = si->GetCallback()->Resolve(wrapper, cx, obj, id, &resolved, &retval);
+        rv = scr->Resolve(wrapper, cx, obj, id, &resolved, &retval);
 
         if (allowPropMods)
             (void)ccx.SetResolvingWrapper(oldResolvingWrapper);
     }
 
     old = ccx.SetResolveName(old);
     MOZ_ASSERT(old == id, "bad nest");
 
@@ -830,93 +829,81 @@ XPC_WN_Helper_Resolve(JSContext* cx, Han
         XPCNativeMember* member = nullptr;
         RefPtr<XPCNativeInterface> iface;
         bool IsLocal = false;
 
         if (set->FindMember(id, &member, &iface, protoSet, &IsLocal) &&
             IsLocal) {
 
             XPCWrappedNative* wrapperForInterfaceNames =
-                (si && si->GetCallback()->DontReflectInterfaceNames())
-                ? nullptr
-                : wrapper;
+                (scr && scr->DontReflectInterfaceNames()) ? nullptr : wrapper;
 
             XPCWrappedNative* oldResolvingWrapper =
                 ccx.SetResolvingWrapper(wrapper);
             retval = DefinePropertyIfFound(ccx, obj, id,
                                            set, iface, member,
                                            wrapper->GetScope(),
                                            false,
                                            wrapperForInterfaceNames,
-                                           nullptr, si,
+                                           nullptr, scr,
                                            JSPROP_ENUMERATE, resolvedp);
             (void)ccx.SetResolvingWrapper(oldResolvingWrapper);
         }
     }
 
     return retval;
 }
 
 bool
 XPC_WN_Helper_Enumerate(JSContext* cx, HandleObject obj)
 {
     XPCCallContext ccx(cx, obj);
     XPCWrappedNative* wrapper = ccx.GetWrapper();
     THROW_AND_RETURN_IF_BAD_WRAPPER(cx, wrapper);
 
-    XPCNativeScriptableInfo* si = wrapper->GetScriptableInfo();
-    if (!si || !si->GetCallback()->WantEnumerate())
+    nsCOMPtr<nsIXPCScriptable> scr = wrapper->GetScriptable();
+    if (!scr || !scr->WantEnumerate())
         return Throw(NS_ERROR_XPC_BAD_OP_ON_WN_PROTO, cx);
 
     if (!XPC_WN_Shared_Enumerate(cx, obj))
         return false;
 
     bool retval = true;
-    nsresult rv = si->GetCallback()->Enumerate(wrapper, cx, obj, &retval);
+    nsresult rv = scr->Enumerate(wrapper, cx, obj, &retval);
     if (NS_FAILED(rv))
         return Throw(rv, cx);
     return retval;
 }
 
 /***************************************************************************/
 
 static bool
 XPC_WN_JSOp_Enumerate(JSContext* cx, HandleObject obj, AutoIdVector& properties,
                       bool enumerableOnly)
 {
     XPCCallContext ccx(cx, obj);
     XPCWrappedNative* wrapper = ccx.GetWrapper();
     THROW_AND_RETURN_IF_BAD_WRAPPER(cx, wrapper);
 
-    XPCNativeScriptableInfo* si = wrapper->GetScriptableInfo();
-    if (!si || !si->GetCallback()->WantNewEnumerate())
+    nsCOMPtr<nsIXPCScriptable> scr = wrapper->GetScriptable();
+    if (!scr || !scr->WantNewEnumerate())
         return Throw(NS_ERROR_XPC_BAD_OP_ON_WN_PROTO, cx);
 
     if (!XPC_WN_Shared_Enumerate(cx, obj))
         return false;
 
     bool retval = true;
-    nsresult rv = si->GetCallback()->NewEnumerate(wrapper, cx, obj, properties, &retval);
+    nsresult rv = scr->NewEnumerate(wrapper, cx, obj, properties, &retval);
     if (NS_FAILED(rv))
         return Throw(rv, cx);
     return retval;
 }
 
 /***************************************************************************/
 
-// static
-XPCNativeScriptableInfo*
-XPCNativeScriptableInfo::Construct(const XPCNativeScriptableCreateInfo* sci)
-{
-    MOZ_ASSERT(sci, "bad param");
-    nsCOMPtr<nsIXPCScriptable> callback = sci->GetCallback();
-    MOZ_ASSERT(callback);
-    return new XPCNativeScriptableInfo(callback);
-}
-
 const js::ObjectOps XPC_WN_ObjectOpsWithEnumerate = {
     nullptr,  // lookupProperty
     nullptr,  // defineProperty
     nullptr,  // hasProperty
     nullptr,  // getProperty
     nullptr,  // setProperty
     nullptr,  // getOwnPropertyDescriptor
     nullptr,  // deleteProperty
@@ -1108,21 +1095,21 @@ XPC_WN_ModsAllowed_Proto_Resolve(JSConte
         (XPCWrappedNativeProto*) xpc_GetJSPrivate(obj);
     if (!self)
         return false;
 
     XPCCallContext ccx(cx);
     if (!ccx.IsValid())
         return false;
 
-    XPCNativeScriptableInfo* si = self->GetScriptableInfo();
+    nsCOMPtr<nsIXPCScriptable> scr = self->GetScriptable();
     return DefinePropertyIfFound(ccx, obj, id,
                                  self->GetSet(), nullptr, nullptr,
                                  self->GetScope(),
-                                 true, nullptr, nullptr, si,
+                                 true, nullptr, nullptr, scr,
                                  JSPROP_ENUMERATE, resolvep);
 }
 
 static const js::ClassOps XPC_WN_ModsAllowed_Proto_JSClassOps = {
     nullptr,                            // addProperty
     nullptr,                            // delProperty
     nullptr,                            // getProperty
     nullptr,                            // setProperty
@@ -1185,22 +1172,22 @@ XPC_WN_NoMods_Proto_Resolve(JSContext* c
         (XPCWrappedNativeProto*) xpc_GetJSPrivate(obj);
     if (!self)
         return false;
 
     XPCCallContext ccx(cx);
     if (!ccx.IsValid())
         return false;
 
-    XPCNativeScriptableInfo* si = self->GetScriptableInfo();
+    nsCOMPtr<nsIXPCScriptable> scr = self->GetScriptable();
 
     return DefinePropertyIfFound(ccx, obj, id,
                                  self->GetSet(), nullptr, nullptr,
                                  self->GetScope(),
-                                 true, nullptr, nullptr, si,
+                                 true, nullptr, nullptr, scr,
                                  JSPROP_READONLY |
                                  JSPROP_PERMANENT |
                                  JSPROP_ENUMERATE, resolvedp);
 }
 
 static const js::ClassOps XPC_WN_NoMods_Proto_JSClassOps = {
     XPC_WN_OnlyIWrite_Proto_AddPropertyStub,   // addProperty
     XPC_WN_CannotDeletePropertyStub,           // delProperty
--- a/js/xpconnect/src/XPCWrappedNativeProto.cpp
+++ b/js/xpconnect/src/XPCWrappedNativeProto.cpp
@@ -16,18 +16,17 @@ int32_t XPCWrappedNativeProto::gDEBUG_Li
 #endif
 
 XPCWrappedNativeProto::XPCWrappedNativeProto(XPCWrappedNativeScope* Scope,
                                              nsIClassInfo* ClassInfo,
                                              already_AddRefed<XPCNativeSet>&& Set)
     : mScope(Scope),
       mJSProtoObject(nullptr),
       mClassInfo(ClassInfo),
-      mSet(Set),
-      mScriptableInfo(nullptr)
+      mSet(Set)
 {
     // This native object lives as long as its associated JSObject - killed
     // by finalization of the JSObject (or explicitly if Init fails).
 
     MOZ_COUNT_CTOR(XPCWrappedNativeProto);
     MOZ_ASSERT(mScope);
 
 #ifdef DEBUG
@@ -43,38 +42,31 @@ XPCWrappedNativeProto::~XPCWrappedNative
 
 #ifdef DEBUG
     gDEBUG_LiveProtoCount--;
 #endif
 
     // Note that our weak ref to mScope is not to be trusted at this point.
 
     XPCNativeSet::ClearCacheEntryForClassInfo(mClassInfo);
-
-    delete mScriptableInfo;
 }
 
 bool
 XPCWrappedNativeProto::Init(const XPCNativeScriptableCreateInfo* scriptableCreateInfo,
                             bool callPostCreatePrototype)
 {
     AutoJSContext cx;
-    nsIXPCScriptable* callback = scriptableCreateInfo ?
-                                 scriptableCreateInfo->GetCallback() :
-                                 nullptr;
-    if (callback) {
-        mScriptableInfo =
-            XPCNativeScriptableInfo::Construct(scriptableCreateInfo);
-        if (!mScriptableInfo)
-            return false;
-    }
+    nsCOMPtr<nsIXPCScriptable> callback = scriptableCreateInfo
+                                        ? scriptableCreateInfo->GetCallback()
+                                        : nullptr;
+    if (callback)
+        mScriptable = callback;
 
     const js::Class* jsclazz =
-        (mScriptableInfo &&
-         mScriptableInfo->GetCallback()->AllowPropModsToPrototype())
+        (mScriptable && mScriptable->AllowPropModsToPrototype())
         ? &XPC_WN_ModsAllowed_Proto_JSClass
         : &XPC_WN_NoMods_Proto_JSClass;
 
     JS::RootedObject global(cx, mScope->GetGlobalJSObject());
     JS::RootedObject proto(cx, JS_GetObjectPrototype(cx, global));
     mJSProtoObject = JS_NewObjectWithUniqueType(cx, js::Jsvalify(jsclazz),
                                                 proto);
 
@@ -89,24 +81,22 @@ XPCWrappedNativeProto::Init(const XPCNat
 }
 
 bool
 XPCWrappedNativeProto::CallPostCreatePrototype()
 {
     AutoJSContext cx;
 
     // Nothing to do if we don't have a scriptable callback.
-    nsIXPCScriptable* callback = mScriptableInfo ? mScriptableInfo->GetCallback()
-                                                 : nullptr;
-    if (!callback)
+    if (!mScriptable)
         return true;
 
     // Call the helper. This can handle being called if it's not implemented,
     // so we don't have to check any sort of "want" here. See xpc_map_end.h.
-    nsresult rv = callback->PostCreatePrototype(cx, mJSProtoObject);
+    nsresult rv = mScriptable->PostCreatePrototype(cx, mJSProtoObject);
     if (NS_FAILED(rv)) {
         JS_SetPrivate(mJSProtoObject, nullptr);
         mJSProtoObject = nullptr;
         XPCThrower::Throw(rv, cx);
         return false;
     }
 
     return true;
@@ -188,22 +178,20 @@ XPCWrappedNativeProto::DebugDump(int16_t
 #ifdef DEBUG
     depth-- ;
     XPC_LOG_ALWAYS(("XPCWrappedNativeProto @ %x", this));
     XPC_LOG_INDENT();
         XPC_LOG_ALWAYS(("gDEBUG_LiveProtoCount is %d", gDEBUG_LiveProtoCount));
         XPC_LOG_ALWAYS(("mScope @ %x", mScope));
         XPC_LOG_ALWAYS(("mJSProtoObject @ %x", mJSProtoObject.get()));
         XPC_LOG_ALWAYS(("mSet @ %x", mSet.get()));
-        XPC_LOG_ALWAYS(("mScriptableInfo @ %x", mScriptableInfo));
-        if (depth && mScriptableInfo) {
-            nsCOMPtr<nsIXPCScriptable> scr = mScriptableInfo->GetCallback();
+        XPC_LOG_ALWAYS(("mScriptable @ %x", mScriptable.get()));
+        if (depth && mScriptable) {
             XPC_LOG_INDENT();
-            XPC_LOG_ALWAYS(("mScriptable @ %x", scr.get()));
-            XPC_LOG_ALWAYS(("mFlags of %x", scr->GetScriptableFlags()));
-            XPC_LOG_ALWAYS(("mJSClass @ %x", mScriptableInfo->GetJSClass()));
+            XPC_LOG_ALWAYS(("mFlags of %x", mScriptable->GetScriptableFlags()));
+            XPC_LOG_ALWAYS(("mJSClass @ %x", mScriptable->GetJSClass()));
             XPC_LOG_OUTDENT();
         }
     XPC_LOG_OUTDENT();
 #endif
 }
 
 
--- a/js/xpconnect/src/XPCWrapper.h
+++ b/js/xpconnect/src/XPCWrapper.h
@@ -6,24 +6,16 @@
 
 #ifndef XPC_WRAPPER_H
 #define XPC_WRAPPER_H 1
 
 #include "js/TypeDecls.h"
 
 namespace XPCNativeWrapper {
 
-// Given an XPCWrappedNative pointer and the name of a function on
-// nsIXPCScriptable corresponding with a flag, returns 'true' if the flag is
-// set.
-// XXX Convert to using GetFlags() and not a macro.
-#define NATIVE_HAS_FLAG(_wn, _flag)                                           \
-  ((_wn)->GetScriptableInfo() &&                                              \
-   (_wn)->GetScriptableInfo()->GetCallback()->_flag())
-
 bool
 AttachNewConstructorObject(JSContext* aCx, JS::HandleObject aGlobalObject);
 
 } // namespace XPCNativeWrapper
 
 // This namespace wraps some common functionality between the three existing
 // wrappers. Its main purpose is to allow XPCCrossOriginWrapper to act both
 // as an XPCSafeJSObjectWrapper and as an XPCNativeWrapper when required to
--- a/js/xpconnect/src/xpcprivate.h
+++ b/js/xpconnect/src/xpcprivate.h
@@ -53,18 +53,17 @@
  * outside of the existing set, the set will grow. All QueryInterface results
  * are cached in XPCWrappedNativeTearOff objects, which are linked off of the
  * XPCWrappedNative.
  *
  * Besides having class info, a C++ object may be "scriptable" (i.e., implement
  * nsIXPCScriptable). This allows it to implement a more DOM-like interface,
  * besides just exposing XPCOM methods and constants. An nsIXPCScriptable
  * instance has hooks that correspond to all the normal JSClass hooks. Each
- * nsIXPCScriptable instance is mirrored by an XPCNativeScriptableInfo in
- * XPConnect. These can have pointers from XPCWrappedNativeProto and
+ * nsIXPCScriptable instance can have pointers from XPCWrappedNativeProto and
  * XPCWrappedNative (since C++ objects can have scriptable info without having
  * class info).
  */
 
 /* All the XPConnect private declarations - only include locally. */
 
 #ifndef xpcprivate_h___
 #define xpcprivate_h___
@@ -698,17 +697,17 @@ public:
     inline JSObject*                    GetFlattenedJSObject() const ;
     inline nsISupports*                 GetIdentityObject() const ;
     inline XPCWrappedNative*            GetWrapper() const ;
     inline XPCWrappedNativeProto*       GetProto() const ;
 
     inline bool                         CanGetTearOff() const ;
     inline XPCWrappedNativeTearOff*     GetTearOff() const ;
 
-    inline XPCNativeScriptableInfo*     GetScriptableInfo() const ;
+    inline nsIXPCScriptable*            GetScriptable() const ;
     inline bool                         CanGetSet() const ;
     inline XPCNativeSet*                GetSet() const ;
     inline bool                         CanGetInterface() const ;
     inline XPCNativeInterface*          GetInterface() const ;
     inline XPCNativeMember*             GetMember() const ;
     inline bool                         HasInterfaceAndMember() const ;
     inline jsid                         GetName() const ;
     inline bool                         GetStaticMemberIsLocal() const ;
@@ -774,17 +773,17 @@ private:
 
     // ctor does not necessarily init the following. BEWARE!
 
     XPCCallContext*                 mPrevCallContext;
 
     XPCWrappedNative*               mWrapper;
     XPCWrappedNativeTearOff*        mTearOff;
 
-    XPCNativeScriptableInfo*        mScriptableInfo;
+    nsCOMPtr<nsIXPCScriptable>      mScriptable;
 
     RefPtr<XPCNativeSet>            mSet;
     RefPtr<XPCNativeInterface>      mInterface;
     XPCNativeMember*                mMember;
 
     JS::RootedId                    mName;
     bool                            mStaticMemberIsLocal;
 
@@ -1379,56 +1378,18 @@ class XPCNativeSet final
     uint16_t                mMemberCount;
     uint16_t                mInterfaceCount;
     // Always last - object sized for array.
     // These are strong references.
     XPCNativeInterface*     mInterfaces[1];
 };
 
 /***************************************************************************/
-// XPCNativeScriptableInfo is a trivial wrapper for nsIXPCScriptable which
-// should be removed eventually.
-
-class XPCNativeScriptableInfo final
-{
-public:
-    static XPCNativeScriptableInfo*
-    Construct(const XPCNativeScriptableCreateInfo* sci);
-
-    nsIXPCScriptable*
-    GetCallback() const { return mCallback; }
-
-    const JSClass*
-    GetJSClass() { return Jsvalify(mCallback->GetClass()); }
-
-protected:
-    explicit XPCNativeScriptableInfo(nsIXPCScriptable* aCallback)
-        : mCallback(aCallback)
-    {
-        MOZ_COUNT_CTOR(XPCNativeScriptableInfo);
-    }
-public:
-    ~XPCNativeScriptableInfo()
-    {
-        MOZ_COUNT_DTOR(XPCNativeScriptableInfo);
-    }
-private:
-
-    // disable copy ctor and assignment
-    XPCNativeScriptableInfo(const XPCNativeScriptableInfo& r) = delete;
-    XPCNativeScriptableInfo& operator= (const XPCNativeScriptableInfo& r) = delete;
-
-private:
-    nsCOMPtr<nsIXPCScriptable> mCallback;
-};
-
-/***************************************************************************/
 // XPCNativeScriptableCreateInfo is used in creating new wrapper and protos.
-// it abstracts out the scriptable interface pointer and the flags. After
-// creation these are factored differently using XPCNativeScriptableInfo.
+// It abstracts out the scriptable interface pointer and the flags.
 
 class MOZ_STACK_CLASS XPCNativeScriptableCreateInfo final
 {
 public:
     XPCNativeScriptableCreateInfo() {}
 
     nsIXPCScriptable*
     GetCallback() const {return mCallback;}
@@ -1464,18 +1425,18 @@ public:
     GetJSProtoObject() const { return mJSProtoObject; }
 
     nsIClassInfo*
     GetClassInfo()     const {return mClassInfo;}
 
     XPCNativeSet*
     GetSet()           const {return mSet;}
 
-    XPCNativeScriptableInfo*
-    GetScriptableInfo()   {return mScriptableInfo;}
+    nsIXPCScriptable*
+    GetScriptable() const { return mScriptable; }
 
     bool CallPostCreatePrototype();
     void JSProtoObjectFinalized(js::FreeOp* fop, JSObject* obj);
     void JSProtoObjectMoved(JSObject* obj, const JSObject* old);
 
     void SystemIsBeingShutDown();
 
     void DebugDump(int16_t depth);
@@ -1524,17 +1485,17 @@ private:
     static int32_t gDEBUG_LiveProtoCount;
 #endif
 
 private:
     XPCWrappedNativeScope*   mScope;
     JS::ObjectPtr            mJSProtoObject;
     nsCOMPtr<nsIClassInfo>   mClassInfo;
     RefPtr<XPCNativeSet>     mSet;
-    XPCNativeScriptableInfo* mScriptableInfo;
+    nsCOMPtr<nsIXPCScriptable> mScriptable;
 };
 
 /***********************************************/
 // XPCWrappedNativeTearOff represents the info needed to make calls to one
 // interface on the underlying native object of a XPCWrappedNative.
 
 class XPCWrappedNativeTearOff final
 {
@@ -1687,21 +1648,18 @@ public:
 private:
     inline void
     ExpireWrapper()
         {mMaybeScope = (XPCWrappedNativeScope*)
                        (XPC_SCOPE_WORD(mMaybeScope) | XPC_WRAPPER_EXPIRED);}
 
 public:
 
-    XPCNativeScriptableInfo*
-    GetScriptableInfo() const {return mScriptableInfo;}
-
-    nsIXPCScriptable*      // call this wrong and you deserve to crash
-    GetScriptableCallback() const  {return mScriptableInfo->GetCallback();}
+    nsIXPCScriptable*
+    GetScriptable() const { return mScriptable; }
 
     nsIClassInfo*
     GetClassInfo() const {return IsValid() && HasProto() ?
                             GetProto()->GetClassInfo() : nullptr;}
 
     bool
     HasMutatedSet() const {return IsValid() &&
                                   (!HasProto() ||
@@ -1839,17 +1797,17 @@ public:
 private:
     union
     {
         XPCWrappedNativeScope* mMaybeScope;
         XPCWrappedNativeProto* mMaybeProto;
     };
     RefPtr<XPCNativeSet> mSet;
     JS::TenuredHeap<JSObject*> mFlatJSObject;
-    XPCNativeScriptableInfo* mScriptableInfo;
+    nsCOMPtr<nsIXPCScriptable> mScriptable;
     XPCWrappedNativeTearOff mFirstTearOff;
 };
 
 /***************************************************************************
 ****************************************************************************
 *
 * Core classes for wrapped JSObject for use from native code...
 *
--- a/js/xpconnect/wrappers/WrapperFactory.cpp
+++ b/js/xpconnect/wrappers/WrapperFactory.cpp
@@ -198,25 +198,25 @@ WrapperFactory::PrepareForWrapping(JSCon
 
     XPCWrappedNative* wn = XPCWrappedNative::Get(obj);
 
     JSAutoCompartment ac(cx, obj);
     XPCCallContext ccx(cx, obj);
     RootedObject wrapScope(cx, scope);
 
     {
-        if (NATIVE_HAS_FLAG(&ccx, WantPreCreate)) {
+        if (ccx.GetScriptable() && ccx.GetScriptable()->WantPreCreate()) {
             // We have a precreate hook. This object might enforce that we only
             // ever create JS object for it.
 
             // Note: this penalizes objects that only have one wrapper, but are
             // being accessed across compartments. We would really prefer to
             // replace the above code with a test that says "do you only have one
             // wrapper?"
-            nsresult rv = wn->GetScriptableInfo()->GetCallback()->
+            nsresult rv = wn->GetScriptable()->
                 PreCreate(wn->Native(), cx, scope, wrapScope.address());
             if (NS_FAILED(rv)) {
                 retObj.set(waive ? WaiveXray(cx, obj) : obj);
                 return;
             }
 
             // If the handed back scope differs from the passed-in scope and is in
             // a separate compartment, then this object is explicitly requesting
@@ -245,17 +245,17 @@ WrapperFactory::PrepareForWrapping(JSCon
                 // case, we want to return the existing wrapper.
                 //
                 // So we do a trick: call PreCreate _again_, but say that we're
                 // wrapping for the old scope, rather than the new one. If (1) is
                 // the case, then PreCreate will return the scope we pass to it
                 // (the old scope). If (2) is the case, PreCreate will return the
                 // scope of the document (the new scope).
                 RootedObject probe(cx);
-                rv = wn->GetScriptableInfo()->GetCallback()->
+                rv = wn->GetScriptable()->
                     PreCreate(wn->Native(), cx, currentScope, probe.address());
 
                 // Check for case (2).
                 if (probe != currentScope) {
                     MOZ_ASSERT(probe == wrapScope);
                     retObj.set(waive ? WaiveXray(cx, obj) : obj);
                     return;
                 }
--- a/js/xpconnect/wrappers/XrayWrapper.cpp
+++ b/js/xpconnect/wrappers/XrayWrapper.cpp
@@ -1568,24 +1568,23 @@ XPCWrappedNativeXrayTraits::createHolder
 
 bool
 XPCWrappedNativeXrayTraits::call(JSContext* cx, HandleObject wrapper,
                                  const JS::CallArgs& args,
                                  const js::Wrapper& baseInstance)
 {
     // Run the call hook of the wrapped native.
     XPCWrappedNative* wn = getWN(wrapper);
-    if (NATIVE_HAS_FLAG(wn, WantCall)) {
+    if (wn->GetScriptable() && wn->GetScriptable()->WantCall()) {
         XPCCallContext ccx(cx, wrapper, nullptr, JSID_VOIDHANDLE, args.length(),
                            args.array(), args.rval().address());
         if (!ccx.IsValid())
             return false;
         bool ok = true;
-        nsresult rv = wn->GetScriptableInfo()->GetCallback()->Call(
-            wn, cx, wrapper, args, &ok);
+        nsresult rv = wn->GetScriptable()->Call(wn, cx, wrapper, args, &ok);
         if (NS_FAILED(rv)) {
             if (ok)
                 XPCThrower::Throw(rv, cx);
             return false;
         }
     }
 
     return true;
@@ -1594,24 +1593,24 @@ XPCWrappedNativeXrayTraits::call(JSConte
 
 bool
 XPCWrappedNativeXrayTraits::construct(JSContext* cx, HandleObject wrapper,
                                       const JS::CallArgs& args,
                                       const js::Wrapper& baseInstance)
 {
     // Run the construct hook of the wrapped native.
     XPCWrappedNative* wn = getWN(wrapper);
-    if (NATIVE_HAS_FLAG(wn, WantConstruct)) {
+    if (wn->GetScriptable() && wn->GetScriptable()->WantConstruct()) {
         XPCCallContext ccx(cx, wrapper, nullptr, JSID_VOIDHANDLE, args.length(),
                            args.array(), args.rval().address());
         if (!ccx.IsValid())
             return false;
         bool ok = true;
-        nsresult rv = wn->GetScriptableInfo()->GetCallback()->Construct(
-            wn, cx, wrapper, args, &ok);
+        nsresult rv =
+            wn->GetScriptable()->Construct(wn, cx, wrapper, args, &ok);
         if (NS_FAILED(rv)) {
             if (ok)
                 XPCThrower::Throw(rv, cx);
             return false;
         }
     }
 
     return true;
--- a/layout/base/ServoRestyleManager.cpp
+++ b/layout/base/ServoRestyleManager.cpp
@@ -222,21 +222,28 @@ ServoRestyleManager::RecreateStyleContex
   }
 
   bool traverseElementChildren = aElement->HasDirtyDescendantsForServo();
   bool traverseTextChildren = recreateContext;
   if (traverseElementChildren || traverseTextChildren) {
     StyleChildrenIterator it(aElement);
     for (nsIContent* n = it.GetNextChild(); n; n = it.GetNextChild()) {
       if (traverseElementChildren && n->IsElement()) {
-        MOZ_ASSERT(primaryFrame,
-                   "Frame construction should be scheduled, and it takes the "
-                   "correct style for the children, so no need to be here.");
-        RecreateStyleContexts(n->AsElement(), primaryFrame->StyleContext(),
-                              aStyleSet, aChangeListToProcess);
+        if (!primaryFrame) {
+          // The frame constructor presumably decided to suppress frame
+          // construction on this subtree. Just clear the dirty descendants
+          // bit from the subtree, since there's no point in harvesting the
+          // change hints.
+          MOZ_ASSERT(!n->AsElement()->GetPrimaryFrame(),
+                     "Only display:contents should do this, and we don't handle that yet");
+          ClearDirtyDescendantsFromSubtree(n->AsElement());
+        } else {
+          RecreateStyleContexts(n->AsElement(), primaryFrame->StyleContext(),
+                                aStyleSet, aChangeListToProcess);
+        }
       } else if (traverseTextChildren && n->IsNodeOfType(nsINode::eTEXT)) {
         RecreateStyleContextsForText(n, primaryFrame->StyleContext(),
                                      aStyleSet);
       }
     }
   }
 
   aElement->UnsetHasDirtyDescendantsForServo();
--- a/layout/base/crashtests/crashtests.list
+++ b/layout/base/crashtests/crashtests.list
@@ -124,17 +124,17 @@ load 358729-1.xhtml
 load 360339-1.xul
 load 360339-2.xul
 asserts-if(stylo,28) load 363729-1.html # bug 1324633
 load 363729-2.html
 load 363729-3.html
 load 364427-1.html
 load 365909-1.xhtml
 load 365909-2.xhtml
-skip-if(stylo) load 366128-1.xhtml # bug 1323654
+load 366128-1.xhtml
 load 366271-1.html
 load 366967-1.html
 load 367015-1.html
 load 367243-1.html
 load 367498-1.html
 load 367498-2.html
 load 369176-1.html
 load 369547-1.html
@@ -206,17 +206,17 @@ load 401734-1.html
 load 401734-2.html
 needs-focus pref(accessibility.browsewithcaret,true) load 403048.html
 skip load 403175-1.html # times out occasionally, bug 473680
 skip-if(stylo) load 403245-1.html # bug 1323652
 load 403454.html
 load 403569-1.xhtml
 load 403569-2.xhtml
 load 403569-3.xhtml
-skip-if(stylo) load 404218-1.xhtml # bug 1323671
+load 404218-1.xhtml
 load 404491-1.html
 load 404721-1.xhtml
 load 404721-2.xhtml
 load 405049-1.xul
 load 405184-1.xhtml
 asserts-if(stylo,2) load 405186-1.xhtml # bug 1324661
 load 406675-1.html
 load 408292.html
@@ -311,17 +311,17 @@ load 490376-1.xhtml
 load 490559-1.html
 load 490747.html
 load 491547-1.xul
 load 491547-2.xul
 load 492014.xhtml
 load 492112-1.xhtml
 load 492163-1.xhtml
 load 495350-1.html
-skip-if(stylo) load 496011-1.xhtml # bug 1323649
+load 496011-1.xhtml
 load 497519-1.xhtml
 load 497519-2.xhtml
 load 497519-3.xhtml
 load 497519-4.xhtml
 load 499741-1.xhtml
 load 499841-1.xhtml
 load 499858-1.xhtml
 load 500467-1.html
--- a/layout/base/nsCSSFrameConstructor.cpp
+++ b/layout/base/nsCSSFrameConstructor.cpp
@@ -7361,40 +7361,47 @@ nsCSSFrameConstructor::ContentAppended(n
     nsIContent* bindingParent = aContainer->GetBindingParent();
     LAYOUT_PHASE_TEMP_EXIT();
     nsresult rv = RecreateFramesForContent(bindingParent, false,
                                            REMOVE_FOR_RECONSTRUCTION, nullptr);
     LAYOUT_PHASE_TEMP_REENTER();
     return rv;
   }
 
+  // The frame constructor uses this codepath both for bonafide newly-added
+  // content and for RestyleManager-driven frame construction (RECONSTRUCT_FRAME
+  // and lazy frame construction). If we're using the Servo style system, we
+  // want to ensure that styles get resolved in the first case, whereas for the
+  // second case they should have already been resolved if needed.
+  bool isNewlyAddedContentForServo = aContainer->IsStyledByServo() &&
+                                     !RestyleManager()->AsBase()->IsInStyleRefresh();
+
   // See comment in ContentRangeInserted for why this is necessary.
   if (!GetContentInsertionFrameFor(aContainer) &&
       !aContainer->IsActiveChildrenElement()) {
+    // We're punting on frame construction because there's no container frame.
+    // The Servo-backed style system handles this case like the lazy frame
+    // construction case.
+    if (isNewlyAddedContentForServo) {
+      aContainer->AsElement()->NoteDirtyDescendantsForServo();
+    }
     return NS_OK;
   }
 
   if (aAllowLazyConstruction &&
       MaybeConstructLazily(CONTENTAPPEND, aContainer, aFirstNewContent)) {
-    if (aContainer->IsStyledByServo()) {
+    if (isNewlyAddedContentForServo) {
       aContainer->AsElement()->NoteDirtyDescendantsForServo();
     }
     return NS_OK;
   }
 
   // We couldn't construct lazily. Make Servo eagerly traverse the subtree.
-  if (ServoStyleSet* set = mPresShell->StyleSet()->GetAsServo()) {
-    // We use the same codepaths to handle both of the following cases:
-    //   (a) Newly-appended content for which lazy frame construction is disallowed.
-    //   (b) Lazy frame construction driven by the restyle manager.
-    // We need the styles for (a). In the case of (b), the Servo traversal has
-    // already happened, so we don't need to do it again.
-    if (!RestyleManager()->AsBase()->IsInStyleRefresh()) {
-      set->StyleNewChildren(aContainer->AsElement());
-    }
+  if (isNewlyAddedContentForServo) {
+    mPresShell->StyleSet()->AsServo()->StyleNewChildren(aContainer->AsElement());
   }
 
   LAYOUT_PHASE_TEMP_EXIT();
   InsertionPoint insertion =
     GetRangeInsertionPoint(aContainer, aFirstNewContent, nullptr,
                            aAllowLazyConstruction);
   nsContainerFrame*& parentFrame = insertion.mParentFrame;
   LAYOUT_PHASE_TEMP_REENTER();
@@ -7812,50 +7819,58 @@ nsCSSFrameConstructor::ContentRangeInser
     nsIContent* bindingParent = aContainer->GetBindingParent();
     LAYOUT_PHASE_TEMP_EXIT();
     nsresult rv = RecreateFramesForContent(bindingParent, false,
                                            REMOVE_FOR_RECONSTRUCTION, nullptr);
     LAYOUT_PHASE_TEMP_REENTER();
     return rv;
   }
 
+  // The frame constructor uses this codepath both for bonafide newly-added
+  // content and for RestyleManager-driven frame construction (RECONSTRUCT_FRAME
+  // and lazy frame construction). If we're using the Servo style system, we
+  // want to ensure that styles get resolved in the first case, whereas for the
+  // second case they should have already been resolved if needed.
+  bool isNewlyAddedContentForServo = aContainer->IsStyledByServo() &&
+                                     !RestyleManager()->AsBase()->IsInStyleRefresh();
+
+
   // Put 'parentFrame' inside a scope so we don't confuse it with
   // 'insertion.mParentFrame' later.
   {
     nsContainerFrame* parentFrame = GetContentInsertionFrameFor(aContainer);
     // The xbl:children element won't have a frame, but default content can have the children as
     // a parent. While its uncommon to change the structure of the default content itself, a label,
     // for example, can be reframed by having its value attribute set or removed.
     if (!parentFrame && !aContainer->IsActiveChildrenElement()) {
+      // We're punting on frame construction because there's no container frame.
+      // The Servo-backed style system handles this case like the lazy frame
+      // construction case.
+      if (isNewlyAddedContentForServo) {
+        aContainer->AsElement()->NoteDirtyDescendantsForServo();
+      }
       return NS_OK;
     }
 
     // Otherwise, we've got parent content. Find its frame.
     NS_ASSERTION(!parentFrame || parentFrame->GetContent() == aContainer ||
                  GetDisplayContentsStyleFor(aContainer), "New XBL code is possibly wrong!");
 
     if (aAllowLazyConstruction &&
         MaybeConstructLazily(CONTENTINSERT, aContainer, aStartChild)) {
-      if (aContainer->IsStyledByServo()) {
+      if (isNewlyAddedContentForServo) {
         aContainer->AsElement()->NoteDirtyDescendantsForServo();
       }
       return NS_OK;
     }
   }
 
   // We couldn't construct lazily. Make Servo eagerly traverse the subtree.
-  if (ServoStyleSet* set = mPresShell->StyleSet()->GetAsServo()) {
-    // We use the same codepaths to handle both of the following cases:
-    //   (a) Newly-appended content for which lazy frame construction is disallowed.
-    //   (b) Lazy frame construction driven by the restyle manager.
-    // We need the styles for (a). In the case of (b), the Servo traversal has
-    // already happened, so we don't need to do it again.
-    if (!RestyleManager()->AsBase()->IsInStyleRefresh()) {
-      set->StyleNewChildren(aContainer->AsElement());
-    }
+  if (isNewlyAddedContentForServo) {
+    mPresShell->StyleSet()->AsServo()->StyleNewChildren(aContainer->AsElement());
   }
 
   InsertionPoint insertion;
   if (isSingleInsert) {
     // See if we have an XBL insertion point. If so, then that's our
     // real parent frame; if not, then the frame hasn't been built yet
     // and we just bail.
     insertion = GetInsertionPoint(aContainer, aStartChild);
--- a/layout/generic/crashtests/crashtests.list
+++ b/layout/generic/crashtests/crashtests.list
@@ -202,17 +202,17 @@ load 404204-1.html
 load 404215-1.html
 load 404215-2.html
 load 404215-3.html
 load 404219-1.html
 load 404219-2.html
 load 406137.html
 load 406380.html
 load 406902-1.html
-skip-if(stylo) load 407009-1.xhtml # bug 1323654
+load 407009-1.xhtml
 load 408304-1.xhtml
 load 408602-1.html
 load 408737-1.html
 load 408737-2.html
 load 408749-1.xhtml
 load 408883-1.html
 load 410198.html
 load 410228-1.html
@@ -257,17 +257,17 @@ load 422283-1.html
 load 422301-1.html
 load 423055-1.html
 load 423098.html
 load 423264-1.html
 load 424629.html
 load 425253-1.html
 load 426040-1.html
 load 426272-1.html
-skip-if(stylo) load 428263-1.html # bug 1323671
+load 428263-1.html
 load 429458.xhtml
 load 429960-1.html
 load 429960-2.html
 load 429969-1.html
 load 429981-1.html
 load 430332-1.html
 load 430344-1.html
 load 430352-1.html
--- a/layout/style/crashtests/crashtests.list
+++ b/layout/style/crashtests/crashtests.list
@@ -6,17 +6,17 @@ load 285727-1.html
 load 286707-1.html
 load 317561-1.html
 load 330998-1.html
 load 363950.html
 load 368175-1.html
 load 368740.html
 load 379788-1.html
 load 383979-1.xhtml
-skip-if(stylo) load 383979-2.html # bug 1323671
+load 383979-2.html
 load 386939-1.html
 load 391034-1.xhtml
 asserts-if(stylo,1) load 397022-1.html # bug 1324704
 load 399289-1.svg
 load 404470-1.html
 load 411603-1.html
 asserts-if(stylo,2) load 412588-1.html # bug 1324634
 load 413274-1.xhtml
--- a/layout/style/test/mochitest.ini
+++ b/layout/style/test/mochitest.ini
@@ -155,17 +155,17 @@ support-files = file_bug1089417_iframe.h
 [test_bug1203766.html]
 [test_bug1232829.html]
 [test_bug1292447.html]
 [test_cascade.html]
 [test_ch_ex_no_infloops.html]
 [test_change_hint_optimizations.html]
 [test_clip-path_polygon.html]
 [test_compute_data_with_start_struct.html]
-skip-if = toolkit == 'android'
+skip-if = toolkit == 'android' || stylo # bug 1330824 for stylo
 [test_computed_style.html]
 [test_computed_style_min_size_auto.html]
 [test_computed_style_no_pseudo.html]
 [test_computed_style_prefs.html]
 [test_condition_text.html]
 [test_condition_text_assignment.html]
 [test_contain_formatting_context.html]
 [test_counter_descriptor_storage.html]
@@ -267,16 +267,17 @@ skip-if = toolkit == 'android' #bug 7752
 [test_text_decoration_shorthands.html]
 [test_transitions_and_reframes.html]
 [test_transitions_and_restyles.html]
 [test_transitions_and_zoom.html]
 skip-if = stylo # timeout bug 1328499
 [test_transitions_cancel_near_end.html]
 skip-if = stylo # timeout bug 1328499
 [test_transitions_computed_values.html]
+skip-if = stylo # bug 1330825
 [test_transitions_computed_value_combinations.html]
 [test_transitions_events.html]
 skip-if = stylo # timeout bug 1328499
 [test_transitions.html]
 skip-if = (android_version == '18' && debug) # bug 1159532
 [test_transitions_bug537151.html]
 skip-if = stylo # timeout bug 1328499
 [test_transitions_dynamic_changes.html]
@@ -296,20 +297,21 @@ support-files = ../../reftests/fonts/mar
 [test_units_frequency.html]
 [test_units_length.html]
 [test_units_time.html]
 [test_unprefixing_service.html]
 support-files = unprefixing_service_iframe.html unprefixing_service_utils.js
 [test_unprefixing_service_prefs.html]
 support-files = unprefixing_service_iframe.html unprefixing_service_utils.js
 [test_value_cloning.html]
-skip-if = toolkit == 'android' #bug 775227
+skip-if = toolkit == 'android' || stylo # bug 775227 for android, bug 1330824 for stylo
 [test_value_computation.html]
-skip-if = toolkit == 'android'
+skip-if = toolkit == 'android' || stylo # bug 1330824 for stylo
 [test_value_storage.html]
+skip-if = stylo # bug 1330824
 [test_variable_serialization_computed.html]
 [test_variable_serialization_specified.html]
 [test_variables.html]
 support-files = support/external-variable-url.css
 [test_video_object_fit.html]
 [test_viewport_units.html]
 [test_visited_image_loading.html]
 skip-if = (toolkit == 'android' || stylo) # TIMED_OUT for android, timeout bug 1328511 for stylo
--- a/layout/tables/crashtests/crashtests.list
+++ b/layout/tables/crashtests/crashtests.list
@@ -110,17 +110,17 @@ load 423514-1.xhtml
 load 430374.html
 load 444431-1.html
 load 444702-1.html
 asserts-if(stylo,1) load 448988-1.xhtml # bug 1324681
 load 450311-1.html
 load 451170.html
 load 451355-1.html
 load 456041.html
-skip-if(stylo) load 457115.html # bug 1323671
+load 457115.html
 load 460637-1.xhtml
 load 460637-2.xhtml
 load 460637-3.xhtml
 load 462849.xhtml
 load 467141-1.html
 load 488388-1.html
 load 501870-1.html
 load 509562-1.xhtml
--- a/mobile/android/components/PromptService.js
+++ b/mobile/android/components/PromptService.js
@@ -667,17 +667,17 @@ var PromptUtils = {
       propBag.setProperty("timePasswordChanged", now);
     }
     propBag.setProperty("timeLastUsed", now);
     propBag.setProperty("timesUsedIncrement", 1);
 
     this.pwmgr.modifyLogin(aLogin, propBag);
   },
 
-  // JS port of http://mxr.mozilla.org/mozilla-central/source/embedding/components/windowwatcher/nsPrompt.cpp#388
+  // JS port of http://mxr.mozilla.org/mozilla-central/source/toolkit/components/windowwatcher/nsPrompt.cpp#388
   makeDialogText: function pu_makeDialogText(aChannel, aAuthInfo) {
     let isProxy    = (aAuthInfo.flags & Ci.nsIAuthInformation.AUTH_PROXY);
     let isPassOnly = (aAuthInfo.flags & Ci.nsIAuthInformation.ONLY_PASSWORD);
     let isCrossOrig = (aAuthInfo.flags &
                        Ci.nsIAuthInformation.CROSS_ORIGIN_SUB_RESOURCE);
 
     let username = aAuthInfo.username;
     let [displayHost, realm] = this.getAuthTarget(aChannel, aAuthInfo);
@@ -704,17 +704,17 @@ var PromptUtils = {
       text = this.bundle.formatStringFromName("EnterUserPasswordFor2", [displayHost], 1);
     } else {
       text = this.bundle.formatStringFromName("EnterLoginForRealm3", [realm, displayHost], 2);
     }
 
     return text;
   },
 
-  // JS port of http://mxr.mozilla.org/mozilla-central/source/embedding/components/windowwatcher/nsPromptUtils.h#89
+  // JS port of http://mxr.mozilla.org/mozilla-central/source/toolkit/components/windowwatcher/nsPromptUtils.h#89
   getAuthHostPort: function pu_getAuthHostPort(aChannel, aAuthInfo) {
     let uri = aChannel.URI;
     let res = { host: null, port: -1 };
     if (aAuthInfo.flags & aAuthInfo.AUTH_PROXY) {
       let proxy = aChannel.QueryInterface(Ci.nsIProxiedChannel);
       res.host = proxy.proxyInfo.host;
       res.port = proxy.proxyInfo.port;
     } else {
--- a/mobile/android/installer/package-manifest.in
+++ b/mobile/android/installer/package-manifest.in
@@ -145,23 +145,21 @@
 #endif
 @BINPATH@/components/dom_xbl.xpt
 @BINPATH@/components/dom_xhr.xpt
 @BINPATH@/components/dom_xpath.xpt
 @BINPATH@/components/dom_xul.xpt
 @BINPATH@/components/dom_presentation.xpt
 @BINPATH@/components/downloads.xpt
 @BINPATH@/components/editor.xpt
-@BINPATH@/components/embed_base.xpt
 @BINPATH@/components/extensions.xpt
 @BINPATH@/components/exthandler.xpt
 @BINPATH@/components/exthelper.xpt
 @BINPATH@/components/fastfind.xpt
 @BINPATH@/components/feeds.xpt
-@BINPATH@/components/find.xpt
 @BINPATH@/components/gfx.xpt
 @BINPATH@/components/html5.xpt
 @BINPATH@/components/htmlparser.xpt
 @BINPATH@/components/imglib2.xpt
 @BINPATH@/components/inspector.xpt
 @BINPATH@/components/intl.xpt
 @BINPATH@/components/jar.xpt
 @BINPATH@/components/jsdebugger.xpt
@@ -237,16 +235,17 @@
 @BINPATH@/components/unicharutil.xpt
 @BINPATH@/components/update.xpt
 @BINPATH@/components/uriloader.xpt
 @BINPATH@/components/urlformatter.xpt
 @BINPATH@/components/webBrowser_core.xpt
 @BINPATH@/components/webbrowserpersist.xpt
 @BINPATH@/components/widget.xpt
 @BINPATH@/components/widget_android.xpt
+@BINPATH@/components/windowcreator.xpt
 @BINPATH@/components/windowds.xpt
 @BINPATH@/components/windowwatcher.xpt
 @BINPATH@/components/xpcom_base.xpt
 @BINPATH@/components/xpcom_system.xpt
 @BINPATH@/components/xpcom_components.xpt
 @BINPATH@/components/xpcom_ds.xpt
 @BINPATH@/components/xpcom_io.xpt
 @BINPATH@/components/xpcom_threads.xpt
rename from embedding/browser/build/moz.build
rename to toolkit/components/browser/build/moz.build
rename from embedding/browser/build/nsWebBrowserModule.cpp
rename to toolkit/components/browser/build/nsWebBrowserModule.cpp
new file mode 100644
--- /dev/null
+++ b/toolkit/components/browser/moz.build
@@ -0,0 +1,51 @@
+# -*- Mode: python; 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 += ['build']
+
+XPIDL_SOURCES += [
+    'nsCWebBrowser.idl',
+    'nsICommandHandler.idl',
+    'nsIEmbeddingSiteWindow.idl',
+    'nsIWebBrowser.idl',
+    'nsIWebBrowserChrome.idl',
+    'nsIWebBrowserChrome2.idl',
+    'nsIWebBrowserChrome3.idl',
+    'nsIWebBrowserChromeFocus.idl',
+    'nsIWebBrowserFocus.idl',
+    'nsIWebBrowserSetup.idl',
+    'nsIWebBrowserStream.idl',
+]
+
+if CONFIG['NS_PRINTING']:
+    XPIDL_SOURCES += [
+        'nsIPrintingPromptService.idl',
+        'nsIWebBrowserPrint.idl',
+    ]
+
+XPIDL_MODULE = 'webBrowser_core'
+
+UNIFIED_SOURCES += [
+    'nsCommandHandler.cpp',
+    'nsEmbedStream.cpp',
+    'nsWebBrowser.cpp',
+    'nsWebBrowserContentPolicy.cpp',
+]
+
+FINAL_LIBRARY = 'xul'
+LOCAL_INCLUDES += [
+    '/docshell/base',
+    '/dom/base',
+    '/dom/svg',
+    '/layout/style',
+]
+
+if CONFIG['GNU_CXX']:
+    CXXFLAGS += ['-Wno-error=shadow']
+
+EXPORTS += [
+    'nsEmbedCID.h',
+]
rename from embedding/browser/nsCWebBrowser.idl
rename to toolkit/components/browser/nsCWebBrowser.idl
rename from embedding/browser/nsCommandHandler.cpp
rename to toolkit/components/browser/nsCommandHandler.cpp
rename from embedding/browser/nsCommandHandler.h
rename to toolkit/components/browser/nsCommandHandler.h
rename from embedding/nsEmbedCID.h
rename to toolkit/components/browser/nsEmbedCID.h
rename from embedding/browser/nsEmbedStream.cpp
rename to toolkit/components/browser/nsEmbedStream.cpp
rename from embedding/browser/nsEmbedStream.h
rename to toolkit/components/browser/nsEmbedStream.h
rename from embedding/browser/nsICommandHandler.idl
rename to toolkit/components/browser/nsICommandHandler.idl
rename from embedding/browser/nsIEmbeddingSiteWindow.idl
rename to toolkit/components/browser/nsIEmbeddingSiteWindow.idl
rename from embedding/browser/nsIPrintPreviewNavigation.idl
rename to toolkit/components/browser/nsIPrintPreviewNavigation.idl
new file mode 100644
--- /dev/null
+++ b/toolkit/components/browser/nsIPrintingPromptService.idl
@@ -0,0 +1,165 @@
+/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+/* Doc interface here */
+
+#include "nsISupports.idl"
+#include "nsIWebBrowserPrint.idl"
+#include "nsIWebProgressListener.idl"
+#include "nsIPrintProgressParams.idl"
+#include "nsIPrintSettings.idl"
+#include "nsIObserver.idl"
+
+interface nsIDOMWindow;
+
+[scriptable, uuid(328daa3e-09e4-455f-bb6f-0a921766042f)]
+interface nsIPrintingPromptService : nsISupports
+{
+   /**
+   *  This service enables embedders to implement their own Print and Progress Dialogs.
+   *  Each platform has a "base" or "basckstop" implementation of the service. The 
+   *  service is automatically registered at start up.
+   *
+   *  Historically, platform toolkits with native dialogs have implemented them in the GFX layer
+   *  Usually they were displayed when a new DeviceContextSpec specific to that platform
+   *  was created.
+   *
+   *  Windows: The GFX layer no longers supports default toolkit behavior for displaying the 
+   *           native Print Dialog.
+   *           If an embedder implemented service returns any error code (other than NS_ERROR_ABORT)
+   *           printing will terminate.
+   *
+   *           Returning NS_OK assumes that the PrintSettings object was correctly filled in and
+   *           if it does not have valid fields for printer name, etc. it may also terminate.
+   *
+   *           Defaults for platform service:           
+   *             showPrintDialog       - displays a native dialog
+   *             showPageSetup         - displays a XUL dialog
+   *             showProgress          - displays a XUL dialog
+   *             showPrinterProperties - n/a
+   *
+   *           Summary for Windows Embedders:
+   *             Stated once again: There is no "fallback" native platform support in GFX for the
+   *             displaying of the native print dialog. The current default implementation for Windows
+   *             display a native print dialog but a XUL-based progress dialog.
+   *             If you wish to have a native progress dialog on Windows you will have to create and 
+   *             register your own service.
+   *  
+   *             Note: The Windows version Mozilla implements this service which is 
+   *                   automatically built and registered for you. You can use it as an example.
+   *                   It is located at "mozilla/toolkit/components/printingui/win". That service
+   *                   is capable of displaying a native print dialog and a XUL progress dialog.
+   *
+   *             To fly your own dialog you may:
+   *
+   *              1) Implement this service to display at least the Print Dialog and a Print Progress Dialog
+   *                 or you may implement just one of the dialogs and pass back NS_ERROR_NOT_IMPLEMENTED
+   *                 for any of the others.
+   *
+   *              2) For the Print Dialog:
+   *                 You may stub out this service by having all the methods return NS_ERROR_NOT_IMPLEMENTED.
+   *                 You can then fly you own dialog and then properly fill in the PrintSettings object
+   *                 before calling nsIWebBrowserPrint's Print method. If you stub out this service  
+   *                 you MUST set "printSilent" to true, if you do not, Printing will terminate and an 
+   *                 error dialog will be displayed.
+   *
+   *  Mac: The GFX layer still supports default toolkit behavior for displaying the Print Dialog.
+   *       If an embedder implemented service returns NS_ERROR_NOT_IMPLEMENTED for "showPrintDialog"
+   *       The toolkit will display the native print dialog.
+   *
+   *       Defaults for platform service:           
+   *       Mac OS9: showPrintDialog       - displays a native dialog
+   *                showPageSetup         - displays a native dialog
+   *                showProgress          - displays a XUL dialog
+   *                showPrinterProperties - n/a
+   *                
+   *       Mac OSX: showPrintDialog       - displays a native dialog
+   *                showPageSetup         - displays a native dialog
+   *                showProgress          - not implemented (provided by OS)
+   *                showPrinterProperties - n/a
+   *                
+   *  GTK: There are no native dialog for GTK.
+   *
+   *       Defaults for platform service:           
+   *         showPrintDialog       - displays a XUL dialog
+   *         showPageSetup         - displays a XUL dialog
+   *         showProgress          - displays a XUL dialog
+   *         showPrinterProperties - displays a XUL dialog
+   *
+   */
+ 
+
+
+  /**
+   *  Show the Print Dialog 
+   *
+   *  @param parent - a DOM windows the dialog will be parented to (required)
+   *  @param webBrowserPrint - represents the document to be printed (required)
+   *  @param printSettings - PrintSettings for print "job" (required)
+   *
+   */
+  void showPrintDialog(in mozIDOMWindowProxy parent,
+                       in nsIWebBrowserPrint webBrowserPrint,
+                       in nsIPrintSettings printSettings);
+
+  /**
+   *  Shows the print progress dialog
+   *
+   *  @param parent - a DOM windows the dialog will be parented to
+   *  @param webBrowserPrint - represents the document to be printed
+   *  @param printSettings - PrintSettings for print "job"
+   *  @param openDialogObserver - an observer that will be notifed when the dialog is opened
+   *  @param isForPrinting - true - for printing, false for print preview
+   *  @param webProgressListener - additional listener can be registered for progress notifications
+   *  @param printProgressParams - parameter object for passing progress state
+   *  @param notifyOnOpen - this indicates that the observer will be notified when the progress
+   *                        dialog has been opened. If false is returned it means the observer
+   *                        (usually the caller) shouldn't wait
+   *                        For Print Preview Progress there is intermediate progress
+   */
+  void showProgress(in mozIDOMWindowProxy parent,
+                    in nsIWebBrowserPrint webBrowserPrint,
+                    in nsIPrintSettings printSettings,
+                    in nsIObserver openDialogObserver,
+                    in boolean isForPrinting,
+                    out nsIWebProgressListener webProgressListener,
+                    out nsIPrintProgressParams printProgressParams,
+                    out boolean notifyOnOpen);
+
+  /**
+   *  Shows the print progress dialog
+   *
+   *  @param parent - a DOM windows the dialog will be parented to (required)
+   *  @param printSettings - PrintSettings for page setup (required)
+   *  @param aObs - An observer to know if the contents of the Print Settings 
+   *                object has changed while the dialog is being shown. 
+   *                For example, some platforms may implement an "Apply" button (not required)
+   */
+  void showPageSetup(in mozIDOMWindowProxy parent,
+                     in nsIPrintSettings printSettings,
+                     in nsIObserver aObs);
+
+  /**
+   *  Sometimes platforms need to bring up a special properties dialog for showing
+   *  print specific properties. Although the PrintSettings has a place to set the 
+   *  printer name, here is is an argument to be clear as to what printer is being
+   *  asked to have the properties set for it. The Printer name in the PS is ignored.
+   *
+   *  @param parent - a DOM windows the dialog will be parented to (required)
+   *  @param printerName - name of printer (required)
+   *  @param printSettings - PrintSettings for page setup (required)
+   */
+  void showPrinterProperties(in mozIDOMWindowProxy parent,
+                             in wstring printerName,
+                             in nsIPrintSettings printSettings);
+
+};
+
+%{C++
+// {260FEDC5-524D-4aa6-9A41-E829F4C78B92}
+#define NS_PRINTINGPROMPTSERVICE_IID \
+ {0x260fedc5, 0x524d, 0x4aa6, { 0x9a, 0x41, 0xe8, 0x29, 0xf4, 0xc7, 0x8b, 0x92}}
+%}
+
rename from embedding/browser/nsIWebBrowser.idl
rename to toolkit/components/browser/nsIWebBrowser.idl
rename from embedding/browser/nsIWebBrowserChrome.idl
rename to toolkit/components/browser/nsIWebBrowserChrome.idl
rename from embedding/browser/nsIWebBrowserChrome2.idl
rename to toolkit/components/browser/nsIWebBrowserChrome2.idl
rename from embedding/browser/nsIWebBrowserChrome3.idl
rename to toolkit/components/browser/nsIWebBrowserChrome3.idl
rename from embedding/browser/nsIWebBrowserChromeFocus.idl
rename to toolkit/components/browser/nsIWebBrowserChromeFocus.idl
rename from embedding/browser/nsIWebBrowserFocus.idl
rename to toolkit/components/browser/nsIWebBrowserFocus.idl
rename from embedding/browser/nsIWebBrowserPrint.idl
rename to toolkit/components/browser/nsIWebBrowserPrint.idl
rename from embedding/browser/nsIWebBrowserSetup.idl
rename to toolkit/components/browser/nsIWebBrowserSetup.idl
rename from embedding/browser/nsIWebBrowserStream.idl
rename to toolkit/components/browser/nsIWebBrowserStream.idl
rename from embedding/browser/nsWebBrowser.cpp
rename to toolkit/components/browser/nsWebBrowser.cpp
rename from embedding/browser/nsWebBrowser.h
rename to toolkit/components/browser/nsWebBrowser.h
rename from embedding/browser/nsWebBrowserContentPolicy.cpp
rename to toolkit/components/browser/nsWebBrowserContentPolicy.cpp
rename from embedding/browser/nsWebBrowserContentPolicy.h
rename to toolkit/components/browser/nsWebBrowserContentPolicy.h
--- a/toolkit/components/find/moz.build
+++ b/toolkit/components/find/moz.build
@@ -1,17 +1,24 @@
 # -*- Mode: python; indent-tabs-mode: nil; tab-width: 40 -*-
 # vim: set filetype=python:
 # This Source Code Form is subject to the terms of the Mozilla Public
 # License, v. 2.0. If a copy of the MPL was not distributed with this
 # file, You can obtain one at http://mozilla.org/MPL/2.0/.
 
 XPIDL_SOURCES += [
+    'nsIFind.idl',
     'nsIFindService.idl',
+    'nsIWebBrowserFind.idl',
 ]
 
 XPIDL_MODULE = 'mozfind'
 
+UNIFIED_SOURCES += [
+    'nsFind.cpp',
+    'nsWebBrowserFind.cpp',
+]
+
 SOURCES += [
     'nsFindService.cpp',
 ]
 
 FINAL_LIBRARY = 'xul'
rename from embedding/components/find/nsFind.cpp
rename to toolkit/components/find/nsFind.cpp
rename from embedding/components/find/nsFind.h
rename to toolkit/components/find/nsFind.h
rename from embedding/components/find/nsIFind.idl
rename to toolkit/components/find/nsIFind.idl
rename from embedding/components/find/nsIWebBrowserFind.idl
rename to toolkit/components/find/nsIWebBrowserFind.idl
rename from embedding/components/find/nsWebBrowserFind.cpp
rename to toolkit/components/find/nsWebBrowserFind.cpp
rename from embedding/components/find/nsWebBrowserFind.h
rename to toolkit/components/find/nsWebBrowserFind.h
--- a/toolkit/components/moz.build
+++ b/toolkit/components/moz.build
@@ -12,16 +12,17 @@ DIRS += [
     'aboutcache',
     'aboutcheckerboard',
     'aboutmemory',
     'aboutperformance',
     'addoncompat',
     'alerts',
     'apppicker',
     'asyncshutdown',
+    'browser',
     'commandlines',
     'contentprefs',
     'contextualidentity',
     'crashmonitor',
     'diskspacewatcher',
     'downloads',
     'extensions',
     'exthelper',
@@ -56,16 +57,18 @@ DIRS += [
     'thumbnails',
     'timermanager',
     'tooltiptext',
     'typeaheadfind',
     'utils',
     'url-classifier',
     'urlformatter',
     'viewconfig',
+    'windowcreator',
+    'windowwatcher',
     'workerloader',
     'xulstore'
 ]
 
 if CONFIG['ENABLE_INTL_API']:
     DIRS += ['mozintl']
 
 if CONFIG['MOZ_BUILD_APP'] != 'mobile/android':
@@ -79,17 +82,17 @@ if CONFIG['MOZ_CRASHREPORTER']:
 
 if CONFIG['BUILD_CTYPES']:
     DIRS += ['ctypes']
 
 if CONFIG['MOZ_FEEDS']:
     DIRS += ['feeds']
 
 if CONFIG['MOZ_XUL']:
-    DIRS += ['autocomplete', 'satchel']
+    DIRS += ['autocomplete', 'printingui', 'satchel']
 
 if 'gtk' in CONFIG['MOZ_WIDGET_TOOLKIT']:
     DIRS += ['filepicker']
 
 if CONFIG['MOZ_TOOLKIT_SEARCH']:
     DIRS += ['search']
 
 DIRS += ['captivedetect']
rename from embedding/components/printingui/ipc/PPrintProgressDialog.ipdl
rename to toolkit/components/printingui/ipc/PPrintProgressDialog.ipdl
rename from embedding/components/printingui/ipc/PPrintSettingsDialog.ipdl
rename to toolkit/components/printingui/ipc/PPrintSettingsDialog.ipdl
rename from embedding/components/printingui/ipc/PPrinting.ipdl
rename to toolkit/components/printingui/ipc/PPrinting.ipdl
rename from embedding/components/printingui/ipc/PPrintingTypes.ipdlh
rename to toolkit/components/printingui/ipc/PPrintingTypes.ipdlh
rename from embedding/components/printingui/ipc/PrintDataUtils.cpp
rename to toolkit/components/printingui/ipc/PrintDataUtils.cpp
rename from embedding/components/printingui/ipc/PrintDataUtils.h
rename to toolkit/components/printingui/ipc/PrintDataUtils.h
rename from embedding/components/printingui/ipc/PrintProgressDialogChild.cpp
rename to toolkit/components/printingui/ipc/PrintProgressDialogChild.cpp
rename from embedding/components/printingui/ipc/PrintProgressDialogChild.h
rename to toolkit/components/printingui/ipc/PrintProgressDialogChild.h
rename from embedding/components/printingui/ipc/PrintProgressDialogParent.cpp
rename to toolkit/components/printingui/ipc/PrintProgressDialogParent.cpp
rename from embedding/components/printingui/ipc/PrintProgressDialogParent.h
rename to toolkit/components/printingui/ipc/PrintProgressDialogParent.h
rename from embedding/components/printingui/ipc/PrintSettingsDialogChild.cpp
rename to toolkit/components/printingui/ipc/PrintSettingsDialogChild.cpp
rename from embedding/components/printingui/ipc/PrintSettingsDialogChild.h
rename to toolkit/components/printingui/ipc/PrintSettingsDialogChild.h
rename from embedding/components/printingui/ipc/PrintSettingsDialogParent.cpp
rename to toolkit/components/printingui/ipc/PrintSettingsDialogParent.cpp
rename from embedding/components/printingui/ipc/PrintSettingsDialogParent.h
rename to toolkit/components/printingui/ipc/PrintSettingsDialogParent.h
rename from embedding/components/printingui/ipc/PrintingParent.cpp
rename to toolkit/components/printingui/ipc/PrintingParent.cpp
rename from embedding/components/printingui/ipc/PrintingParent.h
rename to toolkit/components/printingui/ipc/PrintingParent.h
rename from embedding/components/printingui/ipc/moz.build
rename to toolkit/components/printingui/ipc/moz.build
rename from embedding/components/printingui/ipc/nsPrintingProxy.cpp
rename to toolkit/components/printingui/ipc/nsPrintingProxy.cpp
rename from embedding/components/printingui/ipc/nsPrintingProxy.h
rename to toolkit/components/printingui/ipc/nsPrintingProxy.h
rename from embedding/components/printingui/mac/moz.build
rename to toolkit/components/printingui/mac/moz.build
rename from embedding/components/printingui/mac/nsPrintProgress.cpp
rename to toolkit/components/printingui/mac/nsPrintProgress.cpp
rename from embedding/components/printingui/mac/nsPrintProgress.h
rename to toolkit/components/printingui/mac/nsPrintProgress.h
rename from embedding/components/printingui/win/nsPrintProgressParams.cpp
rename to toolkit/components/printingui/mac/nsPrintProgressParams.cpp
rename from embedding/components/printingui/mac/nsPrintProgressParams.h
rename to toolkit/components/printingui/mac/nsPrintProgressParams.h
rename from embedding/components/printingui/mac/nsPrintingPromptService.h
rename to toolkit/components/printingui/mac/nsPrintingPromptService.h
rename from embedding/components/printingui/mac/nsPrintingPromptServiceX.mm
rename to toolkit/components/printingui/mac/nsPrintingPromptServiceX.mm
rename from embedding/components/printingui/moz.build
rename to toolkit/components/printingui/moz.build
rename from embedding/components/printingui/unixshared/moz.build
rename to toolkit/components/printingui/unixshared/moz.build
rename from embedding/components/printingui/unixshared/nsPrintProgress.cpp
rename to toolkit/components/printingui/unixshared/nsPrintProgress.cpp
rename from embedding/components/printingui/unixshared/nsPrintProgress.h
rename to toolkit/components/printingui/unixshared/nsPrintProgress.h
rename from embedding/components/printingui/unixshared/nsPrintProgressParams.cpp
rename to toolkit/components/printingui/unixshared/nsPrintProgressParams.cpp
rename from embedding/components/printingui/unixshared/nsPrintProgressParams.h
rename to toolkit/components/printingui/unixshared/nsPrintProgressParams.h
rename from embedding/components/printingui/unixshared/nsPrintingPromptService.cpp
rename to toolkit/components/printingui/unixshared/nsPrintingPromptService.cpp
rename from embedding/components/printingui/unixshared/nsPrintingPromptService.h
rename to toolkit/components/printingui/unixshared/nsPrintingPromptService.h
rename from embedding/components/printingui/win/moz.build
rename to toolkit/components/printingui/win/moz.build
rename from embedding/components/printingui/win/nsPrintDialogUtil.cpp
rename to toolkit/components/printingui/win/nsPrintDialogUtil.cpp
rename from embedding/components/printingui/win/nsPrintDialogUtil.h
rename to toolkit/components/printingui/win/nsPrintDialogUtil.h
rename from embedding/components/printingui/win/nsPrintProgress.cpp
rename to toolkit/components/printingui/win/nsPrintProgress.cpp
rename from embedding/components/printingui/win/nsPrintProgress.h
rename to toolkit/components/printingui/win/nsPrintProgress.h
rename from embedding/components/printingui/mac/nsPrintProgressParams.cpp
rename to toolkit/components/printingui/win/nsPrintProgressParams.cpp
rename from embedding/components/printingui/win/nsPrintProgressParams.h
rename to toolkit/components/printingui/win/nsPrintProgressParams.h
rename from embedding/components/printingui/win/nsPrintingPromptService.cpp
rename to toolkit/components/printingui/win/nsPrintingPromptService.cpp
rename from embedding/components/printingui/win/nsPrintingPromptService.h
rename to toolkit/components/printingui/win/nsPrintingPromptService.h
--- a/toolkit/components/url-classifier/nsUrlClassifierDBService.h
+++ b/toolkit/components/url-classifier/nsUrlClassifierDBService.h
@@ -20,16 +20,23 @@
 #include "nsICryptoHMAC.h"
 #include "mozilla/Attributes.h"
 #include "mozilla/Mutex.h"
 #include "mozilla/TimeStamp.h"
 
 #include "Entries.h"
 #include "LookupCache.h"
 
+// GCC < 6.1 workaround, see bug 1329593
+#if defined(XP_WIN) && defined(__MINGW32__)
+#define GCC_MANGLING_WORKAROUND __stdcall
+#else
+#define GCC_MANGLING_WORKAROUND
+#endif
+
 // The hash length for a domain key.
 #define DOMAIN_LENGTH 4
 
 // The hash length of a partial hash entry.
 #define PARTIAL_LENGTH 4
 
 // The hash length of a complete hash entry.
 #define COMPLETE_LENGTH 32
@@ -162,20 +169,20 @@ public:
 
   // Perform a blocking classifier lookup for a given url. Can be called on
   // either the main thread or the worker thread.
   nsresult DoLocalLookup(const nsACString& spec,
                          const nsACString& tables,
                          LookupResultArray* results);
 
   // Open the DB connection
-  nsresult OpenDb();
+  nsresult GCC_MANGLING_WORKAROUND OpenDb();
 
   // Provide a way to forcibly close the db connection.
-  nsresult CloseDb();
+  nsresult GCC_MANGLING_WORKAROUND CloseDb();
 
   nsresult CacheCompletions(CacheResultArray * aEntries);
   nsresult CacheMisses(PrefixArray * aEntries);
 
 private:
   // No subclassing
   ~nsUrlClassifierDBServiceWorker();
 
new file mode 100644
--- /dev/null
+++ b/toolkit/components/windowcreator/moz.build
@@ -0,0 +1,18 @@
+# -*- Mode: python; 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']
+
+if CONFIG['ENABLE_TESTS']:
+    XPCSHELL_TESTS_MANIFESTS += ['tests/unit/xpcshell.ini']
+
+XPIDL_SOURCES += [
+    'nsIWindowCreator.idl',
+    'nsIWindowCreator2.idl',
+    'nsIWindowProvider.idl',
+]
+
+XPIDL_MODULE = 'windowcreator'
rename from embedding/nsIWindowCreator.idl
rename to toolkit/components/windowcreator/nsIWindowCreator.idl
rename from embedding/nsIWindowCreator2.idl
rename to toolkit/components/windowcreator/nsIWindowCreator2.idl
rename from embedding/nsIWindowProvider.idl
rename to toolkit/components/windowcreator/nsIWindowProvider.idl
rename from embedding/test/320x240.ogv
rename to toolkit/components/windowcreator/test/320x240.ogv
rename from embedding/test/browser.ini
rename to toolkit/components/windowcreator/test/browser.ini
rename from embedding/test/browser_bug1204626.js
rename to toolkit/components/windowcreator/test/browser_bug1204626.js
--- a/embedding/test/browser_bug1204626.js
+++ b/toolkit/components/windowcreator/test/browser_bug1204626.js
@@ -1,35 +1,35 @@
 "use strict"; // -*- js-indent-level: 2; indent-tabs-mode: nil -*-
 var Cc = Components.classes;
 var Ci = Components.interfaces;
-const contentBase = "https://example.com/browser/embedding/test/";
-const chromeBase = "chrome://mochitests/content/browser/embedding/test/";
+const contentBase = "https://example.com/browser/toolkit/components/windowcreator/test/";
+const chromeBase = "chrome://mochitests/content/browser/toolkit/components/windowcreator/test/";
 const testPageURL = contentBase + "bug1204626_doc0.html";
 
 function one_test(delay, continuation) {
   let delayStr = delay === null ? "no delay" : "delay = " + delay + "ms";
   let browser;
 
   BrowserTestUtils.openNewForegroundTab(gBrowser, testPageURL).then((tab) => {
     browser = tab.linkedBrowser;
     let persistable = browser.QueryInterface(Ci.nsIFrameLoaderOwner)
                              .frameLoader
                              .QueryInterface(Ci.nsIWebBrowserPersistable);
     persistable.startPersistence(/* outer window ID: */ 0, {
       onDocumentReady,
-      onError: function(status) {
+      onError(status) {
         ok(false, new Components.Exception("startPersistence failed", status));
         continuation();
       }
     });
   });
 
   function onDocumentReady(doc) {
-    const nameStem="test_bug1204626_" + Date.now();
+    const nameStem = "test_bug1204626_" + Date.now();
     let wbp = Cc["@mozilla.org/embedding/browser/nsWebBrowserPersist;1"]
               .createInstance(Ci.nsIWebBrowserPersist);
     let tmp = Cc["@mozilla.org/file/directory_service;1"]
               .getService(Ci.nsIProperties)
               .get("TmpD", Ci.nsIFile);
     let tmpFile = tmp.clone();
     tmpFile.append(nameStem + "_saved.html");
     let tmpDir = tmp.clone();
@@ -40,21 +40,21 @@ function one_test(delay, continuation) {
         tmpFile.remove(/* recursive: */ false);
       }
       if (tmpDir.exists()) {
         tmpDir.remove(/* recursive: */ true);
       }
     });
 
     wbp.progressListener = {
-      onProgressChange: function(){},
-      onLocationChange: function(){},
-      onStatusChange: function(){},
-      onSecurityChange: function(){},
-      onStateChange: function wbp_stateChange(_wbp, _req, state, _status) {
+      onProgressChange() {},
+      onLocationChange() {},
+      onStatusChange() {},
+      onSecurityChange() {},
+      onStateChange(_wbp, _req, state, _status) {
         if ((state & Ci.nsIWebProgressListener.STATE_STOP) == 0) {
           return;
         }
         ok(true, "Finished save (" + delayStr + ") but might have crashed.");
         continuation();
       }
     }
 
rename from embedding/test/bug1170334_iframe.xml
rename to toolkit/components/windowcreator/test/bug1170334_iframe.xml
rename from embedding/test/bug1170334_style.css
rename to toolkit/components/windowcreator/test/bug1170334_style.css
rename from embedding/test/bug1204626_doc0.html
rename to toolkit/components/windowcreator/test/bug1204626_doc0.html
rename from embedding/test/bug1204626_doc1.html
rename to toolkit/components/windowcreator/test/bug1204626_doc1.html
rename from embedding/test/bug293834_form.html
rename to toolkit/components/windowcreator/test/bug293834_form.html
rename from embedding/test/bug449141_page.html
rename to toolkit/components/windowcreator/test/bug449141_page.html
rename from embedding/test/chrome.ini
rename to toolkit/components/windowcreator/test/chrome.ini
rename from embedding/test/mochitest.ini
rename to toolkit/components/windowcreator/test/mochitest.ini
rename from embedding/test/moz.build
rename to toolkit/components/windowcreator/test/moz.build
rename from embedding/test/test_bug1170334_wbp_xmlstyle.html
rename to toolkit/components/windowcreator/test/test_bug1170334_wbp_xmlstyle.html
rename from embedding/test/test_bug1192654.html
rename to toolkit/components/windowcreator/test/test_bug1192654.html
rename from embedding/test/test_bug293834.html
rename to toolkit/components/windowcreator/test/test_bug293834.html
--- a/embedding/test/test_bug293834.html
+++ b/toolkit/components/windowcreator/test/test_bug293834.html
@@ -22,37 +22,37 @@ https://bugzilla.mozilla.org/show_bug.cg
 <pre id="test">
 <script class="testbody" type="text/javascript">
 /** Test for Bug 293834 **/
 
 var textareas = ["a-textbox", "a-prefilled-textbox"];
 var textboxes = ["a-text", "a-prefilled-text"];
 
 function fillform(doc) {
-    for (var i in textareas) {
+    for (let i in textareas) {
         doc.getElementById(textareas[i]).textContent += "form state";
     }
-    for (var i in textboxes) {
+    for (let i in textboxes) {
         doc.getElementById(textboxes[i]).value += "form state";
     }
     doc.getElementById('a-checkbox').checked = true;
     doc.getElementById("radioa").checked = true;
     doc.getElementById("aselect").selectedIndex = 0;
 }
 
 function checkform(doc) {
-    for (var i in textareas) {
+    for (let i in textareas) {
         var textContent = doc.getElementById(textareas[i]).textContent;
         ok(/form\s+state/m.test(textContent),
-            "Modified textarea "+textareas[i]+" form state not preserved!");
+            "Modified textarea " + textareas[i] + " form state not preserved!");
     }
-    for (var i in textboxes) {
+    for (let i in textboxes) {
         var value = doc.getElementById(textboxes[i]).value;
         ok(/form\s+state/m.test(value),
-            "Modified textbox "+textboxes[i]+" form state not preserved!");
+            "Modified textbox " + textboxes[i] + " form state not preserved!");
     }
     ok(doc.getElementById('a-checkbox').checked,
         "Modified checkbox checked state not preserved!");
     ok(doc.getElementById("radioa").checked,
         "Modified radio checked state not preserved!");
     ok(doc.getElementById("aselect").selectedIndex == 0,
         "Modified select selected index not preserved");
 }
@@ -65,27 +65,27 @@ function getTempDir() {
             .getService(Ci.nsIProperties)
             .get("TmpD", Ci.nsILocalFile);
 }
 
 function getFileContents(aFile) {
     const PR_RDONLY = 0x01;
     var fileStream = Cc["@mozilla.org/network/file-input-stream;1"]
                         .createInstance(Ci.nsIFileInputStream);
-    fileStream.init(aFile, PR_RDONLY, 0400,
+    fileStream.init(aFile, PR_RDONLY, 0o400,
                     Ci.nsIFileInputStream.DELETE_ON_CLOSE
                   | Ci.nsIFileInputStream.CLOSE_ON_EOF);
     var inputStream = Cc["@mozilla.org/scriptableinputstream;1"]
                         .createInstance(Ci.nsIScriptableInputStream);
     inputStream.init(fileStream);
     var data = "";
     do {
         var str = inputStream.read(inputStream.available());
         data += str;
-    } while(str.length > 0);
+    } while (str.length > 0);
 
     return data;
 }
 
 function persistDocument(aDoc) {
     const nsIWBP = Ci.nsIWebBrowserPersist;
     const persistFlags =
                   nsIWBP.PERSIST_FLAGS_REPLACE_EXISTING_FILES
rename from embedding/test/test_bug449141.html
rename to toolkit/components/windowcreator/test/test_bug449141.html
--- a/embedding/test/test_bug449141.html
+++ b/toolkit/components/windowcreator/test/test_bug449141.html
@@ -29,35 +29,35 @@ function getTempDir() {
             .getService(Ci.nsIProperties)
             .get("TmpD", Ci.nsILocalFile);
 }
 
 // STATE_STOP from nsIWebProgressListener.idl
 const STATE_STOP = 0x00000010;
 
 var progressListener = {
-  onProgressChange: function() {
+  onProgressChange() {
     /* Ignore progress callback */
   },
-  onStateChange: function(aProgress, aRequest, aStateFlag, aStatus) {
+  onStateChange(aProgress, aRequest, aStateFlag, aStatus) {
     if (aStateFlag & STATE_STOP) {
       var dirExists = false;
       var videoExists = false;
 
       var videoFile = getTempDir();
       videoFile.append(this.dirName);
       dirExists = videoFile.exists();
       videoFile.append("320x240.ogv");
       videoExists = videoFile.exists();
       this.folder.remove(true);
       this.file.remove(false);
       ok(dirExists, 'Directory containing video file should be created');
       ok(videoExists, 'Video should be persisted with document');
       SimpleTest.finish();
-    }    
+    }
   }
 };
 
 function persistDocument(aDoc) {
     const nsIWBP = Ci.nsIWebBrowserPersist;
     const persistFlags =
                   nsIWBP.PERSIST_FLAGS_REPLACE_EXISTING_FILES
                 | nsIWBP.PERSIST_FLAGS_AUTODETECT_APPLY_CONVERSION
rename from embedding/test/test_bug499115.html
rename to toolkit/components/windowcreator/test/test_bug499115.html
--- a/embedding/test/test_bug499115.html
+++ b/toolkit/components/windowcreator/test/test_bug499115.html
@@ -18,17 +18,17 @@ https://bugzilla.mozilla.org/show_bug.cg
   <div id="content" style="display: none">
   </div>
   <pre id="test">
     <script type="application/javascript">
 
       /** Test for Bug 499115 **/
       SimpleTest.waitForExplicitFinish();
 
-      const SEARCH_TEXT="minefield";
+      const SEARCH_TEXT = "minefield";
 
       function getMatches() {
         var numMatches = 0;
 
         var searchRange = document.createRange();
         searchRange.selectNodeContents(document.body);
 
         var startPoint = searchRange.cloneRange();
rename from embedding/test/test_nsFind.html
rename to toolkit/components/windowcreator/test/test_nsFind.html
--- a/embedding/test/test_nsFind.html
+++ b/toolkit/components/windowcreator/test/test_nsFind.html
@@ -34,63 +34,63 @@ https://bugzilla.mozilla.org/show_bug.cg
   var endPt = searchRange;
 
   // Check |null| detection on |aPatText| parameter.
   try {
     rf.Find(null, searchRange, startPt, endPt);
 
     ok(false, "Missing NS_ERROR_NULL_POINTER exception");
   } catch (e) {
-    e = SpecialPowers.wrap(e);
-    if (e.result == SpecialPowers.Cr.NS_ERROR_NULL_POINTER) {
+    let wrappedError = SpecialPowers.wrap(e);
+    if (wrappedError.result == SpecialPowers.Cr.NS_ERROR_NULL_POINTER) {
       ok(true, null);
     } else {
-      throw e;
+      throw wrappedError;
     }
   }
 
   // Check |null| detection on |aSearchRange| parameter.
   try {
     rf.Find("", null, startPt, endPt);
 
     ok(false, "Missing NS_ERROR_ILLEGAL_VALUE exception");
   } catch (e) {
-    e = SpecialPowers.wrap(e);
-    if (e.result == SpecialPowers.Cr.NS_ERROR_ILLEGAL_VALUE) {
+    let wrappedError = SpecialPowers.wrap(e);
+    if (wrappedError.result == SpecialPowers.Cr.NS_ERROR_ILLEGAL_VALUE) {
       ok(true, null);
     } else {
-      throw e;
+      throw wrappedError;
     }
   }
 
   // Check |null| detection on |aStartPoint| parameter.
   try {
     rf.Find("", searchRange, null, endPt);
 
     ok(false, "Missing NS_ERROR_ILLEGAL_VALUE exception");
   } catch (e) {
-    e = SpecialPowers.wrap(e);
-    if (e.result == SpecialPowers.Cr.NS_ERROR_ILLEGAL_VALUE) {
+    let wrappedError = SpecialPowers.wrap(e);
+    if (wrappedError.result == SpecialPowers.Cr.NS_ERROR_ILLEGAL_VALUE) {
       ok(true, null);
     } else {
-      throw e;
+      throw wrappedError;
     }
   }
 
   // Check |null| detection on |aEndPoint| parameter.
   try {
     rf.Find("", searchRange, startPt, null);
 
     ok(false, "Missing NS_ERROR_ILLEGAL_VALUE exception");
   } catch (e) {
-    e = SpecialPowers.wrap(e);
-    if (e.result == SpecialPowers.Cr.NS_ERROR_ILLEGAL_VALUE) {
+    let wrappedError = SpecialPowers.wrap(e);
+    if (wrappedError.result == SpecialPowers.Cr.NS_ERROR_ILLEGAL_VALUE) {
       ok(true, null);
     } else {
-      throw e;
+      throw wrappedError;
     }
   }
 
   var searchValue, retRange;
 
   rf.findBackwards = false;
 
   rf.caseSensitive = false;
rename from embedding/test/test_private_window_from_content.html
rename to toolkit/components/windowcreator/test/test_private_window_from_content.html
rename from embedding/test/test_window_open_position_constraint.html
rename to toolkit/components/windowcreator/test/test_window_open_position_constraint.html
rename from embedding/test/test_window_open_units.html
rename to toolkit/components/windowcreator/test/test_window_open_units.html
--- a/embedding/test/test_window_open_units.html
+++ b/toolkit/components/windowcreator/test/test_window_open_units.html
@@ -12,17 +12,16 @@
 </div>
 <pre id="test">
 <script class="testbody" type="text/javascript">
 SimpleTest.waitForExplicitFinish();
 
 SimpleTest.waitForFocus(function() {
   SpecialPowers.setFullZoom(window, 2);
 
-  var p = window;
   var w = window.open("about:blank", "", "width=200,height=100");
   SimpleTest.waitForFocus(function() {
     ok(w.innerWidth <= 402 && w.innerWidth >= 398,
        "width (" + w.innerWidth + ") should be around twice what was requested (200)");
     ok(w.innerHeight <= 202 && w.innerHeight >= 198,
        "height (" + w.innerHeight + ") should be around twice what was requested (100)");
 
     SpecialPowers.setFullZoom(window, 1);
rename from embedding/tests/unit/test_wwauthpromptfactory.js
rename to toolkit/components/windowcreator/tests/unit/test_wwauthpromptfactory.js
rename from embedding/tests/unit/test_wwpromptfactory.js
rename to toolkit/components/windowcreator/tests/unit/test_wwpromptfactory.js
rename from embedding/tests/unit/xpcshell.ini
rename to toolkit/components/windowcreator/tests/unit/xpcshell.ini
rename from embedding/components/windowwatcher/moz.build
rename to toolkit/components/windowwatcher/moz.build
rename from embedding/components/windowwatcher/nsAutoWindowStateHelper.cpp
rename to toolkit/components/windowwatcher/nsAutoWindowStateHelper.cpp
rename from embedding/components/windowwatcher/nsAutoWindowStateHelper.h
rename to toolkit/components/windowwatcher/nsAutoWindowStateHelper.h
rename from embedding/components/windowwatcher/nsDialogParamBlock.cpp
rename to toolkit/components/windowwatcher/nsDialogParamBlock.cpp
rename from embedding/components/windowwatcher/nsDialogParamBlock.h
rename to toolkit/components/windowwatcher/nsDialogParamBlock.h
rename from embedding/components/windowwatcher/nsIDialogParamBlock.idl
rename to toolkit/components/windowwatcher/nsIDialogParamBlock.idl
rename from embedding/components/windowwatcher/nsIPromptFactory.idl
rename to toolkit/components/windowwatcher/nsIPromptFactory.idl
rename from embedding/components/windowwatcher/nsIPromptService.idl
rename to toolkit/components/windowwatcher/nsIPromptService.idl
rename from embedding/components/windowwatcher/nsIPromptService2.idl
rename to toolkit/components/windowwatcher/nsIPromptService2.idl
rename from embedding/components/windowwatcher/nsIWindowWatcher.idl
rename to toolkit/components/windowwatcher/nsIWindowWatcher.idl
rename from embedding/components/windowwatcher/nsPIPromptService.idl
rename to toolkit/components/windowwatcher/nsPIPromptService.idl
rename from embedding/components/windowwatcher/nsPIWindowWatcher.idl
rename to toolkit/components/windowwatcher/nsPIWindowWatcher.idl
rename from embedding/components/windowwatcher/nsPromptUtils.h
rename to toolkit/components/windowwatcher/nsPromptUtils.h
rename from embedding/components/windowwatcher/nsWindowWatcher.cpp
rename to toolkit/components/windowwatcher/nsWindowWatcher.cpp
rename from embedding/components/windowwatcher/nsWindowWatcher.h
rename to toolkit/components/windowwatcher/nsWindowWatcher.h
rename from embedding/components/windowwatcher/test/browser.ini
rename to toolkit/components/windowwatcher/test/browser.ini
rename from embedding/components/windowwatcher/test/browser_new_content_window_chromeflags.js
rename to toolkit/components/windowwatcher/test/browser_new_content_window_chromeflags.js
--- a/embedding/components/windowwatcher/test/browser_new_content_window_chromeflags.js
+++ b/toolkit/components/windowwatcher/test/browser_new_content_window_chromeflags.js
@@ -238,17 +238,17 @@ add_task(function* test_new_remote_windo
     let b = win.gBrowser.selectedBrowser;
     let contentChromeFlags = yield ContentTask.spawn(b, null, function*() {
       docShell.QueryInterface(Ci.nsIInterfaceRequestor);
       try {
         // This will throw if we're not a remote browser.
         return docShell.getInterface(Ci.nsITabChild)
                        .QueryInterface(Ci.nsIWebBrowserChrome)
                        .chromeFlags;
-      } catch(e) {
+      } catch (e) {
         // This must be a non-remote browser...
         return docShell.QueryInterface(Ci.nsIDocShellTreeItem)
                        .treeOwner
                        .QueryInterface(Ci.nsIWebBrowserChrome)
                        .chromeFlags;
       }
     });
 
rename from embedding/components/windowwatcher/test/browser_new_content_window_from_chrome_principal.js
rename to toolkit/components/windowwatcher/test/browser_new_content_window_from_chrome_principal.js
--- a/embedding/components/windowwatcher/test/browser_new_content_window_from_chrome_principal.js
+++ b/toolkit/components/windowwatcher/test/browser_new_content_window_from_chrome_principal.js
@@ -26,9 +26,9 @@ add_task(function* test_chrome_opens_win
     Assert.ok(!content.document.nodePrincipal.isSystemPrincipal,
               "We should not have a system principal.")
     Assert.equal(content.document.nodePrincipal.origin,
                  "http://example.com",
                  "Should have the example.com principal");
   });
 
   yield BrowserTestUtils.closeWindow(win);
-});
\ No newline at end of file
+});
rename from embedding/components/windowwatcher/test/browser_new_remote_window_flags.js
rename to toolkit/components/windowwatcher/test/browser_new_remote_window_flags.js
rename from embedding/components/windowwatcher/test/browser_new_sized_window.js
rename to toolkit/components/windowwatcher/test/browser_new_sized_window.js
rename from embedding/components/windowwatcher/test/chrome.ini
rename to toolkit/components/windowwatcher/test/chrome.ini
rename from embedding/components/windowwatcher/test/file_storage_copied.html
rename to toolkit/components/windowwatcher/test/file_storage_copied.html
rename from embedding/components/windowwatcher/test/file_test_dialog.html
rename to toolkit/components/windowwatcher/test/file_test_dialog.html
rename from embedding/components/windowwatcher/test/mochitest.ini
rename to toolkit/components/windowwatcher/test/mochitest.ini
rename from embedding/components/windowwatcher/test/moz.build
rename to toolkit/components/windowwatcher/test/moz.build
rename from embedding/components/windowwatcher/test/test_blank_named_window.html
rename to toolkit/components/windowwatcher/test/test_blank_named_window.html
rename from embedding/components/windowwatcher/test/test_dialog_arguments.html
rename to toolkit/components/windowwatcher/test/test_dialog_arguments.html
rename from embedding/components/windowwatcher/test/test_modal_windows.html
rename to toolkit/components/windowwatcher/test/test_modal_windows.html
rename from embedding/components/windowwatcher/test/test_named_window.html
rename to toolkit/components/windowwatcher/test/test_named_window.html
rename from embedding/components/windowwatcher/test/test_storage_copied.html
rename to toolkit/components/windowwatcher/test/test_storage_copied.html
--- a/toolkit/toolkit.mozbuild
+++ b/toolkit/toolkit.mozbuild
@@ -82,17 +82,16 @@ DIRS += [
     '/gfx',
     '/image',
     '/dom',
     '/view',
     '/widget',
     '/editor',
     '/layout',
     '/docshell',
-    '/embedding',
     '/xpfe/appshell'
 ]
 
 # This needs to be built after the gfx/ directory
 # to ensure all dependencies for skia (e.g. mozalloc, xpcom)
 # have been built
 if CONFIG['MOZ_WIDGET_TOOLKIT'] == 'android':
     DIRS += ['/other-licenses/skia-npapi']
--- a/toolkit/xre/moz.build
+++ b/toolkit/xre/moz.build
@@ -16,34 +16,45 @@ XPIDL_SOURCES += [
 
 if CONFIG['OS_ARCH'] == 'WINNT':
     XPIDL_SOURCES += [
         'nsIWinAppHelper.idl',
     ]
 
 XPIDL_MODULE = 'xulapp'
 
-EXPORTS += ['nsAppRunner.h']
+EXPORTS += [
+    'nsAppRunner.h',
+    'nsIAppStartupNotifier.h',
+]
 
 if CONFIG['MOZ_INSTRUMENT_EVENT_LOOP']:
     EXPORTS += ['EventTracer.h']
 
 if CONFIG['MOZ_WIDGET_TOOLKIT'] == 'windows':
     UNIFIED_SOURCES += [
         'nsNativeAppSupportWin.cpp',
     ]
+    DEFINES['PROXY_PRINTING'] = 1
+    LOCAL_INCLUDES += [
+        '../components/printingui/win',
+    ]
 elif CONFIG['MOZ_WIDGET_TOOLKIT'] == 'cocoa':
     UNIFIED_SOURCES += [
         'MacApplicationDelegate.mm',
         'MacAutoreleasePool.mm',
         'MacLaunchHelper.mm',
         'nsCommandLineServiceMac.cpp',
         'nsNativeAppSupportCocoa.mm',
         'updaterfileutils_osx.mm',
     ]
+    DEFINES['PROXY_PRINTING'] = 1
+    LOCAL_INCLUDES += [
+        '../components/printingui/mac',
+    ]
 elif CONFIG['MOZ_WIDGET_TOOLKIT'] == 'uikit':
     UNIFIED_SOURCES += [
         'nsNativeAppSupportDefault.cpp',
         'UIKitDirProvider.mm',
     ]
 elif 'gtk' in CONFIG['MOZ_WIDGET_TOOLKIT']:
     UNIFIED_SOURCES += [
         'nsNativeAppSupportUnix.cpp',
@@ -65,17 +76,19 @@ if CONFIG['MOZ_X11']:
 
 if CONFIG['MOZ_WIDGET_TOOLKIT'] == 'android':
     UNIFIED_SOURCES += [
         'nsAndroidStartup.cpp',
     ]
 
 UNIFIED_SOURCES += [
     'CreateAppData.cpp',
+    'nsAppStartupNotifier.cpp',
     'nsConsoleWriter.cpp',
+    'nsEmbeddingModule.cpp',
     'nsNativeAppSupportBase.cpp',
     'nsSigHandlers.cpp',
     'nsXREDirProvider.cpp',
 ]
 
 # nsAppRunner.cpp and ProfileReset.cpp cannot be built in unified mode because
 # they pull in OS X system headers.
 # nsEmbedFunctions.cpp cannot be built in unified mode because it pulls in X11 headers.
@@ -96,16 +109,22 @@ if CONFIG['MOZ_INSTRUMENT_EVENT_LOOP']:
     ]
 
 if CONFIG['MOZ_UPDATER']:
     if CONFIG['MOZ_WIDGET_TOOLKIT'] != 'android':
         UNIFIED_SOURCES += [
             'nsUpdateDriver.cpp',
         ]
 
+if CONFIG['MOZ_PDF_PRINTING']:
+    DEFINES['PROXY_PRINTING'] = 1
+    LOCAL_INCLUDES += [
+        '../components/printingui/unixshared',
+    ]
+
 include('/ipc/chromium/chromium-config.mozbuild')
 
 FINAL_LIBRARY = 'xul'
 
 if CONFIG['MOZ_GL_DEFAULT_PROVIDER'] == 'GLX':
     DEFINES['USE_GLX_TEST'] = True
 
 for var in ('MOZ_APP_NAME', 'MOZ_APP_BASENAME', 'MOZ_APP_VERSION', 'OS_TARGET',
@@ -134,20 +153,25 @@ DEFINES['GRE_MILESTONE'] = CONFIG['GRE_M
 
 for var in ('APP_VERSION', 'APP_ID'):
     DEFINES[var] = CONFIG['MOZ_%s' % var]
 
 if CONFIG['MOZ_BUILD_APP'] == 'browser':
     DEFINES['MOZ_BUILD_APP_IS_BROWSER'] = True
 
 LOCAL_INCLUDES += [
+    '../components/find',
+    '../components/printingui/ipc',
+    '../components/windowwatcher',
     '../profile',
     '/config',
     '/dom/base',
+    '/dom/commandhandler',
     '/dom/ipc',
+    '/dom/webbrowserpersist',
     '/testing/gtest/mozilla',
     '/toolkit/crashreporter',
     '/xpcom/build',
 ]
 
 if CONFIG['MOZ_SANDBOX'] and CONFIG['OS_ARCH'] == 'WINNT':
     LOCAL_INCLUDES += [
         '/security/sandbox/chromium',
rename from embedding/components/appstartup/nsAppStartupNotifier.cpp
rename to toolkit/xre/nsAppStartupNotifier.cpp
rename from embedding/components/appstartup/nsAppStartupNotifier.h
rename to toolkit/xre/nsAppStartupNotifier.h
rename from embedding/components/build/nsEmbeddingModule.cpp
rename to toolkit/xre/nsEmbeddingModule.cpp
rename from embedding/components/appstartup/nsIAppStartupNotifier.h
rename to toolkit/xre/nsIAppStartupNotifier.h
--- a/tools/profiler/core/GeckoSampler.cpp
+++ b/tools/profiler/core/GeckoSampler.cpp
@@ -985,31 +985,31 @@ void GeckoSampler::doNativeBacktrace(Thr
   // doesn't use the frame number argument.
   StackWalkCallback(/* frameNumber */ 0, aSample->pc, aSample->sp, &nativeStack);
 
   uint32_t maxFrames = uint32_t(nativeStack.size - nativeStack.count);
   // win X64 doesn't support disabling frame pointers emission so we need
   // to fallback to using StackWalk64 which is slower.
 #if defined(XP_MACOSX) || (defined(XP_WIN) && !defined(V8_HOST_ARCH_X64))
   void *stackEnd = aSample->threadProfile->GetStackTop();
-  bool rv = true;
-  if (aSample->fp >= aSample->sp && aSample->fp <= stackEnd)
-    rv = FramePointerStackWalk(StackWalkCallback, /* skipFrames */ 0,
-                               maxFrames, &nativeStack,
-                               reinterpret_cast<void**>(aSample->fp), stackEnd);
+  if (aSample->fp >= aSample->sp && aSample->fp <= stackEnd) {
+    FramePointerStackWalk(StackWalkCallback, /* skipFrames */ 0, maxFrames,
+                          &nativeStack, reinterpret_cast<void**>(aSample->fp),
+                          stackEnd);
+  }
 #else
   void *platformData = nullptr;
 
   uintptr_t thread = GetThreadHandle(aSample->threadProfile->GetPlatformData());
   MOZ_ASSERT(thread);
-  bool rv = MozStackWalk(StackWalkCallback, /* skipFrames */ 0, maxFrames,
-                             &nativeStack, thread, platformData);
+  MozStackWalk(StackWalkCallback, /* skipFrames */ 0, maxFrames, &nativeStack,
+               thread, platformData);
 #endif
-  if (rv)
-    mergeStacksIntoProfile(aProfile, aSample, nativeStack);
+
+  mergeStacksIntoProfile(aProfile, aSample, nativeStack);
 }
 #endif
 
 
 #ifdef USE_EHABI_STACKWALK
 void GeckoSampler::doNativeBacktrace(ThreadProfile &aProfile, TickSample* aSample)
 {
   void *pc_array[1000];