Merge inbound to mozilla-central. a=merge
authorBrindusan Cristian <cbrindusan@mozilla.com>
Tue, 18 Dec 2018 11:50:37 +0200
changeset 451088 d62e952be812fa33581a570769ddefbbec10ede5
parent 451087 b0002d2ea03f3a91a8fb3319b9eb03367919e398 (current diff)
parent 451078 3dce47a0184b26b38ba08a387ac6a931f6a81012 (diff)
child 451089 3b3152b561903a8f70e80e9b333aa3ce9f69229d
child 451142 54e8d7c8b51c04ae0350f18c6a0f3693b2b60e5f
push id110599
push usercbrindusan@mozilla.com
push dateTue, 18 Dec 2018 09:54:40 +0000
treeherdermozilla-inbound@3b3152b56190 [default view] [failures only]
perfherder[talos] [build metrics] [platform microbench] (compared to previous push)
reviewersmerge
milestone66.0a1
first release with
nightly linux32
d62e952be812 / 66.0a1 / 20181218095120 / files
nightly linux64
d62e952be812 / 66.0a1 / 20181218095120 / files
nightly mac
d62e952be812 / 66.0a1 / 20181218095120 / files
nightly win32
d62e952be812 / 66.0a1 / 20181218095120 / files
nightly win64
d62e952be812 / 66.0a1 / 20181218095120 / files
last release without
nightly linux32
nightly linux64
nightly mac
nightly win32
nightly win64
releases
nightly linux32
nightly linux64
nightly mac
nightly win32
nightly win64
Merge inbound to mozilla-central. a=merge
build/autoconf/lto.m4
build/macosx/build-cctools.sh
testing/web-platform/meta/css/css-grid/alignment/grid-alignment-style-changes-005.html.ini
testing/web-platform/meta/css/css-grid/alignment/grid-alignment-style-changes-006.html.ini
testing/web-platform/meta/css/css-grid/alignment/grid-alignment-style-changes-007.html.ini
testing/web-platform/meta/css/css-grid/alignment/grid-alignment-style-changes-008.html.ini
toolkit/components/extensions/extension-process-script.js
--- a/aclocal.m4
+++ b/aclocal.m4
@@ -11,17 +11,16 @@ builtin(include, build/autoconf/toolchai
 builtin(include, build/autoconf/nspr.m4)dnl
 builtin(include, build/autoconf/nspr-build.m4)dnl
 builtin(include, build/autoconf/nss.m4)dnl
 builtin(include, build/autoconf/pkg.m4)dnl
 builtin(include, build/autoconf/codeset.m4)dnl
 builtin(include, build/autoconf/altoptions.m4)dnl
 builtin(include, build/autoconf/mozprog.m4)dnl
 builtin(include, build/autoconf/mozheader.m4)dnl
-builtin(include, build/autoconf/lto.m4)dnl
 builtin(include, build/autoconf/frameptr.m4)dnl
 builtin(include, build/autoconf/compiler-opts.m4)dnl
 builtin(include, build/autoconf/expandlibs.m4)dnl
 builtin(include, build/autoconf/arch.m4)dnl
 builtin(include, build/autoconf/android.m4)dnl
 builtin(include, build/autoconf/zlib.m4)dnl
 builtin(include, build/autoconf/icu.m4)dnl
 builtin(include, build/autoconf/clang-plugin.m4)dnl
--- a/browser/base/content/test/performance/browser_startup_content.js
+++ b/browser/base/content/test/performance/browser_startup_content.js
@@ -15,17 +15,16 @@
 "use strict";
 
 /* Set this to true only for debugging purpose; it makes the output noisy. */
 const kDumpAllStacks = false;
 
 const whitelist = {
   components: new Set([
     "ContentProcessSingleton.js",
-    "extension-process-script.js",
   ]),
   modules: new Set([
     "chrome://mochikit/content/ShutdownLeaksCollector.jsm",
     "resource://specialpowers/specialpowers.js",
     "resource://specialpowers/specialpowersAPI.js",
 
     // General utilities
     "resource://gre/modules/AppConstants.jsm",
@@ -63,16 +62,17 @@ const whitelist = {
     // Pocket
     "chrome://pocket/content/AboutPocket.jsm",
 
     // Telemetry
     "resource://gre/modules/TelemetryController.jsm", // bug 1470339
     "resource://gre/modules/TelemetryUtils.jsm", // bug 1470339
 
     // Extensions
+    "resource://gre/modules/ExtensionProcessScript.jsm",
     "resource://gre/modules/ExtensionUtils.jsm",
     "resource://gre/modules/MessageChannel.jsm",
   ]),
 };
 
 // Items on this list are allowed to be loaded but not
 // required, as opposed to items in the main whitelist,
 // which are all required.
--- a/browser/components/payments/res/containers/address-form.js
+++ b/browser/components/payments/res/containers/address-form.js
@@ -302,22 +302,17 @@ export default class AddressForm extends
   updateRequiredState() {
     for (let field of this.form.elements) {
       let container = field.closest(`#${field.id}-container`);
       if (field.localName == "button" || !container) {
         continue;
       }
       let span = container.querySelector(".label-text");
       span.setAttribute("fieldRequiredSymbol", this.dataset.fieldRequiredSymbol);
-      let required = field.required && !field.disabled;
-      if (required) {
-        container.setAttribute("required", "true");
-      } else {
-        container.removeAttribute("required");
-      }
+      container.toggleAttribute("required", field.required && !field.disabled);
     }
   }
 
   updateSaveButtonState() {
     this.saveButton.disabled = !this.form.checkValidity();
   }
 
   async saveRecord() {
--- a/browser/components/payments/res/containers/basic-card-form.js
+++ b/browser/components/payments/res/containers/basic-card-form.js
@@ -416,22 +416,17 @@ export default class BasicCardForm exten
     for (let field of this.form.elements) {
       let container = field.closest(".container");
       let span = container.querySelector(".label-text");
       if (!span) {
         // The billing address field doesn't use a label inside the field.
         continue;
       }
       span.setAttribute("fieldRequiredSymbol", this.dataset.fieldRequiredSymbol);
-      let required = field.required && !field.disabled;
-      if (required) {
-        container.setAttribute("required", "true");
-      } else {
-        container.removeAttribute("required");
-      }
+      container.toggleAttribute("required", field.required && !field.disabled);
     }
   }
 
   async saveRecord() {
     let record = this.formHandler.buildFormObject();
     let currentState = this.requestStore.getState();
     let {
       tempBasicCards,
--- a/browser/components/payments/res/containers/payment-dialog.js
+++ b/browser/components/payments/res/containers/payment-dialog.js
@@ -506,19 +506,15 @@ export default class PaymentDialog exten
     }
 
     this._renderPayButton(state);
 
     for (let page of this._mainContainer.querySelectorAll(":scope > .page")) {
       page.hidden = state.page.id != page.id;
     }
 
-    if (state.changesPrevented) {
-      this.setAttribute("changes-prevented", "");
-    } else {
-      this.removeAttribute("changes-prevented");
-    }
+    this.toggleAttribute("changes-prevented", state.changesPrevented);
     this.setAttribute("complete-status", request.completeStatus);
     this._disabledOverlay.hidden = !state.changesPrevented;
   }
 }
 
 customElements.define("payment-dialog", PaymentDialog);
--- a/browser/extensions/pdfjs/README.mozilla
+++ b/browser/extensions/pdfjs/README.mozilla
@@ -1,5 +1,5 @@
 This is the PDF.js project output, https://github.com/mozilla/pdf.js
 
-Current extension version is: 2.1.97
+Current extension version is: 2.1.117
 
-Taken from upstream commit: 45c01974
+Taken from upstream commit: 417c234c
--- a/browser/extensions/pdfjs/content/build/pdf.js
+++ b/browser/extensions/pdfjs/content/build/pdf.js
@@ -118,18 +118,18 @@ return /******/ (function(modules) { // 
 /************************************************************************/
 /******/ ([
 /* 0 */
 /***/ (function(module, exports, __w_pdfjs_require__) {
 
 "use strict";
 
 
-var pdfjsVersion = '2.1.97';
-var pdfjsBuild = '45c01974';
+var pdfjsVersion = '2.1.117';
+var pdfjsBuild = '417c234c';
 
 var pdfjsSharedUtil = __w_pdfjs_require__(1);
 
 var pdfjsDisplayAPI = __w_pdfjs_require__(7);
 
 var pdfjsDisplayTextLayer = __w_pdfjs_require__(19);
 
 var pdfjsDisplayAnnotationLayer = __w_pdfjs_require__(20);
@@ -5136,17 +5136,17 @@ function _fetchDocument(worker, source, 
 
   if (pdfDataRangeTransport) {
     source.length = pdfDataRangeTransport.length;
     source.initialData = pdfDataRangeTransport.initialData;
   }
 
   return worker.messageHandler.sendWithPromise('GetDocRequest', {
     docId,
-    apiVersion: '2.1.97',
+    apiVersion: '2.1.117',
     source: {
       data: source.data,
       url: source.url,
       password: source.password,
       disableAutoFetch: source.disableAutoFetch,
       rangeChunkSize: source.rangeChunkSize,
       length: source.length
     },
@@ -6855,19 +6855,19 @@ const InternalRenderTask = function Inte
       }
     }
 
   }
 
   return InternalRenderTask;
 }();
 
-const version = '2.1.97';
+const version = '2.1.117';
 exports.version = version;
-const build = '45c01974';
+const build = '417c234c';
 exports.build = build;
 
 /***/ }),
 /* 8 */
 /***/ (function(module, exports, __w_pdfjs_require__) {
 
 "use strict";
 
--- a/browser/extensions/pdfjs/content/build/pdf.worker.js
+++ b/browser/extensions/pdfjs/content/build/pdf.worker.js
@@ -118,18 +118,18 @@ return /******/ (function(modules) { // 
 /************************************************************************/
 /******/ ([
 /* 0 */
 /***/ (function(module, exports, __w_pdfjs_require__) {
 
 "use strict";
 
 
-var pdfjsVersion = '2.1.97';
-var pdfjsBuild = '45c01974';
+var pdfjsVersion = '2.1.117';
+var pdfjsBuild = '417c234c';
 
 var pdfjsCoreWorker = __w_pdfjs_require__(1);
 
 exports.WorkerMessageHandler = pdfjsCoreWorker.WorkerMessageHandler;
 
 /***/ }),
 /* 1 */
 /***/ (function(module, exports, __w_pdfjs_require__) {
@@ -370,17 +370,17 @@ var WorkerMessageHandler = {
   },
 
   createDocumentHandler(docParams, port) {
     var pdfManager;
     var terminated = false;
     var cancelXHRs = null;
     var WorkerTasks = [];
     let apiVersion = docParams.apiVersion;
-    let workerVersion = '2.1.97';
+    let workerVersion = '2.1.117';
 
     if (apiVersion !== workerVersion) {
       throw new Error(`The API version "${apiVersion}" does not match ` + `the Worker version "${workerVersion}".`);
     }
 
     var docId = docParams.docId;
     var docBaseUrl = docParams.docBaseUrl;
     var workerHandlerName = docParams.docId + '_worker';
@@ -22040,16 +22040,17 @@ class WidgetAnnotation extends Annotatio
 
     if (!Number.isInteger(data.fieldFlags) || data.fieldFlags < 0) {
       data.fieldFlags = 0;
     }
 
     data.readOnly = this.hasFieldFlag(_util.AnnotationFieldFlag.READONLY);
 
     if (data.fieldType === 'Sig') {
+      data.fieldValue = null;
       this.setFlags(_util.AnnotationFlag.HIDDEN);
     }
   }
 
   _constructFieldName(dict) {
     if (!dict.has('T') && !dict.has('Parent')) {
       (0, _util.warn)('Unknown field name, falling back to empty field name.');
       return '';
--- a/browser/extensions/pdfjs/content/web/viewer.css
+++ b/browser/extensions/pdfjs/content/web/viewer.css
@@ -1925,17 +1925,17 @@ html[dir='rtl'] #documentPropertiesOverl
 @page {
   margin: 0;
 }
 
 #printContainer {
   display: none;
 }
 
-@media screen and (min-resolution: 2dppx) {
+@media screen and (min-resolution: 1.1dppx) {
   /* Rules for Retina screens */
   .toolbarButton::before {
     transform: scale(0.5);
     top: -5px;
   }
 
   .secondaryToolbarButton::before {
     transform: scale(0.5);
--- a/browser/extensions/pdfjs/content/web/viewer.js
+++ b/browser/extensions/pdfjs/content/web/viewer.js
@@ -318,16 +318,17 @@ var _secondary_toolbar = __webpack_requi
 
 var _toolbar = __webpack_require__(31);
 
 var _view_history = __webpack_require__(32);
 
 const DEFAULT_SCALE_DELTA = 1.1;
 const DISABLE_AUTO_FETCH_LOADING_BAR_TIMEOUT = 5000;
 const FORCE_PAGES_LOADED_TIMEOUT = 10000;
+const WHEEL_ZOOM_DISABLED_TIMEOUT = 1000;
 const DefaultExternalServices = {
   updateFindControlState(data) {},
 
   updateFindMatchesCount(data) {},
 
   initPassiveLoading(callbacks) {},
 
   fallback(data, callback) {},
@@ -1418,16 +1419,17 @@ let PDFViewerApplication = {
     };
 
     _boundEvents.windowAfterPrint = () => {
       eventBus.dispatch('afterprint', {
         source: window
       });
     };
 
+    window.addEventListener('visibilitychange', webViewerVisibilityChange);
     window.addEventListener('wheel', webViewerWheel);
     window.addEventListener('click', webViewerClick);
     window.addEventListener('keydown', webViewerKeyDown);
     window.addEventListener('resize', _boundEvents.windowResize);
     window.addEventListener('hashchange', _boundEvents.windowHashChange);
     window.addEventListener('beforeprint', _boundEvents.windowBeforePrint);
     window.addEventListener('afterprint', _boundEvents.windowAfterPrint);
   },
@@ -1477,16 +1479,17 @@ let PDFViewerApplication = {
     _boundEvents.beforePrint = null;
     _boundEvents.afterPrint = null;
   },
 
   unbindWindowEvents() {
     let {
       _boundEvents
     } = this;
+    window.removeEventListener('visibilitychange', webViewerVisibilityChange);
     window.removeEventListener('wheel', webViewerWheel);
     window.removeEventListener('click', webViewerClick);
     window.removeEventListener('keydown', webViewerKeyDown);
     window.removeEventListener('resize', _boundEvents.windowResize);
     window.removeEventListener('hashchange', _boundEvents.windowHashChange);
     window.removeEventListener('beforeprint', _boundEvents.windowBeforePrint);
     window.removeEventListener('afterprint', _boundEvents.windowAfterPrint);
     _boundEvents.windowResize = null;
@@ -1912,18 +1915,33 @@ function webViewerPageChanging(evt) {
     let pageView = PDFViewerApplication.pdfViewer.getPageView(page - 1);
 
     if (pageView && pageView.stats) {
       Stats.add(page, pageView.stats);
     }
   }
 }
 
-let zoomDisabled = false,
-    zoomDisabledTimeout;
+function webViewerVisibilityChange(evt) {
+  if (document.visibilityState === 'visible') {
+    setZoomDisabledTimeout();
+  }
+}
+
+let zoomDisabledTimeout = null;
+
+function setZoomDisabledTimeout() {
+  if (zoomDisabledTimeout) {
+    clearTimeout(zoomDisabledTimeout);
+  }
+
+  zoomDisabledTimeout = setTimeout(function () {
+    zoomDisabledTimeout = null;
+  }, WHEEL_ZOOM_DISABLED_TIMEOUT);
+}
 
 function webViewerWheel(evt) {
   let pdfViewer = PDFViewerApplication.pdfViewer;
 
   if (pdfViewer.isInPresentationMode) {
     return;
   }
 
@@ -1931,17 +1949,17 @@ function webViewerWheel(evt) {
     let support = PDFViewerApplication.supportedMouseWheelZoomModifierKeys;
 
     if (evt.ctrlKey && !support.ctrlKey || evt.metaKey && !support.metaKey) {
       return;
     }
 
     evt.preventDefault();
 
-    if (zoomDisabled) {
+    if (zoomDisabledTimeout || document.visibilityState === 'hidden') {
       return;
     }
 
     let previousScale = pdfViewer.currentScale;
     let delta = (0, _ui_utils.normalizeWheelEventDelta)(evt);
     const MOUSE_WHEEL_DELTA_PER_PAGE_SCALE = 3.0;
     let ticks = delta * MOUSE_WHEEL_DELTA_PER_PAGE_SCALE;
 
@@ -1957,21 +1975,17 @@ function webViewerWheel(evt) {
       let scaleCorrectionFactor = currentScale / previousScale - 1;
       let rect = pdfViewer.container.getBoundingClientRect();
       let dx = evt.clientX - rect.left;
       let dy = evt.clientY - rect.top;
       pdfViewer.container.scrollLeft += dx * scaleCorrectionFactor;
       pdfViewer.container.scrollTop += dy * scaleCorrectionFactor;
     }
   } else {
-    zoomDisabled = true;
-    clearTimeout(zoomDisabledTimeout);
-    zoomDisabledTimeout = setTimeout(function () {
-      zoomDisabled = false;
-    }, 1000);
+    setZoomDisabledTimeout();
   }
 }
 
 function webViewerClick(evt) {
   if (!PDFViewerApplication.secondaryToolbar.isOpen) {
     return;
   }
 
@@ -2204,16 +2218,20 @@ function webViewerKeyDown(evt) {
 
       case 72:
         PDFViewerApplication.pdfCursorTools.switchTool(_pdf_cursor_tools.CursorTool.HAND);
         break;
 
       case 82:
         PDFViewerApplication.rotatePages(90);
         break;
+
+      case 115:
+        PDFViewerApplication.pdfSidebar.toggle();
+        break;
     }
 
     if (turnPage !== 0 && (!turnOnlyIfPageFit || pdfViewer.currentScaleValue === 'page-fit')) {
       if (turnPage > 0) {
         if (PDFViewerApplication.page < PDFViewerApplication.pagesCount) {
           PDFViewerApplication.page++;
         }
       } else {
--- a/browser/extensions/pdfjs/moz.yaml
+++ b/browser/extensions/pdfjs/moz.yaml
@@ -15,15 +15,15 @@ origin:
   description: Portable Document Format (PDF) viewer that is built with HTML5
 
   # Full URL for the package's homepage/etc
   # Usually different from repository url
   url: https://github.com/mozilla/pdf.js
 
   # Human-readable identifier for this version/release
   # Generally "version NNN", "tag SSS", "bookmark SSS"
-  release: version 2.1.97
+  release: version 2.1.117
 
   # The package's license, where possible using the mnemonic from
   # https://spdx.org/licenses/
   # Multiple licenses can be specified (as a YAML list)
   # A "LICENSE" file must exist containing the full license text
   license: Apache-2.0
--- a/browser/installer/package-manifest.in
+++ b/browser/installer/package-manifest.in
@@ -354,17 +354,16 @@
 @RESPATH@/browser/components/startupRecorder.js
 #endif
 
 @RESPATH@/components/mozDOMLocalization.js
 @RESPATH@/components/mozDOMLocalization.manifest
 
 ; [Extensions]
 @RESPATH@/components/extensions-toolkit.manifest
-@RESPATH@/components/extension-process-script.js
 @RESPATH@/browser/components/extensions-browser.manifest
 
 ; [Normandy]
 @RESPATH@/components/shield.manifest
 @RESPATH@/components/shield-content-process.js
 
 ; [PDF Viewer]
 @RESPATH@/browser/components/pdfjs.manifest
--- a/browser/installer/windows/nsis/installer.nsi
+++ b/browser/installer/windows/nsis/installer.nsi
@@ -1547,16 +1547,17 @@ Function .onInit
   ${If} "$R7" == "0"
     MessageBox MB_OKCANCEL|MB_ICONSTOP "$(WARN_MIN_SUPPORTED_CPU_MSG)" IDCANCEL +2
     ExecShell "open" "${URLSystemRequirements}"
     Quit
   ${EndIf}
 
 !ifdef HAVE_64BIT_BUILD
   ${Unless} ${RunningX64}
+  ${AndUnless} ${IsNativeARM64}
     MessageBox MB_OKCANCEL|MB_ICONSTOP "$(WARN_MIN_SUPPORTED_OSVER_MSG)" IDCANCEL +2
     ExecShell "open" "${URLSystemRequirements}"
     Quit
   ${EndUnless}
   SetRegView 64
 !endif
 
   SetShellVarContext all
--- a/browser/installer/windows/nsis/maintenanceservice_installer.nsi
+++ b/browser/installer/windows/nsis/maintenanceservice_installer.nsi
@@ -176,16 +176,17 @@ Section "MaintenanceService"
     ExecWait '"$INSTDIR\$TempMaintServiceName" upgrade'
   ${EndIf}
 
   WriteUninstaller "$INSTDIR\Uninstall.exe"
 
   ; Since the Maintenance service can be installed either x86 or x64,
   ; always use the 64-bit registry.
   ${If} ${RunningX64}
+  ${OrIf} ${IsNativeARM64}
     ; Previous versions always created the uninstall key in the 32-bit registry.
     ; Clean those old entries out if they still exist.
     SetRegView 32
     DeleteRegKey HKLM "${MaintUninstallKey}"
     ; Preserve the lastused value before we switch to 64.
     SetRegView lastused
 
     SetRegView 64
@@ -213,16 +214,17 @@ Section "MaintenanceService"
   DeleteRegValue HKLM "Software\Mozilla\MaintenanceService" "FFPrefetchDisabled"
 
   ; Included here for debug purposes only.  
   ; These keys are used to bypass the installation dir is a valid installation
   ; check from the service so that tests can be run.
   ; WriteRegStr HKLM "${FallbackKey}\0" "name" "Mozilla Corporation"
   ; WriteRegStr HKLM "${FallbackKey}\0" "issuer" "DigiCert SHA2 Assured ID Code Signing CA"
   ${If} ${RunningX64}
+  ${OrIf} ${IsNativeARM64}
     SetRegView lastused
   ${EndIf}
 SectionEnd
 
 ; By renaming before deleting we improve things slightly in case
 ; there is a file in use error. In this case a new install can happen.
 Function un.RenameDelete
   Pop $9
@@ -313,18 +315,20 @@ Section "Uninstall"
   Call un.RenameDelete
   RMDir /REBOOTOK "$APPDATA\Mozilla\logs"
   RMDir /REBOOTOK "$APPDATA\Mozilla"
   RMDir /REBOOTOK "$INSTDIR\logs"
   RMDir /REBOOTOK "$INSTDIR\update"
   RMDir /REBOOTOK "$INSTDIR"
 
   ${If} ${RunningX64}
+  ${OrIf} ${IsNativeARM64}
     SetRegView 64
   ${EndIf}
   DeleteRegKey HKLM "${MaintUninstallKey}"
   DeleteRegValue HKLM "Software\Mozilla\MaintenanceService" "Installed"
   DeleteRegValue HKLM "Software\Mozilla\MaintenanceService" "FFPrefetchDisabled"
   DeleteRegKey HKLM "${FallbackKey}\"
   ${If} ${RunningX64}
+  ${OrIf} ${IsNativeARM64}
     SetRegView lastused
   ${EndIf}
 SectionEnd
--- a/browser/installer/windows/nsis/shared.nsh
+++ b/browser/installer/windows/nsis/shared.nsh
@@ -123,21 +123,23 @@
   Pop $R0
   ${If} $R0 == "true"
   ; Only proceed if we have HKLM write access
   ${AndIf} $TmpVal == "HKLM"
     ; We check to see if the maintenance service install was already attempted.
     ; Since the Maintenance service can be installed either x86 or x64,
     ; always use the 64-bit registry for checking if an attempt was made.
     ${If} ${RunningX64}
+    ${OrIf} ${IsNativeARM64}
       SetRegView 64
     ${EndIf}
     ReadRegDWORD $5 HKLM "Software\Mozilla\MaintenanceService" "Attempted"
     ClearErrors
     ${If} ${RunningX64}
+    ${OrIf} ${IsNativeARM64}
       SetRegView lastused
     ${EndIf}
 
     ; Add the registry keys for allowed certificates.
     ${AddMaintCertKeys}
 
     ; If the maintenance service is already installed, do nothing.
     ; The maintenance service will launch:
@@ -585,16 +587,17 @@
   ${AndIf} $2 != 1
     WriteRegDWORD HKCU "Software\Mozilla\${AppName}\32to64DidMigrate" "$1" 1
   ${EndIf}
 
 !else
 
   ; Running Firefox 32 bit
   ${If} ${RunningX64}
+  ${OrIf} ${IsNativeARM64}
     ; Running Firefox 32 bit on a Windows 64 bit system
     ClearErrors
     ReadRegDWORD $2 HKLM "Software\Mozilla\${AppName}\32to64DidMigrate" "$1"
     ; If there were errors the value doesn't exist yet.
     ${If} ${Errors}
       ClearErrors
       WriteRegDWORD HKLM "Software\Mozilla\${AppName}\32to64DidMigrate" "$1" 0
       ; If there were errors write the value in HKCU.
@@ -898,16 +901,17 @@
   Pop $R0
   ${If} $R0 != ""
     ; More than one certificate can be specified in a different subfolder
     ; for example: $R0\1, but each individual binary can be signed
     ; with at most one certificate.  A fallback certificate can only be used
     ; if the binary is replaced with a different certificate.
     ; We always use the 64bit registry for certs.
     ${If} ${RunningX64}
+    ${OrIf} ${IsNativeARM64}
       SetRegView 64
     ${EndIf}
 
     ; PrefetchProcessName was originally used to experiment with deleting
     ; Windows prefetch as a speed optimization.  It is no longer used though.
     DeleteRegValue HKLM "$R0" "prefetchProcessName"
 
     ; Setting the Attempted value will ensure that a new Maintenance Service
@@ -920,16 +924,17 @@
     WriteRegStr HKLM "$R0\0" "name" "${CERTIFICATE_NAME}"
     WriteRegStr HKLM "$R0\0" "issuer" "${CERTIFICATE_ISSUER}"
     ; These values associate the allowed certificates for the previous
     ;  installation, so that we can update from it cleanly using the
     ;  old updater.exe (which will still have this signature).
     WriteRegStr HKLM "$R0\1" "name" "${CERTIFICATE_NAME_PREVIOUS}"
     WriteRegStr HKLM "$R0\1" "issuer" "${CERTIFICATE_ISSUER_PREVIOUS}"
     ${If} ${RunningX64}
+    ${OrIf} ${IsNativeARM64}
       SetRegView lastused
     ${EndIf}
     ClearErrors
   ${EndIf}
   ; Restore the previously used value back
   Pop $R0
 !macroend
 !define AddMaintCertKeys "!insertmacro AddMaintCertKeys"
--- a/browser/installer/windows/nsis/uninstaller.nsi
+++ b/browser/installer/windows/nsis/uninstaller.nsi
@@ -189,46 +189,50 @@ Function un.UninstallServiceIfNotUsed
   ; $0 will store if a subkey exists
   ; $1 will store the first subkey if it exists or an empty string if it doesn't
   ; Backup the old values
   Push $0
   Push $1
 
   ; The maintenance service always uses the 64-bit registry on x64 systems
   ${If} ${RunningX64}
+  ${OrIf} ${IsNativeARM64}
     SetRegView 64
   ${EndIf}
 
   ; Figure out the number of subkeys
   StrCpy $0 0
   ${Do}
     EnumRegKey $1 HKLM "Software\Mozilla\MaintenanceService" $0
     ${If} "$1" == ""
       ${ExitDo}
     ${EndIf}
     IntOp $0 $0 + 1
   ${Loop}
 
   ; Restore back the registry view
   ${If} ${RunningX64}
+  ${OrIf} ${IsNativeARM64}
     SetRegView lastUsed
   ${EndIf}
 
   ${If} $0 == 0
     ; Get the path of the maintenance service uninstaller.
     ; Look in both the 32-bit and 64-bit registry views.
     SetRegView 32
     ReadRegStr $1 HKLM ${MaintUninstallKey} "UninstallString"
     SetRegView lastused
 
-    ${If} $1 == ""
-    ${AndIf} ${RunningX64}
-      SetRegView 64
-      ReadRegStr $1 HKLM ${MaintUninstallKey} "UninstallString"
-      SetRegView lastused
+    ${If} ${RunningX64}
+    ${OrIf} ${IsNativeARM64}
+      ${If} $1 == ""
+        SetRegView 64
+        ReadRegStr $1 HKLM ${MaintUninstallKey} "UninstallString"
+        SetRegView lastused
+      ${EndIf}
     ${EndIf}
 
     ; If the uninstall string does not exist, skip executing it
     ${If} $1 != ""
       ; $1 is already a quoted string pointing to the install path
       ; so we're already protected against paths with spaces
       nsExec::Exec "$1 /S"
     ${EndIf}
@@ -470,20 +474,22 @@ Section "Uninstall"
 !ifdef MOZ_MAINTENANCE_SERVICE
   ; Get the path the allowed cert is at and remove it
   ; Keep this block of code last since it modfies the reg view
   ServicesHelper::PathToUniqueRegistryPath "$INSTDIR"
   Pop $MaintCertKey
   ${If} $MaintCertKey != ""
     ; Always use the 64bit registry for certs on 64bit systems.
     ${If} ${RunningX64}
+    ${OrIf} ${IsNativeARM64}
       SetRegView 64
     ${EndIf}
     DeleteRegKey HKLM "$MaintCertKey"
     ${If} ${RunningX64}
+    ${OrIf} ${IsNativeARM64}
       SetRegView lastused
     ${EndIf}
   ${EndIf}
   Call un.UninstallServiceIfNotUsed
 !endif
 
   ${un.IsFirewallSvcRunning}
   Pop $0
deleted file mode 100644
--- a/build/autoconf/lto.m4
+++ /dev/null
@@ -1,19 +0,0 @@
-dnl This Source Code Form is subject to the terms of the Mozilla Public
-dnl License, v. 2.0. If a copy of the MPL was not distributed with this
-dnl file, You can obtain one at http://mozilla.org/MPL/2.0/.
-
-dnl check if the build is using lto. This is really primitive and only detects llvm based
-dnl compilers right now.
-AC_DEFUN([MOZ_DOING_LTO],
-[
-  cat > conftest.c <<EOF
-                  int foo = 1;
-EOF
-  $1=no
-  if ${CC-cc} ${CFLAGS} -S conftest.c -o conftest.s >/dev/null 2>&1; then
-    if grep '^target triple =' conftest.s; then
-      $1=yes
-    fi
-  fi
-  rm -f conftest.[cs]
-])
--- a/build/build-clang/build-clang.py
+++ b/build/build-clang/build-clang.py
@@ -242,17 +242,17 @@ def build_one_stage(cc, cxx, asm, ld, ar
                 "-DCMAKE_FIND_ROOT_PATH=%s" % slashify_path(os.getenv("CROSS_CCTOOLS_PATH")), # noqa
                 "-DCMAKE_FIND_ROOT_PATH_MODE_PROGRAM=NEVER",
                 "-DCMAKE_FIND_ROOT_PATH_MODE_LIBRARY=ONLY",
                 "-DCMAKE_FIND_ROOT_PATH_MODE_INCLUDE=ONLY",
                 "-DCMAKE_MACOSX_RPATH=ON",
                 "-DCMAKE_OSX_ARCHITECTURES=x86_64",
                 "-DDARWIN_osx_ARCHS=x86_64",
                 "-DDARWIN_osx_SYSROOT=%s" % slashify_path(os.getenv("CROSS_SYSROOT")),
-                "-DLLVM_DEFAULT_TARGET_TRIPLE=x86_64-apple-darwin11"
+                "-DLLVM_DEFAULT_TARGET_TRIPLE=x86_64-darwin11"
             ]
         return cmake_args
 
     cmake_args = []
 
     if is_final_stage and android_targets:
         cmake_args += [
             "-DCOMPILER_RT_DEFAULT_TARGET_TRIPLE=%s" % android_targets.keys()[0],
@@ -699,17 +699,17 @@ if __name__ == "__main__":
 
     if osx_cross_compile:
         # undo the damage done in the is_linux() block above, and also simulate
         # the is_darwin() block above.
         extra_cflags = []
         extra_cxxflags = ["-stdlib=libc++"]
         extra_cxxflags2 = ["-stdlib=libc++"]
 
-        extra_flags = ["-target", "x86_64-apple-darwin11", "-mlinker-version=137",
+        extra_flags = ["-target", "x86_64-darwin11", "-mlinker-version=137",
                        "-B", "%s/bin" % os.getenv("CROSS_CCTOOLS_PATH"),
                        "-isysroot", os.getenv("CROSS_SYSROOT"),
                        # technically the sysroot flag there should be enough to deduce this,
                        # but clang needs some help to figure this out.
                        "-I%s/usr/include" % os.getenv("CROSS_SYSROOT"),
                        "-iframework", "%s/System/Library/Frameworks" % os.getenv("CROSS_SYSROOT")]
         extra_cflags += extra_flags
         extra_cxxflags += extra_flags
--- a/build/build-clang/clang-7-macosx64.json
+++ b/build/build-clang/clang-7-macosx64.json
@@ -11,18 +11,18 @@
     "compiler_repo": "https://llvm.org/svn/llvm-project/compiler-rt/tags/RELEASE_700/final",
     "libcxx_repo": "https://llvm.org/svn/llvm-project/libcxx/tags/RELEASE_700/final",
     "libcxxabi_repo": "https://llvm.org/svn/llvm-project/libcxxabi/tags/RELEASE_700/final",
     "python_path": "/usr/bin/python2.7",
     "gcc_dir": "/builds/worker/workspace/build/src/gcc",
     "cc": "/builds/worker/workspace/build/src/clang/bin/clang",
     "cxx": "/builds/worker/workspace/build/src/clang/bin/clang++",
     "as": "/builds/worker/workspace/build/src/clang/bin/clang",
-    "ar": "/builds/worker/workspace/build/src/cctools/bin/x86_64-apple-darwin11-ar",
-    "ranlib": "/builds/worker/workspace/build/src/cctools/bin/x86_64-apple-darwin11-ranlib",
-    "libtool": "/builds/worker/workspace/build/src/cctools/bin/x86_64-apple-darwin11-libtool",
+    "ar": "/builds/worker/workspace/build/src/cctools/bin/x86_64-darwin11-ar",
+    "ranlib": "/builds/worker/workspace/build/src/cctools/bin/x86_64-darwin11-ranlib",
+    "libtool": "/builds/worker/workspace/build/src/cctools/bin/x86_64-darwin11-libtool",
     "ld": "/builds/worker/workspace/build/src/clang/bin/clang",
     "patches": [
       "static-llvm-symbolizer.patch",
       "compiler-rt-cross-compile.patch",
       "compiler-rt-no-codesign.patch"
     ]
 }
--- a/build/build-clang/clang-tidy-macosx64.json
+++ b/build/build-clang/clang-tidy-macosx64.json
@@ -11,15 +11,15 @@
     "extra_repo": "https://llvm.org/svn/llvm-project/clang-tools-extra/tags/RELEASE_700/final",
     "libcxx_repo": "https://llvm.org/svn/llvm-project/libcxx/tags/RELEASE_700/final",
     "libcxxabi_repo": "https://llvm.org/svn/llvm-project/libcxxabi/tags/RELEASE_700/final",
     "python_path": "/usr/bin/python2.7",
     "gcc_dir": "/builds/worker/workspace/build/src/gcc",
     "cc": "/builds/worker/workspace/build/src/clang/bin/clang",
     "cxx": "/builds/worker/workspace/build/src/clang/bin/clang++",
     "as": "/builds/worker/workspace/build/src/clang/bin/clang",
-    "ar": "/builds/worker/workspace/build/src/cctools/bin/x86_64-apple-darwin11-ar",
-    "ranlib": "/builds/worker/workspace/build/src/cctools/bin/x86_64-apple-darwin11-ranlib",
-    "libtool": "/builds/worker/workspace/build/src/cctools/bin/x86_64-apple-darwin11-libtool",
+    "ar": "/builds/worker/workspace/build/src/cctools/bin/x86_64-darwin11-ar",
+    "ranlib": "/builds/worker/workspace/build/src/cctools/bin/x86_64-darwin11-ranlib",
+    "libtool": "/builds/worker/workspace/build/src/cctools/bin/x86_64-darwin11-libtool",
     "ld": "/builds/worker/workspace/build/src/clang/bin/clang",
     "patches": [
     ]
 }
--- a/build/build-clang/compiler-rt-cross-compile.patch
+++ b/build/build-clang/compiler-rt-cross-compile.patch
@@ -1,15 +1,15 @@
-Add `-target x86_64-apple-darwin11' to the compiler-rt overridden CFLAGS
+Add `-target x86_64-darwin11' to the compiler-rt overridden CFLAGS
 
 diff --git a/compiler-rt/cmake/Modules/CompilerRTDarwinUtils.cmake b/compiler-rt/cmake/Modules/CompilerRTDarwinUtils.cmake
 index 28d398672..aac68bf36 100644
 --- a/compiler-rt/cmake/Modules/CompilerRTDarwinUtils.cmake
 +++ b/compiler-rt/cmake/Modules/CompilerRTDarwinUtils.cmake
 @@ -265,7 +265,7 @@ endfunction()
  macro(darwin_add_builtin_libraries)
    set(DARWIN_EXCLUDE_DIR ${CMAKE_CURRENT_SOURCE_DIR}/Darwin-excludes)
  
 -  set(CFLAGS "-fPIC -O3 -fvisibility=hidden -DVISIBILITY_HIDDEN -Wall -fomit-frame-pointer")
-+  set(CFLAGS "-fPIC -O3 -fvisibility=hidden -DVISIBILITY_HIDDEN -Wall -fomit-frame-pointer -target x86_64-apple-darwin11 -isysroot ${CMAKE_OSX_SYSROOT} -I${CMAKE_OSX_SYSROOT}/usr/include")
++  set(CFLAGS "-fPIC -O3 -fvisibility=hidden -DVISIBILITY_HIDDEN -Wall -fomit-frame-pointer -target x86_64-darwin11 -isysroot ${CMAKE_OSX_SYSROOT} -I${CMAKE_OSX_SYSROOT}/usr/include")
    set(CMAKE_C_FLAGS "")
    set(CMAKE_CXX_FLAGS "")
    set(CMAKE_ASM_FLAGS "")
deleted file mode 100755
--- a/build/macosx/build-cctools.sh
+++ /dev/null
@@ -1,26 +0,0 @@
-#!/bin/bash
-
-set -e
-
-if ! git remote -v | grep origin | grep -q cctools-port; then
-    echo "must be in a cctools-port checkout"
-    exit 1
-fi
-
-mkdir build-cctools
-cd build-cctools
-
-CFLAGS='-mcpu=generic -mtune=generic' MACOSX_DEPLOYMENT_TARGET=10.7 ../cctools/configure --target=x86_64-apple-darwin11
-env MACOSX_DEPLOYMENT_TARGET=10.7 make -s -j4
-
-if test ! -e ld64/src/ld/ld; then
-    echo "ld did not get built"
-    exit 1
-fi
-
-gtar jcf cctools.tar.bz2 ld64/src/ld/ld --transform 's#ld64/src/ld#cctools/bin#'
-
-cd ../
-
-echo "build from $(git show --pretty=format:%H -s HEAD) complete!"
-echo "upload the build-cctools/cctools.tar.bz2 file to tooltool"
--- a/build/macosx/cross-mozconfig.common
+++ b/build/macosx/cross-mozconfig.common
@@ -1,54 +1,47 @@
 # 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/.
 
 MOZ_AUTOMATION_L10N_CHECK=0
 
 . "$topsrcdir/build/mozconfig.common"
 
-# Rust requires dsymutil into PATH
-mk_add_options "export PATH=$topsrcdir/llvm-dsymutil/bin:$PATH"
+# cctools for ld, ar, and other related tools ; dsymutil for rust.
+mk_add_options "export PATH=$topsrcdir/cctools/bin:$topsrcdir/llvm-dsymutil/bin:$PATH"
 
 # ld needs libLTO.so from llvm
 mk_add_options "export LD_LIBRARY_PATH=$topsrcdir/clang/lib"
 
-CROSS_CCTOOLS_PATH=$topsrcdir/cctools
 # This SDK was copied from a local XCode install and uploaded to tooltool.
 # Generate the tarball by running this command with the proper SDK version:
 #   sdk_path=$(xcrun --sdk macosx10.12 --show-sdk-path)
 #   tar -C $(dirname ${sdk_path}) -cHjf /tmp/$(basename ${sdk_path}).tar.bz2 $(basename ${sdk_path})
 # Upload the resulting tarball from /tmp to tooltool, and change the entry in
 # `browser/config/tooltool-manifests/macosx64/cross-releng.manifest`.
 CROSS_SYSROOT=$topsrcdir/MacOSX10.11.sdk
 CROSS_PRIVATE_FRAMEWORKS=$CROSS_SYSROOT/System/Library/PrivateFrameworks
-FLAGS="-target x86_64-apple-darwin11 -B $CROSS_CCTOOLS_PATH/bin -isysroot $CROSS_SYSROOT"
 
-export CC="$topsrcdir/clang/bin/clang $FLAGS"
-export CXX="$topsrcdir/clang/bin/clang++ $FLAGS"
-export CPP="$topsrcdir/clang/bin/clang $FLAGS -E"
+export CC="$topsrcdir/clang/bin/clang"
+export CXX="$topsrcdir/clang/bin/clang++"
 export LLVMCONFIG=$topsrcdir/clang/bin/llvm-config
-export LDFLAGS="-Wl,-syslibroot,$CROSS_SYSROOT -Wl,-dead_strip"
-export BINDGEN_CFLAGS="$FLAGS"
-export TOOLCHAIN_PREFIX=$CROSS_CCTOOLS_PATH/bin/x86_64-apple-darwin11-
+export BINDGEN_CFLAGS="-isysroot $CROSS_SYSROOT"
 export DSYMUTIL=$topsrcdir/build/macosx/llvm-dsymutil
 mk_add_options "export REAL_DSYMUTIL=$topsrcdir/llvm-dsymutil/bin/dsymutil"
 export MKFSHFS=$topsrcdir/hfsplus-tools/newfs_hfs
 export DMG_TOOL=$topsrcdir/dmg/dmg
 export HFS_TOOL=$topsrcdir/dmg/hfsplus
 
-export HOST_CC="$topsrcdir/clang/bin/clang"
-export HOST_CXX="$topsrcdir/clang/bin/clang++"
-export HOST_CPP="$topsrcdir/clang/bin/clang -E"
 export HOST_CFLAGS="-g"
 export HOST_CXXFLAGS="-g"
 export HOST_LDFLAGS="-g"
 
-ac_add_options --target=x86_64-apple-darwin
+ac_add_options --target=x86_64-apple-darwin11
+ac_add_options --with-macos-sdk=$CROSS_SYSROOT
 ac_add_options --with-macos-private-frameworks=$CROSS_PRIVATE_FRAMEWORKS
 
 if [ "x$MOZ_PKG_SPECIAL" != "xasan" -a -z "$MOZ_AUTOMATION_ARTIFACT_BUILDS" ]; then
   # Enable static analysis checks by default on OSX cross builds.
   # Exception is ASan, where this breaks.
   # The option is not valid on artifact builds, so don't add it there either.
   ac_add_options --enable-clang-plugin
 fi
--- a/build/moz.configure/old.configure
+++ b/build/moz.configure/old.configure
@@ -235,18 +235,16 @@ def old_configure_options(*options):
     '--with-doc-input-dirs',
     '--with-doc-output-dir',
     '--with-float-abi',
     '--with-fpu',
     '--with-intl-api',
     '--with-ios-sdk',
     '--with-jitreport-granularity',
     '--with-macbundlename-prefix',
-    '--with-macos-private-frameworks',
-    '--with-macos-sdk',
     '--with-nspr-cflags',
     '--with-nspr-exec-prefix',
     '--with-nspr-libs',
     '--with-nspr-prefix',
     '--with-nss-exec-prefix',
     '--with-nss-prefix',
     '--with-qemu-exe',
     '--with-sixgill',
--- a/build/moz.configure/toolchain.configure
+++ b/build/moz.configure/toolchain.configure
@@ -193,38 +193,75 @@ add_old_configure_assignment('YASM', hav
 
 @depends('--disable-compile-environment', build_project)
 def compiling_android(compile_env, build_project):
     return compile_env and build_project in ('mobile/android', 'js')
 
 
 include('android-ndk.configure', when=compiling_android)
 
-# MacOS deployment target version
-# ==============================================================
-# This needs to happen before any compilation test is done.
+with only_when(target_is_osx):
+    # MacOS deployment target version
+    # ==============================================================
+    # This needs to happen before any compilation test is done.
+
+    option('--enable-macos-target', env='MACOSX_DEPLOYMENT_TARGET', nargs=1,
+           default='10.9', help='Set the minimum MacOS version needed at runtime')
 
-option('--enable-macos-target', env='MACOSX_DEPLOYMENT_TARGET', nargs=1,
-       default='10.9', help='Set the minimum MacOS version needed at runtime')
+
+    @depends('--enable-macos-target')
+    @imports(_from='os', _import='environ')
+    def macos_target(value):
+        if value:
+            # Ensure every compiler process we spawn uses this value.
+            environ['MACOSX_DEPLOYMENT_TARGET'] = value[0]
+            return value[0]
 
 
-@depends('--enable-macos-target', target)
-@imports(_from='os', _import='environ')
-def macos_target(value, target):
-    if value and target.os == 'OSX':
-        # Ensure every compiler process we spawn uses this value.
-        environ['MACOSX_DEPLOYMENT_TARGET'] = value[0]
+    set_config('MACOSX_DEPLOYMENT_TARGET', macos_target)
+    add_old_configure_assignment('MACOSX_DEPLOYMENT_TARGET', macos_target)
+
+    # MacOS SDK
+    # =========
+
+    option('--with-macos-sdk', nargs=1, help='Location of platform SDK to use')
+
+    @depends_if('--with-macos-sdk')
+    @imports(_from='os.path', _import='isdir')
+    def macos_sdk(value):
+        if not isdir(value[0]):
+            die('SDK not found in %s. When using --with-macos-sdk, you must specify a '
+                'valid SDK. SDKs are installed when the optional cross-development '
+                'tools are selected during the Xcode/Developer Tools installation.'
+                % value[0])
         return value[0]
-    if value and value.origin != 'default':
-        die('--enable-macos-target cannot be used when targeting %s',
-            target.os)
+
+    set_config('MACOS_SDK_DIR', macos_sdk)
+
+    with only_when(cross_compiling):
+        option('--with-macos-private-frameworks', nargs=1,
+               help='Location of private frameworks to use')
 
+        @depends_if('--with-macos-private-frameworks')
+        @imports(_from='os.path', _import='isdir')
+        def macos_private_frameworks(value):
+            if value and not isdir(value[0]):
+                die('PrivateFrameworks not found not found in %s. When using '
+                    '--with-macos-private-frameworks, you must specify a valid '
+                    'directory', value[0])
+            return value[0]
 
-set_config('MACOSX_DEPLOYMENT_TARGET', macos_target)
-add_old_configure_assignment('MACOSX_DEPLOYMENT_TARGET', macos_target)
+    @depends(macos_private_frameworks)
+    def macos_private_frameworks(value):
+        if value:
+            return value
+        return '/System/Library/PrivateFrameworks'
+
+    set_config('MACOS_PRIVATE_FRAMEWORKS_DIR', macos_private_frameworks)
+
 
 # Xcode state
 # ===========
 
 js_option('--disable-xcode-checks',
           help='Do not check that Xcode is installed and properly configured')
 
 
@@ -382,18 +419,18 @@ def toolchain_prefix(value, target, cros
     if cross_compiling:
         return ('%s-' % target.toolchain, '%s-' % target.alias)
 
 
 @depends(toolchain_prefix, target)
 def first_toolchain_prefix(toolchain_prefix, target):
     # Pass TOOLCHAIN_PREFIX down to the build system if it was given from the
     # command line/environment (in which case there's only one value in the tuple),
-    # or when cross-compiling for Android.
-    if toolchain_prefix and (target.os == 'Android' or len(toolchain_prefix) == 1):
+    # or when cross-compiling for Android or OSX.
+    if toolchain_prefix and (target.os in ('Android', 'OSX') or len(toolchain_prefix) == 1):
         return toolchain_prefix[0]
 
 
 set_config('TOOLCHAIN_PREFIX', first_toolchain_prefix)
 add_old_configure_assignment('TOOLCHAIN_PREFIX', first_toolchain_prefix)
 
 
 # Compilers
@@ -934,34 +971,37 @@ def compiler(language, host_or_target, c
     # Normally, we'd use `var` instead of `_var`, but the interaction with
     # old-configure complicates things, and for now, we a) can't take the plain
     # result from check_prog as CC/CXX/HOST_CC/HOST_CXX and b) have to let
     # old-configure AC_SUBST it (because it's autoconf doing it, not us)
     compiler = check_prog('_%s' % var, what=what, progs=default_compilers,
                           input=provided_compiler.program,
                           paths=toolchain_search_path)
 
-    @depends(compiler, provided_compiler, compiler_wrapper, host_or_target)
+    @depends(compiler, provided_compiler, compiler_wrapper, host_or_target, macos_sdk)
     @checking('whether %s can be used' % what, lambda x: bool(x))
     @imports(_from='mozbuild.shellutil', _import='quote')
     def valid_compiler(compiler, provided_compiler, compiler_wrapper,
-                       host_or_target):
+                       host_or_target, macos_sdk):
         wrapper = list(compiler_wrapper or ())
         if provided_compiler:
             provided_wrapper = list(provided_compiler.wrapper)
             # When doing a subconfigure, the compiler is set by old-configure
             # and it contains the wrappers from --with-compiler-wrapper and
             # --with-ccache.
             if provided_wrapper[:len(wrapper)] == wrapper:
                 provided_wrapper = provided_wrapper[len(wrapper):]
             wrapper.extend(provided_wrapper)
             flags = provided_compiler.flags
         else:
             flags = []
 
+        if not flags and macos_sdk and host_or_target.os == 'OSX':
+            flags = ['-isysroot', macos_sdk]
+
         # Ideally, we'd always use the absolute path, but unfortunately, on
         # Windows, the compiler is very often in a directory containing spaces.
         # Unfortunately, due to the way autoconf does its compiler tests with
         # eval, that doesn't work out. So in that case, check that the
         # compiler can still be found in $PATH, and use the file name instead
         # of the full path.
         if quote(compiler) != compiler:
             full_path = os.path.abspath(compiler)
@@ -1846,19 +1886,32 @@ def select_linker(linker, c_compiler, de
 
     # If an explicit linker was given, error out if what we found is different.
     if linker and not linker.startswith(result.KIND):
         die("Could not use {} as linker".format(linker))
 
     return result
 
 
-set_config('LD_IS_BFD', depends(select_linker.KIND)
-           (lambda x: x == 'bfd' or None))
-add_old_configure_assignment('LINKER_LDFLAGS', select_linker.LINKER_FLAG)
+set_config('LINKER_KIND', select_linker.KIND)
+
+
+@depends_if(select_linker, macos_sdk)
+def linker_ldflags(linker, macos_sdk):
+    flags = list(linker.LINKER_FLAG or [])
+    if macos_sdk:
+        if linker.KIND == 'ld64':
+            flags.append('-Wl,-syslibroot,%s' % macos_sdk)
+        else:
+            flags.append('-Wl,--sysroot=%s' % macos_sdk)
+
+    return flags
+
+
+add_old_configure_assignment('LINKER_LDFLAGS', linker_ldflags)
 
 
 # There's a wrinkle with MinGW: linker configuration is not enabled, so
 # `select_linker` is never invoked.  Hard-code around it.
 @depends(select_linker, target, c_compiler)
 def gcc_use_gnu_ld(select_linker, target, c_compiler):
     if select_linker is not None:
         return select_linker.KIND in ('bfd', 'gold', 'lld')
--- a/build/pgo/profileserver.py
+++ b/build/pgo/profileserver.py
@@ -1,16 +1,17 @@
 #!/usr/bin/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/.
 
 import json
 import os
+import sys
 
 from buildconfig import substs
 from mozbuild.base import MozbuildObject
 from mozfile import TemporaryDirectory
 from mozhttpd import MozHttpd
 from mozprofile import FirefoxProfile, Preferences
 from mozprofile.permissions import ServerLocations
 from mozrunner import FirefoxRunner, CLI
@@ -91,23 +92,31 @@ if __name__ == '__main__':
                     break
 
         # Run Firefox a first time to initialize its profile
         runner = FirefoxRunner(profile=profile,
                                binary=binary,
                                cmdargs=['data:text/html,<script>Quitter.quit()</script>'],
                                env=env)
         runner.start()
-        runner.wait()
+        ret = runner.wait()
+        if ret:
+            print("Firefox exited with code %d during profile initialization"
+                  % ret)
+            httpd.stop()
+            sys.exit(ret)
 
         jarlog = os.getenv("JARLOG_FILE")
         if jarlog:
             env["MOZ_JAR_LOG_FILE"] = os.path.abspath(jarlog)
             print("jarlog: %s" % env["MOZ_JAR_LOG_FILE"])
 
         cmdargs = ["http://localhost:%d/index.html" % PORT]
         runner = FirefoxRunner(profile=profile,
                                binary=binary,
                                cmdargs=cmdargs,
                                env=env)
         runner.start(debug_args=debug_args, interactive=interactive)
-        runner.wait()
+        ret = runner.wait()
         httpd.stop()
+        if ret:
+            print("Firefox exited with code %d during profiling" % ret)
+            sys.exit(ret)
--- a/devtools/client/debugger/new/test/mochitest/browser_dbg-expressions.js
+++ b/devtools/client/debugger/new/test/mochitest/browser_dbg-expressions.js
@@ -83,16 +83,16 @@ add_task(async function() {
   await deleteExpression(dbg, "foo");
   await deleteExpression(dbg, "location");
   is(findAllElements(dbg, "expressionNodes").length, 0);
 
   // Test expanding properties when the debuggee is active
   await resume(dbg);
   await addExpression(dbg, "location");
 
-  is(findAllElements(dbg, "expressionNodes").length, 34);
+  is(findAllElements(dbg, "expressionNodes").length, 1);
 
   await toggleExpressionNode(dbg, 1);
-  is(findAllElements(dbg, "expressionNodes").length, 1);
+  is(findAllElements(dbg, "expressionNodes").length, 34);
 
   await deleteExpression(dbg, "location");
   is(findAllElements(dbg, "expressionNodes").length, 0);
 });
--- a/devtools/client/debugger/new/test/mochitest/browser_dbg-scopes.js
+++ b/devtools/client/debugger/new/test/mochitest/browser_dbg-scopes.js
@@ -22,10 +22,10 @@ add_task(async function() {
   is(getLabel(dbg, 1), "secondCall");
   is(getLabel(dbg, 2), "<this>");
   is(getLabel(dbg, 4), "foo()");
   await toggleScopeNode(dbg, 4);
   is(getLabel(dbg, 5), "arguments");
 
   await stepOver(dbg);
   is(getLabel(dbg, 4), "foo()");
-  is(getLabel(dbg, 11), "Window");
+  is(getLabel(dbg, 5), "Window");
 });
--- a/devtools/client/inspector/grids/test/browser_grids_highlighter-toggle-telemetry.js
+++ b/devtools/client/inspector/grids/test/browser_grids_highlighter-toggle-telemetry.js
@@ -26,21 +26,31 @@ add_task(async function() {
   const { highlighters, store } = inspector;
 
   await selectNode("#grid", inspector);
   const gridList = doc.getElementById("grid-list");
   const checkbox = gridList.children[0].querySelector("input");
 
   info("Toggling ON the CSS grid highlighter from the layout panel.");
   const onHighlighterShown = highlighters.once("grid-highlighter-shown");
-  const onCheckboxChange = waitUntilState(store, state =>
+  let onCheckboxChange = waitUntilState(store, state =>
     state.grids.length == 1 &&
     state.grids[0].highlighted);
   checkbox.click();
   await onHighlighterShown;
   await onCheckboxChange;
 
+  info("Toggling OFF the CSS grid highlighter from the layout panel.");
+  const onHighlighterHidden = highlighters.once("grid-highlighter-hidden");
+  onCheckboxChange = waitUntilState(store, state =>
+    state.grids.length == 1 &&
+    !state.grids[0].highlighted);
+  checkbox.click();
+  await onHighlighterHidden;
+  await onCheckboxChange;
+
   checkResults();
 });
 
 function checkResults() {
   checkTelemetry("devtools.grid.gridinspector.opened", "", 1, "scalar");
+  checkTelemetry("DEVTOOLS_GRID_HIGHLIGHTER_TIME_ACTIVE_SECONDS", "", null, "hasentries");
 }
--- a/devtools/client/inspector/shared/highlighters-overlay.js
+++ b/devtools/client/inspector/shared/highlighters-overlay.js
@@ -38,16 +38,21 @@ class HighlightersOverlay {
     // ShapesHighlighter and GeometryEditorHighlighter.
     this.highlighters = {};
     // Map of grid container NodeFront to their instantiated grid highlighter actors.
     this.gridHighlighters = new Map();
     // Array of reusable grid highlighters that have been instantiated and are not
     // associated with any NodeFront.
     this.extraGridHighlighterPool = [];
 
+    // Boolean flag to keep track of whether or not the telemetry timer for the grid
+    // highlighter active time is active. We keep track of this to avoid re-starting a
+    // new timer when an additional grid highlighter is turned on.
+    this.isGridHighlighterTimerActive = false;
+
     // Collection of instantiated in-context editors, like ShapesInContextEditor, which
     // behave like highlighters but with added editing capabilities that need to map value
     // changes to properties in the Rule view.
     this.editors = {};
 
     // Saved state to be restore on page navigation.
     this.state = {
       flexbox: {},
@@ -513,16 +518,22 @@ class HighlightersOverlay {
 
     const isShown = await highlighter.show(node, options);
     if (!isShown) {
       return;
     }
 
     this._toggleRuleViewIcon(node, true, ".ruleview-grid");
 
+    if (!this.isGridHighlighterTimerActive) {
+      this.telemetry.toolOpened("grid_highlighter", this.inspector.toolbox.sessionId,
+        this);
+      this.isGridHighlighterTimerActive = true;
+    }
+
     if (trigger === "grid") {
       this.telemetry.scalarAdd("devtools.grid.gridinspector.opened", 1);
     } else if (trigger === "markup") {
       this.telemetry.scalarAdd("devtools.markup.gridinspector.opened", 1);
     } else if (trigger === "rule") {
       this.telemetry.scalarAdd("devtools.rules.gridinspector.opened", 1);
     }
 
@@ -557,16 +568,22 @@ class HighlightersOverlay {
     await highlighter.hide();
     this.extraGridHighlighterPool.push(highlighter);
 
     this.state.grids.delete(node);
     this.gridHighlighters.delete(node);
 
     this._toggleRuleViewIcon(node, false, ".ruleview-grid");
 
+    if (this.isGridHighlighterTimerActive && !this.gridHighlighters.size) {
+      this.telemetry.toolClosed("grid_highlighter", this.inspector.toolbox.sessionId,
+        this);
+      this.isGridHighlighterTimerActive = false;
+    }
+
     // Emit the NodeFront of the grid container element that the grid highlighter was
     // hidden for.
     this.emit("grid-highlighter-hidden", node);
   }
 
   /**
    * Show the box model highlighter for the given node.
    *
--- a/devtools/client/shared/components/reps/reps.js
+++ b/devtools/client/shared/components/reps/reps.js
@@ -2507,16 +2507,23 @@ function reducer(state = initialState(),
     return cloneState({
       actors: data.actor ? new Set(state.actors || []).add(data.result.from) : state.actors,
       evaluations: new Map(state.evaluations).set(data.node.path, {
         getterValue: data.result && data.result.value && (data.result.value.return || data.result.value.throw)
       })
     });
   }
 
+
+  // NOTE: we clear the state on resume because otherwise the scopes pane 
+  // would be out of date. Bug 1514760 
+  if (type === "RESUME" || type == "NAVIGATE") {
+    return initialState();
+  }
+
   return state;
 }
 
 function getObjectInspectorState(state) {
   return state.objectInspector;
 }
 
 function getExpandedPaths(state) {
--- a/devtools/client/shared/telemetry.js
+++ b/devtools/client/shared/telemetry.js
@@ -733,16 +733,17 @@ function getChartsFromToolId(id) {
     case "FONTINSPECTOR":
     case "LAYOUTVIEW":
     case "RULEVIEW":
       useTimedEvent = true;
       timerHist = `DEVTOOLS_${id}_TIME_ACTIVE_SECONDS`;
       countHist = `DEVTOOLS_${id}_OPENED_COUNT`;
       break;
     case "FLEXBOX_HIGHLIGHTER":
+    case "GRID_HIGHLIGHTER":
       timerHist = `DEVTOOLS_${id}_TIME_ACTIVE_SECONDS`;
       break;
     default:
       timerHist = `DEVTOOLS_CUSTOM_TIME_ACTIVE_SECONDS`;
       countHist = `DEVTOOLS_CUSTOM_OPENED_COUNT`;
   }
 
   return {
--- a/devtools/client/sourceeditor/codemirror/mozilla.css
+++ b/devtools/client/sourceeditor/codemirror/mozilla.css
@@ -281,15 +281,8 @@
 .CodeMirror-Tern-fhint-guess {
   opacity: .7;
 }
 
 /* Override the background-color: white applied to filler elements in codemirror.css */
 .CodeMirror-scrollbar-filler, .CodeMirror-gutter-filler {
   -moz-appearance: scrollcorner;
 }
-
-/* This scrollable element doesn't need to have its size influenced by its
-   children, so we can give it "contain: layout size" to make it a containment
-   boundary and to hint that it can be a reflow root. */
-.CodeMirror-scroll {
-  contain: layout size;
-}
--- a/devtools/server/actors/replay/moz.build
+++ b/devtools/server/actors/replay/moz.build
@@ -4,8 +4,15 @@
 # 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/.
 
 DevToolsModules(
     'debugger.js',
     'graphics.js',
     'replay.js',
 )
+
+XPIDL_MODULE = 'devtools_rr'
+
+XPIDL_SOURCES = [
+    'rrIGraphics.idl',
+    'rrIReplay.idl',
+]
new file mode 100644
--- /dev/null
+++ b/devtools/server/actors/replay/rrIGraphics.idl
@@ -0,0 +1,13 @@
+/* -*- Mode: C++; c-basic-offset: 2; indent-tabs-mode: nil; tab-width: 8 -*- */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#include "nsISupports.idl"
+
+[scriptable, uuid(941b2e20-8558-4881-b5ad-dc3a1f2d9678)]
+interface rrIGraphics : nsISupports {
+  void UpdateCanvas(in jsval buffer, in long width, in long height,
+                    in boolean hadFailure);
+};
+
new file mode 100644
--- /dev/null
+++ b/devtools/server/actors/replay/rrIReplay.idl
@@ -0,0 +1,19 @@
+/* -*- Mode: C++; c-basic-offset: 2; indent-tabs-mode: nil; tab-width: 8 -*- */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#include "nsISupports.idl"
+
+[scriptable, uuid(8b86b71f-8471-472e-9997-c5f21f9d0598)]
+interface rrIReplay : nsISupports {
+  jsval ProcessRequest(in jsval request);
+
+  void EnsurePositionHandler(in jsval position);
+
+  void ClearPositionHandlers();
+
+  void ClearPausedState();
+
+  jsval GetEntryPosition(in jsval position);
+};
--- a/dom/svg/SVGAElement.cpp
+++ b/dom/svg/SVGAElement.cpp
@@ -207,17 +207,17 @@ static bool IsNodeInEditableRegion(nsINo
       return true;
     }
     aNode = aNode->GetParent();
   }
   return false;
 }
 
 bool SVGAElement::IsSVGFocusable(bool* aIsFocusable, int32_t* aTabIndex) {
-  if (nsSVGElement::IsSVGFocusable(aIsFocusable, aTabIndex)) {
+  if (SVGGraphicsElement::IsSVGFocusable(aIsFocusable, aTabIndex)) {
     return true;
   }
 
   // cannot focus links if there is no link handler
   nsIDocument* doc = GetComposedDoc();
   if (doc) {
     nsPresContext* presContext = doc->GetPresContext();
     if (presContext && !presContext->GetLinkHandler()) {
--- a/dom/svg/SVGDefsElement.h
+++ b/dom/svg/SVGDefsElement.h
@@ -23,15 +23,20 @@ class SVGDefsElement final : public SVGG
   explicit SVGDefsElement(already_AddRefed<mozilla::dom::NodeInfo>&& aNodeInfo);
   virtual JSObject* WrapNode(JSContext* aCx,
                              JS::Handle<JSObject*> aGivenProto) override;
 
  public:
   // nsIContent
   NS_IMETHOD_(bool) IsAttributeMapped(const nsAtom* aAttribute) const override;
 
+  // defs elements are not focusable.
+  bool IsFocusableInternal(int32_t* aTabIndex, bool aWithMouse) override {
+    return nsIContent::IsFocusableInternal(aTabIndex, aWithMouse);
+  }
+
   virtual nsresult Clone(dom::NodeInfo*, nsINode** aResult) const override;
 };
 
 }  // namespace dom
 }  // namespace mozilla
 
 #endif  // mozilla_dom_SVGDefsElement_h
--- a/dom/svg/SVGGraphicsElement.cpp
+++ b/dom/svg/SVGGraphicsElement.cpp
@@ -23,10 +23,44 @@ NS_INTERFACE_MAP_END_INHERITING(SVGGraph
 // Implementation
 
 SVGGraphicsElement::SVGGraphicsElement(
     already_AddRefed<mozilla::dom::NodeInfo>&& aNodeInfo)
     : SVGGraphicsElementBase(std::move(aNodeInfo)) {}
 
 SVGGraphicsElement::~SVGGraphicsElement() {}
 
+bool SVGGraphicsElement::IsSVGFocusable(bool* aIsFocusable,
+                                        int32_t* aTabIndex) {
+  nsIDocument* doc = GetComposedDoc();
+  if (!doc || doc->HasFlag(NODE_IS_EDITABLE)) {
+    // In designMode documents we only allow focusing the document.
+    if (aTabIndex) {
+      *aTabIndex = -1;
+    }
+
+    *aIsFocusable = false;
+
+    return true;
+  }
+
+  int32_t tabIndex = TabIndex();
+
+  if (aTabIndex) {
+    *aTabIndex = tabIndex;
+  }
+
+  // If a tabindex is specified at all, or the default tabindex is 0, we're
+  // focusable
+  *aIsFocusable = tabIndex >= 0 || HasAttr(nsGkAtoms::tabindex);
+
+  return false;
+}
+
+bool SVGGraphicsElement::IsFocusableInternal(int32_t* aTabIndex,
+                                             bool aWithMouse) {
+  bool isFocusable = false;
+  IsSVGFocusable(&isFocusable, aTabIndex);
+  return isFocusable;
+}
+
 }  // namespace dom
 }  // namespace mozilla
--- a/dom/svg/SVGGraphicsElement.h
+++ b/dom/svg/SVGGraphicsElement.h
@@ -20,15 +20,17 @@ class SVGGraphicsElement : public SVGGra
   explicit SVGGraphicsElement(
       already_AddRefed<mozilla::dom::NodeInfo>&& aNodeInfo);
   ~SVGGraphicsElement();
 
  public:
   // interfaces:
   NS_DECL_ISUPPORTS_INHERITED
 
+  virtual bool IsSVGFocusable(bool* aIsFocusable, int32_t* aTabIndex);
+  bool IsFocusableInternal(int32_t* aTabIndex, bool aWithMouse) override;
   nsSVGElement* AsSVGElement() final { return this; }
 };
 
 }  // namespace dom
 }  // namespace mozilla
 
 #endif  // mozilla_dom_SVGGraphicsElement_h
--- a/dom/svg/nsSVGElement.cpp
+++ b/dom/svg/nsSVGElement.cpp
@@ -1012,48 +1012,16 @@ SVGSVGElement* nsSVGElement::GetOwnerSVG
 nsSVGElement* nsSVGElement::GetViewportElement() {
   return SVGContentUtils::GetNearestViewportElement(this);
 }
 
 already_AddRefed<SVGAnimatedString> nsSVGElement::ClassName() {
   return mClassAttribute.ToDOMAnimatedString(this);
 }
 
-bool nsSVGElement::IsSVGFocusable(bool* aIsFocusable, int32_t* aTabIndex) {
-  nsIDocument* doc = GetComposedDoc();
-  if (!doc || doc->HasFlag(NODE_IS_EDITABLE)) {
-    // In designMode documents we only allow focusing the document.
-    if (aTabIndex) {
-      *aTabIndex = -1;
-    }
-
-    *aIsFocusable = false;
-
-    return true;
-  }
-
-  int32_t tabIndex = TabIndex();
-
-  if (aTabIndex) {
-    *aTabIndex = tabIndex;
-  }
-
-  // If a tabindex is specified at all, or the default tabindex is 0, we're
-  // focusable
-  *aIsFocusable = tabIndex >= 0 || HasAttr(nsGkAtoms::tabindex);
-
-  return false;
-}
-
-bool nsSVGElement::IsFocusableInternal(int32_t* aTabIndex, bool aWithMouse) {
-  bool isFocusable = false;
-  IsSVGFocusable(&isFocusable, aTabIndex);
-  return isFocusable;
-}
-
 //------------------------------------------------------------------------
 // Helper class: MappedAttrParser, for parsing values of mapped attributes
 
 namespace {
 
 class MOZ_STACK_CLASS MappedAttrParser {
  public:
   MappedAttrParser(css::Loader* aLoader, nsIURI* aDocURI,
--- a/dom/svg/nsSVGElement.h
+++ b/dom/svg/nsSVGElement.h
@@ -299,20 +299,16 @@ class nsSVGElement : public nsSVGElement
   virtual void ClearAnyCachedPath() {}
   virtual bool IsTransformable() { return false; }
 
   // WebIDL
   mozilla::dom::SVGSVGElement* GetOwnerSVGElement();
   nsSVGElement* GetViewportElement();
   already_AddRefed<mozilla::dom::SVGAnimatedString> ClassName();
 
-  virtual bool IsSVGFocusable(bool* aIsFocusable, int32_t* aTabIndex);
-  virtual bool IsFocusableInternal(int32_t* aTabIndex,
-                                   bool aWithMouse) override;
-
   void UpdateContentDeclarationBlock();
   const mozilla::DeclarationBlock* GetContentDeclarationBlock() const;
 
  protected:
   virtual JSObject* WrapNode(JSContext* cx,
                              JS::Handle<JSObject*> aGivenProto) override;
 
   // We define BeforeSetAttr here and mark it final to ensure it is NOT used
--- a/dom/xslt/xslt/moz.build
+++ b/dom/xslt/xslt/moz.build
@@ -3,16 +3,22 @@
 # 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.mozilla.dom += [
     'txMozillaXSLTProcessor.h'
 ]
 
+XPIDL_MODULE = 'dom_xslt'
+
+XPIDL_SOURCES += [
+    'txIEXSLTFunctions.idl',
+]
+
 UNIFIED_SOURCES += [
     'txBufferingHandler.cpp',
     'txCurrentFunctionCall.cpp',
     'txDocumentFunctionCall.cpp',
     'txExecutionState.cpp',
     'txEXSLTFunctions.cpp',
     'txFormatNumberFunctionCall.cpp',
     'txGenerateIdFunctionCall.cpp',
--- a/dom/xslt/xslt/txEXSLTFunctions.cpp
+++ b/dom/xslt/xslt/txEXSLTFunctions.cpp
@@ -10,20 +10,22 @@
 #include "mozilla/MacroArgs.h"
 #include "mozilla/MacroForEach.h"
 
 #include "nsAtom.h"
 #include "nsGkAtoms.h"
 #include "txExecutionState.h"
 #include "txExpr.h"
 #include "txIXPathContext.h"
+#include "txIEXSLTFunctions.h"
 #include "txNodeSet.h"
 #include "txOutputFormat.h"
 #include "txRtfHandler.h"
 #include "txXPathTreeWalker.h"
+#include "nsImportModule.h"
 #include "nsPrintfCString.h"
 #include "nsComponentManagerUtils.h"
 #include "nsContentCID.h"
 #include "nsContentCreatorFunctions.h"
 #include "nsIContent.h"
 #include "txMozillaXMLOutput.h"
 #include "nsTextNode.h"
 #include "mozilla/dom/DocumentFragmentBinding.h"
@@ -657,70 +659,28 @@ nsresult txEXSLTRegExFunctionCall::evalu
   NS_ENSURE_SUCCESS(rv, rv);
 
   nsAutoString flags;
   if (mParams.Length() >= 3) {
     rv = mParams[2]->evaluateToString(aContext, flags);
     NS_ENSURE_SUCCESS(rv, rv);
   }
 
-  AutoJSAPI jsapi;
-  if (!jsapi.Init(xpc::PrivilegedJunkScope())) {
-    return NS_ERROR_FAILURE;
-  }
-  JSContext* cx = jsapi.cx();
-
-  xpc::SandboxOptions options;
-  options.sandboxName.AssignLiteral("txEXSLTRegExFunctionCall sandbox");
-  options.invisibleToDebugger = true;
-  JS::RootedValue v(cx);
-  rv = CreateSandboxObject(cx, &v, nsXPConnect::SystemPrincipal(), options);
-  MOZ_ALWAYS_SUCCEEDS(rv);
-  JS::RootedObject sandbox(cx, js::UncheckedUnwrap(&v.toObject()));
-
-  JSAutoRealm ar(cx, sandbox);
-  ErrorResult er;
-  GlobalObject global(cx, sandbox);
-  Optional<JS::HandleObject> targetObj(cx, sandbox);
-  JS::RootedObject obj(cx);
-  ChromeUtils::Import(
-      global,
-      NS_LITERAL_STRING("resource://gre/modules/txEXSLTRegExFunctions.jsm"),
-      targetObj, &obj, er);
-  MOZ_ALWAYS_TRUE(!er.Failed());
-
-  JS::RootedString str(
-      cx, JS_NewUCStringCopyZ(cx, PromiseFlatString(string).get()));
-  JS::RootedString re(cx,
-                      JS_NewUCStringCopyZ(cx, PromiseFlatString(regex).get()));
-  JS::RootedString fl(cx,
-                      JS_NewUCStringCopyZ(cx, PromiseFlatString(flags).get()));
+  nsCOMPtr<txIEXSLTFunctions> funcs =
+      do_ImportModule("resource://gre/modules/txEXSLTRegExFunctions.jsm");
+  MOZ_ALWAYS_TRUE(funcs);
 
   switch (mType) {
     case txEXSLTType::MATCH: {
       nsCOMPtr<nsIDocument> sourceDoc = getSourceDocument(aContext);
       NS_ENSURE_STATE(sourceDoc);
 
-      JS::RootedValue doc(cx);
-      if (!GetOrCreateDOMReflector(cx, sourceDoc, &doc)) {
-        return NS_ERROR_FAILURE;
-      }
-
-      JS::AutoValueArray<4> args(cx);
-      args[0].setString(str);
-      args[1].setString(re);
-      args[2].setString(fl);
-      args[3].setObject(doc.toObject());
-
-      JS::RootedValue rval(cx);
-      if (!JS_CallFunctionName(cx, sandbox, "match", args, &rval)) {
-        return NS_ERROR_FAILURE;
-      }
       RefPtr<DocumentFragment> docFrag;
-      rv = UNWRAP_OBJECT(DocumentFragment, &rval, docFrag);
+      rv = funcs->Match(string, regex, flags, sourceDoc,
+                        getter_AddRefs(docFrag));
       NS_ENSURE_SUCCESS(rv, rv);
       NS_ENSURE_STATE(docFrag);
 
       RefPtr<txNodeSet> resultSet;
       rv = aContext->recycler()->getNodeSet(getter_AddRefs(resultSet));
       NS_ENSURE_SUCCESS(rv, rv);
 
       nsAutoPtr<txXPathNode> node;
@@ -735,51 +695,29 @@ nsresult txEXSLTRegExFunctionCall::evalu
 
       return NS_OK;
     }
     case txEXSLTType::REPLACE: {
       nsAutoString replace;
       rv = mParams[3]->evaluateToString(aContext, replace);
       NS_ENSURE_SUCCESS(rv, rv);
 
-      JS::RootedString repl(
-          cx, JS_NewUCStringCopyZ(cx, PromiseFlatString(replace).get()));
-
-      JS::AutoValueArray<4> args(cx);
-      args[0].setString(str);
-      args[1].setString(re);
-      args[2].setString(fl);
-      args[3].setString(repl);
-
-      JS::RootedValue rval(cx);
-      if (!JS_CallFunctionName(cx, sandbox, "replace", args, &rval)) {
-        return NS_ERROR_FAILURE;
-      }
-      nsString result;
-      if (!ConvertJSValueToString(cx, rval, result)) {
-        return NS_ERROR_FAILURE;
-      }
+      nsAutoString result;
+      rv = funcs->Replace(string, regex, flags, replace, result);
+      NS_ENSURE_SUCCESS(rv, rv);
 
       rv = aContext->recycler()->getStringResult(result, aResult);
       NS_ENSURE_SUCCESS(rv, rv);
 
       return NS_OK;
     }
     case txEXSLTType::TEST: {
-      JS::AutoValueArray<3> args(cx);
-      args[0].setString(str);
-      args[1].setString(re);
-      args[2].setString(fl);
-
-      JS::RootedValue rval(cx);
-      if (!JS_CallFunctionName(cx, sandbox, "test", args, &rval)) {
-        return NS_ERROR_FAILURE;
-      }
-
-      bool result = rval.toBoolean();
+      bool result;
+      rv = funcs->Test(string, regex, flags, &result);
+      NS_ENSURE_SUCCESS(rv, rv);
 
       aContext->recycler()->getBoolResult(result, aResult);
 
       return NS_OK;
     }
     default: {
       aContext->receiveError(NS_LITERAL_STRING("Internal error"),
                              NS_ERROR_UNEXPECTED);
new file mode 100644
--- /dev/null
+++ b/dom/xslt/xslt/txIEXSLTFunctions.idl
@@ -0,0 +1,21 @@
+/* -*- Mode: C++; c-basic-offset: 2; indent-tabs-mode: nil; tab-width: 8 -*- */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#include "nsISupports.idl"
+
+webidl Document;
+webidl DocumentFragment;
+
+[scriptable, uuid(21b1cfa4-00ce-4cc1-bfc1-92af1d00e580)]
+interface txIEXSLTFunctions : nsISupports {
+  DocumentFragment match(in AString str, in AString regex,
+                         in AString flags, in Document doc);
+
+  AString replace(in AString str, in AString regex, in AString flags,
+                  in AString replace);
+
+  boolean test(in AString str, in AString regex, in AString flags);
+};
+
--- a/gfx/gl/GLScreenBuffer.cpp
+++ b/gfx/gl/GLScreenBuffer.cpp
@@ -97,16 +97,21 @@ UniquePtr<GLScreenBuffer> GLScreenBuffer
     if (gl->GetContextType() == GLContextType::EGL) {
       if (XRE_IsParentProcess()) {
         factory = SurfaceFactory_EGLImage::Create(gl, caps, ipcChannel, flags);
       }
     }
 #endif
   } else if (useD3D) {
 #ifdef XP_WIN
+    // Ensure devices initialization. SharedSurfaceANGLE and
+    // SharedSurfaceD3D11Interop use them. The devices are lazily initialized
+    // with WebRender to reduce memory usage.
+    gfxPlatform::GetPlatform()->EnsureDevicesInitialized();
+
     // Enable surface sharing only if ANGLE and compositing devices
     // are both WARP or both not WARP
     gfx::DeviceManagerDx* dm = gfx::DeviceManagerDx::Get();
     if (gl->IsANGLE() && (gl->IsWARP() == dm->IsWARP()) &&
         dm->TextureSharingWorks()) {
       factory =
           SurfaceFactory_ANGLEShareHandle::Create(gl, caps, ipcChannel, flags);
     }
--- a/gfx/layers/d3d11/TextureD3D11.cpp
+++ b/gfx/layers/d3d11/TextureD3D11.cpp
@@ -1610,17 +1610,18 @@ bool SyncObjectD3D11Host::Synchronize(bo
   }
 
   return true;
 }
 
 SyncObjectD3D11Client::SyncObjectD3D11Client(SyncHandle aSyncHandle,
                                              ID3D11Device* aDevice)
     : mSyncHandle(aSyncHandle), mSyncLock("SyncObjectD3D11") {
-  if (!aDevice) {
+  if (!aDevice && !XRE_IsGPUProcess() &&
+      gfxPlatform::GetPlatform()->DevicesInitialized()) {
     mDevice = DeviceManagerDx::Get()->GetContentDevice();
     return;
   }
 
   mDevice = aDevice;
 }
 
 bool SyncObjectD3D11Client::Init(bool aFallible) {
@@ -1659,17 +1660,27 @@ bool SyncObjectD3D11Client::Init(bool aF
   return true;
 }
 
 void SyncObjectD3D11Client::RegisterTexture(ID3D11Texture2D* aTexture) {
   mSyncedTextures.push_back(aTexture);
 }
 
 bool SyncObjectD3D11Client::IsSyncObjectValid() {
-  RefPtr<ID3D11Device> dev = DeviceManagerDx::Get()->GetContentDevice();
+  RefPtr<ID3D11Device> dev;
+  // There is a case that devices are not initialized yet with WebRender.
+  if (gfxPlatform::GetPlatform()->DevicesInitialized()) {
+    dev = DeviceManagerDx::Get()->GetContentDevice();
+  }
+
+  // Update mDevice if the ContentDevice initialization is detected.
+  if (!mDevice && dev && NS_IsMainThread() && gfxVars::UseWebRender()) {
+    mDevice = dev;
+  }
+
   if (!dev || (NS_IsMainThread() && dev != mDevice)) {
     return false;
   }
   return true;
 }
 
 // We have only 1 sync object. As a thing that somehow works,
 // we copy each of the textures that need to be synced with the compositor
--- a/gfx/layers/wr/WebRenderBridgeChild.cpp
+++ b/gfx/layers/wr/WebRenderBridgeChild.cpp
@@ -541,16 +541,21 @@ void WebRenderBridgeChild::SetWebRenderL
 }
 
 ipc::IShmemAllocator* WebRenderBridgeChild::GetShmemAllocator() {
   return static_cast<CompositorBridgeChild*>(Manager());
 }
 
 RefPtr<KnowsCompositor> WebRenderBridgeChild::GetForMedia() {
   MOZ_ASSERT(NS_IsMainThread());
+
+  // Ensure devices initialization for video playback. The devices are lazily
+  // initialized with WebRender to reduce memory usage.
+  gfxPlatform::GetPlatform()->EnsureDevicesInitialized();
+
   return MakeAndAddRef<KnowsCompositorMediaProxy>(
       GetTextureFactoryIdentifier());
 }
 
 bool WebRenderBridgeChild::AllocResourceShmem(size_t aSize,
                                               RefCountedShmem& aShm) {
   // We keep a single shmem around to reuse later if it is reference count has
   // dropped back to 1 (the reference held by the WebRenderBridgeChild).
--- a/gfx/layers/wr/WebRenderLayerManager.cpp
+++ b/gfx/layers/wr/WebRenderLayerManager.cpp
@@ -660,16 +660,21 @@ void WebRenderLayerManager::ScheduleComp
 void WebRenderLayerManager::SetRoot(Layer* aLayer) {
   // This should never get called
   MOZ_ASSERT(false);
 }
 
 already_AddRefed<PersistentBufferProvider>
 WebRenderLayerManager::CreatePersistentBufferProvider(
     const gfx::IntSize& aSize, gfx::SurfaceFormat aFormat) {
+
+  // Ensure devices initialization for canvas 2d. The devices are lazily
+  // initialized with WebRender to reduce memory usage.
+  gfxPlatform::GetPlatform()->EnsureDevicesInitialized();
+
   if (gfxPrefs::PersistentBufferProviderSharedEnabled()) {
     RefPtr<PersistentBufferProvider> provider =
         PersistentBufferProviderShared::Create(aSize, aFormat,
                                                AsKnowsCompositor());
     if (provider) {
       return provider.forget();
     }
   }
--- a/gfx/thebes/DeviceManagerDx.cpp
+++ b/gfx/thebes/DeviceManagerDx.cpp
@@ -986,16 +986,19 @@ void DeviceManagerDx::DisableD3D11AfterC
 }
 
 RefPtr<ID3D11Device> DeviceManagerDx::GetCompositorDevice() {
   MutexAutoLock lock(mDeviceLock);
   return mCompositorDevice;
 }
 
 RefPtr<ID3D11Device> DeviceManagerDx::GetContentDevice() {
+  MOZ_ASSERT(XRE_IsGPUProcess() ||
+             gfxPlatform::GetPlatform()->DevicesInitialized());
+
   MutexAutoLock lock(mDeviceLock);
   return mContentDevice;
 }
 
 RefPtr<ID3D11Device> DeviceManagerDx::GetImageDevice() {
   MutexAutoLock lock(mDeviceLock);
   if (mImageDevice) {
     return mImageDevice;
--- a/gfx/thebes/gfxPlatform.cpp
+++ b/gfx/thebes/gfxPlatform.cpp
@@ -908,16 +908,23 @@ void gfxPlatform::Init() {
   gPlatform = new gfxPlatformGtk;
 #elif defined(ANDROID)
   gPlatform = new gfxAndroidPlatform;
 #else
 #error "No gfxPlatform implementation available"
 #endif
   gPlatform->InitAcceleration();
   gPlatform->InitWebRenderConfig();
+  // When using WebRender, we defer initialization of the D3D11 devices until
+  // the (rare) cases where they're used. Note that the GPU process where WebRender
+  // runs doesn't initialize gfxPlatform and performs explicit initialization of
+  // the bits it needs.
+  if (!gfxVars::UseWebRender()) {
+    gPlatform->EnsureDevicesInitialized();
+  }
   gPlatform->InitOMTPConfig();
 
   if (gfxConfig::IsEnabled(Feature::GPU_PROCESS)) {
     GPUProcessManager* gpu = GPUProcessManager::Get();
     gpu->LaunchGPUProcess();
   }
 
   if (XRE_IsParentProcess() &&
--- a/gfx/thebes/gfxPlatform.h
+++ b/gfx/thebes/gfxPlatform.h
@@ -747,16 +747,19 @@ class gfxPlatform : public mozilla::laye
   // you probably want to use gfxVars::UseWebRender() instead of this
   static bool WebRenderEnvvarEnabled();
 
   void NotifyFrameStats(nsTArray<mozilla::layers::FrameStats>&& aFrameStats);
 
   virtual void OnMemoryPressure(
       mozilla::layers::MemoryPressureReason aWhy) override;
 
+  virtual void EnsureDevicesInitialized() {};
+  virtual bool DevicesInitialized() { return true; };
+
  protected:
   gfxPlatform();
   virtual ~gfxPlatform();
 
   virtual bool HasBattery() { return true; }
 
   virtual void InitAcceleration();
   virtual void InitWebRenderConfig();
--- a/gfx/thebes/gfxWindowsPlatform.cpp
+++ b/gfx/thebes/gfxWindowsPlatform.cpp
@@ -419,17 +419,16 @@ bool gfxWindowsPlatform::HasBattery() {
 }
 
 void gfxWindowsPlatform::InitAcceleration() {
   gfxPlatform::InitAcceleration();
 
   DeviceManagerDx::Init();
 
   InitializeConfig();
-  InitializeDevices();
   UpdateANGLEConfig();
   UpdateRenderMode();
 
   // If we have Skia and we didn't init dwrite already, do it now.
   if (!DWriteEnabled() && GetDefaultContentBackend() == BackendType::SKIA) {
     InitDWriteSupport();
   }
 
@@ -492,17 +491,19 @@ bool gfxWindowsPlatform::HandleDeviceRes
   gfxAlphaBoxBlur::ShutdownBlurCache();
 
   gfxConfig::Reset(Feature::D3D11_COMPOSITING);
   gfxConfig::Reset(Feature::ADVANCED_LAYERS);
   gfxConfig::Reset(Feature::D3D11_HW_ANGLE);
   gfxConfig::Reset(Feature::DIRECT2D);
 
   InitializeConfig();
-  InitializeDevices();
+  if (mInitializedDevices) {
+    InitializeDevices();
+  }
   UpdateANGLEConfig();
   return true;
 }
 
 BackendPrefsData gfxWindowsPlatform::GetBackendPrefs() const {
   BackendPrefsData data;
 
   data.mCanvasBitmask =
@@ -1465,17 +1466,35 @@ void gfxWindowsPlatform::InitializeD3D11
   // This would not normally be displayed in about:support.
   if (!XRE_IsContentProcess()) {
     return;
   }
   Telemetry::Accumulate(Telemetry::GFX_CONTENT_FAILED_TO_ACQUIRE_DEVICE,
                         uint32_t(aDevice));
 }
 
+// Supports lazy device initialization on Windows, so that WebRender can avoid
+// initializing GPU state and allocating swap chains for most non-GPU processes.
+void gfxWindowsPlatform::EnsureDevicesInitialized() {
+  if (!mInitializedDevices) {
+    mInitializedDevices = true;
+    InitializeDevices();
+    UpdateBackendPrefs();
+  }
+}
+
+bool
+gfxWindowsPlatform::DevicesInitialized() {
+
+  return mInitializedDevices;
+}
+
 void gfxWindowsPlatform::InitializeDevices() {
+  MOZ_ASSERT(NS_IsMainThread());
+
   if (XRE_IsParentProcess()) {
     // If we're the UI process, and the GPU process is enabled, then we don't
     // initialize any DirectX devices. We do leave them enabled in gfxConfig
     // though. If the GPU process fails to create these devices it will send
     // a message back and we'll update their status.
     if (InitGPUProcessSupport()) {
       return;
     }
@@ -2027,16 +2046,20 @@ void gfxWindowsPlatform::BuildContentDev
 
   if (d3d11.IsEnabled()) {
     DeviceManagerDx* dm = DeviceManagerDx::Get();
     dm->ExportDeviceInfo(&aOut->d3d11());
   }
 }
 
 bool gfxWindowsPlatform::SupportsPluginDirectDXGIDrawing() {
+  // Ensure devices initialization for plugin's DXGISurface. The devices are
+  // lazily initialized with WebRender to reduce memory usage.
+  EnsureDevicesInitialized();
+
   DeviceManagerDx* dm = DeviceManagerDx::Get();
   if (!dm->GetContentDevice() || !dm->TextureSharingWorks()) {
     return false;
   }
   return true;
 }
 
 bool gfxWindowsPlatform::CheckVariationFontSupport() {
--- a/gfx/thebes/gfxWindowsPlatform.h
+++ b/gfx/thebes/gfxWindowsPlatform.h
@@ -100,16 +100,19 @@ class gfxWindowsPlatform : public gfxPla
   };
 
   gfxWindowsPlatform();
   virtual ~gfxWindowsPlatform();
   static gfxWindowsPlatform* GetPlatform() {
     return (gfxWindowsPlatform*)gfxPlatform::GetPlatform();
   }
 
+  virtual void EnsureDevicesInitialized() override;
+  virtual bool DevicesInitialized() override;
+
   virtual gfxPlatformFontList* CreatePlatformFontList() override;
 
   virtual already_AddRefed<gfxASurface> CreateOffscreenSurface(
       const IntSize& aSize, gfxImageFormat aFormat) override;
 
   enum RenderMode {
     /* Use GDI and windows surfaces */
     RENDER_GDI = 0,
@@ -254,11 +257,12 @@ class gfxWindowsPlatform : public gfxPla
   void InitializeD2DConfig();
   void InitializeDirectDrawConfig();
   void InitializeAdvancedLayersConfig();
 
   RefPtr<IDWriteRenderingParams> mRenderingParams[TEXT_RENDERING_COUNT];
   DWRITE_MEASURING_MODE mMeasuringMode;
 
   RefPtr<mozilla::layers::ReadbackManagerD3D11> mD3D11ReadbackManager;
+  bool mInitializedDevices = false;
 };
 
 #endif /* GFX_WINDOWS_PLATFORM_H */
--- a/js/public/GCAPI.h
+++ b/js/public/GCAPI.h
@@ -260,16 +260,34 @@ typedef enum JSGCParamKey {
   /**
    * Attempt to run a minor GC in the idle time if the free space falls
    * below this threshold.
    *
    * Default: NurseryChunkUsableSize / 4
    * Pref: None
    */
   JSGC_NURSERY_FREE_THRESHOLD_FOR_IDLE_COLLECTION = 27,
+
+  /**
+   * If this percentage of the nursery is tenured, then proceed to examine which
+   * groups we should pretenure.
+   *
+   * Default: PretenureThreshold
+   * Pref: None
+   */
+  JSGC_PRETENURE_THRESHOLD = 28,
+
+  /**
+   * If the above condition is met, then any object group that tenures more than
+   * this number of objects will be pretenured (if it can be).
+   *
+   * Default: PretenureGroupThreshold
+   * Pref: None
+   */
+  JSGC_PRETENURE_GROUP_THRESHOLD = 29,
 } JSGCParamKey;
 
 /*
  * Generic trace operation that calls JS::TraceEdge on each traceable thing's
  * location reachable from data.
  */
 typedef void (*JSTraceDataOp)(JSTracer* trc, void* data);
 
--- a/js/src/aclocal.m4
+++ b/js/src/aclocal.m4
@@ -10,17 +10,16 @@ builtin(include, ../../build/autoconf/co
 builtin(include, ../../build/autoconf/toolchain.m4)dnl
 builtin(include, ../../build/autoconf/pkg.m4)dnl
 builtin(include, ../../build/autoconf/nspr.m4)dnl
 builtin(include, ../../build/autoconf/nspr-build.m4)dnl
 builtin(include, ../../build/autoconf/codeset.m4)dnl
 builtin(include, ../../build/autoconf/altoptions.m4)dnl
 builtin(include, ../../build/autoconf/mozprog.m4)dnl
 builtin(include, ../../build/autoconf/mozheader.m4)dnl
-builtin(include, ../../build/autoconf/lto.m4)dnl
 builtin(include, ../../build/autoconf/frameptr.m4)dnl
 builtin(include, ../../build/autoconf/compiler-opts.m4)dnl
 builtin(include, ../../build/autoconf/expandlibs.m4)dnl
 builtin(include, ../../build/autoconf/arch.m4)dnl
 builtin(include, ../../build/autoconf/android.m4)dnl
 builtin(include, ../../build/autoconf/zlib.m4)dnl
 builtin(include, ../../build/autoconf/icu.m4)dnl
 builtin(include, ../../build/autoconf/clang-plugin.m4)dnl
--- a/js/src/gc/GC.cpp
+++ b/js/src/gc/GC.cpp
@@ -343,16 +343,22 @@ static const JSGCMode Mode = JSGC_MODE_I
 
 /* JSGC_COMPACTING_ENABLED */
 static const bool CompactingEnabled = true;
 
 /* JSGC_NURSERY_FREE_THRESHOLD_FOR_IDLE_COLLECTION */
 static const uint32_t NurseryFreeThresholdForIdleCollection =
     Nursery::NurseryChunkUsableSize / 4;
 
+/* JSGC_PRETENURE_THRESHOLD */
+static const float PretenureThreashold = 0.6f;
+
+/* JSGC_PRETENURE_GROUP_THRESHOLD */
+static const float PretenureGroupThreshold = 3000;
+
 }  // namespace TuningDefaults
 }  // namespace gc
 }  // namespace js
 
 /*
  * We start to incremental collection for a zone when a proportion of its
  * threshold is reached. This is configured by the
  * JSGC_ALLOCATION_THRESHOLD_FACTOR and
@@ -1255,16 +1261,27 @@ bool GCRuntime::init(uint32_t maxbytes, 
     const char* size = getenv("JSGC_MARK_STACK_LIMIT");
     if (size) {
       setMarkStackLimit(atoi(size), lock);
     }
 
     if (!nursery().init(maxNurseryBytes, lock)) {
       return false;
     }
+
+    const char* pretenureThresholdStr = getenv("JSGC_PRETENURE_THRESHOLD");
+    if (pretenureThresholdStr && pretenureThresholdStr[0]) {
+      char* last;
+      long pretenureThreshold = strtol(pretenureThresholdStr, &last, 10);
+      if (last[0] || !tunables.setParameter(JSGC_PRETENURE_THRESHOLD,
+                                            pretenureThreshold, lock)) {
+        fprintf(stderr, "Invalid value for JSGC_PRETENURE_THRESHOLD: %s\n",
+                pretenureThresholdStr);
+      }
+    }
   }
 
 #ifdef JS_GC_ZEAL
   const char* zealSpec = getenv("JS_GC_ZEAL");
   if (zealSpec && zealSpec[0] && !parseAndSetZeal(zealSpec)) {
     return false;
   }
 #endif
@@ -1459,16 +1476,30 @@ bool GCSchedulingTunables::setParameter(
       setMaxEmptyChunkCount(value);
       break;
     case JSGC_NURSERY_FREE_THRESHOLD_FOR_IDLE_COLLECTION:
       if (value > gcMaxNurseryBytes()) {
         value = gcMaxNurseryBytes();
       }
       nurseryFreeThresholdForIdleCollection_ = value;
       break;
+    case JSGC_PRETENURE_THRESHOLD: {
+      // 100 disables pretenuring
+      if (value == 0 || value > 100) {
+        return false;
+      }
+      pretenureThreshold_ = value / 100.0f;
+      break;
+    }
+    case JSGC_PRETENURE_GROUP_THRESHOLD:
+      if (value <= 0) {
+        return false;
+      }
+      pretenureGroupThreshold_ = value;
+      break;
     default:
       MOZ_CRASH("Unknown GC parameter.");
   }
 
   return true;
 }
 
 void GCSchedulingTunables::setMaxMallocBytes(size_t value) {
@@ -1546,17 +1577,19 @@ GCSchedulingTunables::GCSchedulingTunabl
       highFrequencyHighLimitBytes_(TuningDefaults::HighFrequencyHighLimitBytes),
       highFrequencyHeapGrowthMax_(TuningDefaults::HighFrequencyHeapGrowthMax),
       highFrequencyHeapGrowthMin_(TuningDefaults::HighFrequencyHeapGrowthMin),
       lowFrequencyHeapGrowth_(TuningDefaults::LowFrequencyHeapGrowth),
       dynamicMarkSliceEnabled_(TuningDefaults::DynamicMarkSliceEnabled),
       minEmptyChunkCount_(TuningDefaults::MinEmptyChunkCount),
       maxEmptyChunkCount_(TuningDefaults::MaxEmptyChunkCount),
       nurseryFreeThresholdForIdleCollection_(
-          TuningDefaults::NurseryFreeThresholdForIdleCollection) {}
+          TuningDefaults::NurseryFreeThresholdForIdleCollection),
+      pretenureThreshold_(TuningDefaults::PretenureThreashold),
+      pretenureGroupThreshold_(TuningDefaults::PretenureGroupThreshold) {}
 
 void GCRuntime::resetParameter(JSGCParamKey key, AutoLockGC& lock) {
   switch (key) {
     case JSGC_MAX_MALLOC_BYTES:
       setMaxMallocBytes(TuningDefaults::MaxMallocBytes, lock);
       break;
     case JSGC_SLICE_TIME_BUDGET:
       defaultTimeBudget_ = TuningDefaults::DefaultTimeBudget;
@@ -1628,16 +1661,22 @@ void GCSchedulingTunables::resetParamete
       break;
     case JSGC_MAX_EMPTY_CHUNK_COUNT:
       setMaxEmptyChunkCount(TuningDefaults::MaxEmptyChunkCount);
       break;
     case JSGC_NURSERY_FREE_THRESHOLD_FOR_IDLE_COLLECTION:
       nurseryFreeThresholdForIdleCollection_ =
           TuningDefaults::NurseryFreeThresholdForIdleCollection;
       break;
+    case JSGC_PRETENURE_THRESHOLD:
+      pretenureThreshold_ = TuningDefaults::PretenureThreashold;
+      break;
+    case JSGC_PRETENURE_GROUP_THRESHOLD:
+      pretenureGroupThreshold_ = TuningDefaults::PretenureGroupThreshold;
+      break;
     default:
       MOZ_CRASH("Unknown GC parameter.");
   }
 }
 
 uint32_t GCRuntime::getParameter(JSGCParamKey key, const AutoLockGC& lock) {
   switch (key) {
     case JSGC_MAX_BYTES:
@@ -1686,16 +1725,20 @@ uint32_t GCRuntime::getParameter(JSGCPar
     case JSGC_ALLOCATION_THRESHOLD_FACTOR_AVOID_INTERRUPT:
       return uint32_t(tunables.allocThresholdFactorAvoidInterrupt() * 100);
     case JSGC_MIN_EMPTY_CHUNK_COUNT:
       return tunables.minEmptyChunkCount(lock);
     case JSGC_MAX_EMPTY_CHUNK_COUNT:
       return tunables.maxEmptyChunkCount();
     case JSGC_COMPACTING_ENABLED:
       return compactingEnabled;
+    case JSGC_PRETENURE_THRESHOLD:
+      return uint32_t(tunables.pretenureThreshold() * 100);
+    case JSGC_PRETENURE_GROUP_THRESHOLD:
+      return tunables.pretenureGroupThreshold();
     default:
       MOZ_ASSERT(key == JSGC_NUMBER);
       return uint32_t(number);
   }
 }
 
 void GCRuntime::setMarkStackLimit(size_t limit, AutoLockGC& lock) {
   MOZ_ASSERT(!JS::RuntimeHeapIsBusy());
--- a/js/src/gc/GCInternals.h
+++ b/js/src/gc/GCInternals.h
@@ -170,17 +170,17 @@ struct MovingTracer : JS::CallbackTracer
   template <typename T>
   void updateEdge(T** thingp);
 };
 
 // Structure for counting how many times objects in a particular group have
 // been tenured during a minor collection.
 struct TenureCount {
   ObjectGroup* group;
-  int count;
+  unsigned count;
 
   // ObjectGroups are never nursery-allocated, and TenureCounts are only used
   // in minor GC (not compacting GC), so prevent the analysis from
   // complaining about TenureCounts being held live across a minor GC.
 } JS_HAZ_NON_GC_POINTER;
 
 // Keep rough track of how many times we tenure objects in particular groups
 // during minor collections, using a fixed size hash for efficiency at the cost
--- a/js/src/gc/Nursery.cpp
+++ b/js/src/gc/Nursery.cpp
@@ -689,17 +689,17 @@ inline void js::Nursery::startProfile(Pr
 
 inline void js::Nursery::endProfile(ProfileKey key) {
   profileDurations_[key] = ReallyNow() - startTimes_[key];
   totalDurations_[key] += profileDurations_[key];
 }
 
 bool js::Nursery::needIdleTimeCollection() const {
   uint32_t threshold =
-      runtime()->gc.tunables.nurseryFreeThresholdForIdleCollection();
+      tunables().nurseryFreeThresholdForIdleCollection();
   return minorGCRequested() || freeSpace() < threshold;
 }
 
 static inline bool IsFullStoreBufferReason(JS::gcreason::Reason reason) {
   return reason == JS::gcreason::FULL_WHOLE_CELL_BUFFER ||
          reason == JS::gcreason::FULL_GENERIC_BUFFER ||
          reason == JS::gcreason::FULL_VALUE_BUFFER ||
          reason == JS::gcreason::FULL_CELL_PTR_BUFFER ||
@@ -763,23 +763,25 @@ void js::Nursery::collect(JS::gcreason::
   // If we are promoting the nursery, or exhausted the store buffer with
   // pointers to nursery things, which will force a collection well before
   // the nursery is full, look for object groups that are getting promoted
   // excessively and try to pretenure them.
   startProfile(ProfileKey::Pretenure);
   bool validPromotionRate;
   const float promotionRate = calcPromotionRate(&validPromotionRate);
   uint32_t pretenureCount = 0;
-  bool shouldPretenure = (validPromotionRate && promotionRate > 0.6) ||
-                         IsFullStoreBufferReason(reason);
+  bool shouldPretenure = tunables().attemptPretenuring() &&
+                         ((validPromotionRate &&
+                          promotionRate > tunables().pretenureThreshold()) ||
+                         IsFullStoreBufferReason(reason));
 
   if (shouldPretenure) {
     JSContext* cx = rt->mainContextFromOwnThread();
     for (auto& entry : tenureCounts.entries) {
-      if (entry.count >= 3000) {
+      if (entry.count >= tunables().pretenureGroupThreshold()) {
         ObjectGroup* group = entry.group;
         AutoRealm ar(cx, group);
         AutoSweepObjectGroup sweep(group);
         if (group->canPreTenure(sweep)) {
           group->setShouldPreTenure(sweep, cx);
           pretenureCount++;
         }
       }
@@ -817,17 +819,17 @@ void js::Nursery::collect(JS::gcreason::
   stats().setStat(gcstats::STAT_NURSERY_STRING_REALMS_DISABLED,
                   numNurseryStringRealmsDisabled);
   stats().setStat(gcstats::STAT_STRINGS_TENURED, numStringsTenured);
   endProfile(ProfileKey::Pretenure);
 
   // We ignore gcMaxBytes when allocating for minor collection. However, if we
   // overflowed, we disable the nursery. The next time we allocate, we'll fail
   // because gcBytes >= gcMaxBytes.
-  if (rt->gc.usage.gcBytes() >= rt->gc.tunables.gcMaxBytes()) {
+  if (rt->gc.usage.gcBytes() >= tunables().gcMaxBytes()) {
     disable();
   }
   // Disable the nursery if the user changed the configuration setting.  The
   // nursery can only be re-enabled by resetting the configurationa and
   // restarting firefox.
   if (chunkCountLimit_ == 0) {
     disable();
   }
@@ -1173,18 +1175,17 @@ void js::Nursery::maybeResizeNursery(JS:
 
 #ifdef JS_GC_ZEAL
   // This zeal mode disabled nursery resizing.
   if (runtime()->hasZealMode(ZealMode::GenerationalGC)) {
     return;
   }
 #endif
 
-  newMaxNurseryChunks =
-      runtime()->gc.tunables.gcMaxNurseryBytes() >> ChunkShift;
+  newMaxNurseryChunks = tunables().gcMaxNurseryBytes() >> ChunkShift;
   if (newMaxNurseryChunks != chunkCountLimit_) {
     chunkCountLimit_ = newMaxNurseryChunks;
     /* The configured maximum nursery size is changing */
     if (maxChunkCount() > newMaxNurseryChunks) {
       /* We need to shrink the nursery */
       shrinkAllocableSpace(newMaxNurseryChunks);
       return;
     }
@@ -1255,16 +1256,20 @@ uintptr_t js::Nursery::currentEnd() cons
   MOZ_ASSERT(currentEnd_ == chunk(currentChunk_).end());
   return currentEnd_;
 }
 
 gcstats::Statistics& js::Nursery::stats() const {
   return runtime()->gc.stats();
 }
 
+MOZ_ALWAYS_INLINE const js::gc::GCSchedulingTunables& js::Nursery::tunables() const {
+  return runtime()->gc.tunables;
+}
+
 void js::Nursery::sweepDictionaryModeObjects() {
   for (auto obj : dictionaryModeObjects_) {
     if (!IsForwarded(obj)) {
       obj->sweepDictionaryListPointer();
     } else {
       Forwarded(obj)->updateDictionaryListPointerAfterMinorGC(obj);
     }
   }
--- a/js/src/gc/Nursery.h
+++ b/js/src/gc/Nursery.h
@@ -54,16 +54,17 @@ class HeapSlot;
 class JSONPrinter;
 class MapObject;
 class SetObject;
 
 namespace gc {
 class AutoMaybeStartBackgroundAllocation;
 class AutoTraceSession;
 struct Cell;
+class GCSchedulingTunables;
 class MinorCollectionTracer;
 class RelocationOverlay;
 struct TenureCountCache;
 enum class AllocKind : uint8_t;
 class TenuredCell;
 } /* namespace gc */
 
 namespace jit {
@@ -543,16 +544,18 @@ class Nursery {
 
   MOZ_ALWAYS_INLINE uintptr_t currentEnd() const;
 
   uintptr_t position() const { return position_; }
 
   JSRuntime* runtime() const { return runtime_; }
   gcstats::Statistics& stats() const;
 
+  const js::gc::GCSchedulingTunables& tunables() const;
+
   /* Common internal allocator function. */
   void* allocate(size_t size);
 
   void doCollection(JS::gcreason::Reason reason,
                     gc::TenureCountCache& tenureCounts);
 
   /*
    * Move the object at |src| in the Nursery to an already-allocated cell
--- a/js/src/gc/Scheduling.h
+++ b/js/src/gc/Scheduling.h
@@ -428,16 +428,34 @@ class GCSchedulingTunables {
   /*
    * JSGC_NURSERY_FREE_THRESHOLD_FOR_IDLE_COLLECTION
    *
    * Attempt to run a minor GC in the idle time if the free space falls
    * below this threshold.
    */
   UnprotectedData<uint32_t> nurseryFreeThresholdForIdleCollection_;
 
+  /*
+   * JSGC_PRETENURE_THRESHOLD
+   *
+   * Fraction of objects tenured to trigger pretenuring (between 0 and 1). If
+   * this fraction is met, the GC proceeds to calculate which objects will be
+   * tenured. If this is 1.0f (actually if it is not < 1.0f) then pretenuring
+   * is disabled.
+   */
+  UnprotectedData<float> pretenureThreshold_;
+
+  /*
+   * JSGC_PRETENURE_GROUP_THRESHOLD
+   *
+   * During a single nursery collection, if this many objects from the same
+   * object group are tenured, then that group will be pretenured.
+   */
+  UnprotectedData<uint32_t> pretenureGroupThreshold_;
+
  public:
   GCSchedulingTunables();
 
   size_t gcMaxBytes() const { return gcMaxBytes_; }
   size_t maxMallocBytes() const { return maxMallocBytes_; }
   size_t gcMaxNurseryBytes() const { return gcMaxNurseryBytes_; }
   size_t gcZoneAllocThresholdBase() const { return gcZoneAllocThresholdBase_; }
   double allocThresholdFactor() const { return allocThresholdFactor_; }
@@ -466,16 +484,20 @@ class GCSchedulingTunables {
   unsigned minEmptyChunkCount(const AutoLockGC&) const {
     return minEmptyChunkCount_;
   }
   unsigned maxEmptyChunkCount() const { return maxEmptyChunkCount_; }
   uint32_t nurseryFreeThresholdForIdleCollection() const {
     return nurseryFreeThresholdForIdleCollection_;
   }
 
+  bool attemptPretenuring() const { return pretenureThreshold_ < 1.0f; }
+  float pretenureThreshold() const { return pretenureThreshold_; }
+  uint32_t pretenureGroupThreshold() const { return pretenureGroupThreshold_; }
+
   MOZ_MUST_USE bool setParameter(JSGCParamKey key, uint32_t value,
                                  const AutoLockGC& lock);
   void resetParameter(JSGCParamKey key, const AutoLockGC& lock);
 
   void setMaxMallocBytes(size_t value);
 
  private:
   void setHighFrequencyLowLimit(size_t value);
new file mode 100644
--- /dev/null
+++ b/js/src/jit-test/tests/wasm/timeout/interrupt-multi-instance-activation.js
@@ -0,0 +1,28 @@
+// |jit-test| exitstatus: 6; skip-if: !wasmIsSupported()
+
+const {Module, Instance} = WebAssembly;
+
+const {innerWasm} = new Instance(new Module(wasmTextToBinary(`(module
+    (func (export "innerWasm") (result i32)
+        (local i32)
+        (loop $top
+            (set_local 0 (i32.add (get_local 0) (i32.const 1)))
+            (br_if $top (i32.lt_u (get_local 0) (i32.const 100000)))
+        )
+        (get_local 0)
+    )
+)`))).exports;
+
+function middleJS() {
+    innerWasm();
+}
+
+const {outerWasm} = new Instance(new Module(wasmTextToBinary(`(module
+    (func $middleJS (import "" "middleJS"))
+    (func (export "outerWasm") (call $middleJS))
+)`)), {'':{middleJS}}).exports;
+
+timeout(1);
+while (true) {
+    outerWasm();
+}
--- a/js/src/old-configure.in
+++ b/js/src/old-configure.in
@@ -305,60 +305,16 @@ AC_SUBST(_MSC_VER)
 AC_SUBST(GNU_CC)
 AC_SUBST(GNU_CXX)
 
 dnl ========================================================
 dnl Checks for programs.
 dnl ========================================================
 if test "$COMPILE_ENVIRONMENT"; then
 
-dnl ========================================================
-dnl = Mac OS X SDK support
-dnl ========================================================
-MACOS_SDK_DIR=
-MOZ_ARG_WITH_STRING(macos-sdk,
-[  --with-macos-sdk=dir    Location of platform SDK to use (Mac OS X only)],
-    MACOS_SDK_DIR=$withval)
-
-dnl MACOS_SDK_DIR will be set to the SDK location whenever one is in use.
-AC_SUBST(MACOS_SDK_DIR)
-
-if test "$MACOS_SDK_DIR"; then
-  dnl Sync this section with the ones in NSPR and NSS.
-  dnl Changes to the cross environment here need to be accounted for in
-  dnl the libIDL checks (below) and xpidl build.
-
-  if test ! -d "$MACOS_SDK_DIR"; then
-    AC_MSG_ERROR([SDK not found.  When using --with-macos-sdk, you must
-specify a valid SDK.  SDKs are installed when the optional cross-development
-tools are selected during the Xcode/Developer Tools installation.])
-  fi
-
-  CFLAGS="$CFLAGS -isysroot ${MACOS_SDK_DIR}"
-  CXXFLAGS="$CXXFLAGS -isysroot ${MACOS_SDK_DIR}"
-
-  dnl CPP/CXXCPP needs to be set for MOZ_CHECK_HEADER.
-  CPP="$CPP -isysroot ${MACOS_SDK_DIR}"
-  CXXCPP="$CXXCPP -isysroot ${MACOS_SDK_DIR}"
-
-  AC_LANG_SAVE
-  AC_MSG_CHECKING([for valid compiler/Mac OS X SDK combination])
-  AC_LANG_CPLUSPLUS
-  AC_TRY_COMPILE([#include <new>
-                 int main() { return 0; }],
-   result=yes,
-   result=no)
-  AC_LANG_RESTORE
-  AC_MSG_RESULT($result)
-
-  if test "$result" = "no" ; then
-    AC_MSG_ERROR([The selected compiler and Mac OS X SDK are incompatible.])
-  fi
-fi
-
 AC_PATH_XTRA
 
 XCFLAGS="$X_CFLAGS"
 
 fi # COMPILE_ENVIRONMENT
 
 # Separate version into components for use in shared object naming etc
 changequote(,)
@@ -551,18 +507,16 @@ case "$host" in
     ;;
 
 *)
     HOST_CFLAGS="$HOST_CFLAGS -DXP_UNIX"
     HOST_OPTIMIZE_FLAGS="${HOST_OPTIMIZE_FLAGS=-O2}"
     ;;
 esac
 
-MOZ_DOING_LTO(lto_is_enabled)
-
 dnl ========================================================
 dnl Add optional and non-optional hardening flags from toolchain.configure
 dnl ========================================================
 
 CFLAGS="$CFLAGS $MOZ_HARDENING_CFLAGS_JS"
 CPPFLAGS="$CPPFLAGS $MOZ_HARDENING_CFLAGS_JS"
 CXXFLAGS="$CXXFLAGS $MOZ_HARDENING_CFLAGS_JS"
 
@@ -588,21 +542,19 @@ case "$target" in
                 ac_cv_have_framework_exceptionhandling="yes",
                 ac_cv_have_framework_exceptionhandling="no")
     AC_MSG_RESULT([$ac_cv_have_framework_exceptionhandling])
     if test  "$ac_cv_have_framework_exceptionhandling" = "yes"; then
       MOZ_DEBUG_LDFLAGS="$MOZ_DEBUG_LDFLAGS -framework ExceptionHandling";
     fi
     LDFLAGS=$_SAVE_LDFLAGS
 
-    if test "x$lto_is_enabled" = "xyes"; then
-        echo "Skipping -dead_strip because lto is enabled."
     dnl DTrace and -dead_strip don't interact well. See bug 403132.
     dnl ===================================================================
-    elif test "x$enable_dtrace" = "xyes"; then
+    if test "x$enable_dtrace" = "xyes"; then
         echo "Skipping -dead_strip because DTrace is enabled. See bug 403132."
     else
         dnl check for the presence of the -dead_strip linker flag
         AC_MSG_CHECKING([for -dead_strip option to ld])
         _SAVE_LDFLAGS=$LDFLAGS
         LDFLAGS="$LDFLAGS -Wl,-dead_strip"
         AC_TRY_LINK(,[return 0;],_HAVE_DEAD_STRIP=1,_HAVE_DEAD_STRIP=)
         if test -n "$_HAVE_DEAD_STRIP" ; then
--- a/js/src/wasm/WasmFrameIter.cpp
+++ b/js/src/wasm/WasmFrameIter.cpp
@@ -43,19 +43,21 @@ WasmFrameIter::WasmFrameIter(JitActivati
       unwoundIonFrameType_(jit::FrameType(-1)),
       unwind_(Unwind::False),
       unwoundAddressOfReturnAddress_(nullptr),
       returnAddressToFp_(nullptr) {
   MOZ_ASSERT(fp_);
 
   // When the stack is captured during a trap (viz., to create the .stack
   // for an Error object), use the pc/bytecode information captured by the
-  // signal handler in the runtime.
+  // signal handler in the runtime. Take care not to use this trap unwind
+  // state for wasm frames in the middle of a JitActivation, i.e., wasm frames
+  // that called into JIT frames before the trap.
 
-  if (activation->isWasmTrapping()) {
+  if (activation->isWasmTrapping() && fp_ == activation->wasmExitFP()) {
     const TrapData& trapData = activation->wasmTrapData();
     void* unwoundPC = trapData.unwoundPC;
 
     code_ = &fp_->tls->instance->code();
     MOZ_ASSERT(code_ == LookupCode(unwoundPC));
 
     codeRange_ = code_->lookupFuncRange(unwoundPC);
     MOZ_ASSERT(codeRange_);
--- a/js/xpconnect/loader/moz.build
+++ b/js/xpconnect/loader/moz.build
@@ -4,31 +4,36 @@
 # 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/.
 
 UNIFIED_SOURCES += [
     'AutoMemMap.cpp',
     'ChromeScriptLoader.cpp',
     'mozJSLoaderUtils.cpp',
     'mozJSSubScriptLoader.cpp',
+    'nsImportModule.cpp',
     'ScriptCacheActors.cpp',
     'ScriptPreloader.cpp',
     'URLPreloader.cpp',
 ]
 
 # mozJSComponentLoader.cpp cannot be built in unified mode because it uses
 # windows.h
 SOURCES += [
-    'mozJSComponentLoader.cpp'
+    'mozJSComponentLoader.cpp',
 ]
 
 IPDL_SOURCES += [
     'PScriptCache.ipdl',
 ]
 
+EXPORTS += [
+    'nsImportModule.h'
+]
+
 EXPORTS.mozilla += [
     'AutoMemMap.h',
     'ScriptPreloader.h',
     'URLPreloader.h',
 ]
 
 EXPORTS.mozilla.dom += [
     'PrecompiledScript.h',
new file mode 100644
--- /dev/null
+++ b/js/xpconnect/loader/nsImportModule.cpp
@@ -0,0 +1,34 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#include "nsImportModule.h"
+
+#include "mozilla/ResultExtensions.h"
+#include "mozilla/dom/ScriptSettings.h"
+#include "mozJSComponentLoader.h"
+#include "xpcpublic.h"
+#include "xpcprivate.h"
+
+using mozilla::dom::AutoJSAPI;
+
+namespace mozilla {
+namespace loader {
+
+nsresult ImportModule(const char* aURI, const nsIID& aIID, void** aResult) {
+  AutoJSAPI jsapi;
+  MOZ_ALWAYS_TRUE(jsapi.Init(xpc::PrivilegedJunkScope()));
+  JSContext* cx = jsapi.cx();
+
+  JS::RootedObject global(cx);
+  JS::RootedObject exports(cx);
+  MOZ_TRY(mozJSComponentLoader::Get()->Import(cx, nsDependentCString(aURI),
+                                              &global, &exports));
+
+  return nsXPConnect::XPConnect()->WrapJS(cx, exports, aIID, aResult);
+}
+
+}  // namespace loader
+}  // namespace mozilla
new file mode 100644
--- /dev/null
+++ b/js/xpconnect/loader/nsImportModule.h
@@ -0,0 +1,77 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#ifndef nsImportModule_h
+#define nsImportModule_h
+
+#include "mozilla/Attributes.h"
+
+#include "nsCOMPtr.h"
+#include "mozilla/RefPtr.h"
+
+namespace mozilla {
+namespace loader {
+
+nsresult ImportModule(const char* aURI, const nsIID& aIID, void** aResult);
+
+}  // namespace loader
+}  // namespace mozilla
+
+class MOZ_STACK_CLASS nsImportModule final : public nsCOMPtr_helper {
+ public:
+  nsImportModule(const char* aURI, nsresult* aErrorPtr)
+      : mURI(aURI), mErrorPtr(aErrorPtr) {}
+
+  virtual nsresult NS_FASTCALL operator()(const nsIID& aIID,
+                                          void** aResult) const override {
+    nsresult rv = ::mozilla::loader::ImportModule(mURI, aIID, aResult);
+    if (mErrorPtr) {
+      *mErrorPtr = rv;
+    }
+    return rv;
+  }
+
+ private:
+  const char* mURI;
+  nsresult* mErrorPtr;
+};
+
+/**
+ * These helpers make it considerably easier for C++ code to import a JS module
+ * and wrap it in an appropriately-defined XPIDL interface for its exports.
+ * Typical usage is something like:
+ *
+ * Foo.jsm:
+ *
+ *   var EXPORTED_SYMBOLS = ["foo"];
+ *
+ *   function foo(bar) {
+ *     return bar.toString();
+ *   }
+ *
+ * mozIFoo.idl:
+ *
+ *   interface mozIFoo : nsISupports {
+ *     AString foo(double meh);
+ *   }
+ *
+ * Thing.cpp:
+ *
+ *   nsCOMPtr<mozIFoo> foo = do_ImportModule(
+ *     "resource://meh/Foo.jsm");
+ *
+ *   MOZ_TRY(foo->Foo(42));
+ */
+
+inline nsImportModule do_ImportModule(const char* aURI) {
+  return {aURI, nullptr};
+}
+
+inline nsImportModule do_ImportModule(const char* aURI, nsresult* aRv) {
+  return {aURI, aRv};
+}
+
+#endif  // defined nsImportModule_h
--- a/media/libwebp/src/dsp/moz.build
+++ b/media/libwebp/src/dsp/moz.build
@@ -31,18 +31,17 @@ if CONFIG['CPU_ARCH'] == 'arm' and CONFI
         'rescaler_neon.c',
         'upsampling_neon.c',
         'yuv_neon.c',
     ]
     DEFINES['WEBP_HAVE_NEON'] = 1;
     for f in SOURCES:
       if f.endswith('neon.c'):
         SOURCES[f].flags += CONFIG['NEON_FLAGS']
-elif CONFIG['CPU_ARCH'] == 'aarch64' and CONFIG['OS_ARCH'] != 'WINNT':
-    # Bug 1504017 tracks re-enabling this for Windows.
+elif CONFIG['CPU_ARCH'] == 'aarch64' and CONFIG['CC_TYPE'] != 'msvc':
     SOURCES += [
         'alpha_processing_neon.c',
         'dec_neon.c',
         'filters_neon.c',
         'lossless_neon.c',
         'rescaler_neon.c',
         'upsampling_neon.c',
         'yuv_neon.c',
--- a/mobile/android/installer/package-manifest.in
+++ b/mobile/android/installer/package-manifest.in
@@ -259,17 +259,16 @@
 
 ; [Browser Chrome Files]
 @BINPATH@/chrome/toolkit@JAREXT@
 @BINPATH@/chrome/toolkit.manifest
 
 ; [Extensions]
 @BINPATH@/components/extensions-toolkit.manifest
 @BINPATH@/components/extensions-mobile.manifest
-@BINPATH@/components/extension-process-script.js
 
 ; Features
 @BINPATH@/features/*
 
 ; DevTools
 @BINPATH@/chrome/devtools@JAREXT@
 @BINPATH@/chrome/devtools.manifest
 
--- a/modules/libmar/sign/mar_sign.c
+++ b/modules/libmar/sign/mar_sign.c
@@ -25,45 +25,39 @@
 #include "base64.h"
 
 /**
  * Initializes the NSS context.
  *
  * @param NSSConfigDir The config dir containing the private key to use
  * @return 0 on success
  *         -1 on error
-*/
-int
-NSSInitCryptoContext(const char *NSSConfigDir)
-{
-  SECStatus status = NSS_Initialize(NSSConfigDir,
-                                    "", "", SECMOD_DB, NSS_INIT_READONLY);
+ */
+int NSSInitCryptoContext(const char *NSSConfigDir) {
+  SECStatus status =
+      NSS_Initialize(NSSConfigDir, "", "", SECMOD_DB, NSS_INIT_READONLY);
   if (SECSuccess != status) {
     fprintf(stderr, "ERROR: Could not initialize NSS\n");
     return -1;
   }
 
   return 0;
 }
 
 /**
  * Obtains a signing context.
  *
  * @param  ctx A pointer to the signing context to fill
  * @return 0 on success
  *         -1 on error
-*/
-int
-NSSSignBegin(const char *certName,
-             SGNContext **ctx,
-             SECKEYPrivateKey **privKey,
-             CERTCertificate **cert,
-             uint32_t *signatureLength)
-{
-  secuPWData pwdata = { PW_NONE, 0 };
+ */
+int NSSSignBegin(const char *certName, SGNContext **ctx,
+                 SECKEYPrivateKey **privKey, CERTCertificate **cert,
+                 uint32_t *signatureLength) {
+  secuPWData pwdata = {PW_NONE, 0};
   if (!certName || !ctx || !privKey || !cert || !signatureLength) {
     fprintf(stderr, "ERROR: Invalid parameter passed to NSSSignBegin\n");
     return -1;
   }
 
   /* Get the cert and embedded public key out of the database */
   *cert = PK11_FindCertFromNickname(certName, &pwdata);
   if (!*cert) {
@@ -117,53 +111,50 @@ NSSSignBegin(const char *certName,
  * @param  size     The size of the buffer to write.
  * @param  ctxs     Pointer to the first element in an array of signature
  *                  contexts to update.
  * @param  ctxCount The number of signature contexts pointed to by ctxs
  * @param  err    The name of what is being written to in case of error.
  * @return  0 on success
  *         -2 on write error
  *         -3 on signature update error
-*/
-int
-WriteAndUpdateSignatures(FILE *fpDest, void *buffer,
-                         uint32_t size, SGNContext **ctxs,
-                         uint32_t ctxCount,
-                         const char *err)
-{
+ */
+int WriteAndUpdateSignatures(FILE *fpDest, void *buffer, uint32_t size,
+                             SGNContext **ctxs, uint32_t ctxCount,
+                             const char *err) {
   uint32_t k;
   if (!size) {
     return 0;
   }
 
   if (fwrite(buffer, size, 1, fpDest) != 1) {
     fprintf(stderr, "ERROR: Could not write %s\n", err);
     return -2;
   }
 
   for (k = 0; k < ctxCount; ++k) {
     if (SGN_Update(ctxs[k], buffer, size) != SECSuccess) {
-      fprintf(stderr, "ERROR: Could not update signature context for %s\n", err);
+      fprintf(stderr, "ERROR: Could not update signature context for %s\n",
+              err);
       return -3;
     }
   }
   return 0;
 }
 
 /**
  * Adjusts each entry's content offset in the the passed in index by the
  * specified amount.
  *
  * @param indexBuf     A buffer containing the MAR index
  * @param indexLength  The length of the MAR index
  * @param offsetAmount The amount to adjust each index entry by
-*/
-void
-AdjustIndexContentOffsets(char *indexBuf, uint32_t indexLength, uint32_t offsetAmount)
-{
+ */
+void AdjustIndexContentOffsets(char *indexBuf, uint32_t indexLength,
+                               uint32_t offsetAmount) {
   uint32_t *offsetToContent;
   char *indexBufLoc = indexBuf;
 
   /* Consume the index and adjust each index by the specified amount */
   while (indexBufLoc != (indexBuf + indexLength)) {
     /* Adjust the offset */
     offsetToContent = (uint32_t *)indexBufLoc;
     *offsetToContent = ntohl(*offsetToContent);
@@ -185,52 +176,46 @@ AdjustIndexContentOffsets(char *indexBuf
  * @param  ctxs     Pointer to the first element in an array of signature
  *                  contexts to update.
  * @param  ctxCount The number of signature contexts pointed to by ctxs
  * @param  err    The name of what is being written to in case of error.
  * @return  0 on success
  *         -1 on read error
  *         -2 on write error
  *         -3 on signature update error
-*/
-int
-ReadWriteAndUpdateSignatures(FILE *fpSrc, FILE *fpDest, void *buffer,
-                             uint32_t size, SGNContext **ctxs,
-                             uint32_t ctxCount,
-                             const char *err)
-{
+ */
+int ReadWriteAndUpdateSignatures(FILE *fpSrc, FILE *fpDest, void *buffer,
+                                 uint32_t size, SGNContext **ctxs,
+                                 uint32_t ctxCount, const char *err) {
   if (!size) {
     return 0;
   }
 
   if (fread(buffer, size, 1, fpSrc) != 1) {
     fprintf(stderr, "ERROR: Could not read %s\n", err);
     return -1;
   }
 
   return WriteAndUpdateSignatures(fpDest, buffer, size, ctxs, ctxCount, err);
 }
 
-
 /**
  * Reads from fpSrc, writes it to fpDest.
  *
  * @param  fpSrc  The file pointer to read from.
  * @param  fpDest The file pointer to write to.
  * @param  buffer The buffer to write.
  * @param  size   The size of the buffer to write.
  * @param  err    The name of what is being written to in case of error.
  * @return  0 on success
  *         -1 on read error
  *         -2 on write error
-*/
-int
-ReadAndWrite(FILE *fpSrc, FILE *fpDest, void *buffer,
-             uint32_t size, const char *err)
-{
+ */
+int ReadAndWrite(FILE *fpSrc, FILE *fpDest, void *buffer, uint32_t size,
+                 const char *err) {
   if (!size) {
     return 0;
   }
 
   if (fread(buffer, size, 1, fpSrc) != 1) {
     fprintf(stderr, "ERROR: Could not read %s\n", err);
     return -1;
   }
@@ -247,24 +232,22 @@ ReadAndWrite(FILE *fpSrc, FILE *fpDest, 
  * Writes out a copy of the MAR at src but with the signature block stripped.
  *
  * @param  src  The path of the source MAR file
  * @param  dest The path of the MAR file to write out that
                 has no signature block
  * @return 0 on success
  *         -1 on error
 */
-int
-strip_signature_block(const char *src, const char * dest)
-{
-  uint32_t offsetToIndex, dstOffsetToIndex, indexLength,
-    numSignatures = 0, leftOver;
+int strip_signature_block(const char *src, const char *dest) {
+  uint32_t offsetToIndex, dstOffsetToIndex, indexLength, numSignatures = 0,
+                                                         leftOver;
   int32_t stripAmount = 0;
-  int64_t oldPos, sizeOfEntireMAR = 0, realSizeOfSrcMAR, numBytesToCopy,
-    numChunks, i;
+  int64_t oldPos, numChunks, i, realSizeOfSrcMAR, numBytesToCopy,
+      sizeOfEntireMAR = 0;
   FILE *fpSrc = NULL, *fpDest = NULL;
   int rv = -1, hasSignatureBlock;
   char buf[BLOCKSIZE];
   char *indexBuf = NULL;
 
   if (!src || !dest) {
     fprintf(stderr, "ERROR: Invalid parameter passed in.\n");
     return -1;
@@ -309,18 +292,17 @@ strip_signature_block(const char *src, c
   realSizeOfSrcMAR = ftello(fpSrc);
   if (fseeko(fpSrc, oldPos, SEEK_SET)) {
     fprintf(stderr, "ERROR: Could not seek back to current location.\n");
     goto failure;
   }
 
   if (hasSignatureBlock) {
     /* Get the MAR length and adjust its size */
-    if (fread(&sizeOfEntireMAR,
-              sizeof(sizeOfEntireMAR), 1, fpSrc) != 1) {
+    if (fread(&sizeOfEntireMAR, sizeof(sizeOfEntireMAR), 1, fpSrc) != 1) {
       fprintf(stderr, "ERROR: Could read mar size\n");
       goto failure;
     }
     sizeOfEntireMAR = NETWORK_TO_HOST64(sizeOfEntireMAR);
     if (sizeOfEntireMAR != realSizeOfSrcMAR) {
       fprintf(stderr, "ERROR: Source MAR is not of the right size\n");
       goto failure;
     }
@@ -414,43 +396,41 @@ strip_signature_block(const char *src, c
   /* Read each file and write it to the MAR file */
   for (i = 0; i < numChunks; ++i) {
     if (ReadAndWrite(fpSrc, fpDest, buf, BLOCKSIZE, "content block")) {
       goto failure;
     }
   }
 
   /* Write out the left over */
-  if (ReadAndWrite(fpSrc, fpDest, buf,
-                   leftOver, "left over content block")) {
+  if (ReadAndWrite(fpSrc, fpDest, buf, leftOver, "left over content block")) {
     goto failure;
   }
 
   /* Length of the index */
-  if (ReadAndWrite(fpSrc, fpDest, &indexLength,
-                   sizeof(indexLength), "index length")) {
+  if (ReadAndWrite(fpSrc, fpDest, &indexLength, sizeof(indexLength),
+                   "index length")) {
     goto failure;
   }
   indexLength = ntohl(indexLength);
 
   /* Consume the index and adjust each index by the difference */
   indexBuf = malloc(indexLength);
   if (fread(indexBuf, indexLength, 1, fpSrc) != 1) {
     fprintf(stderr, "ERROR: Could not read index\n");
     goto failure;
   }
 
   /* Adjust each entry in the index */
   if (hasSignatureBlock) {
     AdjustIndexContentOffsets(indexBuf, indexLength, -stripAmount);
   } else {
-    AdjustIndexContentOffsets(indexBuf, indexLength,
-                              sizeof(sizeOfEntireMAR) +
-                              sizeof(numSignatures) -
-                              stripAmount);
+    AdjustIndexContentOffsets(
+        indexBuf, indexLength,
+        sizeof(sizeOfEntireMAR) + sizeof(numSignatures) - stripAmount);
   }
 
   if (fwrite(indexBuf, indexLength, 1, fpDest) != 1) {
     fprintf(stderr, "ERROR: Could not write index\n");
     goto failure;
   }
 
   rv = 0;
@@ -480,20 +460,18 @@ failure:
 /**
  * Extracts a signature from a MAR file, base64 encodes it, and writes it out
  *
  * @param  src       The path of the source MAR file
  * @param  sigIndex  The index of the signature to extract
  * @param  dest      The path of file to write the signature to
  * @return 0 on success
  *         -1 on error
-*/
-int
-extract_signature(const char *src, uint32_t sigIndex, const char * dest)
-{
+ */
+int extract_signature(const char *src, uint32_t sigIndex, const char *dest) {
   FILE *fpSrc = NULL, *fpDest = NULL;
   uint32_t i;
   uint32_t signatureCount;
   uint32_t signatureLen;
   uint8_t *extractedSignature = NULL;
   char *base64Encoded = NULL;
   int rv = -1;
   if (!src || !dest) {
@@ -594,31 +572,30 @@ failure:
 }
 
 /**
  * Imports a base64 encoded signature into a MAR file
  *
  * @param  src           The path of the source MAR file
  * @param  sigIndex      The index of the signature to import
  * @param  base64SigFile A file which contains the signature to import
- * @param  dest          The path of the destination MAR file with replaced signature
+ * @param  dest          The path of the destination MAR file with replaced
+ *                       signature
  * @return 0 on success
  *         -1 on error
-*/
-int
-import_signature(const char *src, uint32_t sigIndex,
-                 const char *base64SigFile, const char *dest)
-{
+ */
+int import_signature(const char *src, uint32_t sigIndex,
+                     const char *base64SigFile, const char *dest) {
   int rv = -1;
   FILE *fpSrc = NULL;
   FILE *fpDest = NULL;
   FILE *fpSigFile = NULL;
   uint32_t i;
-  uint32_t signatureCount, signatureLen, signatureAlgorithmID,
-           numChunks, leftOver;
+  uint32_t signatureCount, signatureLen, signatureAlgorithmID, numChunks,
+      leftOver;
   char buf[BLOCKSIZE];
   uint64_t sizeOfSrcMAR, sizeOfBase64EncodedFile;
   char *passedInSignatureB64 = NULL;
   uint8_t *passedInSignatureRaw = NULL;
   uint8_t *extractedMARSignature = NULL;
   unsigned int passedInSignatureLenRaw;
 
   if (!src || !dest) {
@@ -633,17 +610,17 @@ import_signature(const char *src, uint32
   }
 
   fpDest = fopen(dest, "wb");
   if (!fpDest) {
     fprintf(stderr, "ERROR: could not open dest file: %s\n", dest);
     goto failure;
   }
 
-  fpSigFile = fopen(base64SigFile , "rb");
+  fpSigFile = fopen(base64SigFile, "rb");
   if (!fpSigFile) {
     fprintf(stderr, "ERROR: could not open sig file: %s\n", base64SigFile);
     goto failure;
   }
 
   /* Get the src file size */
   if (fseeko(fpSrc, 0, SEEK_END)) {
     fprintf(stderr, "ERROR: Could not seek to end of src file.\n");
@@ -655,46 +632,47 @@ import_signature(const char *src, uint32
     goto failure;
   }
 
   /* Get the sig file size */
   if (fseeko(fpSigFile, 0, SEEK_END)) {
     fprintf(stderr, "ERROR: Could not seek to end of sig file.\n");
     goto failure;
   }
-  sizeOfBase64EncodedFile= ftello(fpSigFile);
+  sizeOfBase64EncodedFile = ftello(fpSigFile);
   if (fseeko(fpSigFile, 0, SEEK_SET)) {
     fprintf(stderr, "ERROR: Could not seek to start of sig file.\n");
     goto failure;
   }
 
   /* Read in the base64 encoded signature to import */
   passedInSignatureB64 = malloc(sizeOfBase64EncodedFile + 1);
   passedInSignatureB64[sizeOfBase64EncodedFile] = '\0';
   if (fread(passedInSignatureB64, sizeOfBase64EncodedFile, 1, fpSigFile) != 1) {
     fprintf(stderr, "ERROR: Could read b64 sig file.\n");
     goto failure;
   }
 
   /* Decode the base64 encoded data */
-  passedInSignatureRaw = ATOB_AsciiToData(passedInSignatureB64, &passedInSignatureLenRaw);
+  passedInSignatureRaw =
+      ATOB_AsciiToData(passedInSignatureB64, &passedInSignatureLenRaw);
   if (!passedInSignatureRaw) {
     fprintf(stderr, "ERROR: could not obtain base64 decoded data\n");
     goto failure;
   }
 
   /* Read everything up until the signature block offset and write it out */
-  if (ReadAndWrite(fpSrc, fpDest, buf,
-                   SIGNATURE_BLOCK_OFFSET, "signature block offset")) {
+  if (ReadAndWrite(fpSrc, fpDest, buf, SIGNATURE_BLOCK_OFFSET,
+                   "signature block offset")) {
     goto failure;
   }
 
   /* Get the number of signatures */
-  if (ReadAndWrite(fpSrc, fpDest, &signatureCount,
-                   sizeof(signatureCount), "signature count")) {
+  if (ReadAndWrite(fpSrc, fpDest, &signatureCount, sizeof(signatureCount),
+                   "signature count")) {
     goto failure;
   }
   signatureCount = ntohl(signatureCount);
   if (signatureCount > MAX_SIGNATURES) {
     fprintf(stderr, "ERROR: Signature count was out of range\n");
     goto failure;
   }
 
@@ -703,25 +681,24 @@ import_signature(const char *src, uint32
     goto failure;
   }
 
   /* Read and write the whole signature block, but if we reach the
      signature offset, then we should replace it with the specified
      base64 decoded signature */
   for (i = 0; i < signatureCount; i++) {
     /* Read/Write the signature algorithm ID */
-    if (ReadAndWrite(fpSrc, fpDest,
-                     &signatureAlgorithmID,
+    if (ReadAndWrite(fpSrc, fpDest, &signatureAlgorithmID,
                      sizeof(signatureAlgorithmID), "sig algorithm ID")) {
       goto failure;
     }
 
     /* Read/Write the signature length */
-    if (ReadAndWrite(fpSrc, fpDest,
-                     &signatureLen, sizeof(signatureLen), "sig length")) {
+    if (ReadAndWrite(fpSrc, fpDest, &signatureLen, sizeof(signatureLen),
+                     "sig length")) {
       goto failure;
     }
     signatureLen = ntohl(signatureLen);
 
     /* Get the signature */
     if (extractedMARSignature) {
       free(extractedMARSignature);
     }
@@ -733,24 +710,24 @@ import_signature(const char *src, uint32
         goto failure;
       }
 
       if (fread(extractedMARSignature, signatureLen, 1, fpSrc) != 1) {
         fprintf(stderr, "ERROR: Could not read signature\n");
         goto failure;
       }
 
-      if (fwrite(passedInSignatureRaw, passedInSignatureLenRaw,
-                 1, fpDest) != 1) {
+      if (fwrite(passedInSignatureRaw, passedInSignatureLenRaw, 1, fpDest) !=
+          1) {
         fprintf(stderr, "ERROR: Could not write signature\n");
         goto failure;
       }
     } else {
-      if (ReadAndWrite(fpSrc, fpDest,
-                       extractedMARSignature, signatureLen, "signature")) {
+      if (ReadAndWrite(fpSrc, fpDest, extractedMARSignature, signatureLen,
+                       "signature")) {
         goto failure;
       }
     }
   }
 
   /* We replaced the signature so let's just skip past the rest o the
      file. */
   numChunks = (sizeOfSrcMAR - ftello(fpSrc)) / BLOCKSIZE;
@@ -802,39 +779,34 @@ failure:
   return rv;
 }
 
 /**
  * Writes out a copy of the MAR at src but with embedded signatures.
  * The passed in MAR file must not already be signed or an error will
  * be returned.
  *
- * @param  NSSConfigDir  The NSS directory containing the private key for signing
+ * @param  NSSConfigDir  The NSS directory containing the private key for
+ *                       signing
  * @param  certNames     The nicknames of the certificate to use for signing
  * @param  certCount     The number of certificate names contained in certNames.
  *                       One signature will be produced for each certificate.
  * @param  src           The path of the source MAR file to sign
  * @param  dest          The path of the MAR file to write out that is signed
  * @return 0 on success
  *         -1 on error
-*/
-int
-mar_repackage_and_sign(const char *NSSConfigDir,
-                       const char * const *certNames,
-                       uint32_t certCount,
-                       const char *src,
-                       const char *dest)
-{
-  uint32_t offsetToIndex, dstOffsetToIndex, indexLength,
-    numSignatures = 0, leftOver,
-    signatureAlgorithmID, signatureSectionLength = 0;
+ */
+int mar_repackage_and_sign(const char *NSSConfigDir,
+                           const char *const *certNames, uint32_t certCount,
+                           const char *src, const char *dest) {
+  uint32_t offsetToIndex, dstOffsetToIndex, indexLength, leftOver,
+      signatureAlgorithmID, numSignatures = 0, signatureSectionLength = 0;
   uint32_t signatureLengths[MAX_SIGNATURES];
-  int64_t oldPos, sizeOfEntireMAR = 0, realSizeOfSrcMAR,
-    signaturePlaceholderOffset, numBytesToCopy,
-    numChunks, i;
+  int64_t oldPos, numChunks, i, realSizeOfSrcMAR, signaturePlaceholderOffset,
+      numBytesToCopy, sizeOfEntireMAR = 0;
   FILE *fpSrc = NULL, *fpDest = NULL;
   int rv = -1, hasSignatureBlock;
   SGNContext *ctxs[MAX_SIGNATURES];
   SECItem secItems[MAX_SIGNATURES];
   char buf[BLOCKSIZE];
   SECKEYPrivateKey *privKeys[MAX_SIGNATURES];
   CERTCertificate *certs[MAX_SIGNATURES];
   char *indexBuf = NULL;
@@ -872,27 +844,26 @@ mar_repackage_and_sign(const char *NSSCo
 
   /* Determine if the source MAR file has the new fields for signing or not */
   if (get_mar_file_info(src, &hasSignatureBlock, NULL, NULL, NULL, NULL)) {
     fprintf(stderr, "ERROR: could not determine if MAR is old or new.\n");
     goto failure;
   }
 
   for (k = 0; k < certCount; k++) {
-    if (NSSSignBegin(certNames[k], &ctxs[k], &privKeys[k],
-                     &certs[k], &signatureLengths[k])) {
+    if (NSSSignBegin(certNames[k], &ctxs[k], &privKeys[k], &certs[k],
+                     &signatureLengths[k])) {
       fprintf(stderr, "ERROR: NSSSignBegin failed\n");
       goto failure;
     }
   }
 
   /* MAR ID */
-  if (ReadWriteAndUpdateSignatures(fpSrc, fpDest,
-                                   buf, MAR_ID_SIZE,
-                                   ctxs, certCount, "MAR ID")) {
+  if (ReadWriteAndUpdateSignatures(fpSrc, fpDest, buf, MAR_ID_SIZE, ctxs,
+                                   certCount, "MAR ID")) {
     goto failure;
   }
 
   /* Offset to index */
   if (fread(&offsetToIndex, sizeof(offsetToIndex), 1, fpSrc) != 1) {
     fprintf(stderr, "ERROR: Could not read offset\n");
     goto failure;
   }
@@ -907,18 +878,17 @@ mar_repackage_and_sign(const char *NSSCo
   realSizeOfSrcMAR = ftello(fpSrc);
   if (fseeko(fpSrc, oldPos, SEEK_SET)) {
     fprintf(stderr, "ERROR: Could not seek back to current location.\n");
     goto failure;
   }
 
   if (hasSignatureBlock) {
     /* Get the MAR length and adjust its size */
-    if (fread(&sizeOfEntireMAR,
-              sizeof(sizeOfEntireMAR), 1, fpSrc) != 1) {
+    if (fread(&sizeOfEntireMAR, sizeof(sizeOfEntireMAR), 1, fpSrc) != 1) {
       fprintf(stderr, "ERROR: Could read mar size\n");
       goto failure;
     }
     sizeOfEntireMAR = NETWORK_TO_HOST64(sizeOfEntireMAR);
     if (sizeOfEntireMAR != realSizeOfSrcMAR) {
       fprintf(stderr, "ERROR: Source MAR is not of the right size\n");
       goto failure;
     }
@@ -943,18 +913,17 @@ mar_repackage_and_sign(const char *NSSCo
   if (((int64_t)offsetToIndex) > sizeOfEntireMAR) {
     fprintf(stderr, "ERROR: Offset to index is larger than the file size.\n");
     goto failure;
   }
 
   /* Calculate the total signature block length */
   for (k = 0; k < certCount; k++) {
     signatureSectionLength += sizeof(signatureAlgorithmID) +
-                              sizeof(signatureLengths[k]) +
-                              signatureLengths[k];
+                              sizeof(signatureLengths[k]) + signatureLengths[k];
   }
   dstOffsetToIndex = offsetToIndex;
   if (!hasSignatureBlock) {
     dstOffsetToIndex += sizeof(sizeOfEntireMAR) + sizeof(numSignatures);
   }
   dstOffsetToIndex += signatureSectionLength;
 
   /* Write out the index offset */
@@ -979,40 +948,39 @@ mar_repackage_and_sign(const char *NSSCo
                                "size of MAR")) {
     goto failure;
   }
   sizeOfEntireMAR = NETWORK_TO_HOST64(sizeOfEntireMAR);
 
   /* Write out the number of signatures */
   numSignatures = certCount;
   numSignatures = htonl(numSignatures);
-  if (WriteAndUpdateSignatures(fpDest, &numSignatures,
-                               sizeof(numSignatures), ctxs, certCount,
-                               "num signatures")) {
+  if (WriteAndUpdateSignatures(fpDest, &numSignatures, sizeof(numSignatures),
+                               ctxs, certCount, "num signatures")) {
     goto failure;
   }
   numSignatures = ntohl(numSignatures);
 
   signaturePlaceholderOffset = ftello(fpDest);
 
   for (k = 0; k < certCount; k++) {
     /* Write out the signature algorithm ID, Only an ID of 2 is supported */
     signatureAlgorithmID = htonl(2);
     if (WriteAndUpdateSignatures(fpDest, &signatureAlgorithmID,
-                                 sizeof(signatureAlgorithmID),
-                                 ctxs, certCount, "num signatures")) {
+                                 sizeof(signatureAlgorithmID), ctxs, certCount,
+                                 "num signatures")) {
       goto failure;
     }
     signatureAlgorithmID = ntohl(signatureAlgorithmID);
 
     /* Write out the signature length */
     signatureLengths[k] = htonl(signatureLengths[k]);
     if (WriteAndUpdateSignatures(fpDest, &signatureLengths[k],
-                                 sizeof(signatureLengths[k]),
-                                 ctxs, certCount, "signature length")) {
+                                 sizeof(signatureLengths[k]), ctxs, certCount,
+                                 "signature length")) {
       goto failure;
     }
     signatureLengths[k] = ntohl(signatureLengths[k]);
 
     /* Write out a placeholder for the signature, we'll come back to this later
       *** THIS IS NOT SIGNED because it is a placeholder that will be replaced
           below, plus it is going to be the signature itself. *** */
     memset(buf, 0, sizeof(buf));
@@ -1030,27 +998,25 @@ mar_repackage_and_sign(const char *NSSCo
     goto failure;
   }
   numBytesToCopy = ((int64_t)offsetToIndex) - ftello(fpSrc);
   numChunks = numBytesToCopy / BLOCKSIZE;
   leftOver = numBytesToCopy % BLOCKSIZE;
 
   /* Read each file and write it to the MAR file */
   for (i = 0; i < numChunks; ++i) {
-    if (ReadWriteAndUpdateSignatures(fpSrc, fpDest, buf,
-                                     BLOCKSIZE, ctxs, certCount,
-                                     "content block")) {
+    if (ReadWriteAndUpdateSignatures(fpSrc, fpDest, buf, BLOCKSIZE, ctxs,
+                                     certCount, "content block")) {
       goto failure;
     }
   }
 
   /* Write out the left over */
-  if (ReadWriteAndUpdateSignatures(fpSrc, fpDest, buf,
-                                   leftOver, ctxs, certCount,
-                                   "left over content block")) {
+  if (ReadWriteAndUpdateSignatures(fpSrc, fpDest, buf, leftOver, ctxs,
+                                   certCount, "left over content block")) {
     goto failure;
   }
 
   /* Length of the index */
   if (ReadWriteAndUpdateSignatures(fpSrc, fpDest, &indexLength,
                                    sizeof(indexLength), ctxs, certCount,
                                    "index length")) {
     goto failure;
@@ -1064,23 +1030,22 @@ mar_repackage_and_sign(const char *NSSCo
     goto failure;
   }
 
   /* Adjust each entry in the index */
   if (hasSignatureBlock) {
     AdjustIndexContentOffsets(indexBuf, indexLength, signatureSectionLength);
   } else {
     AdjustIndexContentOffsets(indexBuf, indexLength,
-                              sizeof(sizeOfEntireMAR) +
-                              sizeof(numSignatures) +
-                              signatureSectionLength);
+                              sizeof(sizeOfEntireMAR) + sizeof(numSignatures) +
+                                  signatureSectionLength);
   }
 
-  if (WriteAndUpdateSignatures(fpDest, indexBuf,
-                               indexLength, ctxs, certCount, "index")) {
+  if (WriteAndUpdateSignatures(fpDest, indexBuf, indexLength, ctxs, certCount,
+                               "index")) {
     goto failure;
   }
 
   /* Ensure that we don't sign a file that is too large to be accepted by
      the verification function. */
   if (ftello(fpDest) > MAX_SIZE_OF_MAR_FILE) {
     goto failure;
   }
@@ -1100,24 +1065,25 @@ mar_repackage_and_sign(const char *NSSCo
   /* Get back to the location of the signature placeholder */
   if (fseeko(fpDest, signaturePlaceholderOffset, SEEK_SET)) {
     fprintf(stderr, "ERROR: Could not seek to signature offset\n");
     goto failure;
   }
 
   for (k = 0; k < certCount; k++) {
     /* Skip to the position of the next signature */
-    if (fseeko(fpDest, sizeof(signatureAlgorithmID) +
-               sizeof(signatureLengths[k]), SEEK_CUR)) {
+    if (fseeko(fpDest,
+               sizeof(signatureAlgorithmID) + sizeof(signatureLengths[k]),
+               SEEK_CUR)) {
       fprintf(stderr, "ERROR: Could not seek to signature offset\n");
       goto failure;
     }
 
     /* Write out the calculated signature.
-      *** THIS IS NOT SIGNED because it is the signature itself. *** */
+     *** THIS IS NOT SIGNED because it is the signature itself. *** */
     if (fwrite(secItems[k].data, secItems[k].len, 1, fpDest) != 1) {
       fprintf(stderr, "ERROR: Could not write signature\n");
       goto failure;
     }
   }
 
   rv = 0;
 failure:
--- a/modules/libmar/src/mar.h
+++ b/modules/libmar/src/mar.h
@@ -14,59 +14,55 @@
 extern "C" {
 #endif
 
 /* We have a MAX_SIGNATURES limit so that an invalid MAR will never
  * waste too much of either updater's or signmar's time.
  * It is also used at various places internally and will affect memory usage.
  * If you want to increase this value above 9 then you need to adjust parsing
  * code in tool/mar.c.
-*/
+ */
 #define MAX_SIGNATURES 8
 #ifdef __cplusplus
 static_assert(MAX_SIGNATURES <= 9, "too many signatures");
 #else
 MOZ_STATIC_ASSERT(MAX_SIGNATURES <= 9, "too many signatures");
 #endif
 
-struct ProductInformationBlock
-{
+struct ProductInformationBlock {
   const char* MARChannelID;
   const char* productVersion;
 };
 
 /**
  * The MAR item data structure.
  */
-typedef struct MarItem_
-{
-  struct MarItem_* next;  /* private field */
-  uint32_t offset;        /* offset into archive */
-  uint32_t length;        /* length of data in bytes */
-  uint32_t flags;         /* contains file mode bits */
-  char name[1];           /* file path */
+typedef struct MarItem_ {
+  struct MarItem_* next; /* private field */
+  uint32_t offset;       /* offset into archive */
+  uint32_t length;       /* length of data in bytes */
+  uint32_t flags;        /* contains file mode bits */
+  char name[1];          /* file path */
 } MarItem;
 
 /**
  * File offset and length for tracking access of byte indexes
  */
-typedef struct SeenIndex_
-{
+typedef struct SeenIndex_ {
   struct SeenIndex_* next; /* private field */
   uint32_t offset;         /* offset into archive */
   uint32_t length;         /* length of the data in bytes */
 } SeenIndex;
 
 #define TABLESIZE 256
 
 /**
  * Mozilla ARchive (MAR) file data structure
  */
-struct MarFile_
-{
+struct MarFile_ {
   FILE* fp;                       /* file pointer to the archive */
   MarItem* item_table[TABLESIZE]; /* hash table of files in the archive */
   SeenIndex* index_list;          /* file indexes processed */
   int item_table_is_valid;        /* header and index validation flag */
 };
 
 typedef struct MarFile_ MarFile;
 
@@ -80,113 +76,99 @@ typedef struct MarFile_ MarFile;
 typedef int (*MarItemCallback)(MarFile* mar, const MarItem* item, void* data);
 
 /**
  * Open a MAR file for reading.
  * @param path      Specifies the path to the MAR file to open.  This path must
  *                  be compatible with fopen.
  * @return          NULL if an error occurs.
  */
-MarFile*
-mar_open(const char* path);
+MarFile* mar_open(const char* path);
 
 #ifdef XP_WIN
-MarFile *mar_wopen(const wchar_t *path);
+MarFile* mar_wopen(const wchar_t* path);
 #endif
 
 /**
  * Close a MAR file that was opened using mar_open.
  * @param mar       The MarFile object to close.
  */
-void
-mar_close(MarFile* mar);
+void mar_close(MarFile* mar);
 
 /**
  * Find an item in the MAR file by name.
  * @param mar       The MarFile object to query.
  * @param item      The name of the item to query.
  * @return          A const reference to a MAR item or NULL if not found.
  */
-const MarItem*
-mar_find_item(MarFile* mar, const char* item);
+const MarItem* mar_find_item(MarFile* mar, const char* item);
 
 /**
  * Enumerate all MAR items via callback function.
  * @param mar       The MAR file to enumerate.
  * @param callback  The function to call for each MAR item.
  * @param data      A caller specified value that is passed along to the
  *                  callback function.
  * @return          0 if the enumeration ran to completion.  Otherwise, any
  *                  non-zero return value from the callback is returned.
  */
-int
-mar_enum_items(MarFile* mar, MarItemCallback callback, void* data);
+int mar_enum_items(MarFile* mar, MarItemCallback callback, void* data);
 
 /**
  * Read from MAR item at given offset up to bufsize bytes.
  * @param mar       The MAR file to read.
  * @param item      The MAR item to read.
  * @param offset    The byte offset relative to the start of the item.
  * @param buf       A pointer to a buffer to copy the data into.
  * @param bufsize   The length of the buffer to copy the data into.
  * @return          The number of bytes written or a negative value if an
  *                  error occurs.
  */
-int
-mar_read(MarFile* mar,
-         const MarItem* item,
-         int offset,
-         uint8_t* buf,
-         int bufsize);
+int mar_read(MarFile* mar, const MarItem* item, int offset, uint8_t* buf,
+             int bufsize);
 
 /**
  * Create a MAR file from a set of files.
  * @param dest      The path to the file to create.  This path must be
  *                  compatible with fopen.
  * @param numfiles  The number of files to store in the archive.
  * @param files     The list of null-terminated file paths.  Each file
  *                  path must be compatible with fopen.
  * @param infoBlock The information to store in the product information block.
  * @return          A non-zero value if an error occurs.
  */
-int
-mar_create(const char* dest,
-           int numfiles,
-           char** files,
-           struct ProductInformationBlock* infoBlock);
+int mar_create(const char* dest, int numfiles, char** files,
+               struct ProductInformationBlock* infoBlock);
 
 /**
  * Extract a MAR file to the current working directory.
  * @param path      The path to the MAR file to extract.  This path must be
  *                  compatible with fopen.
  * @return          A non-zero value if an error occurs.
  */
-int
-mar_extract(const char* path);
+int mar_extract(const char* path);
 
-#define MAR_MAX_CERT_SIZE (16*1024) // Way larger than necessary
+#define MAR_MAX_CERT_SIZE (16 * 1024)  // Way larger than necessary
 
 /* Read the entire file (not a MAR file) into a newly-allocated buffer.
  * This function does not write to stderr. Instead, the caller should
  * write whatever error messages it sees fit. The caller must free the returned
  * buffer using free().
  *
  * @param filePath The path to the file that should be read.
  * @param maxSize  The maximum valid file size.
  * @param data     On success, *data will point to a newly-allocated buffer
  *                 with the file's contents in it.
  * @param size     On success, *size will be the size of the created buffer.
  *
  * @return 0 on success, -1 on error
  */
-int
-mar_read_entire_file(const char* filePath,
-                     uint32_t maxSize,
-                     /*out*/ const uint8_t** data,
-                     /*out*/ uint32_t* size);
+int mar_read_entire_file(const char* filePath, uint32_t maxSize,
+                         /*out*/ const uint8_t** data,
+                         /*out*/ uint32_t* size);
 
 /**
  * Verifies a MAR file by verifying each signature with the corresponding
  * certificate. That is, the first signature will be verified using the first
  * certificate given, the second signature will be verified using the second
  * certificate given, etc. The signature count must exactly match the number of
  * certificates given, and all signature verifications must succeed.
  * We do not check that the certificate was issued by any trusted authority.
@@ -198,31 +180,27 @@ mar_read_entire_file(const char* filePat
  *                       file data.
  * @param certDataSizes  Pointer to the first element in an array for size of
  *                       the cert data.
  * @param certCount      The number of elements in certData and certDataSizes
  * @return 0 on success
  *         a negative number if there was an error
  *         a positive number if the signature does not verify
  */
-int
-mar_verify_signatures(MarFile* mar,
-                      const uint8_t* const* certData,
-                      const uint32_t* certDataSizes,
-                      uint32_t certCount);
+int mar_verify_signatures(MarFile* mar, const uint8_t* const* certData,
+                          const uint32_t* certDataSizes, uint32_t certCount);
 
 /**
  * Reads the product info block from the MAR file's additional block section.
  * The caller is responsible for freeing the fields in infoBlock
  * if the return is successful.
  *
  * @param infoBlock Out parameter for where to store the result to
  * @return 0 on success, -1 on failure
-*/
-int
-mar_read_product_info_block(MarFile* mar,
-                            struct ProductInformationBlock* infoBlock);
+ */
+int mar_read_product_info_block(MarFile* mar,
+                                struct ProductInformationBlock* infoBlock);
 
 #ifdef __cplusplus
 }
 #endif
 
-#endif  /* MAR_H__ */
+#endif /* MAR_H__ */
--- a/modules/libmar/src/mar_cmdline.h
+++ b/modules/libmar/src/mar_cmdline.h
@@ -26,85 +26,77 @@ struct ProductInformationBlock;
  * @param offsetAdditionalBlocks Optional out parameter for the offset to the
  *                               first additional block. Value is only valid if
  *                               hasAdditionalBlocks is not equal to 0.
  * @param numAdditionalBlocks    Optional out parameter for the number of
  *                               additional blocks.  Value is only valid if
  *                               has_additional_blocks is not equal to 0.
  * @return 0 on success and non-zero on failure.
  */
-int get_mar_file_info(const char *path,
-                      int *hasSignatureBlock,
-                      uint32_t *numSignatures,
-                      int *hasAdditionalBlocks,
+int get_mar_file_info(const char *path, int *hasSignatureBlock,
+                      uint32_t *numSignatures, int *hasAdditionalBlocks,
                       uint32_t *offsetAdditionalBlocks,
                       uint32_t *numAdditionalBlocks);
 
 /**
  * Reads the product info block from the MAR file's additional block section.
  * The caller is responsible for freeing the fields in infoBlock
  * if the return is successful.
  *
  * @param infoBlock Out parameter for where to store the result to
  * @return 0 on success, -1 on failure
-*/
-int
-read_product_info_block(char *path,
-                        struct ProductInformationBlock *infoBlock);
+ */
+int read_product_info_block(char *path,
+                            struct ProductInformationBlock *infoBlock);
 
 /**
  * Refreshes the product information block with the new information.
  * The input MAR must not be signed or the function call will fail.
  *
  * @param path             The path to the MAR file whose product info block
  *                         should be refreshed.
  * @param infoBlock        Out parameter for where to store the result to
  * @return 0 on success, -1 on failure
-*/
-int
-refresh_product_info_block(const char *path,
-                           struct ProductInformationBlock *infoBlock);
+ */
+int refresh_product_info_block(const char *path,
+                               struct ProductInformationBlock *infoBlock);
 
 /**
  * Writes out a copy of the MAR at src but with the signature block stripped.
  *
  * @param  src  The path of the source MAR file
  * @param  dest The path of the MAR file to write out that
                 has no signature block
  * @return 0 on success
  *         -1 on error
 */
-int
-strip_signature_block(const char *src, const char * dest);
+int strip_signature_block(const char *src, const char *dest);
 
 /**
  * Extracts a signature from a MAR file, base64 encodes it, and writes it out
  *
  * @param  src       The path of the source MAR file
  * @param  sigIndex  The index of the signature to extract
  * @param  dest      The path of file to write the signature to
  * @return 0 on success
  *         -1 on error
-*/
-int
-extract_signature(const char *src, uint32_t sigIndex, const char * dest);
+ */
+int extract_signature(const char *src, uint32_t sigIndex, const char *dest);
 
 /**
  * Imports a base64 encoded signature into a MAR file
  *
  * @param  src           The path of the source MAR file
  * @param  sigIndex      The index of the signature to import
  * @param  base64SigFile A file which contains the signature to import
- * @param  dest          The path of the destination MAR file with replaced signature
+ * @param  dest          The path of the destination MAR file with replaced
+ *                       signature
  * @return 0 on success
  *         -1 on error
-*/
-int
-import_signature(const char *src,
-                 uint32_t sigIndex,
-                 const char * base64SigFile,
-                 const char *dest);
+ */
+int import_signature(const char *src, uint32_t sigIndex,
+                     const char *base64SigFile, const char *dest);
 
 #ifdef __cplusplus
 }
 #endif
 
-#endif  /* MAR_CMDLINE_H__ */
+#endif /* MAR_CMDLINE_H__ */
--- a/modules/libmar/src/mar_create.c
+++ b/modules/libmar/src/mar_create.c
@@ -40,22 +40,23 @@ static int mar_push(struct MarItemStack 
 
   namelen = strlen(name);
   size = MAR_ITEM_SIZE(namelen);
 
   if (stack->size_allocated - stack->size_used < size) {
     /* increase size of stack */
     size_t size_needed = ROUND_UP(stack->size_used + size, BLOCKSIZE);
     stack->head = realloc(stack->head, size_needed);
-    if (!stack->head)
+    if (!stack->head) {
       return -1;
+    }
     stack->size_allocated = size_needed;
   }
 
-  data = (((char *) stack->head) + stack->size_used);
+  data = (((char *)stack->head) + stack->size_used);
 
   n_offset = htonl(stack->last_offset);
   n_length = htonl(length);
   n_flags = htonl(flags);
 
   memcpy(data, &n_offset, sizeof(n_offset));
   data += sizeof(n_offset);
 
@@ -99,26 +100,23 @@ static int mar_concat_file(FILE *fp, con
 /**
  * Writes out the product information block to the specified file.
  *
  * @param fp           The opened MAR file being created.
  * @param stack        A pointer to the MAR item stack being used to create
  *                     the MAR
  * @param infoBlock    The product info block to store in the file.
  * @return 0 on success.
-*/
-static int
-mar_concat_product_info_block(FILE *fp,
-                              struct MarItemStack *stack,
-                              struct ProductInformationBlock *infoBlock)
-{
+ */
+static int mar_concat_product_info_block(
+    FILE *fp, struct MarItemStack *stack,
+    struct ProductInformationBlock *infoBlock) {
   char buf[PIB_MAX_MAR_CHANNEL_ID_SIZE + PIB_MAX_PRODUCT_VERSION_SIZE];
   uint32_t additionalBlockID = 1, infoBlockSize, unused;
-  if (!fp || !infoBlock ||
-      !infoBlock->MARChannelID ||
+  if (!fp || !infoBlock || !infoBlock->MARChannelID ||
       !infoBlock->productVersion) {
     return -1;
   }
 
   /* The MAR channel name must be < 64 bytes per the spec */
   if (strlen(infoBlock->MARChannelID) > PIB_MAX_MAR_CHANNEL_ID_SIZE) {
     return -1;
   }
@@ -127,55 +125,51 @@ mar_concat_product_info_block(FILE *fp,
   if (strlen(infoBlock->productVersion) > PIB_MAX_PRODUCT_VERSION_SIZE) {
     return -1;
   }
 
   /* Although we don't need the product information block size to include the
      maximum MAR channel name and product version, we allocate the maximum
      amount to make it easier to modify the MAR file for repurposing MAR files
      to different MAR channels. + 2 is for the NULL terminators. */
-  infoBlockSize = sizeof(infoBlockSize) +
-                  sizeof(additionalBlockID) +
-                  PIB_MAX_MAR_CHANNEL_ID_SIZE +
-                  PIB_MAX_PRODUCT_VERSION_SIZE + 2;
+  infoBlockSize = sizeof(infoBlockSize) + sizeof(additionalBlockID) +
+                  PIB_MAX_MAR_CHANNEL_ID_SIZE + PIB_MAX_PRODUCT_VERSION_SIZE +
+                  2;
   if (stack) {
     stack->last_offset += infoBlockSize;
   }
 
   /* Write out the product info block size */
   infoBlockSize = htonl(infoBlockSize);
-  if (fwrite(&infoBlockSize,
-      sizeof(infoBlockSize), 1, fp) != 1) {
+  if (fwrite(&infoBlockSize, sizeof(infoBlockSize), 1, fp) != 1) {
     return -1;
   }
   infoBlockSize = ntohl(infoBlockSize);
 
   /* Write out the product info block ID */
   additionalBlockID = htonl(additionalBlockID);
-  if (fwrite(&additionalBlockID,
-      sizeof(additionalBlockID), 1, fp) != 1) {
+  if (fwrite(&additionalBlockID, sizeof(additionalBlockID), 1, fp) != 1) {
     return -1;
   }
   additionalBlockID = ntohl(additionalBlockID);
 
   /* Write out the channel name and NULL terminator */
-  if (fwrite(infoBlock->MARChannelID,
-      strlen(infoBlock->MARChannelID) + 1, 1, fp) != 1) {
+  if (fwrite(infoBlock->MARChannelID, strlen(infoBlock->MARChannelID) + 1, 1,
+             fp) != 1) {
     return -1;
   }
 
   /* Write out the product version string and NULL terminator */
-  if (fwrite(infoBlock->productVersion,
-      strlen(infoBlock->productVersion) + 1, 1, fp) != 1) {
+  if (fwrite(infoBlock->productVersion, strlen(infoBlock->productVersion) + 1,
+             1, fp) != 1) {
     return -1;
   }
 
   /* Write out the rest of the block that is unused */
-  unused = infoBlockSize - (sizeof(infoBlockSize) +
-                            sizeof(additionalBlockID) +
+  unused = infoBlockSize - (sizeof(infoBlockSize) + sizeof(additionalBlockID) +
                             strlen(infoBlock->MARChannelID) +
                             strlen(infoBlock->productVersion) + 2);
   memset(buf, 0, sizeof(buf));
   if (fwrite(buf, unused, 1, fp) != 1) {
     return -1;
   }
   return 0;
 }
@@ -183,33 +177,28 @@ mar_concat_product_info_block(FILE *fp,
 /**
  * Refreshes the product information block with the new information.
  * The input MAR must not be signed or the function call will fail.
  *
  * @param path             The path to the MAR file whose product info block
  *                         should be refreshed.
  * @param infoBlock        Out parameter for where to store the result to
  * @return 0 on success, -1 on failure
-*/
-int
-refresh_product_info_block(const char *path,
-                           struct ProductInformationBlock *infoBlock)
-{
-  FILE *fp ;
+ */
+int refresh_product_info_block(const char *path,
+                               struct ProductInformationBlock *infoBlock) {
+  FILE *fp;
   int rv;
   uint32_t numSignatures, additionalBlockSize, additionalBlockID,
-    offsetAdditionalBlocks, numAdditionalBlocks, i;
+      offsetAdditionalBlocks, numAdditionalBlocks, i;
   int additionalBlocks, hasSignatureBlock;
   int64_t oldPos;
 
-  rv = get_mar_file_info(path,
-                         &hasSignatureBlock,
-                         &numSignatures,
-                         &additionalBlocks,
-                         &offsetAdditionalBlocks,
+  rv = get_mar_file_info(path, &hasSignatureBlock, &numSignatures,
+                         &additionalBlocks, &offsetAdditionalBlocks,
                          &numAdditionalBlocks);
   if (rv) {
     fprintf(stderr, "ERROR: Could not obtain MAR information.\n");
     return -1;
   }
 
   if (hasSignatureBlock && numSignatures) {
     fprintf(stderr, "ERROR: Cannot refresh a signed MAR\n");
@@ -228,28 +217,24 @@ refresh_product_info_block(const char *p
     return -1;
   }
 
   for (i = 0; i < numAdditionalBlocks; ++i) {
     /* Get the position of the start of this block */
     oldPos = ftello(fp);
 
     /* Read the additional block size */
-    if (fread(&additionalBlockSize,
-              sizeof(additionalBlockSize),
-              1, fp) != 1) {
+    if (fread(&additionalBlockSize, sizeof(additionalBlockSize), 1, fp) != 1) {
       fclose(fp);
       return -1;
     }
     additionalBlockSize = ntohl(additionalBlockSize);
 
     /* Read the additional block ID */
-    if (fread(&additionalBlockID,
-              sizeof(additionalBlockID),
-              1, fp) != 1) {
+    if (fread(&additionalBlockID, sizeof(additionalBlockID), 1, fp) != 1) {
       fclose(fp);
       return -1;
     }
     additionalBlockID = ntohl(additionalBlockID);
 
     if (PRODUCT_INFO_BLOCK_ID == additionalBlockID) {
       if (fseeko(fp, oldPos, SEEK_SET)) {
         fprintf(stderr, "Could not seek back to Product Information Block\n");
@@ -286,114 +271,121 @@ refresh_product_info_block(const char *p
  * @param dest      The path to the file to create.  This path must be
  *                  compatible with fopen.
  * @param numfiles  The number of files to store in the archive.
  * @param files     The list of null-terminated file paths.  Each file
  *                  path must be compatible with fopen.
  * @param infoBlock The information to store in the product information block.
  * @return A non-zero value if an error occurs.
  */
-int mar_create(const char *dest, int
-               num_files, char **files,
+int mar_create(const char *dest, int num_files, char **files,
                struct ProductInformationBlock *infoBlock) {
   struct MarItemStack stack;
-  uint32_t offset_to_index = 0, size_of_index,
-    numSignatures, numAdditionalSections;
+  uint32_t offset_to_index = 0, size_of_index, numSignatures,
+           numAdditionalSections;
   uint64_t sizeOfEntireMAR = 0;
   struct stat st;
   FILE *fp;
   int i, rv = -1;
 
   memset(&stack, 0, sizeof(stack));
 
   fp = fopen(dest, "wb");
   if (!fp) {
     fprintf(stderr, "ERROR: could not create target file: %s\n", dest);
     return -1;
   }
 
-  if (fwrite(MAR_ID, MAR_ID_SIZE, 1, fp) != 1)
+  if (fwrite(MAR_ID, MAR_ID_SIZE, 1, fp) != 1) {
     goto failure;
-  if (fwrite(&offset_to_index, sizeof(uint32_t), 1, fp) != 1)
+  }
+  if (fwrite(&offset_to_index, sizeof(uint32_t), 1, fp) != 1) {
     goto failure;
+  }
 
-  stack.last_offset = MAR_ID_SIZE +
-                      sizeof(offset_to_index) +
-                      sizeof(numSignatures) +
-                      sizeof(numAdditionalSections) +
+  stack.last_offset = MAR_ID_SIZE + sizeof(offset_to_index) +
+                      sizeof(numSignatures) + sizeof(numAdditionalSections) +
                       sizeof(sizeOfEntireMAR);
 
   /* We will circle back on this at the end of the MAR creation to fill it */
   if (fwrite(&sizeOfEntireMAR, sizeof(sizeOfEntireMAR), 1, fp) != 1) {
     goto failure;
   }
 
   /* Write out the number of signatures, for now only at most 1 is supported */
   numSignatures = 0;
   if (fwrite(&numSignatures, sizeof(numSignatures), 1, fp) != 1) {
     goto failure;
   }
 
   /* Write out the number of additional sections, for now just 1
      for the product info block */
   numAdditionalSections = htonl(1);
-  if (fwrite(&numAdditionalSections,
-             sizeof(numAdditionalSections), 1, fp) != 1) {
+  if (fwrite(&numAdditionalSections, sizeof(numAdditionalSections), 1, fp) !=
+      1) {
     goto failure;
   }
   numAdditionalSections = ntohl(numAdditionalSections);
 
   if (mar_concat_product_info_block(fp, &stack, infoBlock)) {
     goto failure;
   }
 
   for (i = 0; i < num_files; ++i) {
     if (stat(files[i], &st)) {
       fprintf(stderr, "ERROR: file not found: %s\n", files[i]);
       goto failure;
     }
 
-    if (mar_push(&stack, st.st_size, st.st_mode & 0777, files[i]))
+    if (mar_push(&stack, st.st_size, st.st_mode & 0777, files[i])) {
       goto failure;
+    }
 
     /* concatenate input file to archive */
-    if (mar_concat_file(fp, files[i]))
+    if (mar_concat_file(fp, files[i])) {
       goto failure;
+    }
   }
 
   /* write out the index (prefixed with length of index) */
   size_of_index = htonl(stack.size_used);
-  if (fwrite(&size_of_index, sizeof(size_of_index), 1, fp) != 1)
+  if (fwrite(&size_of_index, sizeof(size_of_index), 1, fp) != 1) {
     goto failure;
-  if (fwrite(stack.head, stack.size_used, 1, fp) != 1)
+  }
+  if (fwrite(stack.head, stack.size_used, 1, fp) != 1) {
     goto failure;
+  }
 
   /* To protect against invalid MAR files, we assumes that the MAR file
      size is less than or equal to MAX_SIZE_OF_MAR_FILE. */
   if (ftell(fp) > MAX_SIZE_OF_MAR_FILE) {
     goto failure;
   }
 
   /* write out offset to index file in network byte order */
   offset_to_index = htonl(stack.last_offset);
-  if (fseek(fp, MAR_ID_SIZE, SEEK_SET))
+  if (fseek(fp, MAR_ID_SIZE, SEEK_SET)) {
     goto failure;
-  if (fwrite(&offset_to_index, sizeof(offset_to_index), 1, fp) != 1)
+  }
+  if (fwrite(&offset_to_index, sizeof(offset_to_index), 1, fp) != 1) {
     goto failure;
+  }
   offset_to_index = ntohl(stack.last_offset);
 
-  sizeOfEntireMAR = ((uint64_t)stack.last_offset) +
-                    stack.size_used +
-                    sizeof(size_of_index);
+  sizeOfEntireMAR =
+      ((uint64_t)stack.last_offset) + stack.size_used + sizeof(size_of_index);
   sizeOfEntireMAR = HOST_TO_NETWORK64(sizeOfEntireMAR);
-  if (fwrite(&sizeOfEntireMAR, sizeof(sizeOfEntireMAR), 1, fp) != 1)
+  if (fwrite(&sizeOfEntireMAR, sizeof(sizeOfEntireMAR), 1, fp) != 1) {
     goto failure;
+  }
   sizeOfEntireMAR = NETWORK_TO_HOST64(sizeOfEntireMAR);
 
   rv = 0;
 failure:
-  if (stack.head)
+  if (stack.head) {
     free(stack.head);
+  }
   fclose(fp);
-  if (rv)
+  if (rv) {
     remove(dest);
+  }
   return rv;
 }
--- a/modules/libmar/src/mar_extract.c
+++ b/modules/libmar/src/mar_extract.c
@@ -10,24 +10,23 @@
 #include <string.h>
 #include <stdlib.h>
 #include "mar_private.h"
 #include "mar.h"
 
 #ifdef XP_WIN
 #include <io.h>
 #include <direct.h>
+#define fdopen _fdopen
 #endif
 
 /* Ensure that the directory containing this file exists */
-static int mar_ensure_parent_dir(const char *path)
-{
+static int mar_ensure_parent_dir(const char *path) {
   char *slash = strrchr(path, '/');
-  if (slash)
-  {
+  if (slash) {
     *slash = '\0';
     mar_ensure_parent_dir(path);
 #ifdef XP_WIN
     _mkdir(path);
 #else
     mkdir(path, 0755);
 #endif
     *slash = '/';
@@ -35,49 +34,54 @@ static int mar_ensure_parent_dir(const c
   return 0;
 }
 
 static int mar_test_callback(MarFile *mar, const MarItem *item, void *unused) {
   FILE *fp;
   uint8_t buf[BLOCKSIZE];
   int fd, len, offset = 0;
 
-  if (mar_ensure_parent_dir(item->name))
+  if (mar_ensure_parent_dir(item->name)) {
     return -1;
+  }
 
 #ifdef XP_WIN
-  fd = _open(item->name, _O_BINARY|_O_CREAT|_O_TRUNC|_O_WRONLY, item->flags);
+  fd = _open(item->name, _O_BINARY | _O_CREAT | _O_TRUNC | _O_WRONLY,
+             item->flags);
 #else
   fd = creat(item->name, item->flags);
 #endif
   if (fd == -1) {
     fprintf(stderr, "ERROR: could not create file in mar_test_callback()\n");
     perror(item->name);
     return -1;
   }
 
   fp = fdopen(fd, "wb");
-  if (!fp)
+  if (!fp) {
     return -1;
+  }
 
   while ((len = mar_read(mar, item, offset, buf, sizeof(buf))) > 0) {
-    if (fwrite(buf, len, 1, fp) != 1)
+    if (fwrite(buf, len, 1, fp) != 1) {
       break;
+    }
     offset += len;
   }
 
   fclose(fp);
   return len == 0 ? 0 : -1;
 }
 
 int mar_extract(const char *path) {
   MarFile *mar;
   int rv;
 
   mar = mar_open(path);
-  if (!mar)
+  if (!mar) {
     return -1;
+  }
 
   rv = mar_enum_items(mar, mar_test_callback, NULL);
 
   mar_close(mar);
   return rv;
 }
--- a/modules/libmar/src/mar_private.h
+++ b/modules/libmar/src/mar_private.h
@@ -27,29 +27,29 @@
 
 /* Existing code makes assumptions that the file size is
    smaller than LONG_MAX. */
 MOZ_STATIC_ASSERT(MAX_SIZE_OF_MAR_FILE < ((int64_t)LONG_MAX),
                   "max mar file size is too big");
 
 /* We store at most the size up to the signature block + 4
    bytes per BLOCKSIZE bytes */
-MOZ_STATIC_ASSERT(sizeof(BLOCKSIZE) < \
-                  (SIGNATURE_BLOCK_OFFSET + sizeof(uint32_t)),
+MOZ_STATIC_ASSERT(sizeof(BLOCKSIZE) <
+                      (SIGNATURE_BLOCK_OFFSET + sizeof(uint32_t)),
                   "BLOCKSIZE is too big");
 
 /* The maximum size of any signature supported by current and future
    implementations of the signmar program. */
 #define MAX_SIGNATURE_LENGTH 2048
 
 /* Each additional block has a unique ID.
    The product information block has an ID of 1. */
 #define PRODUCT_INFO_BLOCK_ID 1
 
-#define MAR_ITEM_SIZE(namelen) (3*sizeof(uint32_t) + (namelen) + 1)
+#define MAR_ITEM_SIZE(namelen) (3 * sizeof(uint32_t) + (namelen) + 1)
 
 /* Product Information Block (PIB) constants */
 #define PIB_MAX_MAR_CHANNEL_ID_SIZE 63
 #define PIB_MAX_PRODUCT_VERSION_SIZE 31
 
 /* The mar program is compiled as a host bin so we don't have access to NSPR at
    runtime.  For that reason we use ntohl, htonl, and define HOST_TO_NETWORK64
    instead of the NSPR equivalents. */
@@ -60,20 +60,18 @@ MOZ_STATIC_ASSERT(sizeof(BLOCKSIZE) < \
 #else
 #define _FILE_OFFSET_BITS 64
 #include <netinet/in.h>
 #include <unistd.h>
 #endif
 
 #include <stdio.h>
 
-#define HOST_TO_NETWORK64(x) ( \
-  ((((uint64_t) x) & 0xFF) << 56) | \
-  ((((uint64_t) x) >> 8) & 0xFF) << 48) | \
-  (((((uint64_t) x) >> 16) & 0xFF) << 40) | \
-  (((((uint64_t) x) >> 24) & 0xFF) << 32) | \
-  (((((uint64_t) x) >> 32) & 0xFF) << 24) | \
-  (((((uint64_t) x) >> 40) & 0xFF) << 16) | \
-  (((((uint64_t) x) >> 48) & 0xFF) << 8) | \
-  (((uint64_t) x) >> 56)
+#define HOST_TO_NETWORK64(x)                                               \
+  (((((uint64_t)x) & 0xFF) << 56) | ((((uint64_t)x) >> 8) & 0xFF) << 48) | \
+      (((((uint64_t)x) >> 16) & 0xFF) << 40) |                             \
+      (((((uint64_t)x) >> 24) & 0xFF) << 32) |                             \
+      (((((uint64_t)x) >> 32) & 0xFF) << 24) |                             \
+      (((((uint64_t)x) >> 40) & 0xFF) << 16) |                             \
+      (((((uint64_t)x) >> 48) & 0xFF) << 8) | (((uint64_t)x) >> 56)
 #define NETWORK_TO_HOST64 HOST_TO_NETWORK64
 
-#endif  /* MAR_PRIVATE_H__ */
+#endif /* MAR_PRIVATE_H__ */
--- a/modules/libmar/src/mar_read.c
+++ b/modules/libmar/src/mar_read.c
@@ -6,83 +6,77 @@
 
 #include <sys/types.h>
 #include <fcntl.h>
 #include <stdlib.h>
 #include <string.h>
 #include "city.h"
 #include "mar_private.h"
 #include "mar.h"
+#ifdef XP_WIN
+#define strdup _strdup
+#endif
 
 /* This block must be at most 104 bytes.
    MAR channel name < 64 bytes, and product version < 32 bytes + 3 NULL
    terminator bytes. We only check for 96 though because we remove 8
    bytes above from the additionalBlockSize: We subtract
    sizeof(additionalBlockSize) and sizeof(additionalBlockID) */
 #define MAXADDITIONALBLOCKSIZE 96
 
-static uint32_t
-mar_hash_name(const char* name)
-{
+static uint32_t mar_hash_name(const char* name) {
   return CityHash64(name, strlen(name)) % TABLESIZE;
 }
 
-static int
-mar_insert_item(MarFile* mar,
-                const char* name,
-                int namelen,
-                uint32_t offset,
-                uint32_t length,
-                uint32_t flags)
-{
+static int mar_insert_item(MarFile* mar, const char* name, int namelen,
+                           uint32_t offset, uint32_t length, uint32_t flags) {
   MarItem *item, *root;
   uint32_t hash;
 
-  item = (MarItem *) malloc(sizeof(MarItem) + namelen);
-  if (!item)
+  item = (MarItem*)malloc(sizeof(MarItem) + namelen);
+  if (!item) {
     return -1;
+  }
   item->next = NULL;
   item->offset = offset;
   item->length = length;
   item->flags = flags;
   memcpy(item->name, name, namelen + 1);
 
   hash = mar_hash_name(name);
 
   root = mar->item_table[hash];
   if (!root) {
     mar->item_table[hash] = item;
   } else {
     /* append item */
-    while (root->next)
-      root = root->next;
+    while (root->next) root = root->next;
     root->next = item;
   }
   return 0;
 }
 
-static int
-mar_consume_index(MarFile* mar, char** buf, const char* buf_end)
-{
+static int mar_consume_index(MarFile* mar, char** buf, const char* buf_end) {
   /*
    * Each item has the following structure:
    *   uint32_t offset      (network byte order)
    *   uint32_t length      (network byte order)
    *   uint32_t flags       (network byte order)
    *   char     name[N]     (where N >= 1)
    *   char     null_byte;
    */
   uint32_t offset;
   uint32_t length;
   uint32_t flags;
-  const char *name;
+  const char* name;
   int namelen;
 
-  if ((buf_end - *buf) < (int)(3*sizeof(uint32_t) + 2))
+  if ((buf_end - *buf) < (int)(3 * sizeof(uint32_t) + 2)) {
     return -1;
+  }
 
   memcpy(&offset, *buf, sizeof(offset));
   *buf += sizeof(offset);
 
   memcpy(&length, *buf, sizeof(length));
   *buf += sizeof(length);
 
   memcpy(&flags, *buf, sizeof(flags));
@@ -91,83 +85,88 @@ mar_consume_index(MarFile* mar, char** b
   offset = ntohl(offset);
   length = ntohl(length);
   flags = ntohl(flags);
 
   name = *buf;
   /* find namelen; must take care not to read beyond buf_end */
   while (**buf) {
     /* buf_end points one byte past the end of buf's allocation */
-    if (*buf == (buf_end - 1))
+    if (*buf == (buf_end - 1)) {
       return -1;
+    }
     ++(*buf);
   }
   namelen = (*buf - name);
   /* must ensure that namelen is valid */
   if (namelen < 0) {
     return -1;
   }
   /* consume null byte */
-  if (*buf == buf_end)
+  if (*buf == buf_end) {
     return -1;
+  }
   ++(*buf);
 
   return mar_insert_item(mar, name, namelen, offset, length, flags);
 }
 
-static int
-mar_read_index(MarFile* mar)
-{
+static int mar_read_index(MarFile* mar) {
   char id[MAR_ID_SIZE], *buf, *bufptr, *bufend;
   uint32_t offset_to_index, size_of_index;
 
   /* verify MAR ID */
   fseek(mar->fp, 0, SEEK_SET);
-  if (fread(id, MAR_ID_SIZE, 1, mar->fp) != 1)
+  if (fread(id, MAR_ID_SIZE, 1, mar->fp) != 1) {
     return -1;
-  if (memcmp(id, MAR_ID, MAR_ID_SIZE) != 0)
+  }
+  if (memcmp(id, MAR_ID, MAR_ID_SIZE) != 0) {
     return -1;
+  }
 
-  if (fread(&offset_to_index, sizeof(uint32_t), 1, mar->fp) != 1)
+  if (fread(&offset_to_index, sizeof(uint32_t), 1, mar->fp) != 1) {
     return -1;
+  }
   offset_to_index = ntohl(offset_to_index);
 
-  if (fseek(mar->fp, offset_to_index, SEEK_SET))
+  if (fseek(mar->fp, offset_to_index, SEEK_SET)) {
     return -1;
-  if (fread(&size_of_index, sizeof(uint32_t), 1, mar->fp) != 1)
+  }
+  if (fread(&size_of_index, sizeof(uint32_t), 1, mar->fp) != 1) {
     return -1;
+  }
   size_of_index = ntohl(size_of_index);
 
-  buf = (char *) malloc(size_of_index);
-  if (!buf)
+  buf = (char*)malloc(size_of_index);
+  if (!buf) {
     return -1;
+  }
   if (fread(buf, size_of_index, 1, mar->fp) != 1) {
     free(buf);
     return -1;
   }
 
   bufptr = buf;
   bufend = buf + size_of_index;
-  while (bufptr < bufend && mar_consume_index(mar, &bufptr, bufend) == 0);
+  while (bufptr < bufend && mar_consume_index(mar, &bufptr, bufend) == 0)
+    ;
 
   free(buf);
   return (bufptr == bufend) ? 0 : -1;
 }
 
 /**
  * Adds an offset and length to the MarFile's index_list
  * @param mar     The MarFile that owns this offset length pair
  * @param offset  The byte offset in the archive to be marked as processed
  * @param length  The length corresponding to this byte offset
  * @return int    1 on success, 0 if offset has been previously processed
  *                -1 if unable to allocate space for the SeenIndexes
  */
-static int
-mar_insert_offset(MarFile* mar, uint32_t offset, uint32_t length)
-{
+static int mar_insert_offset(MarFile* mar, uint32_t offset, uint32_t length) {
   /* Ignore files with no length */
   if (length == 0) {
     return 1;
   }
 
   SeenIndex* index = (SeenIndex*)malloc(sizeof(SeenIndex));
   if (!index) {
     return -1;
@@ -208,70 +207,62 @@ mar_insert_offset(MarFile* mar, uint32_t
   previous->next = index;
   return 1;
 }
 
 /**
  * Internal shared code for mar_open and mar_wopen.
  * On failure, will fclose(fp).
  */
-static MarFile*
-mar_fpopen(FILE* fp)
-{
+static MarFile* mar_fpopen(FILE* fp) {
   MarFile* mar;
 
   mar = (MarFile*)malloc(sizeof(*mar));
   if (!mar) {
     fclose(fp);
     return NULL;
   }
 
   mar->fp = fp;
   mar->item_table_is_valid = 0;
   memset(mar->item_table, 0, sizeof(mar->item_table));
   mar->index_list = NULL;
 
   return mar;
 }
 
-MarFile*
-mar_open(const char* path)
-{
-  FILE *fp;
+MarFile* mar_open(const char* path) {
+  FILE* fp;
 
   fp = fopen(path, "rb");
   if (!fp) {
     fprintf(stderr, "ERROR: could not open file in mar_open()\n");
     perror(path);
     return NULL;
   }
 
   return mar_fpopen(fp);
 }
 
 #ifdef XP_WIN
-MarFile*
-mar_wopen(const wchar_t* path)
-{
-  FILE *fp;
+MarFile* mar_wopen(const wchar_t* path) {
+  FILE* fp;
 
   _wfopen_s(&fp, path, L"rb");
   if (!fp) {
     fprintf(stderr, "ERROR: could not open file in mar_wopen()\n");
     _wperror(path);
     return NULL;
   }
 
   return mar_fpopen(fp);
 }
 #endif
 
-void
-mar_close(MarFile* mar)
-{
+void mar_close(MarFile* mar) {
   MarItem* item;
   SeenIndex* index;
   int i;
 
   fclose(mar->fp);
 
   for (i = 0; i < TABLESIZE; ++i) {
     item = mar->item_table[i];
@@ -304,45 +295,40 @@ mar_close(MarFile* mar)
  * @param offsetAdditionalBlocks Optional out parameter for the offset to the
  *                               first additional block. Value is only valid if
  *                               hasAdditionalBlocks is not equal to 0.
  * @param numAdditionalBlocks    Optional out parameter for the number of
  *                               additional blocks.  Value is only valid if
  *                               hasAdditionalBlocks is not equal to 0.
  * @return 0 on success and non-zero on failure.
  */
-int
-get_mar_file_info_fp(FILE* fp,
-                     int* hasSignatureBlock,
-                     uint32_t* numSignatures,
-                     int* hasAdditionalBlocks,
-                     uint32_t* offsetAdditionalBlocks,
-                     uint32_t* numAdditionalBlocks)
-{
+int get_mar_file_info_fp(FILE* fp, int* hasSignatureBlock,
+                         uint32_t* numSignatures, int* hasAdditionalBlocks,
+                         uint32_t* offsetAdditionalBlocks,
+                         uint32_t* numAdditionalBlocks) {
   uint32_t offsetToIndex, offsetToContent, signatureCount, signatureLen, i;
 
   /* One of hasSignatureBlock or hasAdditionalBlocks must be non NULL */
   if (!hasSignatureBlock && !hasAdditionalBlocks) {
     return -1;
   }
 
-
   /* Skip to the start of the offset index */
   if (fseek(fp, MAR_ID_SIZE, SEEK_SET)) {
     return -1;
   }
 
   /* Read the offset to the index. */
   if (fread(&offsetToIndex, sizeof(offsetToIndex), 1, fp) != 1) {
     return -1;
   }
   offsetToIndex = ntohl(offsetToIndex);
 
   if (numSignatures) {
-     /* Skip past the MAR file size field */
+    /* Skip past the MAR file size field */
     if (fseek(fp, sizeof(uint64_t), SEEK_CUR)) {
       return -1;
     }
 
     /* Read the number of signatures field */
     if (fread(numSignatures, sizeof(*numSignatures), 1, fp) != 1) {
       return -1;
     }
@@ -376,17 +362,17 @@ get_mar_file_info_fp(FILE* fp,
   }
 
   /* If the caller doesn't care about the product info block
      value, then just return */
   if (!hasAdditionalBlocks) {
     return 0;
   }
 
-   /* Skip to the start of the signature block */
+  /* Skip to the start of the signature block */
   if (fseeko(fp, SIGNATURE_BLOCK_OFFSET, SEEK_SET)) {
     return -1;
   }
 
   /* Get the number of signatures */
   if (fread(&signatureCount, sizeof(signatureCount), 1, fp) != 1) {
     return -1;
   }
@@ -441,87 +427,81 @@ get_mar_file_info_fp(FILE* fp,
 
 /**
  * Reads the product info block from the MAR file's additional block section.
  * The caller is responsible for freeing the fields in infoBlock
  * if the return is successful.
  *
  * @param infoBlock Out parameter for where to store the result to
  * @return 0 on success, -1 on failure
-*/
-int
-read_product_info_block(char* path, struct ProductInformationBlock* infoBlock)
-{
+ */
+int read_product_info_block(char* path,
+                            struct ProductInformationBlock* infoBlock) {
   int rv;
   MarFile mar;
   mar.fp = fopen(path, "rb");
   if (!mar.fp) {
-    fprintf(stderr, "ERROR: could not open file in read_product_info_block()\n");
+    fprintf(stderr,
+            "ERROR: could not open file in read_product_info_block()\n");
     perror(path);
     return -1;
   }
   rv = mar_read_product_info_block(&mar, infoBlock);
   fclose(mar.fp);
   return rv;
 }
 
 /**
  * Reads the product info block from the MAR file's additional block section.
  * The caller is responsible for freeing the fields in infoBlock
  * if the return is successful.
  *
  * @param infoBlock Out parameter for where to store the result to
  * @return 0 on success, -1 on failure
-*/
-int
-mar_read_product_info_block(MarFile* mar,
-                            struct ProductInformationBlock* infoBlock)
-{
-  uint32_t offsetAdditionalBlocks, numAdditionalBlocks,
-    additionalBlockSize, additionalBlockID;
+ */
+int mar_read_product_info_block(MarFile* mar,
+                                struct ProductInformationBlock* infoBlock) {
+  uint32_t offsetAdditionalBlocks, numAdditionalBlocks, additionalBlockSize,
+      additionalBlockID;
   int hasAdditionalBlocks;
 
   /* The buffer size is 97 bytes because the MAR channel name < 64 bytes, and
      product version < 32 bytes + 3 NULL terminator bytes. */
-  char buf[MAXADDITIONALBLOCKSIZE + 1] = { '\0' };
-  if (get_mar_file_info_fp(mar->fp, NULL, NULL,
-                           &hasAdditionalBlocks,
+  char buf[MAXADDITIONALBLOCKSIZE + 1] = {'\0'};
+  if (get_mar_file_info_fp(mar->fp, NULL, NULL, &hasAdditionalBlocks,
                            &offsetAdditionalBlocks,
                            &numAdditionalBlocks) != 0) {
     return -1;
   }
 
   /* We only have the one additional block type and only one is expected to be
      in a MAR file so check if any exist and process the first found */
   if (numAdditionalBlocks > 0) {
     /* Read the additional block size */
-    if (fread(&additionalBlockSize,
-              sizeof(additionalBlockSize),
-              1, mar->fp) != 1) {
+    if (fread(&additionalBlockSize, sizeof(additionalBlockSize), 1, mar->fp) !=
+        1) {
       return -1;
     }
     additionalBlockSize = ntohl(additionalBlockSize) -
                           sizeof(additionalBlockSize) -
                           sizeof(additionalBlockID);
 
     /* Additional Block sizes should only be 96 bytes long */
     if (additionalBlockSize > MAXADDITIONALBLOCKSIZE) {
       return -1;
     }
 
     /* Read the additional block ID */
-    if (fread(&additionalBlockID,
-              sizeof(additionalBlockID),
-              1, mar->fp) != 1) {
+    if (fread(&additionalBlockID, sizeof(additionalBlockID), 1, mar->fp) != 1) {
       return -1;
     }
     additionalBlockID = ntohl(additionalBlockID);
 
     if (PRODUCT_INFO_BLOCK_ID == additionalBlockID) {
-      const char *location;
+      const char* location;
       int len;
 
       if (fread(buf, additionalBlockSize, 1, mar->fp) != 1) {
         return -1;
       }
 
       /* Extract the MAR channel name from the buffer.  For now we
          point to the stack allocated buffer but we strdup this
@@ -538,36 +518,32 @@ mar_read_product_info_block(MarFile* mar
       /* Extract the version from the buffer */
       len = strlen(location);
       infoBlock->productVersion = location;
       if (len >= 32) {
         infoBlock->MARChannelID = NULL;
         infoBlock->productVersion = NULL;
         return -1;
       }
-      infoBlock->MARChannelID =
-        strdup(infoBlock->MARChannelID);
-      infoBlock->productVersion =
-        strdup(infoBlock->productVersion);
+      infoBlock->MARChannelID = strdup(infoBlock->MARChannelID);
+      infoBlock->productVersion = strdup(infoBlock->productVersion);
       return 0;
     } else {
       /* This is not the additional block you're looking for. Move along. */
       if (fseek(mar->fp, additionalBlockSize, SEEK_CUR)) {
         return -1;
       }
     }
   }
 
   /* If we had a product info block we would have already returned */
   return -1;
 }
 
-const MarItem*
-mar_find_item(MarFile* mar, const char* name)
-{
+const MarItem* mar_find_item(MarFile* mar, const char* name) {
   uint32_t hash;
   const MarItem* item;
 
   if (!mar->item_table_is_valid) {
     if (mar_read_index(mar)) {
       return NULL;
     } else {
       mar->item_table_is_valid = 1;
@@ -585,19 +561,17 @@ mar_find_item(MarFile* mar, const char* 
   if (mar_insert_offset(mar, item->offset, item->length) == 1) {
     return item;
   } else {
     fprintf(stderr, "ERROR: file content collision in mar_find_item()\n");
     return NULL;
   }
 }
 
-int
-mar_enum_items(MarFile* mar, MarItemCallback callback, void* closure)
-{
+int mar_enum_items(MarFile* mar, MarItemCallback callback, void* closure) {
   MarItem* item;
   int i, rv;
 
   if (!mar->item_table_is_valid) {
     if (mar_read_index(mar)) {
       return -1;
     } else {
       mar->item_table_is_valid = 1;
@@ -619,36 +593,35 @@ mar_enum_items(MarFile* mar, MarItemCall
       }
       item = item->next;
     }
   }
 
   return 0;
 }
 
-int
-mar_read(MarFile* mar,
-         const MarItem* item,
-         int offset,
-         uint8_t* buf,
-         int bufsize)
-{
+int mar_read(MarFile* mar, const MarItem* item, int offset, uint8_t* buf,
+             int bufsize) {
   int nr;
 
-  if (offset == (int) item->length)
+  if (offset == (int)item->length) {
     return 0;
-  if (offset > (int) item->length)
+  }
+  if (offset > (int)item->length) {
     return -1;
+  }
 
   nr = item->length - offset;
-  if (nr > bufsize)
+  if (nr > bufsize) {
     nr = bufsize;
+  }
 
-  if (fseek(mar->fp, item->offset + offset, SEEK_SET))
+  if (fseek(mar->fp, item->offset + offset, SEEK_SET)) {
     return -1;
+  }
 
   return fread(buf, 1, nr, mar->fp);
 }
 
 /**
  * Determines the MAR file information.
  *
  * @param path                   The path of the MAR file to check.
@@ -661,31 +634,27 @@ mar_read(MarFile* mar,
  * @param offsetAdditionalBlocks Optional out parameter for the offset to the
  *                               first additional block. Value is only valid if
  *                               hasAdditionalBlocks is not equal to 0.
  * @param numAdditionalBlocks    Optional out parameter for the number of
  *                               additional blocks.  Value is only valid if
  *                               has_additional_blocks is not equal to 0.
  * @return 0 on success and non-zero on failure.
  */
-int
-get_mar_file_info(const char* path,
-                  int* hasSignatureBlock,
-                  uint32_t* numSignatures,
-                  int* hasAdditionalBlocks,
-                  uint32_t* offsetAdditionalBlocks,
-                  uint32_t* numAdditionalBlocks)
-{
+int get_mar_file_info(const char* path, int* hasSignatureBlock,
+                      uint32_t* numSignatures, int* hasAdditionalBlocks,
+                      uint32_t* offsetAdditionalBlocks,
+                      uint32_t* numAdditionalBlocks) {
   int rv;
-  FILE *fp = fopen(path, "rb");
+  FILE* fp = fopen(path, "rb");
   if (!fp) {
     fprintf(stderr, "ERROR: could not open file in get_mar_file_info()\n");
     perror(path);
     return -1;
   }
 
-  rv = get_mar_file_info_fp(fp, hasSignatureBlock,
-                            numSignatures, hasAdditionalBlocks,
-                            offsetAdditionalBlocks, numAdditionalBlocks);
+  rv = get_mar_file_info_fp(fp, hasSignatureBlock, numSignatures,
+                            hasAdditionalBlocks, offsetAdditionalBlocks,
+                            numAdditionalBlocks);
 
   fclose(fp);
   return rv;
 }
--- a/modules/libmar/tool/mar.c
+++ b/modules/libmar/tool/mar.c
@@ -21,95 +21,105 @@
 #if !defined(NO_SIGN_VERIFY) && (!defined(XP_WIN) || defined(MAR_NSS))
 #include "cert.h"
 #include "nss.h"
 #include "pk11pub.h"
 int NSSInitCryptoContext(const char *NSSConfigDir);
 #endif
 
 int mar_repackage_and_sign(const char *NSSConfigDir,
-                           const char * const *certNames,
-                           uint32_t certCount,
-                           const char *src,
-                           const char * dest);
+                           const char *const *certNames, uint32_t certCount,
+                           const char *src, const char *dest);
 
 static void print_version() {
   printf("Version: %s\n", MOZ_APP_VERSION);
   printf("Default Channel ID: %s\n", MAR_CHANNEL_ID);
 }
 
 static void print_usage() {
   printf("usage:\n");
   printf("Create a MAR file:\n");
-  printf("  mar [-H MARChannelID] [-V ProductVersion] [-C workingDir] "
-         "-c archive.mar [files...]\n");
+  printf(
+      "  mar [-H MARChannelID] [-V ProductVersion] [-C workingDir] "
+      "-c archive.mar [files...]\n");
 
   printf("Extract a MAR file:\n");
   printf("  mar [-C workingDir] -x archive.mar\n");
 #ifndef NO_SIGN_VERIFY
   printf("Sign a MAR file:\n");
-  printf("  mar [-C workingDir] -d NSSConfigDir -n certname -s "
-         "archive.mar out_signed_archive.mar\n");
+  printf(
+      "  mar [-C workingDir] -d NSSConfigDir -n certname -s "
+      "archive.mar out_signed_archive.mar\n");
 
   printf("Strip a MAR signature:\n");
-  printf("  mar [-C workingDir] -r "
-         "signed_input_archive.mar output_archive.mar\n");
+  printf(
+      "  mar [-C workingDir] -r "
+      "signed_input_archive.mar output_archive.mar\n");
 
   printf("Extract a MAR signature:\n");
-  printf("  mar [-C workingDir] -n(i) -X "
-         "signed_input_archive.mar base_64_encoded_signature_file\n");
+  printf(
+      "  mar [-C workingDir] -n(i) -X "
+      "signed_input_archive.mar base_64_encoded_signature_file\n");
 
   printf("Import a MAR signature:\n");
-  printf("  mar [-C workingDir] -n(i) -I "
-         "signed_input_archive.mar base_64_encoded_signature_file "
-         "changed_signed_output.mar\n");
+  printf(
+      "  mar [-C workingDir] -n(i) -I "
+      "signed_input_archive.mar base_64_encoded_signature_file "
+      "changed_signed_output.mar\n");
   printf("(i) is the index of the certificate to extract\n");
 #if defined(XP_MACOSX) || (defined(XP_WIN) && !defined(MAR_NSS))
   printf("Verify a MAR file:\n");
   printf("  mar [-C workingDir] -D DERFilePath -v signed_archive.mar\n");
-  printf("At most %d signature certificate DER files are specified by "
-         "-D0 DERFilePath1 -D1 DERFilePath2, ...\n", MAX_SIGNATURES);
+  printf(
+      "At most %d signature certificate DER files are specified by "
+      "-D0 DERFilePath1 -D1 DERFilePath2, ...\n",
+      MAX_SIGNATURES);
 #else
   printf("Verify a MAR file:\n");
-  printf("  mar [-C workingDir] -d NSSConfigDir -n certname "
-         "-v signed_archive.mar\n");
-  printf("At most %d signature certificate names are specified by "
-         "-n0 certName -n1 certName2, ...\n", MAX_SIGNATURES);
+  printf(
+      "  mar [-C workingDir] -d NSSConfigDir -n certname "
+      "-v signed_archive.mar\n");
+  printf(
+      "At most %d signature certificate names are specified by "
+      "-n0 certName -n1 certName2, ...\n",
+      MAX_SIGNATURES);
 #endif
-  printf("At most %d verification certificate names are specified by "
-         "-n0 certName -n1 certName2, ...\n", MAX_SIGNATURES);
+  printf(
+      "At most %d verification certificate names are specified by "
+      "-n0 certName -n1 certName2, ...\n",
+      MAX_SIGNATURES);
 #endif
   printf("Print information on a MAR file:\n");
   printf("  mar -t archive.mar\n");
 
   printf("Print detailed information on a MAR file including signatures:\n");
   printf("  mar -T archive.mar\n");
 
   printf("Refresh the product information block of a MAR file:\n");
-  printf("  mar [-H MARChannelID] [-V ProductVersion] [-C workingDir] "
-         "-i unsigned_archive_to_refresh.mar\n");
+  printf(
+      "  mar [-H MARChannelID] [-V ProductVersion] [-C workingDir] "
+      "-i unsigned_archive_to_refresh.mar\n");
 
   printf("Print executable version:\n");
   printf("  mar --version\n");
   printf("This program does not handle unicode file paths properly\n");
 }
 
-static int mar_test_callback(MarFile *mar,
-                             const MarItem *item,
-                             void *unused) {
+static int mar_test_callback(MarFile *mar, const MarItem *item, void *unused) {
   printf("%u\t0%o\t%s\n", item->length, item->flags, item->name);
   return 0;
 }
 
 static int mar_test(const char *path) {
   MarFile *mar;
 
   mar = mar_open(path);
-  if (!mar)
+  if (!mar) {
     return -1;
+  }
 
   printf("SIZE\tMODE\tNAME\n");
   mar_enum_items(mar, mar_test_callback, NULL);
 
   mar_close(mar);
   return 0;
 }
 
@@ -120,308 +130,294 @@ int main(int argc, char **argv) {
   char *productVersion = MOZ_APP_VERSION;
   uint32_t k;
   int rv = -1;
   uint32_t certCount = 0;
   int32_t sigIndex = -1;
 
 #if !defined(NO_SIGN_VERIFY)
   uint32_t fileSizes[MAX_SIGNATURES];
-  const uint8_t* certBuffers[MAX_SIGNATURES];
+  const uint8_t *certBuffers[MAX_SIGNATURES];
 #if ((!defined(MAR_NSS) && defined(XP_WIN)) || defined(XP_MACOSX)) || \
     ((defined(XP_WIN) || defined(XP_MACOSX)) && !defined(MAR_NSS))
-  char* DERFilePaths[MAX_SIGNATURES];
+  char *DERFilePaths[MAX_SIGNATURES];
 #endif
 #if (!defined(XP_WIN) && !defined(XP_MACOSX)) || defined(MAR_NSS)
-  CERTCertificate* certs[MAX_SIGNATURES];
+  CERTCertificate *certs[MAX_SIGNATURES];
 #endif
 #endif
 
-  memset((void*)certNames, 0, sizeof(certNames));
+  memset((void *)certNames, 0, sizeof(certNames));
 #if defined(XP_WIN) && !defined(MAR_NSS) && !defined(NO_SIGN_VERIFY)
-  memset((void*)certBuffers, 0, sizeof(certBuffers));
+  memset((void *)certBuffers, 0, sizeof(certBuffers));
 #endif
-#if !defined(NO_SIGN_VERIFY) && ((!defined(MAR_NSS) && defined(XP_WIN)) || \
-                                 defined(XP_MACOSX))
+#if !defined(NO_SIGN_VERIFY) && \
+    ((!defined(MAR_NSS) && defined(XP_WIN)) || defined(XP_MACOSX))
   memset(DERFilePaths, 0, sizeof(DERFilePaths));
   memset(fileSizes, 0, sizeof(fileSizes));
 #endif
 
   if (argc > 1 && 0 == strcmp(argv[1], "--version")) {
     print_version();
     return 0;
   }
 
   if (argc < 3) {
     print_usage();
     return -1;
   }
 
   while (argc > 0) {
-    if (argv[1][0] == '-' && (argv[1][1] == 'c' ||
-        argv[1][1] == 't' || argv[1][1] == 'x' ||
-        argv[1][1] == 'v' || argv[1][1] == 's' ||
-        argv[1][1] == 'i' || argv[1][1] == 'T' ||
-        argv[1][1] == 'r' || argv[1][1] == 'X' ||
-        argv[1][1] == 'I')) {
+    if (argv[1][0] == '-' &&
+        (argv[1][1] == 'c' || argv[1][1] == 't' || argv[1][1] == 'x' ||
+         argv[1][1] == 'v' || argv[1][1] == 's' || argv[1][1] == 'i' ||
+         argv[1][1] == 'T' || argv[1][1] == 'r' || argv[1][1] == 'X' ||
+         argv[1][1] == 'I')) {
       break;
-    /* -C workingdirectory */
+      /* -C workingdirectory */
     }
     if (argv[1][0] == '-' && argv[1][1] == 'C') {
       if (chdir(argv[2]) != 0) {
         return -1;
       }
       argv += 2;
       argc -= 2;
     }
-#if !defined(NO_SIGN_VERIFY) && ((!defined(MAR_NSS) && defined(XP_WIN)) || \
-                                 defined(XP_MACOSX))
+#if !defined(NO_SIGN_VERIFY) && \
+    ((!defined(MAR_NSS) && defined(XP_WIN)) || defined(XP_MACOSX))
     /* -D DERFilePath, also matches -D[index] DERFilePath
        We allow an index for verifying to be symmetric
        with the import and export command line arguments. */
-    else if (argv[1][0] == '-' &&
-             argv[1][1] == 'D' &&
+    else if (argv[1][0] == '-' && argv[1][1] == 'D' &&
              (argv[1][2] == (char)('0' + certCount) || argv[1][2] == '\0')) {
       if (certCount >= MAX_SIGNATURES) {
         print_usage();
         return -1;
       }
       DERFilePaths[certCount++] = argv[2];
       argv += 2;
       argc -= 2;
     }
 #endif
     /* -d NSSConfigdir */
     else if (argv[1][0] == '-' && argv[1][1] == 'd') {
       NSSConfigDir = argv[2];
       argv += 2;
       argc -= 2;
-     /* -n certName, also matches -n[index] certName
-        We allow an index for verifying to be symmetric
-        with the import and export command line arguments. */
-    } else if (argv[1][0] == '-' &&
-               argv[1][1] == 'n' &&
-               (argv[1][2] == (char)('0' + certCount) ||
-                argv[1][2] == '\0' ||
-                !strcmp(argv[2], "-X") ||
-                !strcmp(argv[2], "-I"))) {
+      /* -n certName, also matches -n[index] certName
+         We allow an index for verifying to be symmetric
+         with the import and export command line arguments. */
+    } else if (argv[1][0] == '-' && argv[1][1] == 'n' &&
+               (argv[1][2] == (char)('0' + certCount) || argv[1][2] == '\0' ||
+                !strcmp(argv[2], "-X") || !strcmp(argv[2], "-I"))) {
       if (certCount >= MAX_SIGNATURES) {
         print_usage();
         return -1;
       }
       certNames[certCount++] = argv[2];
       if (strlen(argv[1]) > 2 &&
           (!strcmp(argv[2], "-X") || !strcmp(argv[2], "-I")) &&
           argv[1][2] >= '0' && argv[1][2] <= '9') {
         sigIndex = argv[1][2] - '0';
         argv++;
         argc--;
       } else {
         argv += 2;
         argc -= 2;
       }
-    /* MAR channel ID */
-    } else if (argv[1][0] == '-' && argv[1][1] == 'H') {
+    } else if (argv[1][0] == '-' && argv[1][1] == 'H') {  // MAR channel ID
       MARChannelID = argv[2];
       argv += 2;
       argc -= 2;
-    /* Product Version */
-    } else if (argv[1][0] == '-' && argv[1][1] == 'V') {
+    } else if (argv[1][0] == '-' && argv[1][1] == 'V') {  // Product Version
       productVersion = argv[2];
       argv += 2;
       argc -= 2;
-    }
-    else {
+    } else {
       print_usage();
       return -1;
     }
   }
 
   if (argv[1][0] != '-') {
     print_usage();
     return -1;
   }
 
   switch (argv[1][1]) {
-  case 'c': {
-    struct ProductInformationBlock infoBlock;
-    infoBlock.MARChannelID = MARChannelID;
-    infoBlock.productVersion = productVersion;
-    return mar_create(argv[2], argc - 3, argv + 3, &infoBlock);
-  }
-  case 'i': {
-    struct ProductInformationBlock infoBlock;
-    infoBlock.MARChannelID = MARChannelID;
-    infoBlock.productVersion = productVersion;
-    return refresh_product_info_block(argv[2], &infoBlock);
-  }
-  case 'T': {
-    struct ProductInformationBlock infoBlock;
-    uint32_t numSignatures, numAdditionalBlocks;
-    int hasSignatureBlock, hasAdditionalBlock;
-    if (!get_mar_file_info(argv[2],
-                           &hasSignatureBlock,
-                           &numSignatures,
-                           &hasAdditionalBlock,
-                           NULL, &numAdditionalBlocks)) {
-      if (hasSignatureBlock) {
-        printf("Signature block found with %d signature%s\n",
-               numSignatures,
-               numSignatures != 1 ? "s" : "");
+    case 'c': {
+      struct ProductInformationBlock infoBlock;
+      infoBlock.MARChannelID = MARChannelID;
+      infoBlock.productVersion = productVersion;
+      return mar_create(argv[2], argc - 3, argv + 3, &infoBlock);
+    }
+    case 'i': {
+      struct ProductInformationBlock infoBlock;
+      infoBlock.MARChannelID = MARChannelID;
+      infoBlock.productVersion = productVersion;
+      return refresh_product_info_block(argv[2], &infoBlock);
+    }
+    case 'T': {
+      struct ProductInformationBlock infoBlock;
+      uint32_t numSignatures, numAdditionalBlocks;
+      int hasSignatureBlock, hasAdditionalBlock;
+      if (!get_mar_file_info(argv[2], &hasSignatureBlock, &numSignatures,
+                             &hasAdditionalBlock, NULL, &numAdditionalBlocks)) {
+        if (hasSignatureBlock) {
+          printf("Signature block found with %d signature%s\n", numSignatures,
+                 numSignatures != 1 ? "s" : "");
+        }
+        if (hasAdditionalBlock) {
+          printf("%d additional block%s found:\n", numAdditionalBlocks,
+                 numAdditionalBlocks != 1 ? "s" : "");
+        }
+
+        rv = read_product_info_block(argv[2], &infoBlock);
+        if (!rv) {
+          printf("  - Product Information Block:\n");
+          printf(
+              "    - MAR channel name: %s\n"
+              "    - Product version: %s\n",
+              infoBlock.MARChannelID, infoBlock.productVersion);
+          free((void *)infoBlock.MARChannelID);
+          free((void *)infoBlock.productVersion);
+        }
       }
-      if (hasAdditionalBlock) {
-        printf("%d additional block%s found:\n",
-               numAdditionalBlocks,
-               numAdditionalBlocks != 1 ? "s" : "");
-      }
+      printf("\n");
+      /* The fall through from 'T' to 't' is intentional */
+    }
+    case 't':
+      return mar_test(argv[2]);
 
-      rv = read_product_info_block(argv[2], &infoBlock);
-      if (!rv) {
-        printf("  - Product Information Block:\n");
-        printf("    - MAR channel name: %s\n"
-               "    - Product version: %s\n",
-               infoBlock.MARChannelID,
-               infoBlock.productVersion);
-        free((void *)infoBlock.MARChannelID);
-        free((void *)infoBlock.productVersion);
-      }
-     }
-    printf("\n");
-    /* The fall through from 'T' to 't' is intentional */
-  }
-  case 't':
-    return mar_test(argv[2]);
-
-  /* Extract a MAR file */
-  case 'x':
-    return mar_extract(argv[2]);
+    case 'x':  // Extract a MAR file
+      return mar_extract(argv[2]);
 
 #ifndef NO_SIGN_VERIFY
-  /* Extract a MAR signature */
-  case 'X':
-    if (sigIndex == -1) {
-      fprintf(stderr, "ERROR: Signature index was not passed.\n");
-      return -1;
-    }
-    if (sigIndex >= MAX_SIGNATURES || sigIndex < -1) {
-      fprintf(stderr, "ERROR: Signature index is out of range: %d.\n",
-              sigIndex);
-      return -1;
-    }
-    return extract_signature(argv[2], sigIndex, argv[3]);
+    case 'X':  // Extract a MAR signature
+      if (sigIndex == -1) {
+        fprintf(stderr, "ERROR: Signature index was not passed.\n");
+        return -1;
+      }
+      if (sigIndex >= MAX_SIGNATURES || sigIndex < -1) {
+        fprintf(stderr, "ERROR: Signature index is out of range: %d.\n",
+                sigIndex);
+        return -1;
+      }
+      return extract_signature(argv[2], sigIndex, argv[3]);
 
-  /* Import a MAR signature */
-  case 'I':
-    if (sigIndex == -1) {
-      fprintf(stderr, "ERROR: signature index was not passed.\n");
-      return -1;
-    }
-    if (sigIndex >= MAX_SIGNATURES || sigIndex < -1) {
-      fprintf(stderr, "ERROR: Signature index is out of range: %d.\n",
-              sigIndex);
-      return -1;
-    }
-    if (argc < 5) {
-      print_usage();
-      return -1;
-    }
-    return import_signature(argv[2], sigIndex, argv[3], argv[4]);
+    case 'I':  // Import a MAR signature
+      if (sigIndex == -1) {
+        fprintf(stderr, "ERROR: signature index was not passed.\n");
+        return -1;
+      }
+      if (sigIndex >= MAX_SIGNATURES || sigIndex < -1) {
+        fprintf(stderr, "ERROR: Signature index is out of range: %d.\n",
+                sigIndex);
+        return -1;
+      }
+      if (argc < 5) {
+        print_usage();
+        return -1;
+      }
+      return import_signature(argv[2], sigIndex, argv[3], argv[4]);
 
-  case 'v':
-    if (certCount == 0) {
-      print_usage();
-      return -1;
-    }
+    case 'v':
+      if (certCount == 0) {
+        print_usage();
+        return -1;
+      }
 
 #if (!defined(XP_WIN) && !defined(XP_MACOSX)) || defined(MAR_NSS)
-    if (!NSSConfigDir || certCount == 0) {
-      print_usage();
-      return -1;
-    }
-
-    if (NSSInitCryptoContext(NSSConfigDir)) {
-      fprintf(stderr, "ERROR: Could not initialize crypto library.\n");
-      return -1;
-    }
-#endif
-
-    rv = 0;
-    for (k = 0; k < certCount; ++k) {
-#if (defined(XP_WIN) || defined(XP_MACOSX)) && !defined(MAR_NSS)
-      rv = mar_read_entire_file(DERFilePaths[k], MAR_MAX_CERT_SIZE,
-                                &certBuffers[k], &fileSizes[k]);
+      if (!NSSConfigDir || certCount == 0) {
+        print_usage();
+        return -1;
+      }
 
-      if (rv) {
-        fprintf(stderr, "ERROR: could not read file %s", DERFilePaths[k]);
-        break;
-      }
-#else
-      /* It is somewhat circuitous to look up a CERTCertificate and then pass
-       * in its DER encoding just so we can later re-create that
-       * CERTCertificate to extract the public key out of it. However, by doing
-       * things this way, we maximize the reuse of the mar_verify_signatures
-       * function and also we keep the control flow as similar as possible
-       * between programs and operating systems, at least for the functions
-       * that are critically important to security.
-       */
-      certs[k] = PK11_FindCertFromNickname(certNames[k], NULL);
-      if (certs[k]) {
-        certBuffers[k] = certs[k]->derCert.data;
-        fileSizes[k] = certs[k]->derCert.len;
-      } else {
-        rv = -1;
-        fprintf(stderr, "ERROR: could not find cert from nickname %s", certNames[k]);
-        break;
+      if (NSSInitCryptoContext(NSSConfigDir)) {
+        fprintf(stderr, "ERROR: Could not initialize crypto library.\n");
+        return -1;
       }
 #endif
-    }
+
+      rv = 0;
+      for (k = 0; k < certCount; ++k) {
+#if (defined(XP_WIN) || defined(XP_MACOSX)) && !defined(MAR_NSS)
+        rv = mar_read_entire_file(DERFilePaths[k], MAR_MAX_CERT_SIZE,
+                                  &certBuffers[k], &fileSizes[k]);
 
-    if (!rv) {
-      MarFile *mar = mar_open(argv[2]);
-      if (mar) {
-        rv = mar_verify_signatures(mar, certBuffers, fileSizes, certCount);
-        mar_close(mar);
-      } else {
-        fprintf(stderr, "ERROR: Could not open MAR file.\n");
-        rv = -1;
-      }
-    }
-    for (k = 0; k < certCount; ++k) {
-#if (defined(XP_WIN) || defined(XP_MACOSX)) && !defined(MAR_NSS)
-      free((void*)certBuffers[k]);
+        if (rv) {
+          fprintf(stderr, "ERROR: could not read file %s", DERFilePaths[k]);
+          break;
+        }
 #else
-      /* certBuffers[k] is owned by certs[k] so don't free it */
-      CERT_DestroyCertificate(certs[k]);
+        /* It is somewhat circuitous to look up a CERTCertificate and then pass
+         * in its DER encoding just so we can later re-create that
+         * CERTCertificate to extract the public key out of it. However, by
+         * doing things this way, we maximize the reuse of the
+         * mar_verify_signatures function and also we keep the control flow as
+         * similar as possible between programs and operating systems, at least
+         * for the functions that are critically important to security.
+         */
+        certs[k] = PK11_FindCertFromNickname(certNames[k], NULL);
+        if (certs[k]) {
+          certBuffers[k] = certs[k]->derCert.data;
+          fileSizes[k] = certs[k]->derCert.len;
+        } else {
+          rv = -1;
+          fprintf(stderr, "ERROR: could not find cert from nickname %s",
+                  certNames[k]);
+          break;
+        }
 #endif
-    }
-    if (rv) {
-      /* Determine if the source MAR file has the new fields for signing */
-      int hasSignatureBlock;
-      if (get_mar_file_info(argv[2], &hasSignatureBlock,
-                            NULL, NULL, NULL, NULL)) {
-        fprintf(stderr, "ERROR: could not determine if MAR is old or new.\n");
-      } else if (!hasSignatureBlock) {
-        fprintf(stderr, "ERROR: The MAR file is in the old format so has"
-                        " no signature to verify.\n");
+      }
+
+      if (!rv) {
+        MarFile *mar = mar_open(argv[2]);
+        if (mar) {
+          rv = mar_verify_signatures(mar, certBuffers, fileSizes, certCount);
+          mar_close(mar);
+        } else {
+          fprintf(stderr, "ERROR: Could not open MAR file.\n");
+          rv = -1;
+        }
+      }
+      for (k = 0; k < certCount; ++k) {
+#if (defined(XP_WIN) || defined(XP_MACOSX)) && !defined(MAR_NSS)
+        free((void *)certBuffers[k]);
+#else
+        /* certBuffers[k] is owned by certs[k] so don't free it */
+        CERT_DestroyCertificate(certs[k]);
+#endif
       }
-    }
+      if (rv) {
+        /* Determine if the source MAR file has the new fields for signing */
+        int hasSignatureBlock;
+        if (get_mar_file_info(argv[2], &hasSignatureBlock, NULL, NULL, NULL,
+                              NULL)) {
+          fprintf(stderr, "ERROR: could not determine if MAR is old or new.\n");
+        } else if (!hasSignatureBlock) {
+          fprintf(stderr,
+                  "ERROR: The MAR file is in the old format so has"
+                  " no signature to verify.\n");
+        }
+      }
 #if (!defined(XP_WIN) && !defined(XP_MACOSX)) || defined(MAR_NSS)
-    (void) NSS_Shutdown();
+      (void)NSS_Shutdown();
 #endif
-    return rv ? -1 : 0;
+      return rv ? -1 : 0;
 
-  case 's':
-    if (!NSSConfigDir || certCount == 0 || argc < 4) {
+    case 's':
+      if (!NSSConfigDir || certCount == 0 || argc < 4) {
+        print_usage();
+        return -1;
+      }
+      return mar_repackage_and_sign(NSSConfigDir, certNames, certCount, argv[2],
+                                    argv[3]);
+
+    case 'r':
+      return strip_signature_block(argv[2], argv[3]);
+#endif /* endif NO_SIGN_VERIFY disabled */
+
+    default:
       print_usage();
       return -1;
-    }
-    return mar_repackage_and_sign(NSSConfigDir, certNames, certCount,
-                                  argv[2], argv[3]);
-
-  case 'r':
-    return strip_signature_block(argv[2], argv[3]);
-#endif /* endif NO_SIGN_VERIFY disabled */
-
-  default:
-    print_usage();
-    return -1;
   }
 }
--- a/modules/libmar/verify/MacVerifyCrypto.cpp
+++ b/modules/libmar/verify/MacVerifyCrypto.cpp
@@ -6,197 +6,176 @@
 #include <Security/Security.h>
 #include <dlfcn.h>
 
 #include "cryptox.h"
 
 // We declare the necessary parts of the Security Transforms API here since
 // we're building with the 10.6 SDK, which doesn't know about Security
 // Transforms.
-#ifdef __cplusplus
+#if defined(__cplusplus)
 extern "C" {
 #endif
-  const CFStringRef kSecTransformInputAttributeName = CFSTR("INPUT");
-  typedef CFTypeRef SecTransformRef;
-  typedef struct OpaqueSecKeyRef* SecKeyRef;
+const CFStringRef kSecTransformInputAttributeName = CFSTR("INPUT");
+typedef CFTypeRef SecTransformRef;
+typedef struct OpaqueSecKeyRef* SecKeyRef;
 
-  typedef SecTransformRef (*SecTransformCreateReadTransformWithReadStreamFunc)
-                            (CFReadStreamRef inputStream);
-  SecTransformCreateReadTransformWithReadStreamFunc
+typedef SecTransformRef (*SecTransformCreateReadTransformWithReadStreamFunc)(
+    CFReadStreamRef inputStream);
+SecTransformCreateReadTransformWithReadStreamFunc
     SecTransformCreateReadTransformWithReadStreamPtr = NULL;
-  typedef CFTypeRef (*SecTransformExecuteFunc)(SecTransformRef transform,
-                                               CFErrorRef* error);
-  SecTransformExecuteFunc SecTransformExecutePtr = NULL;
-  typedef SecTransformRef (*SecVerifyTransformCreateFunc)(SecKeyRef key,
-                                                          CFDataRef signature,
-                                                          CFErrorRef* error);
-  SecVerifyTransformCreateFunc SecVerifyTransformCreatePtr = NULL;
-  typedef Boolean (*SecTransformSetAttributeFunc)(SecTransformRef transform,
-                                                  CFStringRef key,
-                                                  CFTypeRef value,
-                                                  CFErrorRef* error);
-  SecTransformSetAttributeFunc SecTransformSetAttributePtr = NULL;
-#ifdef __cplusplus
+typedef CFTypeRef (*SecTransformExecuteFunc)(SecTransformRef transform,
+                                             CFErrorRef* error);
+SecTransformExecuteFunc SecTransformExecutePtr = NULL;
+typedef SecTransformRef (*SecVerifyTransformCreateFunc)(SecKeyRef key,
+                                                        CFDataRef signature,
+                                                        CFErrorRef* error);
+SecVerifyTransformCreateFunc SecVerifyTransformCreatePtr = NULL;
+typedef Boolean (*SecTransformSetAttributeFunc)(SecTransformRef transform,
+                                                CFStringRef key,
+                                                CFTypeRef value,
+                                                CFErrorRef* error);
+SecTransformSetAttributeFunc SecTransformSetAttributePtr = NULL;
+#if defined(__cplusplus)
 }
 #endif
 
-CryptoX_Result
-CryptoMac_InitCryptoProvider()
-{
+CryptoX_Result CryptoMac_InitCryptoProvider() {
   if (!SecTransformCreateReadTransformWithReadStreamPtr) {
     SecTransformCreateReadTransformWithReadStreamPtr =
-      (SecTransformCreateReadTransformWithReadStreamFunc)
-        dlsym(RTLD_DEFAULT, "SecTransformCreateReadTransformWithReadStream");
+        (SecTransformCreateReadTransformWithReadStreamFunc)dlsym(
+            RTLD_DEFAULT, "SecTransformCreateReadTransformWithReadStream");
   }
   if (!SecTransformExecutePtr) {
-    SecTransformExecutePtr = (SecTransformExecuteFunc)
-      dlsym(RTLD_DEFAULT, "SecTransformExecute");
+    SecTransformExecutePtr =
+        (SecTransformExecuteFunc)dlsym(RTLD_DEFAULT, "SecTransformExecute");
   }
   if (!SecVerifyTransformCreatePtr) {
-    SecVerifyTransformCreatePtr = (SecVerifyTransformCreateFunc)
-      dlsym(RTLD_DEFAULT, "SecVerifyTransformCreate");
+    SecVerifyTransformCreatePtr = (SecVerifyTransformCreateFunc)dlsym(
+        RTLD_DEFAULT, "SecVerifyTransformCreate");
   }
   if (!SecTransformSetAttributePtr) {
-    SecTransformSetAttributePtr = (SecTransformSetAttributeFunc)
-      dlsym(RTLD_DEFAULT, "SecTransformSetAttribute");
+    SecTransformSetAttributePtr = (SecTransformSetAttributeFunc)dlsym(
+        RTLD_DEFAULT, "SecTransformSetAttribute");
   }
   if (!SecTransformCreateReadTransformWithReadStreamPtr ||
-      !SecTransformExecutePtr ||
-      !SecVerifyTransformCreatePtr ||
+      !SecTransformExecutePtr || !SecVerifyTransformCreatePtr ||
       !SecTransformSetAttributePtr) {
     return CryptoX_Error;
   }
   return CryptoX_Success;
 }
 
-CryptoX_Result
-CryptoMac_VerifyBegin(CryptoX_SignatureHandle* aInputData)
-{
+CryptoX_Result CryptoMac_VerifyBegin(CryptoX_SignatureHandle* aInputData) {
   if (!aInputData) {
     return CryptoX_Error;
   }
 
   void* inputData = CFDataCreateMutable(kCFAllocatorDefault, 0);
   if (!inputData) {
     return CryptoX_Error;
   }
 
   *aInputData = inputData;
   return CryptoX_Success;
 }
 
-CryptoX_Result
-CryptoMac_VerifyUpdate(CryptoX_SignatureHandle* aInputData, void* aBuf,
-                       unsigned int aLen)
-{
+CryptoX_Result CryptoMac_VerifyUpdate(CryptoX_SignatureHandle* aInputData,
+                                      void* aBuf, unsigned int aLen) {
   if (aLen == 0) {
     return CryptoX_Success;
   }
   if (!aInputData || !*aInputData) {
     return CryptoX_Error;
   }
 
   CFMutableDataRef inputData = (CFMutableDataRef)*aInputData;
 
   CFDataAppendBytes(inputData, (const uint8*)aBuf, aLen);
   return CryptoX_Success;
 }
 
-CryptoX_Result
-CryptoMac_LoadPublicKey(const unsigned char* aCertData,
-                        unsigned int aDataSize,
-                        CryptoX_PublicKey* aPublicKey)
-{
+CryptoX_Result CryptoMac_LoadPublicKey(const unsigned char* aCertData,
+                                       unsigned int aDataSize,
+                                       CryptoX_PublicKey* aPublicKey) {
   if (!aCertData || aDataSize == 0 || !aPublicKey) {
     return CryptoX_Error;
   }
   *aPublicKey = NULL;
-  CFDataRef certData = CFDataCreate(kCFAllocatorDefault,
-                                    aCertData,
-                                    aDataSize);
+  CFDataRef certData = CFDataCreate(kCFAllocatorDefault, aCertData, aDataSize);
   if (!certData) {
     return CryptoX_Error;
   }
 
-  SecCertificateRef cert = SecCertificateCreateWithData(kCFAllocatorDefault,
-                                                        certData);
+  SecCertificateRef cert =
+      SecCertificateCreateWithData(kCFAllocatorDefault, certData);
   CFRelease(certData);
   if (!cert) {
     return CryptoX_Error;
   }
 
-  OSStatus status = SecCertificateCopyPublicKey(cert,
-                                                (SecKeyRef*)aPublicKey);
+  OSStatus status = SecCertificateCopyPublicKey(cert, (SecKeyRef*)aPublicKey);
   CFRelease(cert);
   if (status != 0) {
     return CryptoX_Error;
   }
 
   return CryptoX_Success;
 }
 
-CryptoX_Result
-CryptoMac_VerifySignature(CryptoX_SignatureHandle* aInputData,
-                          CryptoX_PublicKey* aPublicKey,
-                          const unsigned char* aSignature,
-                          unsigned int aSignatureLen)
-{
+CryptoX_Result CryptoMac_VerifySignature(CryptoX_SignatureHandle* aInputData,
+                                         CryptoX_PublicKey* aPublicKey,
+                                         const unsigned char* aSignature,
+                                         unsigned int aSignatureLen) {
   if (!aInputData || !*aInputData || !aPublicKey || !*aPublicKey ||
       !aSignature || aSignatureLen == 0) {
     return CryptoX_Error;
   }
 
-  CFDataRef signatureData = CFDataCreate(kCFAllocatorDefault,
-                                         aSignature, aSignatureLen);
+  CFDataRef signatureData =
+      CFDataCreate(kCFAllocatorDefault, aSignature, aSignatureLen);
   if (!signatureData) {
     return CryptoX_Error;
   }
 
   CFErrorRef error;
-  SecTransformRef verifier =
-    SecVerifyTransformCreatePtr((SecKeyRef)*aPublicKey,
-                                signatureData,
-                                &error);
+  SecTransformRef verifier = SecVerifyTransformCreatePtr((SecKeyRef)*aPublicKey,
+                                                         signatureData, &error);
   if (!verifier || error) {
     if (error) {
       CFRelease(error);
     }
     CFRelease(signatureData);
     return CryptoX_Error;
   }
 
-  SecTransformSetAttributePtr(verifier,
-                              kSecDigestTypeAttribute,
-                              kSecDigestSHA2,
+  SecTransformSetAttributePtr(verifier, kSecDigestTypeAttribute, kSecDigestSHA2,
                               &error);
   if (error) {
     CFRelease(error);
     CFRelease(signatureData);
     CFRelease(verifier);
     return CryptoX_Error;
   }
 
   int digestLength = 384;
-  CFNumberRef dLen = CFNumberCreate(kCFAllocatorDefault, kCFNumberIntType, &digestLength);
-  SecTransformSetAttributePtr(verifier,
-                              kSecDigestLengthAttribute,
-                              dLen,
+  CFNumberRef dLen =
+      CFNumberCreate(kCFAllocatorDefault, kCFNumberIntType, &digestLength);
+  SecTransformSetAttributePtr(verifier, kSecDigestLengthAttribute, dLen,
                               &error);
   CFRelease(dLen);
   if (error) {
     CFRelease(error);
     CFRelease(signatureData);
     CFRelease(verifier);
     return CryptoX_Error;
   }
 
-  SecTransformSetAttributePtr(verifier,
-                              kSecTransformInputAttributeName,
-                              (CFDataRef)*aInputData,
-                              &error);
+  SecTransformSetAttributePtr(verifier, kSecTransformInputAttributeName,
+                              (CFDataRef)*aInputData, &error);
   if (error) {
     CFRelease(error);
     CFRelease(signatureData);
     CFRelease(verifier);
     return CryptoX_Error;
   }
 
   CryptoX_Result result = CryptoX_Error;
@@ -214,30 +193,26 @@ CryptoMac_VerifySignature(CryptoX_Signat
   }
 
   CFRelease(signatureData);
   CFRelease(verifier);
 
   return result;
 }
 
-void
-CryptoMac_FreeSignatureHandle(CryptoX_SignatureHandle* aInputData)
-{
+void CryptoMac_FreeSignatureHandle(CryptoX_SignatureHandle* aInputData) {
   if (!aInputData || !*aInputData) {
     return;
   }
 
   CFMutableDataRef inputData = NULL;
   inputData = (CFMutableDataRef)*aInputData;
 
   CFRelease(inputData);
 }
 
-void
-CryptoMac_FreePublicKey(CryptoX_PublicKey* aPublicKey)
-{
+void CryptoMac_FreePublicKey(CryptoX_PublicKey* aPublicKey) {
   if (!aPublicKey || !*aPublicKey) {
     return;
   }
 
   CFRelease((SecKeyRef)*aPublicKey);
 }
--- a/modules/libmar/verify/cryptox.c
+++ b/modules/libmar/verify/cryptox.c
@@ -16,23 +16,22 @@
 
 /**
  * Loads the public key for the specified cert name from the NSS store.
  *
  * @param certData  The DER-encoded X509 certificate to extract the key from.
  * @param certDataSize The size of certData.
  * @param publicKey Out parameter for the public key to use.
  * @return CryptoX_Success on success, CryptoX_Error on error.
-*/
-CryptoX_Result
-NSS_LoadPublicKey(const unsigned char *certData, unsigned int certDataSize,
-                  SECKEYPublicKey **publicKey)
-{
-  CERTCertificate * cert;
-  SECItem certDataItem = { siBuffer, (unsigned char*) certData, certDataSize };
+ */
+CryptoX_Result NSS_LoadPublicKey(const unsigned char *certData,
+                                 unsigned int certDataSize,
+                                 SECKEYPublicKey **publicKey) {
+  CERTCertificate *cert;
+  SECItem certDataItem = {siBuffer, (unsigned char *)certData, certDataSize};
 
   if (!certData || !publicKey) {
     return CryptoX_Error;
   }
 
   cert = CERT_NewTempCertificate(CERT_GetDefaultCertDB(), &certDataItem, NULL,
                                  PR_FALSE, PR_TRUE);
   /* Get the cert and embedded public key out of the database */
@@ -43,20 +42,18 @@ NSS_LoadPublicKey(const unsigned char *c
   CERT_DestroyCertificate(cert);
 
   if (!*publicKey) {
     return CryptoX_Error;
   }
   return CryptoX_Success;
 }
 
-CryptoX_Result
-NSS_VerifyBegin(VFYContext **ctx,
-                SECKEYPublicKey * const *publicKey)
-{
+CryptoX_Result NSS_VerifyBegin(VFYContext **ctx,
+                               SECKEYPublicKey *const *publicKey) {
   SECStatus status;
   if (!ctx || !publicKey || !*publicKey) {
     return CryptoX_Error;
   }
 
   /* Check that the key length is large enough for our requirements */
   if ((SECKEY_PublicKeyStrength(*publicKey) * 8) <
       XP_MIN_SIGNATURE_LEN_IN_BYTES) {
@@ -77,193 +74,164 @@ NSS_VerifyBegin(VFYContext **ctx,
 
 /**
  * Verifies if a verify context matches the passed in signature.
  *
  * @param ctx          The verify context that the signature should match.
  * @param signature    The signature to match.
  * @param signatureLen The length of the signature.
  * @return CryptoX_Success on success, CryptoX_Error on error.
-*/
-CryptoX_Result
-NSS_VerifySignature(VFYContext * const *ctx,
-                    const unsigned char *signature,
-                    unsigned int signatureLen)
-{
+ */
+CryptoX_Result NSS_VerifySignature(VFYContext *const *ctx,
+                                   const unsigned char *signature,
+                                   unsigned int signatureLen) {
   SECItem signedItem;
   SECStatus status;
   if (!ctx || !signature || !*ctx) {
     return CryptoX_Error;
   }
 
   signedItem.len = signatureLen;
-  signedItem.data = (unsigned char*)signature;
+  signedItem.data = (unsigned char *)signature;
   status = VFY_EndWithSignature(*ctx, &signedItem);
   return SECSuccess == status ? CryptoX_Success : CryptoX_Error;
 }
 
 #elif defined(XP_WIN)
 /**
  * Verifies if a signature + public key matches a hash context.
  *
  * @param hash      The hash context that the signature should match.
  * @param pubKey    The public key to use on the signature.
  * @param signature The signature to check.
  * @param signatureLen The length of the signature.
  * @return CryptoX_Success on success, CryptoX_Error on error.
-*/
-CryptoX_Result
-CryptoAPI_VerifySignature(HCRYPTHASH *hash,
-                          HCRYPTKEY *pubKey,
-                          const BYTE *signature,
-                          DWORD signatureLen)
-{
+ */
+CryptoX_Result CryptoAPI_VerifySignature(HCRYPTHASH *hash, HCRYPTKEY *pubKey,
+                                         const BYTE *signature,
+                                         DWORD signatureLen) {
   DWORD i;
   BOOL result;
-/* Windows APIs expect the bytes in the signature to be in little-endian
- * order, but we write the signature in big-endian order.  Other APIs like
- * NSS and OpenSSL expect big-endian order.
- */
+  /* Windows APIs expect the bytes in the signature to be in little-endian
+   * order, but we write the signature in big-endian order.  Other APIs like
+   * NSS and OpenSSL expect big-endian order.
+   */
   BYTE *signatureReversed;
   if (!hash || !pubKey || !signature || signatureLen < 1) {
     return CryptoX_Error;
   }
 
   signatureReversed = malloc(signatureLen);
   if (!signatureReversed) {
     return CryptoX_Error;
   }
 
   for (i = 0; i < signatureLen; i++) {
     signatureReversed[i] = signature[signatureLen - 1 - i];
   }
-  result = CryptVerifySignature(*hash, signatureReversed,
-                                signatureLen, *pubKey, NULL, 0);
+  result = CryptVerifySignature(*hash, signatureReversed, signatureLen, *pubKey,
+                                NULL, 0);
   free(signatureReversed);
   return result ? CryptoX_Success : CryptoX_Error;
 }
 
 /**
  * Obtains the public key for the passed in cert data
  *
  * @param provider       The cyrto provider
  * @param certData       Data of the certificate to extract the public key from
  * @param sizeOfCertData The size of the certData buffer
  * @param certStore      Pointer to the handle of the certificate store to use
  * @param CryptoX_Success on success
-*/
-CryptoX_Result
-CryptoAPI_LoadPublicKey(HCRYPTPROV provider,
-                        BYTE *certData,
-                        DWORD sizeOfCertData,
-                        HCRYPTKEY *publicKey)
-{
+ */
+CryptoX_Result CryptoAPI_LoadPublicKey(HCRYPTPROV provider, BYTE *certData,
+                                       DWORD sizeOfCertData,
+                                       HCRYPTKEY *publicKey) {
   CRYPT_DATA_BLOB blob;
   CERT_CONTEXT *context;
   if (!provider || !certData || !publicKey) {
     return CryptoX_Error;
   }
 
   blob.cbData = sizeOfCertData;
   blob.pbData = certData;
   if (!CryptQueryObject(CERT_QUERY_OBJECT_BLOB, &blob,
                         CERT_QUERY_CONTENT_FLAG_CERT,
-                        CERT_QUERY_FORMAT_FLAG_BINARY,
-                        0, NULL, NULL, NULL,
+                        CERT_QUERY_FORMAT_FLAG_BINARY, 0, NULL, NULL, NULL,
                         NULL, NULL, (const void **)&context)) {
     return CryptoX_Error;
   }
 
-  if (!CryptImportPublicKeyInfo(provider,
-                                PKCS_7_ASN_ENCODING | X509_ASN_ENCODING,
-                                &context->pCertInfo->SubjectPublicKeyInfo,
-                                publicKey)) {
+  if (!CryptImportPublicKeyInfo(
+          provider, PKCS_7_ASN_ENCODING | X509_ASN_ENCODING,
+          &context->pCertInfo->SubjectPublicKeyInfo, publicKey)) {
     CertFreeCertificateContext(context);
     return CryptoX_Error;
   }
 
   CertFreeCertificateContext(context);
   return CryptoX_Success;
 }
 
 /* Try to acquire context in this way:
-  * 1. Enhanced provider without creating a new key set
-  * 2. Enhanced provider with creating a new key set
-  * 3. Default provider without creating a new key set
-  * 4. Default provider without creating a new key set
-  * #2 and #4 should not be needed because of the CRYPT_VERIFYCONTEXT,
-  * but we add it just in case.
-  *
-  * @param provider Out parameter containing the provider handle.
-  * @return CryptoX_Success on success, CryptoX_Error on error.
+ * 1. Enhanced provider without creating a new key set
+ * 2. Enhanced provider with creating a new key set
+ * 3. Default provider without creating a new key set
+ * 4. Default provider without creating a new key set
+ * #2 and #4 should not be needed because of the CRYPT_VERIFYCONTEXT,
+ * but we add it just in case.
+ *
+ * @param provider Out parameter containing the provider handle.
+ * @return CryptoX_Success on success, CryptoX_Error on error.
  */
-CryptoX_Result
-CryptoAPI_InitCryptoContext(HCRYPTPROV *provider)
-{
-  if (!CryptAcquireContext(provider,
-                           NULL,
-                           MS_ENH_RSA_AES_PROV,
-                           PROV_RSA_AES,
+CryptoX_Result CryptoAPI_InitCryptoContext(HCRYPTPROV *provider) {
+  if (!CryptAcquireContext(provider, NULL, MS_ENH_RSA_AES_PROV, PROV_RSA_AES,
                            CRYPT_VERIFYCONTEXT)) {
-    if (!CryptAcquireContext(provider,
-                             NULL,
-                             MS_ENH_RSA_AES_PROV,
-                             PROV_RSA_AES,
+    if (!CryptAcquireContext(provider, NULL, MS_ENH_RSA_AES_PROV, PROV_RSA_AES,
                              CRYPT_NEWKEYSET | CRYPT_VERIFYCONTEXT)) {
-      if (!CryptAcquireContext(provider,
-                               NULL,
-                               NULL,
-                               PROV_RSA_AES,
+      if (!CryptAcquireContext(provider, NULL, NULL, PROV_RSA_AES,
                                CRYPT_VERIFYCONTEXT)) {
-        if (!CryptAcquireContext(provider,
-                                 NULL,
-                                 NULL,
-                                 PROV_RSA_AES,
+        if (!CryptAcquireContext(provider, NULL, NULL, PROV_RSA_AES,
                                  CRYPT_NEWKEYSET | CRYPT_VERIFYCONTEXT)) {
           *provider = CryptoX_InvalidHandleValue;
           return CryptoX_Error;
         }
       }
     }
   }
   return CryptoX_Success;
 }
 
 /**
-  * Begins a signature verification hash context
-  *
-  * @param provider The crypt provider to use
-  * @param hash     Out parameter for a handle to the hash context
-  * @return CryptoX_Success on success, CryptoX_Error on error.
-*/
-CryptoX_Result
-CryptoAPI_VerifyBegin(HCRYPTPROV provider, HCRYPTHASH* hash)
-{
+ * Begins a signature verification hash context
+ *
+ * @param provider The crypt provider to use
+ * @param hash     Out parameter for a handle to the hash context
+ * @return CryptoX_Success on success, CryptoX_Error on error.
+ */
+CryptoX_Result CryptoAPI_VerifyBegin(HCRYPTPROV provider, HCRYPTHASH *hash) {
   BOOL result;
   if (!provider || !hash) {
     return CryptoX_Error;
   }
 
   *hash = (HCRYPTHASH)NULL;
-  result = CryptCreateHash(provider, CALG_SHA_384,
-                           0, 0, hash);
+  result = CryptCreateHash(provider, CALG_SHA_384, 0, 0, hash);
   return result ? CryptoX_Success : CryptoX_Error;
 }
 
 /**
-  * Updates a signature verification hash context
-  *
-  * @param hash The hash context to udpate
-  * @param buf  The buffer to update the hash context with
-  * @param len The size of the passed in buffer
-  * @return CryptoX_Success on success, CryptoX_Error on error.
-*/
-CryptoX_Result
-CryptoAPI_VerifyUpdate(HCRYPTHASH* hash, BYTE *buf, DWORD len)
-{
+ * Updates a signature verification hash context
+ *
+ * @param hash The hash context to udpate
+ * @param buf  The buffer to update the hash context with
+ * @param len The size of the passed in buffer
+ * @return CryptoX_Success on success, CryptoX_Error on error.
+ */
+CryptoX_Result CryptoAPI_VerifyUpdate(HCRYPTHASH *hash, BYTE *buf, DWORD len) {
   BOOL result;
   if (!hash || !buf) {
     return CryptoX_Error;
   }
 
   result = CryptHashData(*hash, buf, len, 0);
   return result ? CryptoX_Success : CryptoX_Error;
 }
--- a/modules/libmar/verify/cryptox.h
+++ b/modules/libmar/verify/cryptox.h
@@ -15,60 +15,57 @@
 
 #if defined(MAR_NSS)
 
 #include "cert.h"
 #include "keyhi.h"
 #include "cryptohi.h"
 
 #define CryptoX_InvalidHandleValue NULL
-#define CryptoX_ProviderHandle void*
+#define CryptoX_ProviderHandle void *
 #define CryptoX_SignatureHandle VFYContext *
 #define CryptoX_PublicKey SECKEYPublicKey *
 #define CryptoX_Certificate CERTCertificate *
 
 #ifdef __cplusplus
 extern "C" {
 #endif
-CryptoX_Result NSS_LoadPublicKey(const unsigned char* certData,
+CryptoX_Result NSS_LoadPublicKey(const unsigned char *certData,
                                  unsigned int certDataSize,
-                                 SECKEYPublicKey** publicKey);
+                                 SECKEYPublicKey **publicKey);
 CryptoX_Result NSS_VerifyBegin(VFYContext **ctx,
-                               SECKEYPublicKey * const *publicKey);
-CryptoX_Result NSS_VerifySignature(VFYContext * const *ctx ,
+                               SECKEYPublicKey *const *publicKey);
+CryptoX_Result NSS_VerifySignature(VFYContext *const *ctx,
                                    const unsigned char *signature,
                                    unsigned int signatureLen);
 #ifdef __cplusplus
-} // extern "C"
+}  // extern "C"
 #endif
 
-#define CryptoX_InitCryptoProvider(CryptoHandle) \
-  CryptoX_Success
+#define CryptoX_InitCryptoProvider(CryptoHandle) CryptoX_Success
 #define CryptoX_VerifyBegin(CryptoHandle, SignatureHandle, PublicKey) \
   NSS_VerifyBegin(SignatureHandle, PublicKey)
 #define CryptoX_FreeSignatureHandle(SignatureHandle) \
   VFY_DestroyContext(*SignatureHandle, PR_TRUE)
 #define CryptoX_VerifyUpdate(SignatureHandle, buf, len) \
-  VFY_Update(*SignatureHandle, (const unsigned char*)(buf), len)
+  VFY_Update(*SignatureHandle, (const unsigned char *)(buf), len)
 #define CryptoX_LoadPublicKey(CryptoHandle, certData, dataSize, publicKey) \
   NSS_LoadPublicKey(certData, dataSize, publicKey)
 #define CryptoX_VerifySignature(hash, publicKey, signedData, len) \
   NSS_VerifySignature(hash, (const unsigned char *)(signedData), len)
-#define CryptoX_FreePublicKey(key) \
-  SECKEY_DestroyPublicKey(*key)
-#define CryptoX_FreeCertificate(cert) \
-  CERT_DestroyCertificate(*cert)
+#define CryptoX_FreePublicKey(key) SECKEY_DestroyPublicKey(*key)
+#define CryptoX_FreeCertificate(cert) CERT_DestroyCertificate(*cert)
 
 #elif XP_MACOSX
 
 #define CryptoX_InvalidHandleValue NULL
-#define CryptoX_ProviderHandle void*
-#define CryptoX_SignatureHandle void*
-#define CryptoX_PublicKey void*
-#define CryptoX_Certificate void*
+#define CryptoX_ProviderHandle void *
+#define CryptoX_SignatureHandle void *
+#define CryptoX_PublicKey void *
+#define CryptoX_Certificate void *
 
 // Forward-declare Objective-C functions implemented in MacVerifyCrypto.mm.
 #ifdef __cplusplus
 extern "C" {
 #endif
 CryptoX_Result CryptoMac_InitCryptoProvider();
 CryptoX_Result CryptoMac_VerifyBegin(CryptoX_SignatureHandle* aInputData);
 CryptoX_Result CryptoMac_VerifyUpdate(CryptoX_SignatureHandle* aInputData,
@@ -78,91 +75,85 @@ CryptoX_Result CryptoMac_LoadPublicKey(c
                                        CryptoX_PublicKey* aPublicKey);
 CryptoX_Result CryptoMac_VerifySignature(CryptoX_SignatureHandle* aInputData,
                                          CryptoX_PublicKey* aPublicKey,
                                          const unsigned char* aSignature,
                                          unsigned int aSignatureLen);
 void CryptoMac_FreeSignatureHandle(CryptoX_SignatureHandle* aInputData);
 void CryptoMac_FreePublicKey(CryptoX_PublicKey* aPublicKey);
 #ifdef __cplusplus
-} // extern "C"
+}  // extern "C"
 #endif
 
 #define CryptoX_InitCryptoProvider(aProviderHandle) \
   CryptoMac_InitCryptoProvider()
 #define CryptoX_VerifyBegin(aCryptoHandle, aInputData, aPublicKey) \
   CryptoMac_VerifyBegin(aInputData)
 #define CryptoX_VerifyUpdate(aInputData, aBuf, aLen) \
   CryptoMac_VerifyUpdate(aInputData, aBuf, aLen)
 #define CryptoX_LoadPublicKey(aProviderHandle, aCertData, aDataSize, \
-                              aPublicKey) \
+                              aPublicKey)                            \
   CryptoMac_LoadPublicKey(aCertData, aDataSize, aPublicKey)
 #define CryptoX_VerifySignature(aInputData, aPublicKey, aSignature, \
-                                aSignatureLen) \
+                                aSignatureLen)                      \
   CryptoMac_VerifySignature(aInputData, aPublicKey, aSignature, aSignatureLen)
 #define CryptoX_FreeSignatureHandle(aInputData) \
   CryptoMac_FreeSignatureHandle(aInputData)
-#define CryptoX_FreePublicKey(aPublicKey) \
-  CryptoMac_FreePublicKey(aPublicKey)
+#define CryptoX_FreePublicKey(aPublicKey) CryptoMac_FreePublicKey(aPublicKey)
 #define CryptoX_FreeCertificate(aCertificate)
 
 #elif defined(XP_WIN)
 
 #include <windows.h>
 #include <wincrypt.h>
 
 CryptoX_Result CryptoAPI_InitCryptoContext(HCRYPTPROV *provider);
-CryptoX_Result CryptoAPI_LoadPublicKey(HCRYPTPROV hProv,
-                                       BYTE *certData,
+CryptoX_Result CryptoAPI_LoadPublicKey(HCRYPTPROV hProv, BYTE *certData,
                                        DWORD sizeOfCertData,
                                        HCRYPTKEY *publicKey);
-CryptoX_Result CryptoAPI_VerifyBegin(HCRYPTPROV provider, HCRYPTHASH* hash);
-CryptoX_Result CryptoAPI_VerifyUpdate(HCRYPTHASH* hash,
-                                      BYTE *buf, DWORD len);
-CryptoX_Result CryptoAPI_VerifySignature(HCRYPTHASH *hash,
-                                         HCRYPTKEY *pubKey,
+CryptoX_Result CryptoAPI_VerifyBegin(HCRYPTPROV provider, HCRYPTHASH *hash);
+CryptoX_Result CryptoAPI_VerifyUpdate(HCRYPTHASH *hash, BYTE *buf, DWORD len);
+CryptoX_Result CryptoAPI_VerifySignature(HCRYPTHASH *hash, HCRYPTKEY *pubKey,
                                          const BYTE *signature,
                                          DWORD signatureLen);
 
 #define CryptoX_InvalidHandleValue ((ULONG_PTR)NULL)
 #define CryptoX_ProviderHandle HCRYPTPROV
 #define CryptoX_SignatureHandle HCRYPTHASH
 #define CryptoX_PublicKey HCRYPTKEY
 #define CryptoX_Certificate HCERTSTORE
 #define CryptoX_InitCryptoProvider(CryptoHandle) \
   CryptoAPI_InitCryptoContext(CryptoHandle)
 #define CryptoX_VerifyBegin(CryptoHandle, SignatureHandle, PublicKey) \
   CryptoAPI_VerifyBegin(CryptoHandle, SignatureHandle)
 #define CryptoX_FreeSignatureHandle(SignatureHandle)
 #define CryptoX_VerifyUpdate(SignatureHandle, buf, len) \
   CryptoAPI_VerifyUpdate(SignatureHandle, (BYTE *)(buf), len)
 #define CryptoX_LoadPublicKey(CryptoHandle, certData, dataSize, publicKey) \
-  CryptoAPI_LoadPublicKey(CryptoHandle, (BYTE*)(certData), dataSize, publicKey)
+  CryptoAPI_LoadPublicKey(CryptoHandle, (BYTE *)(certData), dataSize, publicKey)
 #define CryptoX_VerifySignature(hash, publicKey, signedData, len) \
   CryptoAPI_VerifySignature(hash, publicKey, signedData, len)
-#define CryptoX_FreePublicKey(key) \
-  CryptDestroyKey(*(key))
+#define CryptoX_FreePublicKey(key) CryptDestroyKey(*(key))
 #define CryptoX_FreeCertificate(cert) \
   CertCloseStore(*(cert), CERT_CLOSE_STORE_FORCE_FLAG);
 
 #else
 
 /* This default implementation is necessary because we don't want to
  * link to NSS from updater code on non Windows platforms.  On Windows
  * we use CyrptoAPI instead of NSS.  We don't call any function as they
  * would just fail, but this simplifies linking.
  */
 
 #define CryptoX_InvalidHandleValue NULL
-#define CryptoX_ProviderHandle void*
-#define CryptoX_SignatureHandle void*
-#define CryptoX_PublicKey void*
-#define CryptoX_Certificate void*
-#define CryptoX_InitCryptoProvider(CryptoHandle) \
-  CryptoX_Error
+#define CryptoX_ProviderHandle void *
+#define CryptoX_SignatureHandle void *
+#define CryptoX_PublicKey void *
+#define CryptoX_Certificate void *
+#define CryptoX_InitCryptoProvider(CryptoHandle) CryptoX_Error
 #define CryptoX_VerifyBegin(CryptoHandle, SignatureHandle, PublicKey) \
   CryptoX_Error
 #define CryptoX_FreeSignatureHandle(SignatureHandle)
 #define CryptoX_VerifyUpdate(SignatureHandle, buf, len) CryptoX_Error
 #define CryptoX_LoadPublicKey(CryptoHandle, certData, dataSize, publicKey) \
   CryptoX_Error
 #define CryptoX_VerifySignature(hash, publicKey, signedData, len) CryptoX_Error
 #define CryptoX_FreePublicKey(key) CryptoX_Error
--- a/modules/libmar/verify/mar_verify.c
+++ b/modules/libmar/verify/mar_verify.c
@@ -12,40 +12,38 @@
 #include <sys/stat.h>
 #include <fcntl.h>
 #include <stdlib.h>
 #include <string.h>
 #include "mar_private.h"
 #include "mar.h"
 #include "cryptox.h"
 
-int
-mar_read_entire_file(const char * filePath, uint32_t maxSize,
-                     /*out*/ const uint8_t * *data,
-                     /*out*/ uint32_t *size)
-{
+int mar_read_entire_file(const char *filePath, uint32_t maxSize,
+                         /*out*/ const uint8_t **data,
+                         /*out*/ uint32_t *size) {
   int result;
-  FILE * f;
+  FILE *f;
 
   if (!filePath || !data || !size) {
     return -1;
   }
 
   f = fopen(filePath, "rb");
   if (!f) {
     return -1;
   }
 
   result = -1;
   if (!fseeko(f, 0, SEEK_END)) {
     int64_t fileSize = ftello(f);
     if (fileSize > 0 && fileSize <= maxSize && !fseeko(f, 0, SEEK_SET)) {
-      unsigned char * fileData;
+      unsigned char *fileData;
 
-      *size = (unsigned int) fileSize;
+      *size = (unsigned int)fileSize;
       fileData = malloc(*size);
       if (fileData) {
         if (fread(fileData, *size, 1, f) == 1) {
           *data = fileData;
           result = 0;
         } else {
           free(fileData);
         }
@@ -57,46 +55,39 @@ mar_read_entire_file(const char * filePa
 
   return result;
 }
 
 int mar_extract_and_verify_signatures_fp(FILE *fp,
                                          CryptoX_ProviderHandle provider,
                                          CryptoX_PublicKey *keys,
                                          uint32_t keyCount);
-int mar_verify_signatures_for_fp(FILE *fp,
-                                 CryptoX_ProviderHandle provider,
+int mar_verify_signatures_for_fp(FILE *fp, CryptoX_ProviderHandle provider,
                                  CryptoX_PublicKey *keys,
-                                 const uint8_t * const *extractedSignatures,
-                                 uint32_t keyCount,
-                                 uint32_t *numVerified);
+                                 const uint8_t *const *extractedSignatures,
+                                 uint32_t keyCount, uint32_t *numVerified);
 
 /**
  * Reads the specified number of bytes from the file pointer and
  * stores them in the passed buffer.
  *
  * @param  fp     The file pointer to read from.
  * @param  buffer The buffer to store the read results.
  * @param  size   The number of bytes to read, buffer must be
  *                at least of this size.
  * @param  ctxs   Pointer to the first element in an array of verify context.
  * @param  count  The number of elements in ctxs
  * @param  err    The name of what is being written to in case of error.
  * @return  0 on success
  *         -1 on read error
  *         -2 on verify update error
-*/
-int
-ReadAndUpdateVerifyContext(FILE *fp,
-                           void *buffer,
-                           uint32_t size,
-                           CryptoX_SignatureHandle *ctxs,
-                           uint32_t count,
-                           const char *err)
-{
+ */
+int ReadAndUpdateVerifyContext(FILE *fp, void *buffer, uint32_t size,
+                               CryptoX_SignatureHandle *ctxs, uint32_t count,
+                               const char *err) {
   uint32_t k;
   if (!fp || !buffer || !ctxs || count == 0 || !err) {
     fprintf(stderr, "ERROR: Invalid parameter specified.\n");
     return CryptoX_Error;
   }
 
   if (!size) {
     return CryptoX_Success;
@@ -125,22 +116,19 @@ ReadAndUpdateVerifyContext(FILE *fp,
  *
  * @param  mar            The file who's signature should be calculated
  * @param  certData       Pointer to the first element in an array of
  *                        certificate data
  * @param  certDataSizes  Pointer to the first element in an array for size of
  *                        the data stored
  * @param  certCount      The number of elements in certData and certDataSizes
  * @return 0 on success
-*/
-int
-mar_verify_signatures(MarFile *mar,
-                      const uint8_t * const *certData,
-                      const uint32_t *certDataSizes,
-                      uint32_t certCount) {
+ */
+int mar_verify_signatures(MarFile *mar, const uint8_t *const *certData,
+                          const uint32_t *certDataSizes, uint32_t certCount) {
   int rv = -1;
   CryptoX_ProviderHandle provider = CryptoX_InvalidHandleValue;
   CryptoX_PublicKey keys[MAX_SIGNATURES];
   uint32_t k;
 
   memset(keys, 0, sizeof(keys));
 
   if (!mar || !certData || !certDataSizes || certCount == 0) {
@@ -154,18 +142,18 @@ mar_verify_signatures(MarFile *mar,
   }
 
   if (CryptoX_Failed(CryptoX_InitCryptoProvider(&provider))) {
     fprintf(stderr, "ERROR: Could not init crytpo library.\n");
     goto failure;
   }
 
   for (k = 0; k < certCount; ++k) {
-    if (CryptoX_Failed(CryptoX_LoadPublicKey(provider, certData[k], certDataSizes[k],
-                                             &keys[k]))) {
+    if (CryptoX_Failed(CryptoX_LoadPublicKey(provider, certData[k],
+                                             certDataSizes[k], &keys[k]))) {
       fprintf(stderr, "ERROR: Could not load public key.\n");
       goto failure;
     }
   }
 
   rv = mar_extract_and_verify_signatures_fp(mar->fp, provider, keys, certCount);
 
 failure:
@@ -183,22 +171,21 @@ failure:
  * Extracts each signature from the specified MAR file,
  * then calls mar_verify_signatures_for_fp to verify each signature.
  *
  * @param  fp       An opened MAR file handle
  * @param  provider A library provider
  * @param  keys     The public keys to use to verify the MAR
  * @param  keyCount The number of keys pointed to by keys
  * @return 0 on success
-*/
-int
-mar_extract_and_verify_signatures_fp(FILE *fp,
-                                     CryptoX_ProviderHandle provider,
-                                     CryptoX_PublicKey *keys,
-                                     uint32_t keyCount) {
+ */
+int mar_extract_and_verify_signatures_fp(FILE *fp,
+                                         CryptoX_ProviderHandle provider,
+                                         CryptoX_PublicKey *keys,
+                                         uint32_t keyCount) {
   uint32_t signatureCount, signatureLen, numVerified = 0;
   uint32_t signatureAlgorithmIDs[MAX_SIGNATURES];
   uint8_t *extractedSignatures[MAX_SIGNATURES];
   uint32_t i;
 
   memset(signatureAlgorithmIDs, 0, sizeof(signatureAlgorithmIDs));
   memset(extractedSignatures, 0, sizeof(extractedSignatures));
 
@@ -281,22 +268,19 @@ mar_extract_and_verify_signatures_fp(FIL
       }
       return CryptoX_Error;
     }
   }
 
   if (ftello(fp) == -1) {
     return CryptoX_Error;
   }
-  if (mar_verify_signatures_for_fp(fp,
-                                   provider,
-                                   keys,
-                                   (const uint8_t * const *)extractedSignatures,
-                                   signatureCount,
-                                   &numVerified) == CryptoX_Error) {
+  if (mar_verify_signatures_for_fp(
+          fp, provider, keys, (const uint8_t *const *)extractedSignatures,
+          signatureCount, &numVerified) == CryptoX_Error) {
     return CryptoX_Error;
   }
   for (i = 0; i < signatureCount; ++i) {
     free(extractedSignatures[i]);
   }
 
   /* If we reached here and we verified every
      signature, return success. */
@@ -327,25 +311,22 @@ mar_extract_and_verify_signatures_fp(FIL
  * @param  extractedSignatures  Pointer to the first element in an array
  *                              of extracted signatures.
  * @param  signatureCount       The number of signatures in the MAR file
  * @param numVerified           Out parameter which will be filled with
  *                              the number of verified signatures.
  *                              This information can be useful for printing
  *                              error messages.
  * @return 0 on success, *numVerified == signatureCount.
-*/
-int
-mar_verify_signatures_for_fp(FILE *fp,
-                             CryptoX_ProviderHandle provider,
-                             CryptoX_PublicKey *keys,
-                             const uint8_t * const *extractedSignatures,
-                             uint32_t signatureCount,
-                             uint32_t *numVerified)
-{
+ */
+int mar_verify_signatures_for_fp(FILE *fp, CryptoX_ProviderHandle provider,
+                                 CryptoX_PublicKey *keys,
+                                 const uint8_t *const *extractedSignatures,
+                                 uint32_t signatureCount,
+                                 uint32_t *numVerified) {
   CryptoX_SignatureHandle signatureHandles[MAX_SIGNATURES];
   char buf[BLOCKSIZE];
   uint32_t signatureLengths[MAX_SIGNATURES];
   uint32_t i;
   int rv = CryptoX_Error;
 
   memset(signatureHandles, 0, sizeof(signatureHandles));
   memset(signatureLengths, 0, sizeof(signatureLengths));
@@ -362,60 +343,51 @@ mar_verify_signatures_for_fp(FILE *fp,
      make sure a non zero value is passed in.
    */
   if (!signatureCount) {
     fprintf(stderr, "ERROR: There must be at least one signature.\n");
     goto failure;
   }
 
   for (i = 0; i < signatureCount; i++) {
-    if (CryptoX_Failed(CryptoX_VerifyBegin(provider,
-                                           &signatureHandles[i], &keys[i]))) {
+    if (CryptoX_Failed(
+            CryptoX_VerifyBegin(provider, &signatureHandles[i], &keys[i]))) {
       fprintf(stderr, "ERROR: Could not initialize signature handle.\n");
       goto failure;
     }
   }
 
   /* Skip to the start of the file */
   if (fseeko(fp, 0, SEEK_SET)) {
     fprintf(stderr, "ERROR: Could not seek to start of the file\n");
     goto failure;
   }
 
   /* Bytes 0-3: MAR1
      Bytes 4-7: index offset
      Bytes 8-15: size of entire MAR
    */
-  if (CryptoX_Failed(ReadAndUpdateVerifyContext(fp, buf,
-                                                SIGNATURE_BLOCK_OFFSET +
-                                                sizeof(uint32_t),
-                                                signatureHandles,
-                                                signatureCount,
-                                                "signature block"))) {
+  if (CryptoX_Failed(ReadAndUpdateVerifyContext(
+          fp, buf, SIGNATURE_BLOCK_OFFSET + sizeof(uint32_t), signatureHandles,
+          signatureCount, "signature block"))) {
     goto failure;
   }
 
   /* Read the signature block */
   for (i = 0; i < signatureCount; i++) {
     /* Get the signature algorithm ID */
-    if (CryptoX_Failed(ReadAndUpdateVerifyContext(fp,
-                                                  &buf,
-                                                  sizeof(uint32_t),
-                                                  signatureHandles,
-                                                  signatureCount,
-                                                  "signature algorithm ID"))) {
+    if (CryptoX_Failed(ReadAndUpdateVerifyContext(
+            fp, &buf, sizeof(uint32_t), signatureHandles, signatureCount,
+            "signature algorithm ID"))) {
       goto failure;
     }
 
-    if (CryptoX_Failed(ReadAndUpdateVerifyContext(fp,
-                                                  &signatureLengths[i],
-                                                  sizeof(uint32_t),
-                                                  signatureHandles,
-                                                  signatureCount,
-                                                  "signature length"))) {
+    if (CryptoX_Failed(ReadAndUpdateVerifyContext(
+            fp, &signatureLengths[i], sizeof(uint32_t), signatureHandles,
+            signatureCount, "signature length"))) {
       goto failure;
     }
     signatureLengths[i] = ntohl(signatureLengths[i]);
     if (signatureLengths[i] > MAX_SIGNATURE_LENGTH) {
       fprintf(stderr, "ERROR: Embedded signature length is too large.\n");
       goto failure;
     }
 
@@ -423,36 +395,36 @@ mar_verify_signatures_for_fp(FILE *fp,
     if (fseeko(fp, signatureLengths[i], SEEK_CUR)) {
       fprintf(stderr, "ERROR: Could not seek past signature.\n");
       goto failure;
     }
   }
 
   /* Read the rest of the file after the signature block */
   while (!feof(fp)) {
-    int numRead = fread(buf, 1, BLOCKSIZE , fp);
+    int numRead = fread(buf, 1, BLOCKSIZE, fp);
     if (ferror(fp)) {
       fprintf(stderr, "ERROR: Error reading data block.\n");
       goto failure;
     }
 
     for (i = 0; i < signatureCount; i++) {
-      if (CryptoX_Failed(CryptoX_VerifyUpdate(&signatureHandles[i],
-                                              buf, numRead))) {
-        fprintf(stderr, "ERROR: Error updating verify context with"
-                        " data block.\n");
+      if (CryptoX_Failed(
+              CryptoX_VerifyUpdate(&signatureHandles[i], buf, numRead))) {
+        fprintf(stderr,
+                "ERROR: Error updating verify context with"
+                " data block.\n");
         goto failure;
       }
     }
   }
 
   /* Verify the signatures */
   for (i = 0; i < signatureCount; i++) {
-    if (CryptoX_Failed(CryptoX_VerifySignature(&signatureHandles[i],
-                                               &keys[i],
+    if (CryptoX_Failed(CryptoX_VerifySignature(&signatureHandles[i], &keys[i],
                                                extractedSignatures[i],
                                                signatureLengths[i]))) {
       fprintf(stderr, "ERROR: Error verifying signature.\n");
       goto failure;
     }
     ++*numVerified;
   }
 
--- a/old-configure.in
+++ b/old-configure.in
@@ -339,76 +339,16 @@ AC_SUBST(GNU_CXX)
 AC_SUBST_LIST(STL_FLAGS)
 AC_SUBST(WRAP_STL_INCLUDES)
 
 dnl ========================================================
 dnl Checks for programs.
 dnl ========================================================
 if test "$COMPILE_ENVIRONMENT"; then
 
-dnl ========================================================
-dnl = Mac OS X SDK support
-dnl ========================================================
-MACOS_SDK_DIR=
-MOZ_ARG_WITH_STRING(macos-sdk,
-[  --with-macos-sdk=dir    Location of platform SDK to use (Mac OS X only)],
-    MACOS_SDK_DIR=$withval)
-
-MACOS_PRIVATE_FRAMEWORKS_DIR_DEFAULTED=
-MOZ_ARG_WITH_STRING(macos-private-frameworks,
-[  --with-macos-private-frameworks=dir    Location of private frameworks to use (Mac OS X only)],
-    MACOS_PRIVATE_FRAMEWORKS_DIR=$withval,
-    MACOS_PRIVATE_FRAMEWORKS_DIR=/System/Library/PrivateFrameworks
-    MACOS_PRIVATE_FRAMEWORKS_DEFAULTED=1)
-
-if test -z "${MACOS_PRIVATE_FRAMEWORKS_DEFAULTED}"; then
-  if test -z "$CROSS_COMPILE"; then
-    AC_MSG_WARN([You should only be using --with-macos-private-frameworks when cross-compiling.])
-  fi
-  if test ! -d "$MACOS_PRIVATE_FRAMEWORKS_DIR"; then
-    AC_MSG_ERROR([PrivateFrameworks directory not found.])
-  fi
-fi
-
-dnl MACOS_SDK_DIR will be set to the SDK location whenever one is in use.
-AC_SUBST(MACOS_SDK_DIR)
-AC_SUBST(MACOS_PRIVATE_FRAMEWORKS_DIR)
-
-if test "$MACOS_SDK_DIR"; then
-  dnl Sync this section with the ones in NSPR and NSS.
-  dnl Changes to the cross environment here need to be accounted for in
-  dnl the libIDL checks (below) and xpidl build.
-
-  if test ! -d "$MACOS_SDK_DIR"; then
-    AC_MSG_ERROR([SDK not found.  When using --with-macos-sdk, you must
-specify a valid SDK.  SDKs are installed when the optional cross-development
-tools are selected during the Xcode/Developer Tools installation.])
-  fi
-
-  CFLAGS="$CFLAGS -isysroot ${MACOS_SDK_DIR}"
-  CXXFLAGS="$CXXFLAGS -isysroot ${MACOS_SDK_DIR}"
-
-  dnl CPP/CXXCPP needs to be set for MOZ_CHECK_HEADER.
-  CPP="$CPP -isysroot ${MACOS_SDK_DIR}"
-  CXXCPP="$CXXCPP -isysroot ${MACOS_SDK_DIR}"
-
-  AC_LANG_SAVE
-  AC_MSG_CHECKING([for valid compiler/Mac OS X SDK combination])
-  AC_LANG_CPLUSPLUS
-  AC_TRY_COMPILE([#include <new>],[],
-   result=yes,
-   result=no)
-  AC_LANG_RESTORE
-  AC_MSG_RESULT($result)
-
-  if test "$result" = "no" ; then
-    AC_MSG_ERROR([The selected compiler and Mac OS X SDK are incompatible.])
-  fi
-fi
-
 AC_PATH_XTRA
 
 XCFLAGS="$X_CFLAGS"
 
 fi # COMPILE_ENVIRONMENT
 
 dnl ========================================================
 dnl set the defaults first
@@ -684,18 +624,16 @@ case "$host" in
     ;;
 
 *)
     HOST_CFLAGS="$HOST_CFLAGS -DXP_UNIX"
     HOST_OPTIMIZE_FLAGS="${HOST_OPTIMIZE_FLAGS=-O2}"
     ;;
 esac
 
-MOZ_DOING_LTO(lto_is_enabled)
-
 dnl ========================================================
 dnl System overrides of the defaults for target
 dnl ========================================================
 
 case "$target" in
 *-darwin*)
     MOZ_OPTIMIZE_FLAGS="-O3"
     CXXFLAGS="$CXXFLAGS -stdlib=libc++"
@@ -718,21 +656,19 @@ case "$target" in
         direct_nspr_config=1
     else
         # The ExceptionHandling framework is needed for Objective-C exception
         # logging code in nsObjCExceptions.h. Currently we only use that in debug
         # builds.
         MOZ_DEBUG_LDFLAGS="$MOZ_DEBUG_LDFLAGS -framework ExceptionHandling";
     fi
 
-    if test "x$lto_is_enabled" = "xyes"; then
-        echo "Skipping -dead_strip because lto is enabled."
     dnl DTrace and -dead_strip don't interact well. See bug 403132.
     dnl ===================================================================
-    elif test "x$enable_dtrace" = "xyes"; then
+    if test "x$enable_dtrace" = "xyes"; then
         echo "Skipping -dead_strip because DTrace is enabled. See bug 403132."
     else
         dnl check for the presence of the -dead_strip linker flag
         AC_MSG_CHECKING([for -dead_strip option to ld])
         _SAVE_LDFLAGS=$LDFLAGS
         LDFLAGS="$LDFLAGS -Wl,-dead_strip"
         AC_TRY_LINK(,[return 0;],_HAVE_DEAD_STRIP=1,_HAVE_DEAD_STRIP=)
         if test -n "$_HAVE_DEAD_STRIP" ; then
--- a/other-licenses/bsdiff/bsdiff.c
+++ b/other-licenses/bsdiff/bsdiff.c
@@ -21,16 +21,21 @@
 #include <stdlib.h>
 #include <stdio.h>
 #include <string.h>
 #include <fcntl.h>
 #include <stdarg.h>
 #ifdef XP_WIN
 #include <io.h>
 #include <winsock2.h>
+#define open _open
+#define close _close
+#define read _read
+#define lseek _lseek
+#define write _write
 #else
 #include <unistd.h>
 #include <arpa/inet.h>
 #define _O_BINARY 0
 #endif
 
 #include "crctable.h"
 
--- a/taskcluster/scripts/misc/build-cbindgen.sh
+++ b/taskcluster/scripts/misc/build-cbindgen.sh
@@ -31,17 +31,17 @@ cd $WORKSPACE/build/src
 . taskcluster/scripts/misc/tooltool-download.sh
 
 # OSX cross builds are a bit harder
 if [ "$TARGET" == "x86_64-apple-darwin" ]; then
   export PATH="$PWD/llvm-dsymutil/bin:$PATH"
   export PATH="$PWD/cctools/bin:$PATH"
   cat >cross-linker <<EOF
 exec $PWD/clang/bin/clang -v \
-  -fuse-ld=$PWD/cctools/bin/x86_64-apple-darwin11-ld \
+  -fuse-ld=$PWD/cctools/bin/x86_64-darwin11-ld \
   -mmacosx-version-min=10.11 \
   -target $TARGET \
   -B $PWD/cctools/bin \
   -isysroot $PWD/MacOSX10.11.sdk \
   "\$@"
 EOF
   chmod +x cross-linker
   export RUSTFLAGS="-C linker=$PWD/cross-linker"
--- a/taskcluster/scripts/misc/build-cctools-port-macosx.sh
+++ b/taskcluster/scripts/misc/build-cctools-port-macosx.sh
@@ -18,17 +18,17 @@ UPLOAD_DIR=$HOME/artifacts
 # Set some crosstools-port directories
 CROSSTOOLS_SOURCE_DIR=$WORKSPACE/crosstools-port
 CROSSTOOLS_CCTOOLS_DIR=$CROSSTOOLS_SOURCE_DIR/cctools
 CROSSTOOLS_BUILD_DIR=/tmp/cctools
 CLANG_DIR=$WORKSPACE/build/src/clang
 CCTOOLS_DIR=$WORKSPACE/build/src/cctools
 MACOSX_SDK_DIR=$WORKSPACE/build/src/MacOSX10.11.sdk
 
-TARGET_TRIPLE=x86_64-apple-darwin11
+TARGET_TRIPLE=x86_64-darwin11
 
 # Create our directories
 mkdir -p $CROSSTOOLS_BUILD_DIR
 
 git clone --no-checkout $CROSSTOOL_PORT_REPOSITORY $CROSSTOOLS_SOURCE_DIR
 cd $CROSSTOOLS_SOURCE_DIR
 git checkout $CROSSTOOL_PORT_REV
 # Cherry pick two fixes for LTO.
--- a/taskcluster/scripts/misc/build-cctools-port.sh
+++ b/taskcluster/scripts/misc/build-cctools-port.sh
@@ -37,19 +37,21 @@ cd $WORKSPACE/build/src
 . taskcluster/scripts/misc/tooltool-download.sh
 
 # Configure crosstools-port
 cd $CROSSTOOLS_CCTOOLS_DIR
 export CC=$CLANG_DIR/bin/clang
 export CXX=$CLANG_DIR/bin/clang++
 export LDFLAGS="-lpthread -Wl,-rpath-link,$CLANG_DIR/lib"
 ./autogen.sh
-./configure --prefix=$CROSSTOOLS_BUILD_DIR --target=x86_64-apple-darwin11 --with-llvm-config=$CLANG_DIR/bin/llvm-config
+./configure --prefix=$CROSSTOOLS_BUILD_DIR --target=x86_64-darwin11 --with-llvm-config=$CLANG_DIR/bin/llvm-config
 
 # Build cctools
 make -j `nproc --all` install
 strip $CROSSTOOLS_BUILD_DIR/bin/*
 # cctools-port doesn't include dsymutil but clang will need to find it.
-cp $CLANG_DIR/bin/dsymutil $CROSSTOOLS_BUILD_DIR/bin/x86_64-apple-darwin11-dsymutil
+cp $CLANG_DIR/bin/dsymutil $CROSSTOOLS_BUILD_DIR/bin/x86_64-darwin11-dsymutil
+# various build scripts based on cmake want to find `lipo` without a prefix
+cp $CROSSTOOLS_BUILD_DIR/bin/x86_64-darwin11-lipo $CROSSTOOLS_BUILD_DIR/bin/lipo
 
 # Put a tarball in the artifacts dir
 mkdir -p $UPLOAD_DIR
 tar cJf $UPLOAD_DIR/cctools.tar.xz -C $CROSSTOOLS_BUILD_DIR/.. `basename $CROSSTOOLS_BUILD_DIR`
--- a/taskcluster/scripts/misc/build-clang-7-linux-macosx-cross.sh
+++ b/taskcluster/scripts/misc/build-clang-7-linux-macosx-cross.sh
@@ -11,19 +11,17 @@ cd $HOME_DIR/src
 
 . taskcluster/scripts/misc/tooltool-download.sh
 
 # ld needs libLTO.so from llvm
 export LD_LIBRARY_PATH=$HOME_DIR/src/clang/lib
 # these variables are used in build-clang.py
 export CROSS_CCTOOLS_PATH=$HOME_DIR/src/cctools
 export CROSS_SYSROOT=$HOME_DIR/src/MacOSX10.11.sdk
-# cmake doesn't allow us to specify a path to lipo on the command line.
 export PATH=$PATH:$CROSS_CCTOOLS_PATH/bin
-ln -sf $CROSS_CCTOOLS_PATH/bin/x86_64-apple-darwin11-lipo $CROSS_CCTOOLS_PATH/bin/lipo
 
 # gets a bit too verbose here
 set +x
 
 cd build/build-clang
 # |mach python| sets up a virtualenv for us!
 ../../mach python ./build-clang.py -c clang-7-macosx64.json --skip-tar
 
--- a/taskcluster/scripts/misc/build-clang-macosx.sh
+++ b/taskcluster/scripts/misc/build-clang-macosx.sh
@@ -10,19 +10,17 @@ cd $HOME_DIR/src
 
 . taskcluster/scripts/misc/tooltool-download.sh
 
 # ld needs libLTO.so from llvm
 export LD_LIBRARY_PATH=$HOME_DIR/src/clang/lib
 # these variables are used in build-clang.py
 export CROSS_CCTOOLS_PATH=$HOME_DIR/src/cctools
 export CROSS_SYSROOT=$HOME_DIR/src/MacOSX10.11.sdk
-# cmake doesn't allow us to specify a path to lipo on the command line.
 export PATH=$PATH:$CROSS_CCTOOLS_PATH/bin
-ln -sf $CROSS_CCTOOLS_PATH/bin/x86_64-apple-darwin11-lipo $CROSS_CCTOOLS_PATH/bin/lipo
 
 # gets a bit too verbose here
 set +x
 
 cd build/build-clang
 # |mach python| sets up a virtualenv for us!
 ../../mach python ./build-clang.py -c clang-7-macosx64.json
 
--- a/taskcluster/scripts/misc/build-clang-tidy-macosx.sh
+++ b/taskcluster/scripts/misc/build-clang-tidy-macosx.sh
@@ -10,19 +10,17 @@ cd $HOME_DIR/src
 
 . taskcluster/scripts/misc/tooltool-download.sh
 
 # ld needs libLTO.so from llvm
 export LD_LIBRARY_PATH=$HOME_DIR/src/clang/lib
 # these variables are used in build-clang.py
 export CROSS_CCTOOLS_PATH=$HOME_DIR/src/cctools
 export CROSS_SYSROOT=$HOME_DIR/src/MacOSX10.11.sdk
-# cmake doesn't allow us to specify a path to lipo on the command line.
 export PATH=$PATH:$CROSS_CCTOOLS_PATH/bin
-ln -sf $CROSS_CCTOOLS_PATH/bin/x86_64-apple-darwin11-lipo $CROSS_CCTOOLS_PATH/bin/lipo
 
 # gets a bit too verbose here
 set +x
 
 cd build/build-clang
 # |mach python| sets up a virtualenv for us!
 ../../mach python ./build-clang.py -c clang-tidy-macosx64.json
 
--- a/taskcluster/scripts/misc/build-gn-macosx.sh
+++ b/taskcluster/scripts/misc/build-gn-macosx.sh
@@ -9,17 +9,17 @@ COMPRESS_EXT=xz
 
 CROSS_CCTOOLS_PATH=$WORKSPACE/build/src/cctools
 CROSS_SYSROOT=$WORKSPACE/build/src/MacOSX10.11.sdk
 
 export LD_LIBRARY_PATH=$WORKSPACE/build/src/clang/lib
 export CC=$WORKSPACE/build/src/clang/bin/clang
 export CXX=$WORKSPACE/build/src/clang/bin/clang++
 export AR=$WORKSPACE/build/src/clang/bin/clang
-export CFLAGS="-target x86_64-apple-darwin11 -mlinker-version=137 -B ${CROSS_CCTOOLS_PATH}/bin -isysroot ${CROSS_SYSROOT} -I${CROSS_SYSROOT}/usr/include -iframework ${CROSS_SYSROOT}/System/Library/Frameworks"
+export CFLAGS="-target x86_64-darwin11 -mlinker-version=137 -B ${CROSS_CCTOOLS_PATH}/bin -isysroot ${CROSS_SYSROOT} -I${CROSS_SYSROOT}/usr/include -iframework ${CROSS_SYSROOT}/System/Library/Frameworks"
 export CXXFLAGS="-stdlib=libc++ ${CFLAGS}"
 export LDFLAGS="${CXXFLAGS} -Wl,-syslibroot,${CROSS_SYSROOT} -Wl,-dead_strip"
 
 # We patch tools/gn/bootstrap/bootstrap.py to detect this.
 export MAC_CROSS=1
 
 # Gn build scripts use #!/usr/bin/env python, which will be python 2.6 on
 # the worker and cause failures. Work around this by putting python2.7
@@ -29,12 +29,12 @@ ln -s /usr/bin/python2.7 $WORKSPACE/pyth
 export PATH=$WORKSPACE/python_bin:$PATH
 
 cd $WORKSPACE/build/src
 
 . taskcluster/scripts/misc/tooltool-download.sh
 
 # The ninja templates used to bootstrap gn have hard-coded references to
 # 'libtool', make sure we find the right one.
-ln -s $CROSS_CCTOOLS_PATH/bin/x86_64-apple-darwin11-libtool $CROSS_CCTOOLS_PATH/bin/libtool
+ln -s $CROSS_CCTOOLS_PATH/bin/x86_64-darwin11-libtool $CROSS_CCTOOLS_PATH/bin/libtool
 export PATH=$CROSS_CCTOOLS_PATH/bin:$PATH
 
 . taskcluster/scripts/misc/build-gn-common.sh
--- a/testing/talos/talos/tests/tabswitch/content/tabswitch-content-process.js
+++ b/testing/talos/talos/tests/tabswitch/content/tabswitch-content-process.js
@@ -2,25 +2,22 @@ ChromeUtils.import("resource://gre/modul
 ChromeUtils.import("resource://gre/modules/XPCOMUtils.jsm");
 
 const WEBEXTENSION_ID = "tabswitch-talos@mozilla.org";
 const ABOUT_PAGE_NAME = "tabswitch";
 const Registrar = Components.manager.QueryInterface(Ci.nsIComponentRegistrar);
 const UUID = "0f459ab4-b4ba-4741-ac89-ee47dea07adb";
 const ABOUT_PATH_PATH = "content/test.html";
 
-XPCOMUtils.defineLazyGetter(
-  this, "processScript",
-  () => Cc["@mozilla.org/webextensions/extension-process-script;1"]
-          .getService().wrappedJSObject);
+const {WebExtensionPolicy} = Cu.getGlobalForObject(Services);
 
 const TPSProcessScript = {
   init() {
-    let extensionChild = processScript.getExtensionChild(WEBEXTENSION_ID);
-    let aboutPageURI = extensionChild.baseURI.resolve(ABOUT_PATH_PATH);
+    let extensionPolicy = WebExtensionPolicy.getByID(WEBEXTENSION_ID);
+    let aboutPageURI = extensionPolicy.getURL(ABOUT_PATH_PATH);
 
     class TabSwitchAboutModule {
       constructor() {
         this.QueryInterface = ChromeUtils.generateQI([Ci.nsIAboutModule]);
       }
       newChannel(aURI, aLoadInfo) {
         let uri = Services.io.newURI(aboutPageURI);
         let chan = Services.io.newChannelFromURIWithLoadInfo(uri, aLoadInfo);
deleted file mode 100644
--- a/testing/web-platform/meta/css/css-grid/alignment/grid-alignment-style-changes-005.html.ini
+++ /dev/null
@@ -1,19 +0,0 @@
-[grid-alignment-style-changes-005.html]
-  [.before 2]
-    expected: FAIL
-
-  [.before 3]
-    expected: FAIL
-
-  [.before 1]
-    expected: FAIL
-
-  [.after 4]
-    expected: FAIL
-
-  [.after 5]
-    expected: FAIL
-
-  [.after 6]
-    expected: FAIL
-
deleted file mode 100644
--- a/testing/web-platform/meta/css/css-grid/alignment/grid-alignment-style-changes-006.html.ini
+++ /dev/null
@@ -1,19 +0,0 @@
-[grid-alignment-style-changes-006.html]
-  [.before 2]
-    expected: FAIL
-
-  [.before 3]
-    expected: FAIL
-
-  [.before 1]
-    expected: FAIL
-
-  [.after 4]
-    expected: FAIL
-
-  [.after 5]
-    expected: FAIL
-
-  [.after 6]
-    expected: FAIL
-
deleted file mode 100644
--- a/testing/web-platform/meta/css/css-grid/alignment/grid-alignment-style-changes-007.html.ini
+++ /dev/null
@@ -1,19 +0,0 @@
-[grid-alignment-style-changes-007.html]
-  [.before 2]
-    expected: FAIL
-
-  [.before 3]
-    expected: FAIL
-
-  [.before 1]
-    expected: FAIL
-
-  [.after 4]
-    expected: FAIL
-
-  [.after 5]
-    expected: FAIL
-
-  [.after 6]
-    expected: FAIL
-
deleted file mode 100644
--- a/testing/web-platform/meta/css/css-grid/alignment/grid-alignment-style-changes-008.html.ini
+++ /dev/null
@@ -1,19 +0,0 @@
-[grid-alignment-style-changes-008.html]
-  [.before 2]
-    expected: FAIL
-
-  [.before 3]
-    expected: FAIL
-
-  [.before 1]
-    expected: FAIL
-
-  [.after 4]
-    expected: FAIL
-
-  [.after 5]
-    expected: FAIL
-
-  [.after 6]
-    expected: FAIL
-
--- a/testing/web-platform/meta/svg/interact/scripted/tabindex-focus-flag.svg.ini
+++ b/testing/web-platform/meta/svg/interact/scripted/tabindex-focus-flag.svg.ini
@@ -12,35 +12,14 @@
     expected: FAIL
 
   [video[controls\] should be focusable.]
     expected: FAIL
 
   [canvas[tabindex\] should be focusable.]
     expected: FAIL
 
-  [clipPath[tabindex\] should not be focusable.]
-    expected: FAIL
-
-  [defs[tabindex\] should not be focusable.]
-    expected: FAIL
-
-  [hatch[tabindex\] should not be focusable.]
-    expected: FAIL
-
-  [linearGradient[tabindex\] should not be focusable.]
+  [mesh[tabindex\] should be focusable.]
     expected: FAIL
 
-  [marker[tabindex\] should not be focusable.]
-    expected: FAIL
-
-  [mask[tabindex\] should not be focusable.]
+  [unknown[tabindex\] should be focusable.]
     expected: FAIL
 
-  [meshgradient[tabindex\] should not be focusable.]
-    expected: FAIL
-
-  [pattern[tabindex\] should not be focusable.]
-    expected: FAIL
-
-  [radialGradient[tabindex\] should not be focusable.]
-    expected: FAIL
-
--- a/testing/web-platform/tests/css/css-grid/alignment/grid-alignment-style-changes-005.html
+++ b/testing/web-platform/tests/css/css-grid/alignment/grid-alignment-style-changes-005.html
@@ -10,16 +10,17 @@
 <style>
 #container {
   position: relative;
   display: inline-grid;
   grid: 100px / 50px 50px 50px;
   background: grey;
   align-items: baseline;
   font-family: Ahem;
+  line-height: 1;
 }
 #item1 {
   font-size: 20px;
   background: blue;
 }
 #item2 {
   font-size: 40px;
   background: green;
--- a/testing/web-platform/tests/css/css-grid/alignment/grid-alignment-style-changes-006.html
+++ b/testing/web-platform/tests/css/css-grid/alignment/grid-alignment-style-changes-006.html
@@ -10,16 +10,17 @@
 <style>
 #container {
   position: relative;
   display: inline-grid;
   grid: 100px / 50px 50px 50px;
   background: grey;
   align-items: baseline;
   font-family: Ahem;
+  line-height: 1;
 }
 #item1 {
   font-size: 20px;
   background: blue;
 }
 #item2 {
   font-size: 40px;
   background: green;
--- a/testing/web-platform/tests/css/css-grid/alignment/grid-alignment-style-changes-007.html
+++ b/testing/web-platform/tests/css/css-grid/alignment/grid-alignment-style-changes-007.html
@@ -11,16 +11,17 @@
 #container {
   position: relative;
   display: inline-grid;
   grid: 50px 50px 50px / 100px;
   background: grey;
   justify-items: baseline;
   font-family: Ahem;
   text-orientation: sideways;
+  line-height: 1;
 }
 #container > div { writing-mode: vertical-lr; }
 #item1 {
   font-size: 20px;
   background: blue;
 }
 #item2 {
   font-size: 40px;
--- a/testing/web-platform/tests/css/css-grid/alignment/grid-alignment-style-changes-008.html
+++ b/testing/web-platform/tests/css/css-grid/alignment/grid-alignment-style-changes-008.html
@@ -10,16 +10,17 @@
 <style>
 #container {
   position: relative;
   display: inline-grid;
   grid: 50px 50px 50px / 100px;
   background: grey;
   justify-items: baseline;
   font-family: Ahem;
+  line-height: 1;
 }
 #container > div { writing-mode: vertical-lr; }
 #item1 {
   font-size: 20px;
   background: blue;
 }
 #item2 {
   font-size: 40px;
--- a/toolkit/components/antitracking/test/browser/browser.ini
+++ b/toolkit/components/antitracking/test/browser/browser.ini
@@ -16,16 +16,17 @@ support-files =
   3rdPartyWO.html
   3rdPartyOpen.html
   3rdPartyOpenUI.html
   empty.js
   popup.html
   storageAccessAPIHelpers.js
 
 [browser_allowListSeparationInPrivateAndNormalWindows.js]
+skip-if = os == "mac" && !debug # Bug 1503778
 [browser_backgroundImageAssertion.js]
 [browser_blockingCookies.js]
 support-files = server.sjs
 [browser_blockingDOMCache.js]
 skip-if = (os == "win" && os_version == "6.1" && bits == 32 && !debug) # Bug 1491937
 [browser_blockingIndexedDb.js]
 [browser_blockingIndexedDbInWorkers.js]
 [browser_blockingLocalStorage.js]
--- a/toolkit/components/extensions/Extension.jsm
+++ b/toolkit/components/extensions/Extension.jsm
@@ -37,36 +37,32 @@ ChromeUtils.import("resource://gre/modul
 
 XPCOMUtils.defineLazyModuleGetters(this, {
   AddonManager: "resource://gre/modules/AddonManager.jsm",
   AddonManagerPrivate: "resource://gre/modules/AddonManager.jsm",
   AddonSettings: "resource://gre/modules/addons/AddonSettings.jsm",
   AppConstants: "resource://gre/modules/AppConstants.jsm",
   AsyncShutdown: "resource://gre/modules/AsyncShutdown.jsm",
   ExtensionPermissions: "resource://gre/modules/ExtensionPermissions.jsm",
+  ExtensionProcessScript: "resource://gre/modules/ExtensionProcessScript.jsm",
   ExtensionStorage: "resource://gre/modules/ExtensionStorage.jsm",
   ExtensionStorageIDB: "resource://gre/modules/ExtensionStorageIDB.jsm",
   ExtensionTelemetry: "resource://gre/modules/ExtensionTelemetry.jsm",
   ExtensionTestCommon: "resource://testing-common/ExtensionTestCommon.jsm",
   FileSource: "resource://gre/modules/L10nRegistry.jsm",
   L10nRegistry: "resource://gre/modules/L10nRegistry.jsm",
   Log: "resource://gre/modules/Log.jsm",
   MessageChannel: "resource://gre/modules/MessageChannel.jsm",
   NetUtil: "resource://gre/modules/NetUtil.jsm",
   OS: "resource://gre/modules/osfile.jsm",
   PluralForm: "resource://gre/modules/PluralForm.jsm",
   Schemas: "resource://gre/modules/Schemas.jsm",
   XPIProvider: "resource://gre/modules/addons/XPIProvider.jsm",
 });
 
-XPCOMUtils.defineLazyGetter(
-  this, "processScript",
-  () => Cc["@mozilla.org/webextensions/extension-process-script;1"]
-          .getService().wrappedJSObject);
-
 // This is used for manipulating jar entry paths, which always use Unix
 // separators.
 XPCOMUtils.defineLazyGetter(
   this, "OSPath", () => {
     let obj = {};
     ChromeUtils.import("resource://gre/modules/osfile/ospath_unix.jsm", obj);
     return obj;
   });
@@ -1866,17 +1862,17 @@ class Extension extends ExtensionData {
         this.policy.privateBrowsingAllowed = this.manifest.incognito !== "not_allowed";
       }
 
       GlobalManager.init(this);
 
       this.initSharedData();
 
       this.policy.active = false;
-      this.policy = processScript.initExtension(this);
+      this.policy = ExtensionProcessScript.initExtension(this);
       this.policy.extension = this;
 
       this.updatePermissions(this.startupReason);
 
       // Select the storage.local backend if it is already known,
       // and start the data migration if needed.
       if (this.hasPermission("storage")) {
         if (!ExtensionStorageIDB.isBackendEnabled) {
--- a/toolkit/components/extensions/ExtensionChild.jsm
+++ b/toolkit/components/extensions/ExtensionChild.jsm
@@ -21,27 +21,23 @@ ChromeUtils.import("resource://gre/modul
 
 XPCOMUtils.defineLazyServiceGetter(this, "finalizationService",
                                    "@mozilla.org/toolkit/finalizationwitness;1",
                                    "nsIFinalizationWitnessService");
 
 XPCOMUtils.defineLazyModuleGetters(this, {
   ExtensionContent: "resource://gre/modules/ExtensionContent.jsm",
   ExtensionPageChild: "resource://gre/modules/ExtensionPageChild.jsm",
+  ExtensionProcessScript: "resource://gre/modules/ExtensionProcessScript.jsm",
   MessageChannel: "resource://gre/modules/MessageChannel.jsm",
   NativeApp: "resource://gre/modules/NativeMessaging.jsm",
   PerformanceCounters: "resource://gre/modules/PerformanceCounters.jsm",
   PromiseUtils: "resource://gre/modules/PromiseUtils.jsm",
 });
 
-XPCOMUtils.defineLazyGetter(
-  this, "processScript",
-  () => Cc["@mozilla.org/webextensions/extension-process-script;1"]
-          .getService().wrappedJSObject);
-
 // We're using the pref to avoid loading PerformanceCounters.jsm for nothing.
 XPCOMUtils.defineLazyPreferenceGetter(this, "gTimingEnabled",
                                       "extensions.webextensions.enablePerformanceCounters",
                                       false);
 ChromeUtils.import("resource://gre/modules/ExtensionCommon.jsm");
 ChromeUtils.import("resource://gre/modules/ExtensionUtils.jsm");
 
 const {
@@ -720,17 +716,17 @@ class BrowserExtensionContent extends Ev
     return this.policy.canAccessWindow(window);
   }
 
   getAPIManager() {
     let apiManagers = [ExtensionPageChild.apiManager];
 
     if (this.dependencies) {
       for (let id of this.dependencies) {
-        let extension = processScript.getExtensionChild(id);
+        let extension = ExtensionProcessScript.getExtensionChild(id);
         if (extension) {
           apiManagers.push(extension.experimentAPIManager);
         }
       }
     }
 
     if (this.childModules) {
       this.experimentAPIManager =
--- a/toolkit/components/extensions/ExtensionContent.jsm
+++ b/toolkit/components/extensions/ExtensionContent.jsm
@@ -8,30 +8,28 @@
 var EXPORTED_SYMBOLS = ["ExtensionContent"];
 
 /* globals ExtensionContent */
 
 ChromeUtils.import("resource://gre/modules/Services.jsm");
 ChromeUtils.import("resource://gre/modules/XPCOMUtils.jsm");
 
 XPCOMUtils.defineLazyModuleGetters(this, {
+  ExtensionProcessScript: "resource://gre/modules/ExtensionProcessScript.jsm",
   ExtensionTelemetry: "resource://gre/modules/ExtensionTelemetry.jsm",
   LanguageDetector: "resource:///modules/translation/LanguageDetector.jsm",
   MessageChannel: "resource://gre/modules/MessageChannel.jsm",
   Schemas: "resource://gre/modules/Schemas.jsm",
   WebNavigationFrames: "resource://gre/modules/WebNavigationFrames.jsm",
 });
 
 XPCOMUtils.defineLazyServiceGetter(this, "styleSheetService",
                                    "@mozilla.org/content/style-sheet-service;1",
                                    "nsIStyleSheetService");
 
-XPCOMUtils.defineLazyServiceGetter(this, "processScript",
-                                   "@mozilla.org/webextensions/extension-process-script;1");
-
 const Timer = Components.Constructor("@mozilla.org/timer;1", "nsITimer", "initWithCallback");
 
 ChromeUtils.import("resource://gre/modules/ExtensionChild.jsm");
 ChromeUtils.import("resource://gre/modules/ExtensionCommon.jsm");
 ChromeUtils.import("resource://gre/modules/ExtensionUtils.jsm");
 
 XPCOMUtils.defineLazyGlobalGetters(this, ["crypto", "TextEncoder"]);
 
@@ -643,17 +641,17 @@ class UserScript extends Script {
       },
     });
 
     return sandbox;
   }
 }
 
 var contentScripts = new DefaultWeakMap(matcher => {
-  const extension = processScript.extensions.get(matcher.extension);
+  const extension = ExtensionProcessScript.extensions.get(matcher.extension);
 
   if ("userScriptOptions" in matcher) {
     return new UserScript(extension, matcher);
   }
 
   return new Script(extension, matcher);
 });
 
--- a/toolkit/components/extensions/ExtensionPageChild.jsm
+++ b/toolkit/components/extensions/ExtensionPageChild.jsm
@@ -10,30 +10,26 @@
 var EXPORTED_SYMBOLS = ["ExtensionPageChild"];
 
 /**
  * This file handles privileged extension page logic that runs in the
  * child process.
  */
 
 ChromeUtils.import("resource://gre/modules/Services.jsm");
-ChromeUtils.import("resource://gre/modules/XPCOMUtils.jsm");
 
 ChromeUtils.defineModuleGetter(this, "ExtensionChildDevToolsUtils",
                                "resource://gre/modules/ExtensionChildDevToolsUtils.jsm");
+ChromeUtils.defineModuleGetter(this, "ExtensionProcessScript",
+                               "resource://gre/modules/ExtensionProcessScript.jsm");
 ChromeUtils.defineModuleGetter(this, "Schemas",
                                "resource://gre/modules/Schemas.jsm");
 ChromeUtils.defineModuleGetter(this, "WebNavigationFrames",
                                "resource://gre/modules/WebNavigationFrames.jsm");
 
-XPCOMUtils.defineLazyGetter(
-  this, "processScript",
-  () => Cc["@mozilla.org/webextensions/extension-process-script;1"]
-          .getService().wrappedJSObject);
-
 const CATEGORY_EXTENSION_SCRIPTS_ADDON = "webextension-scripts-addon";
 const CATEGORY_EXTENSION_SCRIPTS_DEVTOOLS = "webextension-scripts-devtools";
 
 ChromeUtils.import("resource://gre/modules/ExtensionCommon.jsm");
 ChromeUtils.import("resource://gre/modules/ExtensionChild.jsm");
 ChromeUtils.import("resource://gre/modules/ExtensionUtils.jsm");
 
 const {
@@ -85,17 +81,17 @@ const initializeBackgroundPage = (contex
     }
 
     logWarningMessage({text, filename, lineNumber, columnNumber});
   };
   Cu.exportFunction(alertOverwrite, context.contentWindow, {defineAs: "alert"});
 };
 
 function getFrameData(global) {
-  return processScript.getFrameData(global, true);
+  return ExtensionProcessScript.getFrameData(global, true);
 }
 
 var apiManager = new class extends SchemaAPIManager {
   constructor() {
     super("addon", Schemas);
     this.initialized = false;
   }
 
--- a/toolkit/components/extensions/ExtensionPolicyService.cpp
+++ b/toolkit/components/extensions/ExtensionPolicyService.cpp
@@ -23,16 +23,17 @@
 #include "nsGkAtoms.h"
 #include "nsIChannel.h"
 #include "nsIContentPolicy.h"
 #include "nsIDocShell.h"
 #include "nsIDocument.h"
 #include "nsGlobalWindowOuter.h"
 #include "nsILoadInfo.h"
 #include "nsIXULRuntime.h"
+#include "nsImportModule.h"
 #include "nsNetUtil.h"
 #include "nsPrintfCString.h"
 #include "nsPIDOMWindow.h"
 #include "nsXULAppAPI.h"
 #include "nsQueryObject.h"
 
 namespace mozilla {
 
@@ -51,18 +52,21 @@ using dom::Promise;
 
 #define OBS_TOPIC_PRELOAD_SCRIPT "web-extension-preload-content-script"
 #define OBS_TOPIC_LOAD_SCRIPT "web-extension-load-content-script"
 
 static mozIExtensionProcessScript& ProcessScript() {
   static nsCOMPtr<mozIExtensionProcessScript> sProcessScript;
 
   if (MOZ_UNLIKELY(!sProcessScript)) {
-    sProcessScript =
-        do_GetService("@mozilla.org/webextensions/extension-process-script;1");
+    nsCOMPtr<mozIExtensionProcessScriptJSM> jsm =
+        do_ImportModule("resource://gre/modules/ExtensionProcessScript.jsm");
+    MOZ_RELEASE_ASSERT(jsm);
+
+    Unused << jsm->GetExtensionProcessScript(getter_AddRefs(sProcessScript));
     MOZ_RELEASE_ASSERT(sProcessScript);
     ClearOnShutdown(&sProcessScript);
   }
   return *sProcessScript;
 }
 
 /*****************************************************************************
  * ExtensionPolicyService
rename from toolkit/components/extensions/extension-process-script.js
rename to toolkit/components/extensions/ExtensionProcessScript.jsm
--- a/toolkit/components/extensions/extension-process-script.js
+++ b/toolkit/components/extensions/ExtensionProcessScript.jsm
@@ -5,16 +5,18 @@
 
 /**
  * This script contains the minimum, skeleton content process code that we need
  * in order to lazily load other extension modules when they are first
  * necessary. Anything which is not likely to be needed immediately, or shortly
  * after startup, in *every* browser process live outside of this file.
  */
 
+var EXPORTED_SYMBOLS = ["ExtensionProcessScript"];
+
 ChromeUtils.import("resource://gre/modules/MessageChannel.jsm");
 ChromeUtils.import("resource://gre/modules/Services.jsm");
 ChromeUtils.import("resource://gre/modules/XPCOMUtils.jsm");
 
 XPCOMUtils.defineLazyModuleGetters(this, {
   ExtensionChild: "resource://gre/modules/ExtensionChild.jsm",
   ExtensionCommon: "resource://gre/modules/ExtensionCommon.jsm",
   ExtensionContent: "resource://gre/modules/ExtensionContent.jsm",
@@ -270,27 +272,17 @@ ExtensionManager = {
       }
     } catch (e) {
       Cu.reportError(e);
     }
     Services.cpmm.sendAsyncMessage(`${name}Complete`);
   },
 };
 
-function ExtensionProcessScript() {
-}
-
-ExtensionProcessScript.prototype = {
-  classID: Components.ID("{21f9819e-4cdf-49f9-85a0-850af91a5058}"),
-  QueryInterface: ChromeUtils.generateQI([Ci.mozIExtensionProcessScript]),
-
-  _xpcom_factory: XPCOMUtils.generateSingletonFactory(ExtensionProcessScript),
-
-  get wrappedJSObject() { return this; },
-
+var ExtensionProcessScript = {
   extensions,
 
   getFrameData(global, force) {
     let extGlobal = ExtensionManager.globals.get(global);
     return extGlobal && extGlobal.getFrameData(force);
   },
 
   initExtension(extension) {
@@ -317,11 +309,9 @@ ExtensionProcessScript.prototype = {
     ExtensionContent.contentScripts.get(contentScript).preload();
   },
 
   loadContentScript(contentScript, window) {
     return ExtensionContent.contentScripts.get(contentScript).injectInto(window);
   },
 };
 
-this.NSGetFactory = XPCOMUtils.generateNSGetFactory([ExtensionProcessScript]);
-
 ExtensionManager.init();
--- a/toolkit/components/extensions/extensions-toolkit.manifest
+++ b/toolkit/components/extensions/extensions-toolkit.manifest
@@ -6,12 +6,8 @@ category webextension-scripts b-tabs-bas
 
 category webextension-scripts-content toolkit chrome://extensions/content/child/ext-toolkit.js
 category webextension-scripts-devtools toolkit chrome://extensions/content/child/ext-toolkit.js
 category webextension-scripts-addon toolkit chrome://extensions/content/child/ext-toolkit.js
 
 category webextension-schemas events chrome://extensions/content/schemas/events.json
 category webextension-schemas native_manifest chrome://extensions/content/schemas/native_manifest.json
 category webextension-schemas types chrome://extensions/content/schemas/types.json
-
-
-component {21f9819e-4cdf-49f9-85a0-850af91a5058} extension-process-script.js
-contract @mozilla.org/webextensions/extension-process-script;1 {21f9819e-4cdf-49f9-85a0-850af91a5058}
--- a/toolkit/components/extensions/moz.build
+++ b/toolkit/components/extensions/moz.build
@@ -13,16 +13,17 @@ EXTRA_JS_MODULES += [
     'ExtensionChild.jsm',
     'ExtensionChildDevToolsUtils.jsm',
     'ExtensionCommon.jsm',
     'ExtensionContent.jsm',
     'ExtensionPageChild.jsm',
     'ExtensionParent.jsm',
     'ExtensionPermissions.jsm',
     'ExtensionPreferencesManager.jsm',
+    'ExtensionProcessScript.jsm',
     'ExtensionSettingsStore.jsm',
     'ExtensionStorage.jsm',
     'ExtensionStorageIDB.jsm',
     'ExtensionStorageSync.jsm',
     'ExtensionTelemetry.jsm',
     'ExtensionUtils.jsm',
     'FindContent.jsm',
     'MessageChannel.jsm',
@@ -30,17 +31,16 @@ EXTRA_JS_MODULES += [
     'NativeManifests.jsm',
     'NativeMessaging.jsm',
     'PerformanceCounters.jsm',
     'ProxyScriptContext.jsm',
     'Schemas.jsm',
 ]
 
 EXTRA_COMPONENTS += [
-    'extension-process-script.js',
     'extensions-toolkit.manifest',
 ]
 
 TESTING_JS_MODULES += [
     'ExtensionTestCommon.jsm',
     'ExtensionXPCShellUtils.jsm',
 ]
 
--- a/toolkit/components/extensions/mozIExtensionProcessScript.idl
+++ b/toolkit/components/extensions/mozIExtensionProcessScript.idl
@@ -14,8 +14,14 @@ interface mozIExtensionProcessScript : n
   void preloadContentScript(in nsISupports contentScript);
 
   Promise loadContentScript(in WebExtensionContentScript contentScript,
                             in mozIDOMWindow window);
 
   void initExtensionDocument(in nsISupports extension, in Document doc,
                              in bool privileged);
 };
+
+[scriptable,uuid(9f2a6434-f0ef-4063-ae33-368d929805d2)]
+interface mozIExtensionProcessScriptJSM : nsISupports
+{
+  readonly attribute mozIExtensionProcessScript ExtensionProcessScript;
+};
--- a/toolkit/components/extensions/test/xpcshell/test_ext_startup_perf.js
+++ b/toolkit/components/extensions/test/xpcshell/test_ext_startup_perf.js
@@ -9,16 +9,17 @@ const STARTUP_APIS = [
 const STARTUP_MODULES = [
   "resource://gre/modules/Extension.jsm",
   "resource://gre/modules/ExtensionCommon.jsm",
   "resource://gre/modules/ExtensionParent.jsm",
   // FIXME: This is only loaded at startup for new extension installs.
   // Otherwise the data comes from the startup cache. We should test for
   // this.
   "resource://gre/modules/ExtensionPermissions.jsm",
+  "resource://gre/modules/ExtensionProcessScript.jsm",
   "resource://gre/modules/ExtensionUtils.jsm",
   "resource://gre/modules/ExtensionTelemetry.jsm",
 ];
 
 if (!Services.prefs.getBoolPref("extensions.webextensions.remote")) {
   STARTUP_MODULES.push(
     "resource://gre/modules/ExtensionChild.jsm",
     "resource://gre/modules/ExtensionPageChild.jsm");
--- a/toolkit/components/maintenanceservice/bootstrapinstaller/maintenanceservice_installer.nsi
+++ b/toolkit/components/maintenanceservice/bootstrapinstaller/maintenanceservice_installer.nsi
@@ -189,30 +189,32 @@ Section "MaintenanceService"
   ; Write out that a maintenance service was attempted.
   ; We do this because on upgrades we will check this value and we only
   ; want to install once on the first upgrade to maintenance service.
   ; Also write out that we are currently installed, preferences will check
   ; this value to determine if we should show the service update pref.
   ; Since the Maintenance service can be installed either x86 or x64,
   ; always use the 64-bit registry for checking if an attempt was made.
   ${If} ${RunningX64}
+  ${OrIf} ${IsNativeARM64}
     SetRegView 64
   ${EndIf}
   WriteRegDWORD HKLM "Software\Mozilla\MaintenanceService" "Attempted" 1
   WriteRegDWORD HKLM "Software\Mozilla\MaintenanceService" "Installed" 1
   DeleteRegValue HKLM "Software\Mozilla\MaintenanceService" "FFPrefetchDisabled"
 
   ; Included here for debug purposes only.  
   ; These keys are used to bypass the installation dir is a valid installation
   ; check from the service so that tests can be run.
   WriteRegStr HKLM "${FallbackKey}\0" "name" "Mozilla Corporation"
   WriteRegStr HKLM "${FallbackKey}\0" "issuer" "DigiCert SHA2 Assured ID Code Signing CA"
   WriteRegStr HKLM "${FallbackKey}\1" "name" "Mozilla Fake SPC"
   WriteRegStr HKLM "${FallbackKey}\1" "issuer" "Mozilla Fake CA"
   ${If} ${RunningX64}
+  ${OrIf} ${IsNativeARM64}
     SetRegView lastused
   ${EndIf}
 SectionEnd
 
 ; By renaming before deleting we improve things slightly in case
 ; there is a file in use error. In this case a new install can happen.
 Function un.RenameDelete
   Pop $9
@@ -248,18 +250,20 @@ Section "Uninstall"
   Call un.RenameDelete
   Push "$INSTDIR\update\updater.exe"
   Call un.RenameDelete
   RMDir /REBOOTOK "$INSTDIR\update"
   RMDir /REBOOTOK "$INSTDIR"
   DeleteRegKey HKLM "${MaintUninstallKey}"
 
   ${If} ${RunningX64}
+  ${OrIf} ${IsNativeARM64}
     SetRegView 64
   ${EndIf}
   DeleteRegValue HKLM "Software\Mozilla\MaintenanceService" "Installed"
   DeleteRegValue HKLM "Software\Mozilla\MaintenanceService" "FFPrefetchDisabled"
   DeleteRegKey HKLM "${FallbackKey}\"
   ${If} ${RunningX64}
+  ${OrIf} ${IsNativeARM64}
     SetRegView lastused
   ${EndIf}
 SectionEnd
 
--- a/toolkit/components/telemetry/Histograms.json
+++ b/toolkit/components/telemetry/Histograms.json
@@ -9875,16 +9875,27 @@
     "kind": "exponential",
     "high": 86400,
     "n_buckets": 100,
     "bug_numbers": [1509907],
     "alert_emails": ["dev-developer-tools@lists.mozilla.org", "mbalfanz@mozilla.com"],
     "releaseChannelCollection": "opt-out",
     "description": "How long has the flexbox highlighter been active (seconds)."
   },
+  "DEVTOOLS_GRID_HIGHLIGHTER_TIME_ACTIVE_SECONDS": {
+    "record_in_processes": ["main", "content"],
+    "expires_in_version": "never",
+    "kind": "exponential",
+    "high": 86400,
+    "n_buckets": 100,
+    "bug_numbers": [1513969],
+    "alert_emails": ["dev-developer-tools@lists.mozilla.org", "mbalfanz@mozilla.com"],
+    "releaseChannelCollection": "opt-out",
+    "description": "How long has the grid highlighter been active (seconds)."
+  },
   "DEVTOOLS_TOOLBOX_TIME_ACTIVE_SECONDS": {
     "record_in_processes": ["main", "content"],
     "expires_in_version": "never",
     "kind": "exponential",
     "high": 10000000,
     "n_buckets": 100,
     "bug_numbers": [1446496],
     "alert_emails": ["dev-developer-tools@lists.mozilla.org", "jryans@mozilla.com"],
--- a/toolkit/library/moz.build
+++ b/toolkit/library/moz.build
@@ -60,17 +60,18 @@ def Libxul(name, output_category=None):
 
     # BFD ld doesn't create multiple PT_LOADs as usual when an unknown section
     # exists. Using an implicit linker script to make it fold that section in
     # .data.rel.ro makes it create multiple PT_LOADs. That implicit linker
     # script however makes gold misbehave, first because it doesn't like that
     # the linker script is given after crtbegin.o, and even past that, replaces
     # the default section rules with those from the script instead of
     # supplementing them. Which leads to a lib with a huge load of sections.
-    if CONFIG['OS_TARGET'] not in ('OpenBSD', 'WINNT') and CONFIG['LD_IS_BFD']:
+    if CONFIG['OS_TARGET'] not in ('OpenBSD', 'WINNT') and \
+            CONFIG['LINKER_KIND'] == 'bfd':
         LDFLAGS += [TOPSRCDIR + '/toolkit/library/StaticXULComponents.ld']
 
     Libxul_defines()
 
     if CONFIG['MOZ_NEEDS_LIBATOMIC']:
         OS_LIBS += ['atomic']
 
     # This option should go away in bug 1290972, but we need to wait until
--- a/toolkit/mozapps/extensions/AddonManager.jsm
+++ b/toolkit/mozapps/extensions/AddonManager.jsm
@@ -74,17 +74,17 @@ XPCOMUtils.defineLazyModuleGetters(this,
 
 XPCOMUtils.defineLazyPreferenceGetter(this, "WEBEXT_PERMISSION_PROMPTS",
                                       PREF_WEBEXT_PERM_PROMPTS, false);
 
 // Initialize the WebExtension process script service as early as possible,
 // since it needs to be able to track things like new frameLoader globals that
 // are created before other framework code has been initialized.
 Services.ppmm.loadProcessScript(
-  "data:,Components.classes['@mozilla.org/webextensions/extension-process-script;1'].getService()",
+  "data:,ChromeUtils.import('resource://gre/modules/ExtensionProcessScript.jsm')",
   true);
 
 const INTEGER = /^[1-9]\d*$/;
 
 var EXPORTED_SYMBOLS = [ "AddonManager", "AddonManagerPrivate", "AMTelemetry" ];
 
 const CATEGORY_PROVIDER_MODULE = "addon-provider-module";
 
--- a/toolkit/mozapps/installer/windows/nsis/common.nsh
+++ b/toolkit/mozapps/installer/windows/nsis/common.nsh
@@ -69,17 +69,21 @@
 !endif
 
 ; When including WinVer.nsh check if ___WINVER__NSH___ is defined to prevent
 ; loading the file a second time.
 !ifndef ___WINVER__NSH___
   !include WinVer.nsh
 !endif
 
-!include x64.nsh
+; When including x64.nsh check if ___X64__NSH___ is defined to prevent
+; loading the file a second time.
+!ifndef ___X64__NSH___
+  !include x64.nsh
+!endif
 
 ; NSIS provided macros that we have overridden.
 !include overrides.nsh
 
 !define SHORTCUTS_LOG "shortcuts_log.ini"
 !define TO_BE_DELETED "tobedeleted"
 
 ; !define SHCNF_DWORD     0x0003
@@ -1445,30 +1449,32 @@
 ################################################################################
 # Macros for handling DLL registration
 
 !macro RegisterDLL DLL
 
   ; The x64 regsvr32.exe registers x86 DLL's properly so just use it
   ; when installing on an x64 systems even when installing an x86 application.
   ${If} ${RunningX64}
+  ${OrIf} ${IsNativeARM64}
     ${DisableX64FSRedirection}
     ExecWait '"$SYSDIR\regsvr32.exe" /s "${DLL}"'
     ${EnableX64FSRedirection}
   ${Else}
     RegDLL "${DLL}"
   ${EndIf}
 
 !macroend
 
 !macro UnregisterDLL DLL
 
   ; The x64 regsvr32.exe registers x86 DLL's properly so just use it
   ; when installing on an x64 systems even when installing an x86 application.
   ${If} ${RunningX64}
+  ${OrIf} ${IsNativeARM64}
     ${DisableX64FSRedirection}
     ExecWait '"$SYSDIR\regsvr32.exe" /s /u "${DLL}"'
     ${EnableX64FSRedirection}
   ${Else}
     UnRegDLL "${DLL}"
   ${EndIf}
 
 !macroend
@@ -2468,16 +2474,17 @@
       Push $R2
       Push $R1
       Push $R0
 
       ${${_MOZFUNC_UN}GetLongPath} "$INSTDIR" $R1
       StrCpy $R6 0  ; set the counter for the outer loop to 0
 
       ${If} ${RunningX64}
+      ${OrIf} ${IsNativeARM64}
         StrCpy $R0 "false"
         ; Set the registry to the 32 bit registry for 64 bit installations or to
         ; the 64 bit registry for 32 bit installations at the beginning so it can
         ; easily be set back to the correct registry view when finished.
         !ifdef HAVE_64BIT_BUILD
           SetRegView 32
         !else
           SetRegView 64
@@ -2527,27 +2534,29 @@
       IfErrors outerloop
 
       outerdecrement:
       IntOp $R6 $R6 - 1 ; decrement the outer loop's counter when the key is deleted successfully.
       GoTo outerloop
 
       end:
       ${If} ${RunningX64}
-      ${AndIf} "$R0" == "false"
-        ; Set the registry to the correct view.
-        !ifdef HAVE_64BIT_BUILD
-          SetRegView 64
-        !else
-          SetRegView 32
-        !endif
-
-        StrCpy $R6 0  ; set the counter for the outer loop to 0
-        StrCpy $R0 "true"
-        GoTo outerloop
+      ${OrIf} ${IsNativeARM64}
+        ${If} "$R0" == "false"
+          ; Set the registry to the correct view.
+          !ifdef HAVE_64BIT_BUILD
+            SetRegView 64
+          !else
+            SetRegView 32
+          !endif
+
+          StrCpy $R6 0  ; set the counter for the outer loop to 0
+          StrCpy $R0 "true"
+          GoTo outerloop
+        ${EndIf}
       ${EndIf}
 
       ClearErrors
 
       Pop $R0
       Pop $R1
       Pop $R2
       Pop $R3
@@ -2634,16 +2643,17 @@
       Push $R3
 
       ${${_MOZFUNC_UN}GetLongPath} "$INSTDIR" $R4
       StrCpy $R6 "Software\Microsoft\Windows\CurrentVersion\Uninstall"
       StrCpy $R7 ""
       StrCpy $R8 0
 
       ${If} ${RunningX64}
+      ${OrIf} ${IsNativeARM64}
         StrCpy $R3 "false"
         ; Set the registry to the 32 bit registry for 64 bit installations or to
         ; the 64 bit registry for 32 bit installations at the beginning so it can
         ; easily be set back to the correct registry view when finished.
         !ifdef HAVE_64BIT_BUILD
           SetRegView 32
         !else
           SetRegView 64
@@ -2679,28 +2689,30 @@
       ClearErrors
       DeleteRegKey SHCTX "$R6\$R7"
       IfErrors loop +1
       IntOp $R8 $R8 - 1 ; Decrement the counter on successful deletion
       GoTo loop
 
       end:
       ${If} ${RunningX64}
-      ${AndIf} "$R3" == "false"
-        ; Set the registry to the correct view.
-        !ifdef HAVE_64BIT_BUILD
-          SetRegView 64
-        !else
-          SetRegView 32
-        !endif
-
-        StrCpy $R7 ""
-        StrCpy $R8 0
-        StrCpy $R3 "true"
-        GoTo loop
+      ${OrIf} ${IsNativeARM64}
+        ${If} "$R3" == "false"
+          ; Set the registry to the correct view.
+          !ifdef HAVE_64BIT_BUILD
+            SetRegView 64
+          !else
+            SetRegView 32
+          !endif
+
+          StrCpy $R7 ""
+          StrCpy $R8 0
+          StrCpy $R3 "true"
+          GoTo loop
+        ${EndIf}
       ${EndIf}
 
       ClearErrors
 
       Pop $R3
       Pop $R4
       Pop $R5
       Pop $R6
@@ -3138,16 +3150,17 @@
       ${${_MOZFUNC_UN}GetLongPath} "$INSTDIR" $R9
       ${If} "$R9" != ""
         StrLen $R8 "$R9"
 
         StrCpy $R4 $PROGRAMFILES32
         Call ${_MOZFUNC_UN}CleanVirtualStore_Internal
 
         ${If} ${RunningX64}
+        ${OrIf} ${IsNativeARM64}
           StrCpy $R4 $PROGRAMFILES64
           Call ${_MOZFUNC_UN}CleanVirtualStore_Internal
         ${EndIf}
 
       ${EndIf}
 
       ClearErrors
 
@@ -5755,16 +5768,17 @@ end:
       ${GetSingleInstallPath} "Software\Mozilla\${BrandFullNameInternal}" $R9
 
       StrCmp "$R9" "false" +1 finish_get_install_dir
 
       SetShellVarContext current  ; Set SHCTX to HKCU
       ${GetSingleInstallPath} "Software\Mozilla\${BrandFullNameInternal}" $R9
 
       ${If} ${RunningX64}
+      ${OrIf} ${IsNativeARM64}
         ; In HKCU there is no WOW64 redirection, which means we may have gotten
         ; the path to a 32-bit install even though we're 64-bit, or vice-versa.
         ; In that case, just use the default path instead of offering an upgrade.
         ; But only do that override if the existing install is in Program Files,
         ; because that's the only place we can be sure is specific
         ; to either 32 or 64 bit applications.
         ; The WordFind syntax below searches for the first occurence of the
         ; "delimiter" (the Program Files path) in the install path and returns
--- a/toolkit/mozapps/installer/windows/nsis/overrides.nsh
+++ b/toolkit/mozapps/installer/windows/nsis/overrides.nsh
@@ -3,59 +3,65 @@
 # file, You can obtain one at http://mozilla.org/MPL/2.0/.
 
 ################################################################################
 # Modified versions of macros provided by NSIS
 
 !ifndef OVERRIDES_INCLUDED
 !define OVERRIDES_INCLUDED
 
-!ifndef ___WINVER__NSH___
-!include WinVer.nsh
+!ifndef ___X64__NSH___
+!include x64.nsh
 !endif
 
 ; When including a file check if its verbose macro is defined to prevent
 ; loading the file a second time.
 !ifmacrondef TEXTFUNC_VERBOSE
 !include TextFunc.nsh
 !endif
 
 !ifmacrondef FILEFUNC_VERBOSE
 !include FileFunc.nsh
 !endif
 
-!macro __MOZ__WinVer_DefineOSTests WinVer
-  !insertmacro __WinVer_DefineOSTest AtLeast ${WinVer} ""
-  !insertmacro __WinVer_DefineOSTest Is ${WinVer} ""
-  !insertmacro __WinVer_DefineOSTest AtMost ${WinVer} ""
+; This was added to NSIS 3.0.4 and is needed for Windows ARM64 support
+!ifmacrondef GetNativeMachineArchitecture
+!define GetNativeMachineArchitecture "!insertmacro GetNativeMachineArchitecture "
+!macro GetNativeMachineArchitecture outvar
+  !define GetNativeMachineArchitecture_lbl lbl_GNMA_${__COUNTER__}
+  System::Call kernel32::GetCurrentProcess()p.s
+  System::Call kernel32::IsWow64Process2(ps,*i,*i0s)
+  Pop ${outvar}
+  IntCmp ${outvar} 0 "" ${GetNativeMachineArchitecture_lbl}_done ${GetNativeMachineArchitecture_lbl}_done
+    !if "${NSIS_PTR_SIZE}" <= 4
+    !if "${NSIS_CHAR_SIZE}" <= 1
+    System::Call 'USER32::CharNextW(w"")p.s'
+    Pop ${outvar}
+    IntPtrCmpU ${outvar} 0 "" ${GetNativeMachineArchitecture_lbl}_oldnt ${GetNativeMachineArchitecture_lbl}_oldnt
+      StrCpy ${outvar} 332 ; Always IMAGE_FILE_MACHINE_I386 on Win9x
+      Goto ${GetNativeMachineArchitecture_lbl}_done
+    ${GetNativeMachineArchitecture_lbl}_oldnt:
+    !endif
+    !endif
+    System::Call '*0x7FFE002E(&i2.s)'
+    Pop ${outvar}
+  ${GetNativeMachineArchitecture_lbl}_done:
+  !undef GetNativeMachineArchitecture_lbl
 !macroend
 
-!ifndef WINVER_8
-  !define WINVER_8         0x06020000 ;6.02.9200
-  !insertmacro __MOZ__WinVer_DefineOSTests 8
-!endif
-
-!ifndef WINVER_8.1
-  !define WINVER_8.1       0x06030000 ;6.03.9600
-  !insertmacro __MOZ__WinVer_DefineOSTests 8.1
-!endif
+!macro _IsNativeMachineArchitecture _ignore _arc _t _f
+  !insertmacro _LOGICLIB_TEMP
+  ${GetNativeMachineArchitecture} $_LOGICLIB_TEMP
+  !insertmacro _= $_LOGICLIB_TEMP ${_arc} `${_t}` `${_f}`
+!macroend
 
-!ifndef WINVER_2012
-  !define WINVER_2012      0x06020001 ;6.02.9200
-  !insertmacro __MOZ__WinVer_DefineOSTests 2012
-!endif
-
-!ifndef WINVER_2012R2
-  !define WINVER_2012R2    0x06030001 ;6.03.9600
-  !insertmacro __MOZ__WinVer_DefineOSTests 2012R2
-!endif
-
-!ifndef WINVER_10
-  !define WINVER_10        0x0A000000 ;10.0.10240
-  !insertmacro __MOZ__WinVer_DefineOSTests 10
+!define IsNativeMachineArchitecture `"" IsNativeMachineArchitecture `
+!define IsNativeIA32 '${IsNativeMachineArchitecture} 332' ; Intel x86
+!define IsNativeAMD64 '${IsNativeMachineArchitecture} 34404' ; x86-64/x64
+!define IsNativeARM64 '${IsNativeMachineArchitecture} 43620'
 !endif
 
 !verbose push
 !verbose 3
 !ifndef _OVERRIDE_VERBOSE
   !define _OVERRIDE_VERBOSE 3
 !endif
 !verbose ${_OVERRIDE_VERBOSE}
--- a/toolkit/mozapps/update/updater/bspatch/bspatch.cpp
+++ b/toolkit/mozapps/update/updater/bspatch/bspatch.cpp
@@ -52,59 +52,79 @@
 #endif
 
 #ifndef SSIZE_MAX
 #define SSIZE_MAX LONG_MAX
 #endif
 
 int MBS_ReadHeader(FILE *file, MBSPatchHeader *header) {
   size_t s = fread(header, 1, sizeof(MBSPatchHeader), file);
-  if (s != sizeof(MBSPatchHeader)) return READ_ERROR;
+  if (s != sizeof(MBSPatchHeader)) {
+    return READ_ERROR;
+  }
 
   header->slen = ntohl(header->slen);
   header->scrc32 = ntohl(header->scrc32);
   header->dlen = ntohl(header->dlen);
   header->cblen = ntohl(header->cblen);
   header->difflen = ntohl(header->difflen);
   header->extralen = ntohl(header->extralen);
 
   struct stat hs;
   s = fstat(fileno(file), &hs);
-  if (s != 0) return READ_ERROR;
+  if (s != 0) {
+    return READ_ERROR;
+  }
 
-  if (memcmp(header->tag, "MBDIFF10", 8) != 0) return UNEXPECTED_BSPATCH_ERROR;
+  if (memcmp(header->tag, "MBDIFF10", 8) != 0) {
+    return UNEXPECTED_BSPATCH_ERROR;
+  }
 
-  if (hs.st_size > INT_MAX) return UNEXPECTED_BSPATCH_ERROR;
+  if (hs.st_size > INT_MAX) {
+    return UNEXPECTED_BSPATCH_ERROR;
+  }
 
   size_t size = static_cast<size_t>(hs.st_size);
-  if (size < sizeof(MBSPatchHeader)) return UNEXPECTED_BSPATCH_ERROR;
+  if (size < sizeof(MBSPatchHeader)) {
+    return UNEXPECTED_BSPATCH_ERROR;
+  }
   size -= sizeof(MBSPatchHeader);
 
-  if (size < header->cblen) return UNEXPECTED_BSPATCH_ERROR;
+  if (size < header->cblen) {
+    return UNEXPECTED_BSPATCH_ERROR;
+  }
   size -= header->cblen;
 
-  if (size < header->difflen) return UNEXPECTED_BSPATCH_ERROR;
+  if (size < header->difflen) {
+    return UNEXPECTED_BSPATCH_ERROR;
+  }
   size -= header->difflen;
 
-  if (size < header->extralen) return UNEXPECTED_BSPATCH_ERROR;
+  if (size < header->extralen) {
+    return UNEXPECTED_BSPATCH_ERROR;
+  }
   size -= header->extralen;
 
-  if (size != 0) return UNEXPECTED_BSPATCH_ERROR;
+  if (size != 0) {
+    return UNEXPECTED_BSPATCH_ERROR;
+  }
 
   return OK;
 }
 
 int MBS_ApplyPatch(const MBSPatchHeader *header, FILE *patchFile,
                    unsigned char *fbuffer, FILE *file) {
   unsigned char *fbufstart = fbuffer;
   unsigned char *fbufend = fbuffer + header->slen;
 
   unsigned char *buf = (unsigned char *)malloc(header->cblen + header->difflen +
                                                header->extralen);
-  if (!buf) return BSPATCH_MEM_ERROR;
+  if (!buf) {
+    return BSPATCH_MEM_ERROR;
+  }
 
   int rv = OK;
 
   size_t r = header->cblen + header->difflen + header->extralen;
   unsigned char *wb = buf;
   while (r) {
     const size_t count = (r > SSIZE_MAX) ? SSIZE_MAX : r;
     size_t c = fread(wb, 1, count, patchFile);
--- a/toolkit/recordreplay/ipc/JSControl.cpp
+++ b/toolkit/recordreplay/ipc/JSControl.cpp
@@ -1,21 +1,25 @@
 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*-
  * vim: set ts=8 sts=2 et sw=2 tw=80:
  * This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #include "JSControl.h"
 
+#include "mozilla/ClearOnShutdown.h"
+#include "mozilla/StaticPtr.h"
 #include "js/CharacterEncoding.h"
 #include "js/Conversions.h"
 #include "js/JSON.h"
 #include "ChildInternal.h"
 #include "ParentInternal.h"
+#include "nsImportModule.h"
+#include "rrIReplay.h"
 #include "xpcprivate.h"
 
 using namespace JS;
 
 namespace mozilla {
 namespace recordreplay {
 namespace js {
 
@@ -395,54 +399,32 @@ static bool Middleman_PositionSubsumes(J
   args.rval().setBoolean(firstPosition.Subsumes(secondPosition));
   return true;
 }
 
 ///////////////////////////////////////////////////////////////////////////////
 // Devtools Sandbox
 ///////////////////////////////////////////////////////////////////////////////
 
-static PersistentRootedObject* gDevtoolsSandbox;
+static StaticRefPtr<rrIReplay> gReplay;
 
 // URL of the root script that runs when recording/replaying.
 #define ReplayScriptURL "resource://devtools/server/actors/replay/replay.js"
 
 // Whether to expose chrome:// and resource:// scripts to the debugger.
 static bool gIncludeSystemScripts;
 
 void SetupDevtoolsSandbox() {
-  MOZ_RELEASE_ASSERT(!gDevtoolsSandbox);
-
-  dom::AutoJSAPI jsapi;
-  if (!jsapi.Init(xpc::PrivilegedJunkScope())) {
-    MOZ_CRASH("SetupDevtoolsSandbox");
-  }
-
-  JSContext* cx = jsapi.cx();
+  MOZ_RELEASE_ASSERT(!gReplay);
 
-  xpc::SandboxOptions options;
-  options.sandboxName.AssignLiteral("Record/Replay Devtools Sandbox");
-  options.invisibleToDebugger = true;
-  RootedValue v(cx);
-  nsresult rv =
-      CreateSandboxObject(cx, &v, nsXPConnect::SystemPrincipal(), options);
-  MOZ_RELEASE_ASSERT(NS_SUCCEEDED(rv));
+  nsCOMPtr<rrIReplay> replay = do_ImportModule(ReplayScriptURL);
+  gReplay = replay.forget();
+  ClearOnShutdown(&gReplay);
 
-  gDevtoolsSandbox = new PersistentRootedObject(cx);
-  *gDevtoolsSandbox = ::js::UncheckedUnwrap(&v.toObject());
-
-  JSAutoRealm ar(cx, *gDevtoolsSandbox);
-
-  ErrorResult er;
-  dom::GlobalObject global(cx, *gDevtoolsSandbox);
-  dom::Optional<JS::HandleObject> targetObj(cx, *gDevtoolsSandbox);
-  RootedObject obj(cx);
-  dom::ChromeUtils::Import(global, NS_LITERAL_STRING(ReplayScriptURL),
-                           targetObj, &obj, er);
-  MOZ_RELEASE_ASSERT(!er.Failed());
+  MOZ_RELEASE_ASSERT(gReplay);
 
   gIncludeSystemScripts =
       Preferences::GetBool("devtools.recordreplay.includeSystemScripts");
 }
 
 extern "C" {
 
 MOZ_EXPORT bool RecordReplayInterface_ShouldUpdateProgressCounter(
@@ -463,26 +445,25 @@ MOZ_EXPORT bool RecordReplayInterface_Sh
 }  // extern "C"
 
 #undef ReplayScriptURL
 
 void ProcessRequest(const char16_t* aRequest, size_t aRequestLength,
                     CharBuffer* aResponse) {
   AutoDisallowThreadEvents disallow;
   AutoSafeJSContext cx;
-  JSAutoRealm ar(cx, *gDevtoolsSandbox);
+  JSAutoRealm ar(cx, xpc::PrivilegedJunkScope());
 
   RootedValue requestValue(cx);
   if (!JS_ParseJSON(cx, aRequest, aRequestLength, &requestValue)) {
     MOZ_CRASH("ProcessRequest: ParseJSON failed");
   }
 
   RootedValue responseValue(cx);
-  if (!JS_CallFunctionName(cx, *gDevtoolsSandbox, "ProcessRequest",
-                           HandleValueArray(requestValue), &responseValue)) {
+  if (NS_FAILED(gReplay->ProcessRequest(requestValue, &responseValue))) {
     MOZ_CRASH("ProcessRequest: Handler failed");
   }
 
   // Processing the request may have called into MaybeDivergeFromRecording.
   // Now that we've finished processing it, don't tolerate future events that
   // would otherwise cause us to rewind to the last checkpoint.
   DisallowUnhandledDivergeFromRecording();
 
@@ -495,70 +476,63 @@ void ProcessRequest(const char16_t* aReq
                          aResponse)) {
     MOZ_CRASH("ProcessRequest: ToJSONMaybeSafely failed");
   }
 }
 
 void EnsurePositionHandler(const BreakpointPosition& aPosition) {
   AutoDisallowThreadEvents disallow;
   AutoSafeJSContext cx;
-  JSAutoRealm ar(cx, *gDevtoolsSandbox);
+  JSAutoRealm ar(cx, xpc::PrivilegedJunkScope());
 
   RootedObject obj(cx, aPosition.Encode(cx));
   if (!obj) {
     MOZ_CRASH("EnsurePositionHandler");
   }
 
   RootedValue objValue(cx, ObjectValue(*obj));
-  RootedValue rval(cx);
-  if (!JS_CallFunctionName(cx, *gDevtoolsSandbox, "EnsurePositionHandler",
-                           HandleValueArray(objValue), &rval)) {
+  if (NS_FAILED(gReplay->EnsurePositionHandler(objValue))) {
     MOZ_CRASH("EnsurePositionHandler");
   }
 }
 
 void ClearPositionHandlers() {
   AutoDisallowThreadEvents disallow;
   AutoSafeJSContext cx;
-  JSAutoRealm ar(cx, *gDevtoolsSandbox);
+  JSAutoRealm ar(cx, xpc::PrivilegedJunkScope());
 
-  RootedValue rval(cx);
-  if (!JS_CallFunctionName(cx, *gDevtoolsSandbox, "ClearPositionHandlers",
-                           HandleValueArray::empty(), &rval)) {
+  if (NS_FAILED(gReplay->ClearPositionHandlers())) {
     MOZ_CRASH("ClearPositionHandlers");
   }
 }
 
 void ClearPausedState() {
   AutoDisallowThreadEvents disallow;
   AutoSafeJSContext cx;
-  JSAutoRealm ar(cx, *gDevtoolsSandbox);
+  JSAutoRealm ar(cx, xpc::PrivilegedJunkScope());
 
-  RootedValue rval(cx);
-  if (!JS_CallFunctionName(cx, *gDevtoolsSandbox, "ClearPausedState",
-                           HandleValueArray::empty(), &rval)) {
+  if (NS_FAILED(gReplay->ClearPausedState())) {
     MOZ_CRASH("ClearPausedState");
   }
 }
 
 Maybe<BreakpointPosition> GetEntryPosition(
     const BreakpointPosition& aPosition) {
   AutoDisallowThreadEvents disallow;
   AutoSafeJSContext cx;
-  JSAutoRealm ar(cx, *gDevtoolsSandbox);
+  JSAutoRealm ar(cx, xpc::PrivilegedJunkScope());
 
   RootedObject positionObject(cx, aPosition.Encode(cx));
   if (!positionObject) {
     MOZ_CRASH("GetEntryPosition");
   }
 
   RootedValue rval(cx);
   RootedValue positionValue(cx, ObjectValue(*positionObject));
-  if (!JS_CallFunctionName(cx, *gDevtoolsSandbox, "GetEntryPosition",
-                           HandleValueArray(positionValue), &rval)) {
+  if (NS_FAILED(gReplay->GetEntryPosition(positionValue, &rval))) {
     MOZ_CRASH("GetEntryPosition");
   }
 
   if (!rval.isObject()) {
     return Nothing();
   }
 
   RootedObject rvalObject(cx, &rval.toObject());
--- a/toolkit/recordreplay/ipc/ParentGraphics.cpp
+++ b/toolkit/recordreplay/ipc/ParentGraphics.cpp
@@ -5,21 +5,25 @@
  * You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 // This file has the logic which the middleman process uses to send messages to
 // the UI process with painting data from the child process.
 
 #include "ParentInternal.h"
 
 #include "chrome/common/mach_ipc_mac.h"
+#include "mozilla/ClearOnShutdown.h"
+#include "mozilla/StaticPtr.h"
 #include "mozilla/dom/TabChild.h"
 #include "mozilla/layers/CompositorBridgeChild.h"
 #include "mozilla/layers/ImageDataSerializer.h"
 #include "mozilla/layers/LayerTransactionChild.h"
 #include "mozilla/layers/PTextureChild.h"
+#include "nsImportModule.h"
+#include "rrIGraphics.h"
 
 #include <mach/mach_vm.h>
 
 namespace mozilla {
 namespace recordreplay {
 namespace parent {
 
 // Graphics memory buffer shared with all child processes.
@@ -61,50 +65,27 @@ void SendGraphicsMemoryToChild() {
       MachMsgPortDescriptor(gGraphicsPort, MACH_MSG_TYPE_COPY_SEND));
 
   MachPortSender sender(childPort);
   kr = sender.SendMessage(message, 1000);
   MOZ_RELEASE_ASSERT(kr == KERN_SUCCESS);
 }
 
 // Global object for the sandbox used to paint graphics data in this process.
-static JS::PersistentRootedObject* gGraphicsSandbox;
+static StaticRefPtr<rrIGraphics> gGraphics;
 
 static void InitGraphicsSandbox() {
-  MOZ_RELEASE_ASSERT(!gGraphicsSandbox);
-
-  dom::AutoJSAPI jsapi;
-  if (!jsapi.Init(xpc::PrivilegedJunkScope())) {
-    MOZ_CRASH("InitGraphicsSandbox");
-  }
-
-  JSContext* cx = jsapi.cx();
+  MOZ_RELEASE_ASSERT(!gGraphics);
 
-  xpc::SandboxOptions options;
-  options.sandboxName.AssignLiteral("Record/Replay Graphics Sandbox");
-  options.invisibleToDebugger = true;
-  RootedValue v(cx);
-  nsresult rv =
-      CreateSandboxObject(cx, &v, nsXPConnect::SystemPrincipal(), options);
-  MOZ_RELEASE_ASSERT(NS_SUCCEEDED(rv));
-
-  gGraphicsSandbox = new JS::PersistentRootedObject(cx);
-  *gGraphicsSandbox = ::js::UncheckedUnwrap(&v.toObject());
+  nsCOMPtr<rrIGraphics> graphics =
+      do_ImportModule("resource://devtools/server/actors/replay/graphics.js");
+  gGraphics = graphics.forget();
+  ClearOnShutdown(&gGraphics);
 
-  JSAutoRealm ar(cx, *gGraphicsSandbox);
-
-  ErrorResult er;
-  dom::GlobalObject global(cx, *gGraphicsSandbox);
-  dom::Optional<JS::HandleObject> targetObj(cx, *gGraphicsSandbox);
-  RootedObject obj(cx);
-  dom::ChromeUtils::Import(
-      global,
-      NS_LITERAL_STRING("resource://devtools/server/actors/replay/graphics.js"),
-      targetObj, &obj, er);
-  MOZ_RELEASE_ASSERT(!er.Failed());
+  MOZ_RELEASE_ASSERT(gGraphics);
 }
 
 // Buffer used to transform graphics memory, if necessary.
 static void* gBufferMemory;
 
 // The dimensions of the data in the graphics shmem buffer.
 static size_t gLastPaintWidth, gLastPaintHeight;
 
@@ -140,17 +121,17 @@ void UpdateGraphicsInUIProcess(const Pai
 
   bool hadFailure = !aMsg;
 
   // Clear out the last explicit paint information. This may delete aMsg.
   gLastExplicitPaint = nullptr;
   gLastCheckpoint = CheckpointId::Invalid;
 
   // Make sure there is a sandbox which is running the graphics JS module.
-  if (!gGraphicsSandbox) {
+  if (!gGraphics) {
     InitGraphicsSandbox();
   }
 
   size_t width = gLastPaintWidth;
   size_t height = gLastPaintHeight;
   size_t stride =
       layers::ImageDataSerializer::ComputeRGBStride(gSurfaceFormat, width);
 
@@ -175,32 +156,26 @@ void UpdateGraphicsInUIProcess(const Pai
     for (size_t y = 0; y < height; y++) {
       char* src = (char*)gGraphicsMemory + y * stride;
       char* dst = (char*)gBufferMemory + y * width * 4;
       memcpy(dst, src, width * 4);
     }
   }
 
   AutoSafeJSContext cx;
-  JSAutoRealm ar(cx, *gGraphicsSandbox);
+  JSAutoRealm ar(cx, xpc::PrivilegedJunkScope());
 
   JSObject* bufferObject =
       JS_NewArrayBufferWithExternalContents(cx, width * height * 4, memory);
   MOZ_RELEASE_ASSERT(bufferObject);
 
-  JS::AutoValueArray<4> args(cx);
-  args[0].setObject(*bufferObject);
-  args[1].setInt32(width);
-  args[2].setInt32(height);
-  args[3].setBoolean(hadFailure);
+  JS::RootedValue buffer(cx, ObjectValue(*bufferObject));
 
   // Call into the graphics module to update the canvas it manages.
-  RootedValue rval(cx);
-  if (!JS_CallFunctionName(cx, *gGraphicsSandbox, "UpdateCanvas", args,
-                           &rval)) {
+  if (NS_FAILED(gGraphics->UpdateCanvas(buffer, width, height, hadFailure))) {
     MOZ_CRASH("UpdateGraphicsInUIProcess");
   }
 }
 
 static void MaybeTriggerExplicitPaint() {
   if (gLastExplicitPaint &&
       gLastExplicitPaint->mCheckpointId == gLastCheckpoint) {
     UpdateGraphicsInUIProcess(gLastExplicitPaint.get());
--- a/xpcom/base/ErrorList.py
+++ b/xpcom/base/ErrorList.py
@@ -174,18 +174,16 @@ with modules["XPCOM"]:
     # Various operations are not permitted during XPCOM shutdown and will fail
     # with this exception.
     errors["NS_ERROR_ILLEGAL_DURING_SHUTDOWN"] = FAILURE(30)
     errors["NS_ERROR_SERVICE_NOT_AVAILABLE"] = FAILURE(22)
 
     errors["NS_SUCCESS_LOSS_OF_INSIGNIFICANT_DATA"] = SUCCESS(1)
     # Used by nsCycleCollectionParticipant
     errors["NS_SUCCESS_INTERRUPTED_TRAVERSE"] = SUCCESS(2)
-    # DEPRECATED
-    errors["NS_ERROR_SERVICE_IN_USE"] = SUCCESS(23)
 
 # =======================================================================
 # 2: NS_ERROR_MODULE_BASE
 # =======================================================================
 with modules["BASE"]:
     # I/O Errors
 
     #  Stream closed
@@ -462,18 +460,16 @@ with modules["PLUGINS"]:
     errors["NS_ERROR_PLUGIN_TIME_RANGE_NOT_SUPPORTED"] = FAILURE(1003)
     errors["NS_ERROR_PLUGIN_CLICKTOPLAY"] = FAILURE(1004)
 
 
 # =======================================================================
 # 8: NS_ERROR_MODULE_LAYOUT
 # =======================================================================
 with modules["LAYOUT"]:
-    # Return code for nsITableLayout
-    errors["NS_TABLELAYOUT_CELL_NOT_FOUND"] = SUCCESS(0)
     # Return code for SheetLoadData::VerifySheetReadyToParse
     errors["NS_OK_PARSE_SHEET"] = SUCCESS(1)
     # Return code for nsFrame::GetNextPrevLineFromeBlockFrame
     errors["NS_POSITION_BEFORE_TABLE"] = SUCCESS(3)
 
 
 # =======================================================================
 # 9: NS_ERROR_MODULE_HTMLPARSER
@@ -497,30 +493,24 @@ with modules["HTMLPARSER"]:
     errors["NS_ERROR_HTMLPARSER_BADDTD"] = FAILURE(1013)
     errors["NS_ERROR_HTMLPARSER_BADCONTEXT"] = FAILURE(1014)
     errors["NS_ERROR_HTMLPARSER_STOPPARSING"] = FAILURE(1015)
     errors["NS_ERROR_HTMLPARSER_UNTERMINATEDSTRINGLITERAL"] = FAILURE(1016)
     errors["NS_ERROR_HTMLPARSER_HIERARCHYTOODEEP"] = FAILURE(1017)
     errors["NS_ERROR_HTMLPARSER_FAKE_ENDTAG"] = FAILURE(1018)
     errors["NS_ERROR_HTMLPARSER_INVALID_COMMENT"] = FAILURE(1019)
 
-    errors["NS_HTMLTOKENS_NOT_AN_ENTITY"] = SUCCESS(2000)
-    errors["NS_HTMLPARSER_VALID_META_CHARSET"] = SUCCESS(3000)
-
 
 # =======================================================================
 # 10: NS_ERROR_MODULE_RDF
 # =======================================================================
 with modules["RDF"]:
     # Returned from nsIRDFDataSource::Assert() and Unassert() if the assertion
     # (or unassertion was accepted by the datasource
     errors["NS_RDF_ASSERTION_ACCEPTED"] = errors["NS_OK"]
-    # Returned from nsIRDFCursor::Advance() if the cursor has no more
-    # elements to enumerate
-    errors["NS_RDF_CURSOR_EMPTY"] = SUCCESS(1)
     # Returned from nsIRDFDataSource::GetSource() and GetTarget() if the
     # source/target has no value
     errors["NS_RDF_NO_VALUE"] = SUCCESS(2)
     # Returned from nsIRDFDataSource::Assert() and Unassert() if the assertion
     # (or unassertion) was rejected by the datasource; i.e., the datasource was
     # not willing to record the statement.
     errors["NS_RDF_ASSERTION_REJECTED"] = SUCCESS(3)
     # Return this from rdfITripleVisitor to stop cycling
@@ -530,30 +520,22 @@ with modules["RDF"]:
 # =======================================================================
 # 11: NS_ERROR_MODULE_UCONV
 # =======================================================================
 with modules["UCONV"]:
     errors["NS_ERROR_UCONV_NOCONV"] = FAILURE(1)
     errors["NS_ERROR_UDEC_ILLEGALINPUT"] = FAILURE(14)
 
     errors["NS_OK_HAD_REPLACEMENTS"] = SUCCESS(3)
-    errors["NS_SUCCESS_USING_FALLBACK_LOCALE"] = SUCCESS(2)
-    errors["NS_OK_UDEC_EXACTLENGTH"] = SUCCESS(11)
     errors["NS_OK_UDEC_MOREINPUT"] = SUCCESS(12)
     errors["NS_OK_UDEC_MOREOUTPUT"] = SUCCESS(13)
-    errors["NS_OK_UDEC_NOBOMFOUND"] = SUCCESS(14)
-    errors["NS_OK_UENC_EXACTLENGTH"] = SUCCESS(33)
     errors["NS_OK_UENC_MOREOUTPUT"] = SUCCESS(34)
     errors["NS_ERROR_UENC_NOMAPPING"] = SUCCESS(35)
-    errors["NS_OK_UENC_MOREINPUT"] = SUCCESS(36)
 
     # BEGIN DEPRECATED
-    errors["NS_EXACT_LENGTH"] = errors["NS_OK_UDEC_EXACTLENGTH"]
-    errors["NS_PARTIAL_MORE_INPUT"] = errors["NS_OK_UDEC_MOREINPUT"]
-    errors["NS_PARTIAL_MORE_OUTPUT"] = errors["NS_OK_UDEC_MOREOUTPUT"]
     errors["NS_ERROR_ILLEGAL_INPUT"] = errors["NS_ERROR_UDEC_ILLEGALINPUT"]
     # END DEPRECATED
 
 
 # =======================================================================
 # 13: NS_ERROR_MODULE_FILES
 # =======================================================================
 with modules["FILES"]:
@@ -675,18 +657,16 @@ with modules["DOM"]:
     # Only for legacy use by nsJSUtils.
     errors["NS_SUCCESS_DOM_SCRIPT_EVALUATION_THREW_UNCATCHABLE"] = SUCCESS(3)
 
 
 # =======================================================================
 # 15: NS_ERROR_MODULE_IMGLIB
 # =======================================================================
 with modules["IMGLIB"]:
-    errors["NS_IMAGELIB_SUCCESS_LOAD_FINISHED"] = SUCCESS(0)
-
     errors["NS_IMAGELIB_ERROR_FAILURE"] = FAILURE(5)
     errors["NS_IMAGELIB_ERROR_NO_DECODER"] = FAILURE(6)
     errors["NS_IMAGELIB_ERROR_NOT_FINISHED"] = FAILURE(7)
     errors["NS_IMAGELIB_ERROR_NO_ENCODER"] = FAILURE(9)
 
 
 # =======================================================================
 # 17: NS_ERROR_MODULE_EDITOR
@@ -850,20 +830,16 @@ with modules["CONTENT"]:
     # Error code for XBL
     errors["NS_ERROR_XBL_BLOCKED"] = FAILURE(15)
     # Error code for when the content process crashed
     errors["NS_ERROR_CONTENT_CRASHED"] = FAILURE(16)
     # Error code for when the content process had a different buildID than the
     # parent
     errors["NS_ERROR_BUILDID_MISMATCH"] = FAILURE(17)
 
-    # XXX this is not really used
-    errors["NS_HTML_STYLE_PROPERTY_NOT_THERE"] = SUCCESS(2)
-    errors["NS_CONTENT_BLOCKED"] = SUCCESS(8)
-    errors["NS_CONTENT_BLOCKED_SHOW_ALT"] = SUCCESS(9)
     errors["NS_PROPTABLE_PROP_OVERWRITTEN"] = SUCCESS(11)
     # Error codes for FindBroadcaster in XULDocument.cpp
     errors["NS_FINDBROADCASTER_NOT_FOUND"] = SUCCESS(12)
     errors["NS_FINDBROADCASTER_FOUND"] = SUCCESS(13)
 
 
 # =======================================================================
 # 27: NS_ERROR_MODULE_XSLT
@@ -1133,17 +1109,16 @@ with modules["GENERAL"]:
     errors["NS_ERROR_DOCUMENT_IS_PRINTMODE"] = FAILURE(2001)
 
     errors["NS_SUCCESS_DONT_FIXUP"] = SUCCESS(1)
     # This success code may be returned by nsIAppStartup::Run to indicate that
     # the application should be restarted.  This condition corresponds to the
     # case in which nsIAppStartup::Quit was called with the eRestart flag.
     errors["NS_SUCCESS_RESTART_APP"] = SUCCESS(1)
     errors["NS_SUCCESS_RESTART_APP_NOT_SAME_PROFILE"] = SUCCESS(3)
-    errors["NS_SUCCESS_UNORM_NOTFOUND"] = SUCCESS(17)
 
     # a11y
     # raised when current pivot's position is needed but it's not in the tree
     errors["NS_ERROR_NOT_IN_TREE"] = FAILURE(38)
 
     # see nsTextEquivUtils
     errors["NS_OK_NO_NAME_CLAUSE_HANDLED"] = SUCCESS(34)
 
--- a/xpcom/base/MemoryTelemetry.cpp
+++ b/xpcom/base/MemoryTelemetry.cpp
@@ -3,33 +3,33 @@
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #include "MemoryTelemetry.h"
 #include "nsMemoryReporterManager.h"
 
 #include "GCTelemetry.h"
-#include "mozJSComponentLoader.h"
 #include "mozilla/ClearOnShutdown.h"
 #include "mozilla/Result.h"
 #include "mozilla/ResultExtensions.h"
 #include "mozilla/Services.h"
 #include "mozilla/ScopeExit.h"
 #include "mozilla/SimpleEnumerator.h"
 #include "mozilla/SystemGroup.h"
 #include "mozilla/Telemetry.h"
 #include "mozilla/TimeStamp.h"
 #include "mozilla/dom/ContentParent.h"
 #include "mozilla/dom/ScriptSettings.h"
 #include "nsContentUtils.h"
 #include "nsIBrowserDOMWindow.h"
 #include "nsIDOMChromeWindow.h"
 #include "nsIMemoryReporter.h"
 #include "nsIWindowMediator.h"
+#include "nsImportModule.h"
 #include "nsNetCID.h"
 #include "nsObserverService.h"
 #include "nsReadableUtils.h"
 #include "nsThreadUtils.h"
 #include "nsXULAppAPI.h"
 #include "xpcpublic.h"
 
 #include <cstdlib>
@@ -44,29 +44,21 @@ static constexpr uint32_t kTelemetryInte
 
 static constexpr const char* kTopicCycleCollectorBegin =
     "cycle-collector-begin";
 
 // How long to wait in millis for all the child memory reports to come in
 static constexpr uint32_t kTotalMemoryCollectorTimeout = 200;
 
 static Result<nsCOMPtr<mozIGCTelemetry>, nsresult> GetGCTelemetry() {
-  AutoJSAPI jsapi;
-  MOZ_ALWAYS_TRUE(jsapi.Init(xpc::PrivilegedJunkScope()));
-  JSContext* cx = jsapi.cx();
+  nsresult rv;
 
-  JS::RootedObject global(cx);
-  JS::RootedObject exports(cx);
-  MOZ_TRY(mozJSComponentLoader::Get()->Import(
-      cx, NS_LITERAL_CSTRING("resource://gre/modules/GCTelemetry.jsm"), &global,
-      &exports));
-
-  nsCOMPtr<mozIGCTelemetryJSM> jsm;
-  MOZ_TRY(nsContentUtils::XPConnect()->WrapJS(
-      cx, exports, NS_GET_IID(mozIGCTelemetryJSM), getter_AddRefs(jsm)));
+  nsCOMPtr<mozIGCTelemetryJSM> jsm =
+      do_ImportModule("resource://gre/modules/GCTelemetry.jsm", &rv);
+  MOZ_TRY(rv);
 
   nsCOMPtr<mozIGCTelemetry> gcTelemetry;
   MOZ_TRY(jsm->GetGCTelemetry(getter_AddRefs(gcTelemetry)));
 
   return std::move(gcTelemetry);
 }
 
 namespace {
--- a/xpcom/base/moz.build
+++ b/xpcom/base/moz.build
@@ -214,17 +214,16 @@ elif CONFIG['MOZ_WIDGET_TOOLKIT'] == 'wi
 
 include('/ipc/chromium/chromium-config.mozbuild')
 
 FINAL_LIBRARY = 'xul'
 
 LOCAL_INCLUDES += [
     '../build',
     '/dom/base',
-    '/js/xpconnect/loader', # for mozJSComponentLoader.h
     '/mfbt',
     '/xpcom/ds',
 ]
 
 if 'gtk' in CONFIG['MOZ_WIDGET_TOOLKIT']:
     CXXFLAGS += CONFIG['TK_CFLAGS']
 
 if CONFIG['ENABLE_CLANG_PLUGIN'] and CONFIG['CC_TYPE'] == 'clang-cl':