Merge inbound to mozilla-central r=merge a=merge
authorMargareta Eliza Balazs <ebalazs@mozilla.com>
Tue, 07 Nov 2017 23:57:03 +0200
changeset 390588 40df5dd35fdb7ce3652fe4448ac8961c075c928e
parent 390562 fb76bb12880ce776bfd8584368be3708b511dfeb (current diff)
parent 390587 cc777e5019993d68de03a83d5b8cfe54fece31d8 (diff)
child 390610 eae1b436e4a63c4fcdd3553ad1ffdb26c3e527b6
child 390688 3949da89d1c91ae3ffebe96fc3bdbb53762b58de
push id32837
push userebalazs@mozilla.com
push dateTue, 07 Nov 2017 21:57:29 +0000
treeherdermozilla-central@40df5dd35fdb [default view] [failures only]
perfherder[talos] [build metrics] [platform microbench] (compared to previous push)
reviewersmerge, merge
milestone58.0a1
first release with
nightly linux32
40df5dd35fdb / 58.0a1 / 20171107220115 / files
nightly linux64
40df5dd35fdb / 58.0a1 / 20171107220115 / files
nightly mac
40df5dd35fdb / 58.0a1 / 20171107220115 / files
nightly win32
40df5dd35fdb / 58.0a1 / 20171107220115 / files
nightly win64
40df5dd35fdb / 58.0a1 / 20171107220115 / 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 r=merge a=merge
build/moz.configure/toolchain.configure
testing/web-platform/meta/custom-elements/adopted-callback.html.ini
--- a/browser/base/content/test/urlbar/browser_urlbarAboutHomeLoading.js
+++ b/browser/base/content/test/urlbar/browser_urlbarAboutHomeLoading.js
@@ -67,38 +67,45 @@ add_task(async function clearURLBarAfter
 });
 
 /**
  * Ensure we don't show 'about:home' in the URL bar temporarily in new tabs
  * while we're switching remoteness (when the URL we're loading and the
  * default content principal are different).
  */
 add_task(async function dontTemporarilyShowAboutHome() {
+  requestLongerTimeout(2);
+
   await SpecialPowers.pushPrefEnv({set: [["browser.startup.page", 1]]});
   let windowOpenedPromise = BrowserTestUtils.waitForNewWindow();
   let win = OpenBrowserWindow();
   await windowOpenedPromise;
   let promiseTabSwitch = BrowserTestUtils.switchTab(win.gBrowser, () => {});
   win.BrowserOpenTab();
   await promiseTabSwitch;
+  is(win.gBrowser.visibleTabs.length, 2, "2 tabs opened");
   await TabStateFlusher.flush(win.gBrowser.selectedBrowser);
   await BrowserTestUtils.closeWindow(win);
   ok(SessionStore.getClosedWindowCount(), "Should have a closed window");
 
   await SessionSaver.run();
 
   windowOpenedPromise = BrowserTestUtils.waitForNewWindow();
   win = SessionStore.undoCloseWindow(0);
   await windowOpenedPromise;
   let wpl = {
     onLocationChange() {
       is(win.gURLBar.value, "", "URL bar value should stay empty.");
     },
   };
   win.gBrowser.addProgressListener(wpl);
+
+  if (win.gBrowser.visibleTabs.length < 2) {
+    await BrowserTestUtils.waitForEvent(gBrowser.tabContainer, "TabOpen");
+  }
   let otherTab = win.gBrowser.selectedTab.previousSibling;
   let tabLoaded = BrowserTestUtils.browserLoaded(otherTab.linkedBrowser, false, "about:home");
   await BrowserTestUtils.switchTab(win.gBrowser, otherTab);
   await tabLoaded;
   win.gBrowser.removeProgressListener(wpl);
   is(win.gURLBar.value, "", "URL bar value should be empty.");
 
   await BrowserTestUtils.closeWindow(win);
--- a/browser/components/nsBrowserGlue.js
+++ b/browser/components/nsBrowserGlue.js
@@ -1740,17 +1740,17 @@ BrowserGlue.prototype = {
         return;
       this._openPreferences("sync", { origin: "doorhanger" });
     };
     this.AlertsService.showAlertNotification(null, title, body, true, null, clickCallback);
   },
 
   // eslint-disable-next-line complexity
   _migrateUI: function BG__migrateUI() {
-    const UI_VERSION = 57;
+    const UI_VERSION = 58;
     const BROWSER_DOCURL = "chrome://browser/content/browser.xul";
 
     let currentUIVersion;
     if (Services.prefs.prefHasUserValue("browser.migration.version")) {
       currentUIVersion = Services.prefs.getIntPref("browser.migration.version");
     } else {
       // This is a new profile, nothing to migrate.
       Services.prefs.setIntPref("browser.migration.version", UI_VERSION);
@@ -2165,16 +2165,23 @@ BrowserGlue.prototype = {
           if (renaissanceTheme) {
             renaissanceTheme.accentcolor = "#834d29";
             lwthemePrefs.setStringPref("usedThemes", JSON.stringify(usedThemes));
           }
         } catch (e) { /* Don't panic if this pref isn't what we expect it to be. */ }
       }
     }
 
+    if (currentUIVersion < 58) {
+      // With Firefox 57, we are doing a one time reset of the geo prefs due to bug 1413652
+      Services.prefs.clearUserPref("browser.search.countryCode");
+      Services.prefs.clearUserPref("browser.search.region");
+      Services.prefs.clearUserPref("browser.search.isUS");
+    }
+
     // Update the migration version.
     Services.prefs.setIntPref("browser.migration.version", UI_VERSION);
   },
 
   _checkForDefaultBrowser() {
     // Perform default browser checking.
     if (!ShellService) {
       return;
--- a/build/moz.configure/toolchain.configure
+++ b/build/moz.configure/toolchain.configure
@@ -194,18 +194,18 @@ set_config('XCODE_PATH', xcode_path)
 # ==============================================================
 # Normally, we'd use js_option and automatically have those variables
 # propagated to js/src, but things are complicated by possible additional
 # wrappers in CC/CXX, and by other subconfigures that do not handle those
 # options and do need CC/CXX altered.
 option('--with-compiler-wrapper', env='COMPILER_WRAPPER', nargs=1,
        help='Enable compiling with wrappers such as distcc and ccache')
 
-js_option('--with-ccache', env='CCACHE', nargs='?',
-          help='Enable compiling with ccache')
+option('--with-ccache', env='CCACHE', nargs='?',
+       help='Enable compiling with ccache')
 
 
 @depends_if('--with-ccache')
 def ccache(value):
     if len(value):
         return value
     # If --with-ccache was given without an explicit value, we default to
     # 'ccache'.
@@ -1219,29 +1219,16 @@ def wrap_system_includes(target, visibil
 set_define('HAVE_VISIBILITY_HIDDEN_ATTRIBUTE',
            depends(visibility_flags)(lambda v: bool(v) or None))
 set_define('HAVE_VISIBILITY_ATTRIBUTE',
            depends(visibility_flags)(lambda v: bool(v) or None))
 set_config('WRAP_SYSTEM_INCLUDES', wrap_system_includes)
 set_config('VISIBILITY_FLAGS', visibility_flags)
 
 
-@depends(c_compiler, using_sccache)
-def depend_cflags(info, using_sccache):
-    if info.type not in ('clang-cl', 'msvc'):
-        return '-MD -MP -MF $(MDDEPDIR)/$(@F).pp'
-    elif using_sccache:
-        # sccache supports a special flag to create depfiles
-        # by parsing MSVC's -showIncludes output.
-        return '-deps$(MDDEPDIR)/$(@F).pp'
-
-
-set_config('_DEPEND_CFLAGS', depend_cflags)
-
-
 @depends(c_compiler)
 @imports('multiprocessing')
 @imports(_from='__builtin__', _import='min')
 def pgo_flags(compiler):
     if compiler.type in ('gcc', 'clang'):
         return namespace(
             gen_cflags=['-fprofile-generate'],
             gen_ldflags=['-fprofile-generate'],
--- a/build/moz.configure/windows.configure
+++ b/build/moz.configure/windows.configure
@@ -442,33 +442,8 @@ def alter_path(sdk_bin_path):
     path = os.pathsep.join(sdk_bin_path)
     os.environ['PATH'] = path
     return path
 
 
 set_config('PATH', alter_path)
 
 check_prog('MAKECAB', ('makecab.exe',))
-
-
-@depends(c_compiler, using_sccache)
-def need_showincludes_prefix(info, using_sccache):
-    # sccache does its own -showIncludes prefix checking.
-    if info.type in ('clang-cl', 'msvc') and not using_sccache:
-        return True
-
-
-@depends(c_compiler, when=need_showincludes_prefix)
-@imports(_from='re', _import='compile', _as='re_compile')
-def msvc_showincludes_prefix(c_compiler):
-    pattern = re_compile(br'^([^:]*:.*[ :] )(.*\\stdio.h)$')
-    output = try_invoke_compiler([c_compiler.compiler], 'C', '#include <stdio.h>\n',
-                                 ['-nologo', '-c', '-Fonul', '-showIncludes'])
-    for line in output.splitlines():
-        if line.endswith(b'\\stdio.h'):
-            m = pattern.match(line)
-            if m:
-                return m.group(1)
-    # We should have found the prefix and returned earlier
-    die('Cannot find cl -showIncludes prefix.')
-
-
-set_config('CL_INCLUDES_PREFIX', msvc_showincludes_prefix)
--- a/build/mozconfig.cache
+++ b/build/mozconfig.cache
@@ -119,16 +119,22 @@ else
     esac
     export CCACHE="$topsrcdir/sccache2/sccache${suffix}"
     export SCCACHE_VERBOSE_STATS=1
     mk_add_options MOZ_PREFLIGHT_ALL+=build/sccache.mk
     mk_add_options MOZ_POSTFLIGHT_ALL+=build/sccache.mk
     mk_add_options "UPLOAD_EXTRA_FILES+=sccache.log.gz"
     case "$platform" in
     win*)
+        # sccache supports a special flag to create depfiles.
+        #TODO: bug 1318370 - move this all into toolchain.configure
+        export _DEPEND_CFLAGS='-deps$(MDDEPDIR)/$(@F).pp'
+        # Windows builds have a default wrapper that needs to be overridden
+        mk_add_options "export CC_WRAPPER="
+        mk_add_options "export CXX_WRAPPER="
         # For now, sccache doesn't support separate PDBs so force debug info to be
         # in object files.
         mk_add_options "export COMPILE_PDB_FLAG="
         mk_add_options "export HOST_PDB_FLAG="
         mk_add_options "export MOZ_DEBUG_FLAGS=-Z7"
         ;;
     esac
 fi
--- a/config/config.mk
+++ b/config/config.mk
@@ -115,20 +115,18 @@ else
   win_srcdir := $(srcdir)
   BUILD_TOOLS = $(MOZILLA_DIR)/build/unix
 endif
 
 CONFIG_TOOLS	= $(MOZ_BUILD_ROOT)/config
 AUTOCONF_TOOLS	= $(MOZILLA_DIR)/build/autoconf
 
 ifdef _MSC_VER
-ifndef MOZ_USING_SCCACHE
 CC_WRAPPER ?= $(call py_action,cl)
 CXX_WRAPPER ?= $(call py_action,cl)
-endif
 endif # _MSC_VER
 
 CC := $(CC_WRAPPER) $(CC)
 CXX := $(CXX_WRAPPER) $(CXX)
 MKDIR ?= mkdir
 SLEEP ?= sleep
 TOUCH ?= touch
 
--- a/devtools/client/debugger/test/mochitest/browser_dbg_parser-02.js
+++ b/devtools/client/debugger/test/mochitest/browser_dbg_parser-02.js
@@ -18,13 +18,13 @@ function test() {
 
   ok(parsed,
     "An object should be returned even though the source had a syntax error.");
 
   is(parser.errors.length, 1,
     "There should be one error logged when parsing.");
   is(parser.errors[0].name, "SyntaxError",
     "The correct exception was caught.");
-  is(parser.errors[0].message, "missing ; before statement",
+  is(parser.errors[0].message, "unexpected token: \'+\'",
     "The correct exception was caught.");
 
   finish();
 }
--- a/devtools/client/debugger/test/mochitest/browser_dbg_parser-04.js
+++ b/devtools/client/debugger/test/mochitest/browser_dbg_parser-04.js
@@ -31,22 +31,22 @@ function test() {
 
   ok(parsed,
     "HTML code should be parsed correctly.");
   is(parser.errors.length, 2,
     "There should be two errors logged when parsing.");
 
   is(parser.errors[0].name, "SyntaxError",
     "The correct first exception was caught.");
-  is(parser.errors[0].message, "missing ; before statement",
+  is(parser.errors[0].message, "unexpected token: \'+\'",
     "The correct first exception was caught.");
 
   is(parser.errors[1].name, "SyntaxError",
     "The correct second exception was caught.");
-  is(parser.errors[1].message, "missing ; before statement",
+  is(parser.errors[1].message, "unexpected token: \'+\'",
     "The correct second exception was caught.");
 
   is(parsed.scriptCount, 1,
     "There should be 1 script parsed in the parent HTML source.");
 
   is(parsed.getScriptInfo(source.indexOf("let a")).toSource(), "({start:-1, length:-1, index:-1})",
     "The first script shouldn't be considered valid.");
   is(parsed.getScriptInfo(source.indexOf("let b")).toSource(), "({start:85, length:13, index:0})",
--- a/devtools/server/actors/errordocs.js
+++ b/devtools/server/actors/errordocs.js
@@ -34,17 +34,17 @@ const ErrorDocs = {
   JSMSG_JSON_BAD_PARSE: "JSON_bad_parse",
   JSMSG_UNDECLARED_VAR: "Undeclared_var",
   JSMSG_UNEXPECTED_TOKEN: "Unexpected_token",
   JSMSG_BAD_OCTAL: "Bad_octal",
   JSMSG_PROPERTY_ACCESS_DENIED: "Property_access_denied",
   JSMSG_NO_PROPERTIES: "No_properties",
   JSMSG_ALREADY_HAS_PRAGMA: "Already_has_pragma",
   JSMSG_BAD_RETURN_OR_YIELD: "Bad_return_or_yield",
-  JSMSG_SEMI_BEFORE_STMNT: "Missing_semicolon_before_statement",
+  JSMSG_UNEXPECTED_TOKEN_NO_EXPECT: "Missing_semicolon_before_statement",
   JSMSG_OVER_RECURSED: "Too_much_recursion",
   JSMSG_BRACKET_AFTER_LIST: "Missing_bracket_after_list",
   JSMSG_PAREN_AFTER_ARGS: "Missing_parenthesis_after_argument_list",
   JSMSG_MORE_ARGS_NEEDED: "More_arguments_needed",
   JSMSG_BAD_LEFTSIDE_OF_ASS: "Invalid_assignment_left-hand_side",
   JSMSG_UNTERMINATED_STRING: "Unterminated_string_literal",
   JSMSG_NOT_CONSTRUCTOR: "Not_a_constructor",
   JSMSG_CURLY_AFTER_LIST: "Missing_curly_after_property_list",
--- a/dom/base/nsJSTimeoutHandler.cpp
+++ b/dom/base/nsJSTimeoutHandler.cpp
@@ -110,17 +110,17 @@ NS_IMPL_CYCLE_COLLECTION_CLASS(nsJSScrip
 NS_IMPL_CYCLE_COLLECTION_UNLINK_BEGIN(nsJSScriptTimeoutHandler)
   tmp->ReleaseJSObjects();
 NS_IMPL_CYCLE_COLLECTION_UNLINK_END
 NS_IMPL_CYCLE_COLLECTION_TRAVERSE_BEGIN_INTERNAL(nsJSScriptTimeoutHandler)
   if (MOZ_UNLIKELY(cb.WantDebugInfo())) {
     nsAutoCString name("nsJSScriptTimeoutHandler");
     if (tmp->mFunction) {
       JSObject* obj = tmp->mFunction->CallablePreserveColor();
-      JSFunction* fun = JS_GetObjectFunction(js::UncheckedUnwrap(obj));
+      JSFunction* fun = JS_GetObjectFunction(js::UncheckedUnwrapWithoutExpose(obj));
       if (fun && JS_GetFunctionId(fun)) {
         JSFlatString *funId = JS_ASSERT_STRING_IS_FLAT(JS_GetFunctionId(fun));
         size_t size = 1 + JS_PutEscapedFlatString(nullptr, 0, funId, 0);
         char *funIdName = new char[size];
         if (funIdName) {
           JS_PutEscapedFlatString(funIdName, size, funId, 0);
           name.AppendLiteral(" [");
           name.Append(funIdName);
--- a/dom/base/nsNodeUtils.cpp
+++ b/dom/base/nsNodeUtils.cpp
@@ -645,16 +645,28 @@ nsNodeUtils::CloneAndAdopt(nsINode *aNod
                       aReparentScope, aNodesWithProperties, clone,
                       aError);
       if (NS_WARN_IF(aError.Failed())) {
         return nullptr;
       }
     }
   }
 
+  if (aDeep && !aClone && aNode->IsElement()) {
+    if (ShadowRoot* shadowRoot = aNode->AsElement()->GetShadowRoot()) {
+      nsCOMPtr<nsINode> child =
+        CloneAndAdopt(shadowRoot, aClone, aDeep, nodeInfoManager,
+                      aReparentScope, aNodesWithProperties, clone,
+                      aError);
+      if (NS_WARN_IF(aError.Failed())) {
+        return nullptr;
+      }
+    }
+  }
+
   // Cloning template element.
   if (aDeep && aClone && IsTemplateElement(aNode)) {
     DocumentFragment* origContent =
       static_cast<HTMLTemplateElement*>(aNode)->Content();
     DocumentFragment* cloneContent =
       static_cast<HTMLTemplateElement*>(clone.get())->Content();
 
     // Clone the children into the clone's template content owner
--- a/dom/base/nsWrapperCache.cpp
+++ b/dom/base/nsWrapperCache.cpp
@@ -109,17 +109,17 @@ DebugWrapperTraceCallback(JS::GCCellPtr 
     callback->NoteJSChild(aPtr);
   }
 }
 
 void
 nsWrapperCache::CheckCCWrapperTraversal(void* aScriptObjectHolder,
                                         nsScriptObjectTracer* aTracer)
 {
-  JSObject* wrapper = GetWrapper();
+  JSObject* wrapper = GetWrapperPreserveColor();
   if (!wrapper) {
     return;
   }
 
   DebugWrapperTraversalCallback callback(wrapper);
 
   // The CC traversal machinery cannot trigger GC; however, the analysis cannot
   // see through the COM layer, so we use a suppression to help it.
--- a/dom/base/nsWrapperCache.h
+++ b/dom/base/nsWrapperCache.h
@@ -307,16 +307,17 @@ public:
   }
 
   void PreserveWrapper(void* aScriptObjectHolder, nsScriptObjectTracer* aTracer)
   {
     if (PreservingWrapper()) {
       return;
     }
 
+    GetWrapper(); // Read barrier for incremental GC.
     HoldJSObjects(aScriptObjectHolder, aTracer);
     SetPreservingWrapper(true);
 #ifdef DEBUG
     // Make sure the cycle collector will be able to traverse to the wrapper.
     CheckCCWrapperTraversal(aScriptObjectHolder, aTracer);
 #endif
   }
 
--- a/dom/media/MediaManager.cpp
+++ b/dom/media/MediaManager.cpp
@@ -30,16 +30,17 @@
 #include "nsAppDirectoryServiceDefs.h"
 #include "nsIInputStream.h"
 #include "nsILineInputStream.h"
 #include "mozilla/Telemetry.h"
 #include "mozilla/Types.h"
 #include "mozilla/PeerIdentity.h"
 #include "mozilla/dom/BindingDeclarations.h"
 #include "mozilla/dom/ContentChild.h"
+#include "mozilla/dom/Element.h"
 #include "mozilla/dom/File.h"
 #include "mozilla/dom/MediaStreamBinding.h"
 #include "mozilla/dom/MediaStreamTrackBinding.h"
 #include "mozilla/dom/GetUserMediaRequestBinding.h"
 #include "mozilla/dom/Promise.h"
 #include "mozilla/dom/MediaDevices.h"
 #include "mozilla/Base64.h"
 #include "mozilla/ipc/BackgroundChild.h"
@@ -2125,16 +2126,45 @@ nsresult MediaManager::GenerateUUID(nsAS
   NS_ENSURE_SUCCESS(rv, rv);
 
   char buffer[NSID_LENGTH];
   id.ToProvidedString(buffer);
   aResult.Assign(NS_ConvertUTF8toUTF16(buffer));
   return NS_OK;
 }
 
+static bool IsFullyActive(nsPIDOMWindowInner* aWindow)
+{
+  while (true) {
+    if (!aWindow) {
+      return false;
+    }
+    nsIDocument* document = aWindow->GetExtantDoc();
+    if (!document) {
+      return false;
+    }
+    if (!document->IsCurrentActiveDocument()) {
+      return false;
+    }
+    nsPIDOMWindowOuter* context = aWindow->GetOuterWindow();
+    if (!context) {
+      return false;
+    }
+    if (context->IsTopLevelWindow()) {
+      return true;
+    }
+    nsCOMPtr<Element> frameElement =
+      nsGlobalWindow::Cast(context)->GetRealFrameElementOuter();
+    if (!frameElement) {
+      return false;
+    }
+    aWindow = frameElement->OwnerDoc()->GetInnerWindow();
+  }
+}
+
 enum class GetUserMediaSecurityState {
   Other = 0,
   HTTPS = 1,
   File = 2,
   App = 3,
   Localhost = 4,
   Loop = 5,
   Privileged = 6
@@ -2168,16 +2198,24 @@ MediaManager::GetUserMedia(nsPIDOMWindow
   if (!IsOn(c.mVideo) && !IsOn(c.mAudio)) {
     RefPtr<MediaStreamError> error =
         new MediaStreamError(aWindow,
                              NS_LITERAL_STRING("TypeError"),
                              NS_LITERAL_STRING("audio and/or video is required"));
     onFailure->OnError(error);
     return NS_OK;
   }
+
+  if (!IsFullyActive(aWindow)) {
+    RefPtr<MediaStreamError> error =
+        new MediaStreamError(aWindow, NS_LITERAL_STRING("InvalidStateError"));
+    onFailure->OnError(error);
+    return NS_OK;
+  }
+
   if (sInShutdown) {
     RefPtr<MediaStreamError> error =
         new MediaStreamError(aWindow,
                              NS_LITERAL_STRING("AbortError"),
                              NS_LITERAL_STRING("In shutdown"));
     onFailure->OnError(error);
     return NS_OK;
   }
--- a/image/SurfaceCache.cpp
+++ b/image/SurfaceCache.cpp
@@ -163,17 +163,17 @@ public:
 
   void SetCannotSubstitute() { mProvider->Availability().SetCannotSubstitute(); }
   bool CannotSubstitute() const { return mProvider->Availability().CannotSubstitute(); }
 
   bool IsPlaceholder() const { return mProvider->Availability().IsPlaceholder(); }
   bool IsDecoded() const { return !IsPlaceholder() && mProvider->IsFinished(); }
 
   ImageKey GetImageKey() const { return mProvider->GetImageKey(); }
-  SurfaceKey GetSurfaceKey() const { return mProvider->GetSurfaceKey(); }
+  const SurfaceKey& GetSurfaceKey() const { return mProvider->GetSurfaceKey(); }
   nsExpirationState* GetExpirationState() { return &mExpirationState; }
 
   CostEntry GetCostEntry()
   {
     return image::CostEntry(WrapNotNull(this), mProvider->LogicalSizeInBytes());
   }
 
   // A helper type used by SurfaceCacheImpl::CollectSizeOfSurfaces.
--- a/image/imgRequestProxy.cpp
+++ b/image/imgRequestProxy.cpp
@@ -510,22 +510,22 @@ imgRequestProxy::CancelAndForgetObserver
   // onStopRequest.
   if (mCanceled && !mListener) {
     return NS_ERROR_FAILURE;
   }
 
   LOG_SCOPE(gImgLog, "imgRequestProxy::CancelAndForgetObserver");
 
   mCanceled = true;
+  mForceDispatchLoadGroup = true;
 
   if (GetOwner()) {
     GetOwner()->RemoveProxy(this, aStatus);
   }
 
-  mForceDispatchLoadGroup = true;
   RemoveFromLoadGroup();
   mForceDispatchLoadGroup = false;
 
   NullOutListener();
 
   return NS_OK;
 }
 
--- a/js/rust/src/rust.rs
+++ b/js/rust/src/rust.rs
@@ -30,37 +30,17 @@ use panic;
 const DEFAULT_HEAPSIZE: u32 = 32_u32 * 1024_u32 * 1024_u32;
 
 // From Gecko:
 // Our "default" stack is what we use in configurations where we don't have a compelling reason to
 // do things differently. This is effectively 1MB on 64-bit platforms.
 const STACK_QUOTA: usize = 128 * 8 * 1024;
 
 // From Gecko:
-// The JS engine permits us to set different stack limits for system code,
-// trusted script, and untrusted script. We have tests that ensure that
-// we can always execute 10 "heavy" (eval+with) stack frames deeper in
-// privileged code. Our stack sizes vary greatly in different configurations,
-// so satisfying those tests requires some care. Manual measurements of the
-// number of heavy stack frames achievable gives us the following rough data,
-// ordered by the effective categories in which they are grouped in the
-// JS_SetNativeStackQuota call (which predates this analysis).
-//
-// (NB: These numbers may have drifted recently - see bug 938429)
-// OSX 64-bit Debug: 7MB stack, 636 stack frames => ~11.3k per stack frame
-// OSX64 Opt: 7MB stack, 2440 stack frames => ~3k per stack frame
-//
-// Linux 32-bit Debug: 2MB stack, 426 stack frames => ~4.8k per stack frame
-// Linux 64-bit Debug: 4MB stack, 455 stack frames => ~9.0k per stack frame
-//
-// Windows (Opt+Debug): 900K stack, 235 stack frames => ~3.4k per stack frame
-//
-// Linux 32-bit Opt: 1MB stack, 272 stack frames => ~3.8k per stack frame
-// Linux 64-bit Opt: 2MB stack, 316 stack frames => ~6.5k per stack frame
-//
+// (See js/xpconnect/src/XPCJSContext.cpp)
 // We tune the trusted/untrusted quotas for each configuration to achieve our
 // invariants while attempting to minimize overhead. In contrast, our buffer
 // between system code and trusted script is a very unscientific 10k.
 const SYSTEM_CODE_BUFFER: usize = 10 * 1024;
 
 // Gecko's value on 64-bit.
 const TRUSTED_SCRIPT_BUFFER: usize = 8 * 12800;
 
--- a/js/src/builtin/RegExp.cpp
+++ b/js/src/builtin/RegExp.cpp
@@ -173,17 +173,17 @@ js::ExecuteRegExpLegacy(JSContext* cx, R
     }
 
     return CreateRegExpMatchResult(cx, input, matches, rval);
 }
 
 static bool
 CheckPatternSyntax(JSContext* cx, HandleAtom pattern, RegExpFlag flags)
 {
-    CompileOptions options(cx);
+    CompileOptions options(cx, JSVERSION_DEFAULT);
     frontend::TokenStream dummyTokenStream(cx, options, nullptr, 0, nullptr);
     return irregexp::ParsePatternSyntax(dummyTokenStream, cx->tempLifoAlloc(), pattern,
                                         flags & UnicodeFlag);
 }
 
 enum RegExpSharedUse {
     UseRegExpShared,
     DontUseRegExpShared
--- a/js/src/frontend/Parser.cpp
+++ b/js/src/frontend/Parser.cpp
@@ -2867,30 +2867,30 @@ Parser<ParseHandler, CharT>::matchOrInse
          * it's possibly intended to be an await expression.
          *
          *   await f();
          *        ^
          *        |
          *        tried to insert semicolon here
          *
          * Detect this situation and throw an understandable error.  Otherwise
-         * we'd throw a confusing "missing ; before statement" error.
+         * we'd throw a confusing "unexpected token: (unexpected token)" error.
          */
         if (!pc->isAsync() && tokenStream.currentToken().type == TOK_AWAIT) {
             error(JSMSG_AWAIT_OUTSIDE_ASYNC);
             return false;
         }
         if (!yieldExpressionsSupported() && tokenStream.currentToken().type == TOK_YIELD) {
             error(JSMSG_YIELD_OUTSIDE_GENERATOR);
             return false;
         }
 
         /* Advance the scanner for proper error location reporting. */
         tokenStream.consumeKnownToken(tt, TokenStream::Operand);
-        error(JSMSG_SEMI_BEFORE_STMNT);
+        error(JSMSG_UNEXPECTED_TOKEN_NO_EXPECT, TokenKindToDesc(tt));
         return false;
     }
     bool matched;
     return tokenStream.matchToken(&matched, TOK_SEMI, TokenStream::Operand);
 }
 
 template <class ParseHandler, typename CharT>
 bool
@@ -8999,17 +8999,17 @@ Parser<ParseHandler, CharT>::checkLabelO
         MOZ_ASSERT(hint == ReservedWordTokenKind(ident), "hint doesn't match actual token kind");
         tt = hint;
     }
 
     if (tt == TOK_NAME)
         return true;
     if (TokenKindIsContextualKeyword(tt)) {
         if (tt == TOK_YIELD) {
-            if (yieldHandling == YieldIsKeyword || versionNumber() >= JSVERSION_1_7) {
+            if (yieldHandling == YieldIsKeyword) {
                 errorAt(offset, JSMSG_RESERVED_ID, "yield");
                 return false;
             }
             if (pc->sc()->needStrictChecks()) {
                 if (!strictModeErrorAt(offset, JSMSG_RESERVED_ID, "yield"))
                     return false;
             }
             return true;
--- a/js/src/jit-test/tests/basic/destructuring-rest-identifiers.js
+++ b/js/src/jit-test/tests/basic/destructuring-rest-identifiers.js
@@ -37,32 +37,28 @@ var reserved = [
   'true',
   'false'
 ];
 reserved.forEach(ident => {
   assertThrowsInstanceOf(() => new Function('var [...' + ident + '] = []'), SyntaxError);
 });
 
 var strictIdentifiers = [
-  // XXX: see bug 1032150. Once fixed, please uncomment these values and
-  // remove the assertions below
-  //'yield',
-  //'let',
+  'yield',
+  'let',
   'eval',
   'arguments',
   'implements',
   'interface',
   'package',
   'private',
   'protected',
   'public',
   'static'
 ];
-assertThrowsInstanceOf(() => new Function('[...yield] = []'), SyntaxError);
-assertThrowsInstanceOf(() => new Function('"use strict"; [...let] = []'), SyntaxError);
 
 strictIdentifiers.forEach(ident =>
   assertThrowsInstanceOf(() =>
     new Function('"use strict"; [...' + ident + '] = []'), SyntaxError));
 
 var globalEval = eval;
 strictIdentifiers.forEach(ident => {
   globalEval(ident + ' = null');
--- a/js/src/jit-test/tests/gc/bug-1370069.js
+++ b/js/src/jit-test/tests/gc/bug-1370069.js
@@ -1,6 +1,6 @@
-// |jit-test| error:SyntaxError
+// |jit-test| error:ReferenceError
 try {
     eval("}");
 } catch (exc) {}
 gczeal(17, 1);
 6.900653737167637, (yield);
--- a/js/src/jit-test/tests/generators/yield-regexp.js
+++ b/js/src/jit-test/tests/generators/yield-regexp.js
@@ -1,36 +1,25 @@
 // Bug 1099956
 
 load(libdir + "asserts.js");
 
-// ES6 treating yield as an identifier except in ES6 generators introduces a
-// syntax conflict with permissible JS >= 1.7 legacy generator syntax.  Is
-// |yield /a/g| inside a function an attempt to convert the function into a
-// legacy generator, yielding a RegExp instance?  Or does it instead read as
-// |(yield / a) / g|?  Similar ambiguities exist for different textual content
-// in place of |a| -- |yield /x+17/g| or |(yield / x) + 17 / g|, and so on.
-// (And, much less importantly, is |yield /a/g| a syntax error in global code
-// as in JS >= 1.7, or is it |(yield / a) / g|.)
-//
-// For now, in JS >= 1.7, we preserve the old behavior.  In all other JS we
-// conform to ES6: |yield /a/g| is a YieldExpression inside an ES6 generator,
-// and it's an IdentifierReference divided twice when not in an ES6 generator.
-// This test will need changes if we change our JS >= 1.7 parsing to be
-// ES6-compatible.
+// Parses as IDENT(yield) DIV IDENT(abc) DIV IDENT(g).
+eval(`function f1() { yield /abc/g; }`);
 
-// TODO: fix yield in non-generator functions.
+// Throws a ReferenceError because no global "yield" variable is defined.
 var ex;
 try {
-  eval(`function f1() { yield /abc/g; }`);
+  f1();
 } catch(e) {
   ex = e;
 }
-assertEq(ex.message.includes("reserved identifier"), true);
+assertEq(ex instanceof ReferenceError, true);
 
+// Parses as YIELD REGEXP(/abc/g).
 function* f2() {
   yield /abc/g;
 }
 
 g = f2();
 v = g.next();
 assertEq(v.done, false);
 assertEq(v.value instanceof RegExp, true);
--- a/js/src/jit-test/tests/parser/yield-in-formal-destructuring.js
+++ b/js/src/jit-test/tests/parser/yield-in-formal-destructuring.js
@@ -1,2 +1,1 @@
-// |jit-test| error: SyntaxError
 function d([{ [yield]: {} } ]) f
--- a/js/src/js.msg
+++ b/js/src/js.msg
@@ -315,32 +315,32 @@ MSG_DEF(JSMSG_REDECLARED_CATCH_IDENTIFIE
 MSG_DEF(JSMSG_RESERVED_ID,             1, JSEXN_SYNTAXERR, "{0} is a reserved identifier")
 MSG_DEF(JSMSG_REST_WITH_COMMA,         0, JSEXN_SYNTAXERR, "rest element may not have a trailing comma")
 MSG_DEF(JSMSG_REST_WITH_DEFAULT,       0, JSEXN_SYNTAXERR, "rest parameter may not have a default")
 MSG_DEF(JSMSG_SELFHOSTED_TOP_LEVEL_LEXICAL, 1, JSEXN_SYNTAXERR, "self-hosted code cannot contain top-level {0} declarations")
 MSG_DEF(JSMSG_SELFHOSTED_METHOD_CALL,  0, JSEXN_SYNTAXERR, "self-hosted code may not contain direct method calls. Use callFunction() or callContentFunction()")
 MSG_DEF(JSMSG_SELFHOSTED_UNBOUND_NAME, 0, JSEXN_TYPEERR, "self-hosted code may not contain unbound name lookups")
 MSG_DEF(JSMSG_SEMI_AFTER_FOR_COND,     0, JSEXN_SYNTAXERR, "missing ; after for-loop condition")
 MSG_DEF(JSMSG_SEMI_AFTER_FOR_INIT,     0, JSEXN_SYNTAXERR, "missing ; after for-loop initializer")
-MSG_DEF(JSMSG_SEMI_BEFORE_STMNT,       0, JSEXN_SYNTAXERR, "missing ; before statement")
 MSG_DEF(JSMSG_SOURCE_TOO_LONG,         0, JSEXN_RANGEERR, "source is too long")
 MSG_DEF(JSMSG_STMT_AFTER_RETURN,       0, JSEXN_WARN, "unreachable code after return statement")
 MSG_DEF(JSMSG_STRICT_CODE_WITH,        0, JSEXN_SYNTAXERR, "strict mode code may not contain 'with' statements")
 MSG_DEF(JSMSG_STRICT_NON_SIMPLE_PARAMS, 1, JSEXN_SYNTAXERR, "\"use strict\" not allowed in function with {0} parameter")
 MSG_DEF(JSMSG_TEMPLSTR_UNTERM_EXPR,    0, JSEXN_SYNTAXERR, "missing } in template string")
 MSG_DEF(JSMSG_SIMD_NOT_A_VECTOR,       2, JSEXN_TYPEERR, "expecting a SIMD {0} object as argument {1}")
 MSG_DEF(JSMSG_TOO_MANY_CASES,          0, JSEXN_INTERNALERR, "too many switch cases")
 MSG_DEF(JSMSG_TOO_MANY_CATCH_VARS,     0, JSEXN_SYNTAXERR, "too many catch variables")
 MSG_DEF(JSMSG_TOO_MANY_CON_ARGS,       0, JSEXN_SYNTAXERR, "too many constructor arguments")
 MSG_DEF(JSMSG_TOO_MANY_DEFAULTS,       0, JSEXN_SYNTAXERR, "more than one switch default")
 MSG_DEF(JSMSG_TOO_MANY_FUN_ARGS,       0, JSEXN_SYNTAXERR, "too many function arguments")
 MSG_DEF(JSMSG_TOO_MANY_LOCALS,         0, JSEXN_SYNTAXERR, "too many local variables")
 MSG_DEF(JSMSG_TOO_MANY_YIELDS,         0, JSEXN_SYNTAXERR, "too many yield expressions")
 MSG_DEF(JSMSG_TOUGH_BREAK,             0, JSEXN_SYNTAXERR, "unlabeled break must be inside loop or switch")
 MSG_DEF(JSMSG_UNEXPECTED_TOKEN,        2, JSEXN_SYNTAXERR, "expected {0}, got {1}")
+MSG_DEF(JSMSG_UNEXPECTED_TOKEN_NO_EXPECT,  1, JSEXN_SYNTAXERR, "unexpected token: {0}")
 MSG_DEF(JSMSG_UNEXPECTED_PARAMLIST_END,0, JSEXN_SYNTAXERR, "unexpected end of function parameter list")
 MSG_DEF(JSMSG_UNNAMED_CLASS_STMT,      0, JSEXN_SYNTAXERR, "class statement requires a name")
 MSG_DEF(JSMSG_UNNAMED_FUNCTION_STMT,   0, JSEXN_SYNTAXERR, "function statement requires a name")
 MSG_DEF(JSMSG_UNTERMINATED_COMMENT,    0, JSEXN_SYNTAXERR, "unterminated comment")
 MSG_DEF(JSMSG_UNTERMINATED_REGEXP,     0, JSEXN_SYNTAXERR, "unterminated regular expression literal")
 MSG_DEF(JSMSG_UNTERMINATED_STRING,     0, JSEXN_SYNTAXERR, "unterminated string literal")
 MSG_DEF(JSMSG_USELESS_EXPR,            0, JSEXN_TYPEERR, "useless expression")
 MSG_DEF(JSMSG_USE_ASM_DIRECTIVE_FAIL,  0, JSEXN_SYNTAXERR, "\"use asm\" is only meaningful in the Directive Prologue of a function body")
--- a/js/src/old-configure.in
+++ b/js/src/old-configure.in
@@ -1832,16 +1832,56 @@ fi
 fi # ! SKIP_COMPILER_CHECKS
 
 AC_DEFINE(CPP_THROW_NEW, [throw()])
 AC_LANG_C
 
 MOZ_EXPAND_LIBS
 
 dnl ========================================================
+dnl =
+dnl = Build depencency options
+dnl =
+dnl ========================================================
+MOZ_ARG_HEADER(Build dependencies)
+
+if test "$GNU_CC" -a "$GNU_CXX"; then
+  _DEPEND_CFLAGS='-MD -MP -MF $(MDDEPDIR)/$(@F).pp'
+else
+  dnl Don't override this for MSVC
+  if test -z "$_WIN32_MSVC"; then
+    _USE_CPP_INCLUDE_FLAG=
+    _DEFINES_CFLAGS='$(ACDEFINES) -D_JS_CONFDEFS_H_ -DMOZILLA_CLIENT'
+    _DEFINES_CXXFLAGS='$(ACDEFINES) -D_JS_CONFDEFS_H_ -DMOZILLA_CLIENT'
+  else
+    echo '#include <stdio.h>' > dummy-hello.c
+    changequote(,)
+    dnl This output is localized, split at the first double space or colon and space.
+    _CL_PREFIX_REGEX="^\([^:]*:.*[ :] \)\(.*\\\stdio.h\)$"
+    CL_INCLUDES_PREFIX=`${CC} -showIncludes -c -Fonul dummy-hello.c 2>&1 | sed -ne 's/'"$_CL_PREFIX_REGEX"'/\1/p'`
+    _CL_STDIO_PATH=`${CC} -showIncludes -c -Fonul dummy-hello.c 2>&1 | sed -ne 's/'"$_CL_PREFIX_REGEX"'/\2/p'`
+    changequote([,])
+    if ! test -e "$_CL_STDIO_PATH"; then
+        AC_MSG_ERROR([Unable to parse cl -showIncludes prefix. This compiler's locale has an unsupported formatting.])
+    fi
+    if test -z "$CL_INCLUDES_PREFIX"; then
+        AC_MSG_ERROR([Cannot find cl -showIncludes prefix.])
+    fi
+    AC_SUBST(CL_INCLUDES_PREFIX)
+    rm -f dummy-hello.c
+
+    dnl Make sure that the build system can handle non-ASCII characters
+    dnl in environment variables to prevent it from breaking silently on
+    dnl non-English systems.
+    NONASCII=$'\241\241'
+    AC_SUBST(NONASCII)
+  fi
+fi
+
+dnl ========================================================
 dnl = Link js shell to system readline
 dnl ========================================================
 MOZ_ARG_ENABLE_BOOL(readline,
 [  --enable-readline       Link js shell to system readline library],
     JS_WANT_READLINE=1,
     JS_WANT_READLINE= )
 
 JS_BUNDLED_EDITLINE=
@@ -1965,16 +2005,17 @@ COMPILE_CXXFLAGS=`echo \
     $COMPILE_CXXFLAGS`
 
 HOST_CFLAGS=`echo \
     $HOST_CFLAGS`
 
 HOST_CXXFLAGS=`echo \
     $HOST_CXXFLAGS`
 
+AC_SUBST(_DEPEND_CFLAGS)
 AC_SUBST(MOZ_SYSTEM_NSPR)
 
 OS_CFLAGS="$CFLAGS"
 OS_CXXFLAGS="$CXXFLAGS"
 OS_CPPFLAGS="$CPPFLAGS"
 OS_COMPILE_CFLAGS="$COMPILE_CFLAGS"
 OS_COMPILE_CXXFLAGS="$COMPILE_CXXFLAGS"
 OS_LDFLAGS="$LDFLAGS"
--- a/js/src/tests/ecma_3/LexicalConventions/7.9.1.js
+++ b/js/src/tests/ecma_3/LexicalConventions/7.9.1.js
@@ -86,31 +86,31 @@ function test()
   }
   reportCompare(expect, actual, summary + ': ' + code);
 
   //
 
   var x = 1;
   var y = 1;
   code   = '(x\n)-- y';
-  expect = 'SyntaxError: missing ; before statement';
+  expect = 'SyntaxError: unexpected token: identifier';
 
   try
   {
     eval(code);
     actual = expr;
   }
   catch(ex)
   {
     actual = ex + '';
   }
   reportCompare(expect, actual, summary + ': ' + code);
 
   code   = '(x)-- y';
-  expect = 'SyntaxError: missing ; before statement';
+  expect = 'SyntaxError: unexpected token: identifier';
 
   try
   {
     eval(code);
     actual = expr;
   }
   catch(ex)
   {
--- a/js/src/tests/js1_5/LexicalConventions/regress-469940.js
+++ b/js/src/tests/js1_5/LexicalConventions/regress-469940.js
@@ -14,17 +14,17 @@ var expect = '';
 test();
 //-----------------------------------------------------------------------------
 
 function test()
 {
   printBugNumber(BUGNUMBER);
   printStatus (summary);
  
-  expect = 'SyntaxError: missing ; before statement';
+  expect = 'SyntaxError: unexpected token: identifier';
 
   var s = 'var x = function f() { \n return 42; } print(x);';
 
   try
   {
     eval(s);
   }
   catch(ex)
--- a/js/src/tests/js1_7/lexical/regress-351515.js
+++ b/js/src/tests/js1_7/lexical/regress-351515.js
@@ -11,29 +11,29 @@ var expect = '';
 
 
 //-----------------------------------------------------------------------------
 test();
 //-----------------------------------------------------------------------------
 
 try
 {
-  expect = "SyntaxError";
+  expect = "No Error";
   eval('yield = 1;');
   actual = 'No Error';
 }
 catch(ex)
 {
   actual = ex.name;
 }
 reportCompare(expect, actual, summary + ': global: yield = 1');
 
 try
 {
-  expect = "SyntaxError";
+  expect = "No Error";
   eval('(function(){yield = 1;})');
   actual = 'No Error';
 }
 catch(ex)
 {
   actual = ex.name;
 }
 reportCompare(expect, actual, summary + ': local: yield = 1');
@@ -52,30 +52,30 @@ reportCompare(expect, actual, summary + 
 
 function test()
 {
   printBugNumber(BUGNUMBER);
   printStatus (summary);
  
   try
   {
-    expect = "SyntaxError";
+    expect = "No Error";
     eval('function f(yield, let) { return yield+let; }');
     actual = 'No Error';
   }
   catch(ex)
   {
     actual = ex.name;
   }
   reportCompare(expect, actual, summary +
 		': function f(yield, let) { return yield+let; }');
 
   try
   {
-    expect = "SyntaxError";
+    expect = "No Error";
     eval('var yield = 1;');
     actual = 'No Error';
   }
   catch(ex)
   {
     actual = ex.name;
   }
   reportCompare(expect, actual, summary + ': function () {var yield;}');
--- a/js/src/tests/js1_8/regress/regress-384758.js
+++ b/js/src/tests/js1_8/regress/regress-384758.js
@@ -14,17 +14,17 @@ var expect = '';
 test();
 //-----------------------------------------------------------------------------
 
 function test()
 {
   printBugNumber(BUGNUMBER);
   printStatus (summary);
 
-  expect = 'SyntaxError: missing ; before statement';
+  expect = 'SyntaxError: unexpected token: identifier';
   try
   {
     eval('(function() { if(t) function x() foo() bar(); })');
   }
   catch(ex)
   {
     actual = ex + '';
   }
--- a/js/src/vm/EnvironmentObject.cpp
+++ b/js/src/vm/EnvironmentObject.cpp
@@ -1029,17 +1029,17 @@ LexicalEnvironmentObject::createHollowFo
     return env;
 }
 
 /* static */ LexicalEnvironmentObject*
 LexicalEnvironmentObject::clone(JSContext* cx, Handle<LexicalEnvironmentObject*> env)
 {
     Rooted<LexicalScope*> scope(cx, &env->scope());
     RootedObject enclosing(cx, &env->enclosingEnvironment());
-    Rooted<LexicalEnvironmentObject*> copy(cx, create(cx, scope, enclosing, gc::TenuredHeap));
+    Rooted<LexicalEnvironmentObject*> copy(cx, create(cx, scope, enclosing, gc::DefaultHeap));
     if (!copy)
         return nullptr;
 
     // We can't assert that the clone has the same shape, because it could
     // have been reshaped by PurgeEnvironmentChain.
     MOZ_ASSERT(env->slotSpan() == copy->slotSpan());
     for (uint32_t i = JSSLOT_FREE(&class_); i < copy->slotSpan(); i++)
         copy->setSlot(i, env->getSlot(i));
@@ -1047,17 +1047,17 @@ LexicalEnvironmentObject::clone(JSContex
     return copy;
 }
 
 /* static */ LexicalEnvironmentObject*
 LexicalEnvironmentObject::recreate(JSContext* cx, Handle<LexicalEnvironmentObject*> env)
 {
     Rooted<LexicalScope*> scope(cx, &env->scope());
     RootedObject enclosing(cx, &env->enclosingEnvironment());
-    return create(cx, scope, enclosing, gc::TenuredHeap);
+    return create(cx, scope, enclosing, gc::DefaultHeap);
 }
 
 bool
 LexicalEnvironmentObject::isExtensible() const
 {
     return nonProxyIsExtensible();
 }
 
--- a/js/src/vm/RegExpObject.cpp
+++ b/js/src/vm/RegExpObject.cpp
@@ -237,17 +237,17 @@ RegExpObject::create(JSContext* cx, cons
 
 RegExpObject*
 RegExpObject::create(JSContext* cx, HandleAtom source, RegExpFlag flags,
                      const ReadOnlyCompileOptions* options, TokenStream* tokenStream,
                      LifoAlloc& alloc, NewObjectKind newKind)
 {
     Maybe<CompileOptions> dummyOptions;
     if (!tokenStream && !options) {
-        dummyOptions.emplace(cx);
+        dummyOptions.emplace(cx, JSVERSION_DEFAULT);
         options = dummyOptions.ptr();
     }
     Maybe<TokenStream> dummyTokenStream;
     if (!tokenStream) {
         dummyTokenStream.emplace(cx, *options,
                                    (const char16_t*) nullptr, 0,
                                    (frontend::StrictModeGetter*) nullptr);
         tokenStream = dummyTokenStream.ptr();
@@ -982,17 +982,17 @@ RegExpShared::compile(JSContext* cx, Mut
 
 /* static */ bool
 RegExpShared::compile(JSContext* cx, MutableHandleRegExpShared re, HandleAtom pattern,
                       HandleLinearString input, CompilationMode mode, ForceByteCodeEnum force)
 {
     if (!re->ignoreCase() && !StringHasRegExpMetaChars(pattern))
         re->canStringMatch = true;
 
-    CompileOptions options(cx);
+    CompileOptions options(cx, JSVERSION_DEFAULT);
     frontend::TokenStream dummyTokenStream(cx, options, nullptr, 0, nullptr);
 
     LifoAllocScope scope(&cx->tempLifoAlloc());
 
     /* Parse the pattern. */
     irregexp::RegExpCompileData data;
     if (!irregexp::ParsePattern(dummyTokenStream, cx->tempLifoAlloc(), pattern,
                                 re->multiline(), mode == MatchOnly, re->unicode(),
--- a/js/xpconnect/src/XPCJSContext.cpp
+++ b/js/xpconnect/src/XPCJSContext.cpp
@@ -60,16 +60,22 @@
 
 #include "GeckoProfiler.h"
 #include "nsIInputStream.h"
 #include "nsIXULRuntime.h"
 #include "nsJSPrincipals.h"
 #include "ExpandedPrincipal.h"
 #include "SystemPrincipal.h"
 
+#if defined(XP_LINUX) && !defined(ANDROID)
+// For getrlimit and min/max.
+#include <algorithm>
+#include <sys/resource.h>
+#endif
+
 #ifdef XP_WIN
 #include <windows.h>
 #endif
 
 static MOZ_THREAD_LOCAL(XPCJSContext*) gTlsContext;
 
 using namespace mozilla;
 using namespace xpc;
@@ -1013,27 +1019,36 @@ XPCJSContext::Initialize(XPCJSContext* a
     // trusted script, and untrusted script. We have tests that ensure that
     // we can always execute 10 "heavy" (eval+with) stack frames deeper in
     // privileged code. Our stack sizes vary greatly in different configurations,
     // so satisfying those tests requires some care. Manual measurements of the
     // number of heavy stack frames achievable gives us the following rough data,
     // ordered by the effective categories in which they are grouped in the
     // JS_SetNativeStackQuota call (which predates this analysis).
     //
-    // (NB: These numbers may have drifted recently - see bug 938429)
-    // OSX 64-bit Debug: 7MB stack, 636 stack frames => ~11.3k per stack frame
-    // OSX64 Opt: 7MB stack, 2440 stack frames => ~3k per stack frame
+    // The following "Stack Frames" numbers come from `chromeLimit` in
+    // js/xpconnect/tests/chrome/test_bug732665.xul
     //
-    // Linux 32-bit Debug: 2MB stack, 426 stack frames => ~4.8k per stack frame
-    // Linux 64-bit Debug: 4MB stack, 455 stack frames => ~9.0k per stack frame
-    //
-    // Windows (Opt+Debug): 900K stack, 235 stack frames => ~3.4k per stack frame
-    //
-    // Linux 32-bit Opt: 1MB stack, 272 stack frames => ~3.8k per stack frame
-    // Linux 64-bit Opt: 2MB stack, 316 stack frames => ~6.5k per stack frame
+    //  Platform   | Build | Stack Quota | Stack Frames | Stack Frame Size
+    // ------------+-------+-------------+--------------+------------------
+    //  OSX 64     | Opt   | 7MB         | 1331         | ~5.4k
+    //  OSX 64     | Debug | 7MB         | 1202         | ~6.0k
+    // ------------+-------+-------------+--------------+------------------
+    //  Linux 32   | Opt   | 7.875MB     | 2513         | ~3.2k
+    //  Linux 32   | Debug | 7.875MB     | 2146         | ~3.8k
+    // ------------+-------+-------------+--------------+------------------
+    //  Linux 64   | Opt   | 7.875MB     | 1360         | ~5.9k
+    //  Linux 64   | Debug | 7.875MB     | 1180         | ~6.8k
+    //  Linux 64   | ASan  | 7.875MB     | 473          | ~17.0k
+    // ------------+-------+-------------+--------------+------------------
+    //  Windows 32 | Opt   | 984k        | 188          | ~5.2k
+    //  Windows 32 | Debug | 984k        | 208          | ~4.7k
+    // ------------+-------+-------------+--------------+------------------
+    //  Windows 64 | Opt   | 1.922MB     | 189          | ~10.4k
+    //  Windows 64 | Debug | 1.922MB     | 175          | ~11.2k
     //
     // We tune the trusted/untrusted quotas for each configuration to achieve our
     // invariants while attempting to minimize overhead. In contrast, our buffer
     // between system code and trusted script is a very unscientific 10k.
     const size_t kSystemCodeBuffer = 10 * 1024;
 
     // Our "default" stack is what we use in configurations where we don't have
     // a compelling reason to do things differently. This is effectively 512KB
@@ -1044,47 +1059,79 @@ XPCJSContext::Initialize(XPCJSContext* a
     // the web to base this decision primarily on the default stack size that the
     // underlying platform makes available, but that seems to be what we do. :-(
 
 #if defined(XP_MACOSX) || defined(DARWIN)
     // MacOS has a gargantuan default stack size of 8MB. Go wild with 7MB,
     // and give trusted script 180k extra. The stack is huge on mac anyway.
     const size_t kStackQuota = 7 * 1024 * 1024;
     const size_t kTrustedScriptBuffer = 180 * 1024;
+#elif defined(XP_LINUX) && !defined(ANDROID)
+    // Most Linux distributions set default stack size to 8MB.  Use it as the
+    // maximum value.
+    const size_t kStackQuotaMax = 8 * 1024 * 1024;
+#  if defined(MOZ_ASAN) || defined(DEBUG)
+    // Bug 803182: account for the 4x difference in the size of js::Interpret
+    // between optimized and debug builds.  We use 2x since the JIT part
+    // doesn't increase much.
+    // See the standalone MOZ_ASAN branch below for the ASan case.
+    const size_t kStackQuotaMin = 2 * kDefaultStackQuota;
+#  else
+    const size_t kStackQuotaMin = kDefaultStackQuota;
+#  endif
+    // Allocate 128kB margin for the safe space.
+    const size_t kStackSafeMargin = 128 * 1024;
+
+    struct rlimit rlim;
+    const size_t kStackQuota =
+        getrlimit(RLIMIT_STACK, &rlim) == 0
+        ? std::max(std::min(size_t(rlim.rlim_cur - kStackSafeMargin),
+                            kStackQuotaMax - kStackSafeMargin),
+                   kStackQuotaMin)
+        : kStackQuotaMin;
+#  if defined(MOZ_ASAN)
+    // See the standalone MOZ_ASAN branch below for the ASan case.
+    const size_t kTrustedScriptBuffer = 450 * 1024;
+#  else
+    const size_t kTrustedScriptBuffer = 180 * 1024;
+#  endif
 #elif defined(MOZ_ASAN)
     // ASan requires more stack space due to red-zones, so give it double the
     // default (1MB on 32-bit, 2MB on 64-bit). ASAN stack frame measurements
     // were not taken at the time of this writing, so we hazard a guess that
     // ASAN builds have roughly thrice the stack overhead as normal builds.
     // On normal builds, the largest stack frame size we might encounter is
     // 9.0k (see above), so let's use a buffer of 9.0 * 5 * 10 = 450k.
+    //
+    // FIXME: Does this branch make sense for Windows and Android?
+    // (See bug 1415195)
     const size_t kStackQuota =  2 * kDefaultStackQuota;
     const size_t kTrustedScriptBuffer = 450 * 1024;
 #elif defined(XP_WIN)
-    // 1MB is the default stack size on Windows. We use the /STACK linker flag
-    // to request a larger stack, so we determine the stack size at runtime.
+    // 1MB is the default stack size on Windows. We use the -STACK linker flag
+    // (see WIN32_EXE_LDFLAGS in config/config.mk) to request a larger stack,
+    // so we determine the stack size at runtime.
     const size_t kStackQuota = GetWindowsStackSize();
     const size_t kTrustedScriptBuffer = (sizeof(size_t) == 8) ? 180 * 1024   //win64
                                                               : 120 * 1024;  //win32
-    // The following two configurations are linux-only. Given the numbers above,
-    // we use 50k and 100k trusted buffers on 32-bit and 64-bit respectively.
 #elif defined(ANDROID)
     // Android appears to have 1MB stacks. Allow the use of 3/4 of that size
     // (768KB on 32-bit), since otherwise we can crash with a stack overflow
     // when nearing the 1MB limit.
     const size_t kStackQuota = kDefaultStackQuota + kDefaultStackQuota / 2;
     const size_t kTrustedScriptBuffer = sizeof(size_t) * 12800;
-#elif defined(DEBUG)
-    // Bug 803182: account for the 4x difference in the size of js::Interpret
-    // between optimized and debug builds.
-    // XXXbholley - Then why do we only account for 2x of difference?
+#else
+    // Catch-all configuration for other environments.
+#  if defined(DEBUG)
     const size_t kStackQuota = 2 * kDefaultStackQuota;
-    const size_t kTrustedScriptBuffer = sizeof(size_t) * 12800;
-#else
+#  else
     const size_t kStackQuota = kDefaultStackQuota;
+#  endif
+    // Given the numbers above, we use 50k and 100k trusted buffers on 32-bit
+    // and 64-bit respectively.
     const size_t kTrustedScriptBuffer = sizeof(size_t) * 12800;
 #endif
 
     // Avoid an unused variable warning on platforms where we don't use the
     // default.
     (void) kDefaultStackQuota;
 
     JS_SetNativeStackQuota(cx,
--- a/netwerk/protocol/http/Http2Session.cpp
+++ b/netwerk/protocol/http/Http2Session.cpp
@@ -114,16 +114,18 @@ Http2Session::Http2Session(nsISocketTran
   , mPingSentEpoch(0)
   , mPreviousUsed(false)
   , mWaitingForSettingsAck(false)
   , mGoAwayOnPush(false)
   , mUseH2Deps(false)
   , mAttemptingEarlyData(attemptingEarlyData)
   , mOriginFrameActivated(false)
   , mTlsHandshakeFinished(false)
+  , mFlushOKAddStream(false)
+  , mFlushOKReadSegments(false)
 {
   MOZ_ASSERT(OnSocketThread(), "not on socket thread");
 
   static uint64_t sSerial;
   mSerial = ++sSerial;
 
   LOG3(("Http2Session::Http2Session %p serial=0x%" PRIX64 "\n", this, mSerial));
 
@@ -379,16 +381,23 @@ Http2Session::RegisterStreamID(Http2Stre
 bool
 Http2Session::AddStream(nsAHttpTransaction *aHttpTransaction,
                         int32_t aPriority,
                         bool aUseTunnel,
                         nsIInterfaceRequestor *aCallbacks)
 {
   MOZ_ASSERT(OnSocketThread(), "not on socket thread");
 
+  MOZ_DIAGNOSTIC_ASSERT(!mFlushOKAddStream);
+  mFlushOKAddStream = true;
+  auto cleanup = MakeScopeExit([&] () {
+    MOZ_DIAGNOSTIC_ASSERT(mFlushOKAddStream);
+    mFlushOKAddStream = false;
+  });
+
   // integrity check
   if (mStreamTransactionHash.Get(aHttpTransaction)) {
     LOG3(("   New transaction already present\n"));
     MOZ_ASSERT(false, "AddStream duplicate transaction pointer");
     return false;
   }
 
   if (!mConnection) {
@@ -538,16 +547,34 @@ Http2Session::RealignOutputQueue()
   mOutputQueueUsed -= mOutputQueueSent;
   memmove(mOutputQueueBuffer.get(),
           mOutputQueueBuffer.get() + mOutputQueueSent,
           mOutputQueueUsed);
   mOutputQueueSent = 0;
 }
 
 void
+Http2Session::MaybeFlushOutputQueue()
+{
+  // Only try to flush the output queue if we know any mSegmentReader that's set
+  // is properly set through the right channels. Otherwise, just set our write
+  // callbacks so the connection can call in with a proper segment reader that
+  // we'll be sure we can write to.
+  // See bug 1402014 comment 6
+  MOZ_ASSERT(OnSocketThread(), "not on socket thread");
+  LOG3(("Http2Session::MaybeFlushOutputQueue mFlushOKAddStream=%d, "
+        "mFlushOKReadSegments=%d", mFlushOKAddStream, mFlushOKReadSegments));
+  if (mFlushOKAddStream || mFlushOKReadSegments) {
+    FlushOutputQueue();
+  } else {
+    SetWriteCallbacks();
+  }
+}
+
+void
 Http2Session::FlushOutputQueue()
 {
   if (!mSegmentReader || !mOutputQueueUsed)
     return;
 
   nsresult rv;
   uint32_t countRead;
   uint32_t avail = mOutputQueueUsed - mOutputQueueSent;
@@ -789,44 +816,44 @@ Http2Session::GeneratePing(bool isAck)
     memcpy(packet + kFrameHeaderBytes,
            mInputFrameBuffer.get() + kFrameHeaderBytes, 8);
   } else {
     CreateFrameHeader(packet, 8, FRAME_TYPE_PING, 0, 0);
     memset(packet + kFrameHeaderBytes, 0, 8);
   }
 
   LogIO(this, nullptr, "Generate Ping", packet, kFrameHeaderBytes + 8);
-  FlushOutputQueue();
+  MaybeFlushOutputQueue();
 }
 
 void
 Http2Session::GenerateSettingsAck()
 {
   // need to generate ack of this settings frame
   MOZ_ASSERT(OnSocketThread(), "not on socket thread");
   LOG3(("Http2Session::GenerateSettingsAck %p\n", this));
 
   char *packet = EnsureOutputBuffer(kFrameHeaderBytes);
   mOutputQueueUsed += kFrameHeaderBytes;
   CreateFrameHeader(packet, 0, FRAME_TYPE_SETTINGS, kFlag_ACK, 0);
   LogIO(this, nullptr, "Generate Settings ACK", packet, kFrameHeaderBytes);
-  FlushOutputQueue();
+  MaybeFlushOutputQueue();
 }
 
 void
 Http2Session::GeneratePriority(uint32_t aID, uint8_t aPriorityWeight)
 {
   MOZ_ASSERT(OnSocketThread(), "not on socket thread");
   LOG3(("Http2Session::GeneratePriority %p %X %X\n",
         this, aID, aPriorityWeight));
 
   char *packet = CreatePriorityFrame(aID, 0, aPriorityWeight);
 
   LogIO(this, nullptr, "Generate Priority", packet, kFrameHeaderBytes + 5);
-  FlushOutputQueue();
+  MaybeFlushOutputQueue();
 }
 
 void
 Http2Session::GenerateRstStream(uint32_t aStatusCode, uint32_t aID)
 {
   MOZ_ASSERT(OnSocketThread(), "not on socket thread");
 
   // make sure we don't do this twice for the same stream (at least if we
@@ -843,17 +870,17 @@ Http2Session::GenerateRstStream(uint32_t
   uint32_t frameSize = kFrameHeaderBytes + 4;
   char *packet = EnsureOutputBuffer(frameSize);
   mOutputQueueUsed += frameSize;
   CreateFrameHeader(packet, 4, FRAME_TYPE_RST_STREAM, 0, aID);
 
   NetworkEndian::writeUint32(packet + kFrameHeaderBytes, aStatusCode);
 
   LogIO(this, nullptr, "Generate Reset", packet, frameSize);
-  FlushOutputQueue();
+  MaybeFlushOutputQueue();
 }
 
 void
 Http2Session::GenerateGoAway(uint32_t aStatusCode)
 {
   MOZ_ASSERT(OnSocketThread(), "not on socket thread");
   LOG3(("Http2Session::GenerateGoAway %p code=%X\n", this, aStatusCode));
 
@@ -866,17 +893,17 @@ Http2Session::GenerateGoAway(uint32_t aS
 
   // last-good-stream-id are bytes 9-12 reflecting pushes
   NetworkEndian::writeUint32(packet + kFrameHeaderBytes, mOutgoingGoAwayID);
 
   // bytes 13-16 are the status code.
   NetworkEndian::writeUint32(packet + frameSize - 4, aStatusCode);
 
   LogIO(this, nullptr, "Generate GoAway", packet, frameSize);
-  FlushOutputQueue();
+  MaybeFlushOutputQueue();
 }
 
 // The Hello is comprised of
 // 1] 24 octets of magic, which are designed to
 // flush out silent but broken intermediaries
 // 2] a settings frame which sets a small flow control window for pushes
 // 3] a window update frame which creates a large session flow control window
 // 4] 6 priority frames for streams which will never be opened with headers
@@ -988,32 +1015,32 @@ Http2Session::SendHello()
     MOZ_ASSERT(mNextStreamID == kUrgentStartGroupID);
     CreatePriorityNode(kUrgentStartGroupID, 0, 240, "urgentStart");
     mNextStreamID += 2;
     // Hey, you! YES YOU! If you add/remove any groups here, you almost
     // certainly need to change the lookup of the stream/ID hash in
     // Http2Session::OnTransportStatus. Yeah, that's right. YOU!
   }
 
-  FlushOutputQueue();
+  MaybeFlushOutputQueue();
 }
 
 void
 Http2Session::SendPriorityFrame(uint32_t streamID,
                                 uint32_t dependsOn,
                                 uint8_t weight)
 {
   MOZ_ASSERT(OnSocketThread(), "not on socket thread");
   LOG3(("Http2Session::SendPriorityFrame %p Frame 0x%X depends on 0x%X "
         "weight %d\n", this, streamID, dependsOn, weight));
 
   char *packet = CreatePriorityFrame(streamID, dependsOn, weight);
 
   LogIO(this, nullptr, "SendPriorityFrame", packet, kFrameHeaderBytes + 5);
-  FlushOutputQueue();
+  MaybeFlushOutputQueue();
 }
 
 char *
 Http2Session::CreatePriorityFrame(uint32_t streamID,
                                   uint32_t dependsOn,
                                   uint8_t weight)
 {
   char *packet = EnsureOutputBuffer(kFrameHeaderBytes + 5);
@@ -2740,39 +2767,47 @@ nsresult
 Http2Session::ReadSegmentsAgain(nsAHttpSegmentReader *reader,
                                 uint32_t count, uint32_t *countRead, bool *again)
 {
   MOZ_ASSERT(OnSocketThread(), "not on socket thread");
 
   MOZ_ASSERT(!mSegmentReader || !reader || (mSegmentReader == reader),
              "Inconsistent Write Function Callback");
 
+  MOZ_DIAGNOSTIC_ASSERT(!mFlushOKReadSegments);
+  mFlushOKReadSegments = true;
+  auto cleanup = MakeScopeExit([&] () {
+    MOZ_DIAGNOSTIC_ASSERT(mFlushOKReadSegments);
+    mFlushOKReadSegments = false;
+  });
+
   nsresult rv = ConfirmTLSProfile();
   if (NS_FAILED(rv)) {
     if (mGoAwayReason == INADEQUATE_SECURITY) {
       LOG3(("Http2Session::ReadSegments %p returning INADEQUATE_SECURITY %" PRIx32,
             this, static_cast<uint32_t>(NS_ERROR_NET_INADEQUATE_SECURITY)));
       rv = NS_ERROR_NET_INADEQUATE_SECURITY;
     }
     return rv;
   }
 
-  if (reader)
-    mSegmentReader = reader;
+  if (reader) {
+    SetSegmentReader(reader);
+  }
 
   *countRead = 0;
 
   LOG3(("Http2Session::ReadSegments %p", this));
 
   Http2Stream *stream = static_cast<Http2Stream *>(mReadyForWrite.PopFront());
   if (!stream) {
     LOG3(("Http2Session %p could not identify a stream to write; suspending.",
           this));
     uint32_t availBeforeFlush = mOutputQueueUsed - mOutputQueueSent;
-    FlushOutputQueue();
+    MaybeFlushOutputQueue();
     uint32_t availAfterFlush = mOutputQueueUsed - mOutputQueueSent;
     if (availBeforeFlush != availAfterFlush) {
       LOG3(("Http2Session %p ResumeRecv After early flush in ReadSegments", this));
       Unused << ResumeRecv();
     }
     SetWriteCallbacks();
     if (mAttemptingEarlyData) {
       // We can still try to send our preamble as early-data
@@ -2781,17 +2816,17 @@ Http2Session::ReadSegmentsAgain(nsAHttpS
     return *countRead ? NS_OK : NS_BASE_STREAM_WOULD_BLOCK;
   }
 
   uint32_t earlyDataUsed = 0;
   if (mAttemptingEarlyData) {
     if (!stream->Do0RTT()) {
       LOG3(("Http2Session %p will not get early data from Http2Stream %p 0x%X",
             this, stream, stream->StreamID()));
-      FlushOutputQueue();
+      MaybeFlushOutputQueue();
       SetWriteCallbacks();
       if (!mCannotDo0RTTStreams.Contains(stream)) {
         mCannotDo0RTTStreams.AppendElement(stream);
       }
       // We can still send our preamble
       *countRead = mOutputQueueUsed - mOutputQueueSent;
       return *countRead ? NS_OK : NS_BASE_STREAM_WOULD_BLOCK;
     }
@@ -2823,17 +2858,17 @@ Http2Session::ReadSegmentsAgain(nsAHttpS
           stream->StreamID()));
     m0RTTStreams.AppendElement(stream);
   }
 
   // Not every permutation of stream->ReadSegents produces data (and therefore
   // tries to flush the output queue) - SENDING_FIN_STREAM can be an example
   // of that. But we might still have old data buffered that would be good
   // to flush.
-  FlushOutputQueue();
+  MaybeFlushOutputQueue();
 
   // Allow new server reads - that might be data or control information
   // (e.g. window updates or http replies) that are responses to these writes
   Unused << ResumeRecv();
 
   if (stream->RequestBlockedOnRead()) {
 
     // We are blocked waiting for input - either more http headers or
@@ -3627,17 +3662,17 @@ void
 Http2Session::UpdateLocalRwin(Http2Stream *stream, uint32_t bytes)
 {
   // make sure there is room for 2 window updates even though
   // we may not generate any.
   EnsureOutputBuffer(2 * (kFrameHeaderBytes + 4));
 
   UpdateLocalStreamWindow(stream, bytes);
   UpdateLocalSessionWindow(bytes);
-  FlushOutputQueue();
+  MaybeFlushOutputQueue();
 }
 
 void
 Http2Session::Close(nsresult aReason)
 {
   MOZ_ASSERT(OnSocketThread(), "not on socket thread");
 
   if (mClosed)
@@ -3716,17 +3751,17 @@ Http2Session::OnReadSegment(const char *
                             uint32_t count, uint32_t *countRead)
 {
   MOZ_ASSERT(OnSocketThread(), "not on socket thread");
   nsresult rv;
 
   // If we can release old queued data then we can try and write the new
   // data directly to the network without using the output queue at all
   if (mOutputQueueUsed)
-    FlushOutputQueue();
+    MaybeFlushOutputQueue();
 
   if (!mOutputQueueUsed && mSegmentReader) {
     // try and write directly without output queue
     rv = mSegmentReader->OnReadSegment(buf, count, countRead);
 
     if (rv == NS_BASE_STREAM_WOULD_BLOCK) {
       *countRead = 0;
     } else if (NS_FAILED(rv)) {
@@ -3758,26 +3793,26 @@ Http2Session::OnReadSegment(const char *
 
   if ((mOutputQueueUsed + count) > (mOutputQueueSize - kQueueReserved))
     return NS_BASE_STREAM_WOULD_BLOCK;
 
   memcpy(mOutputQueueBuffer.get() + mOutputQueueUsed, buf, count);
   mOutputQueueUsed += count;
   *countRead = count;
 
-  FlushOutputQueue();
+  MaybeFlushOutputQueue();
 
   return NS_OK;
 }
 
 nsresult
 Http2Session::CommitToSegmentSize(uint32_t count, bool forceCommitment)
 {
   if (mOutputQueueUsed && !mAttemptingEarlyData)
-    FlushOutputQueue();
+    MaybeFlushOutputQueue();
 
   // would there be enough room to buffer this if needed?
   if ((mOutputQueueUsed + count) <= (mOutputQueueSize - kQueueReserved))
     return NS_OK;
 
   // if we are using part of our buffers already, try again later unless
   // forceCommitment is set.
   if (mOutputQueueUsed && !forceCommitment)
@@ -4544,10 +4579,23 @@ Http2Session::TopLevelOuterContentWindow
 
   mCurrentForegroundTabOuterContentWindowId = windowId;
 
   for (auto iter = mStreamTransactionHash.Iter(); !iter.Done(); iter.Next()) {
     iter.Data()->TopLevelOuterContentWindowIdChanged(windowId);
   }
 }
 
+void
+Http2Session::SetSegmentReader(nsAHttpSegmentReader *reader)
+{
+  LOG3(("Http2Session::SetSegmentReader this=%p mClosed=%d mSegmentReader=%p reader=%p",
+        this, mClosed, mSegmentReader, reader));
+  MOZ_DIAGNOSTIC_ASSERT(!mSegmentReader || reader == mSegmentReader);
+  if (mClosed) {
+    mSegmentReader = nullptr;
+  } else {
+    mSegmentReader = reader;
+  }
+}
+
 } // namespace net
 } // namespace mozilla
--- a/netwerk/protocol/http/Http2Session.h
+++ b/netwerk/protocol/http/Http2Session.h
@@ -215,17 +215,17 @@ public:
 
   // a similar version for Http2Stream
   void TransactionHasDataToWrite(Http2Stream *);
 
   // an overload of nsAHttpSegementReader
   virtual MOZ_MUST_USE nsresult CommitToSegmentSize(uint32_t size,
                                                     bool forceCommitment) override;
   MOZ_MUST_USE nsresult BufferOutput(const char *, uint32_t, uint32_t *);
-  void     FlushOutputQueue();
+  void     MaybeFlushOutputQueue();
   uint32_t AmountOfOutputBuffered() { return mOutputQueueUsed - mOutputQueueSent; }
 
   uint32_t GetServerInitialStreamWindow() { return mServerInitialStreamWindow; }
 
   MOZ_MUST_USE bool TryToActivate(Http2Stream *stream);
   void ConnectPushedStream(Http2Stream *stream);
   void ConnectSlowConsumer(Http2Stream *stream);
 
@@ -558,16 +558,22 @@ private:
     nsHttpRequestHead mRequestHead;
   };
 
   // A h2 session will be created before all socket events are trigered,
   // e.g. NS_NET_STATUS_TLS_HANDSHAKE_ENDED and for TFO many others.
   // We should propagate this events to the first nsHttpTransaction.
   RefPtr<nsHttpTransaction> mFirstHttpTransaction;
   bool mTlsHandshakeFinished;
+
+  void SetSegmentReader(nsAHttpSegmentReader *);
+  void FlushOutputQueue();
+  bool mFlushOKAddStream;
+  bool mFlushOKReadSegments;
+
 private:
 /// connect tunnels
   void DispatchOnTunnel(nsAHttpTransaction *, nsIInterfaceRequestor *);
   void CreateTunnel(nsHttpTransaction *, nsHttpConnectionInfo *, nsIInterfaceRequestor *);
   void RegisterTunnel(Http2Stream *);
   void UnRegisterTunnel(Http2Stream *);
   uint32_t FindTunnelCount(nsHttpConnectionInfo *);
   nsDataHashtable<nsCStringHashKey, uint32_t> mTunnelHash;
--- a/netwerk/protocol/http/Http2Stream.cpp
+++ b/netwerk/protocol/http/Http2Stream.cpp
@@ -953,17 +953,17 @@ Http2Stream::TransmitFrame(const char *b
 
     Http2Session::LogIO(mSession, this, "Writing from Transaction Buffer",
                          buf, transmittedCount);
 
     *countUsed += mTxStreamFrameSize;
   }
 
   if (!mAttempting0RTT) {
-    mSession->FlushOutputQueue();
+    mSession->MaybeFlushOutputQueue();
   }
 
   // calling this will trigger waiting_for if mRequestBodyLenRemaining is 0
   UpdateTransportSendEvents(mTxInlineFrameUsed + mTxStreamFrameSize);
 
   mTxInlineFrameUsed = 0;
   mTxStreamFrameSize = 0;
 
--- a/old-configure.in
+++ b/old-configure.in
@@ -4121,16 +4121,58 @@ AC_DEFINE(CPP_THROW_NEW, [throw()])
 AC_LANG_C
 
 if test "$COMPILE_ENVIRONMENT"; then
 MOZ_EXPAND_LIBS
 fi # COMPILE_ENVIRONMENT
 
 dnl ========================================================
 dnl =
+dnl = Build depencency options
+dnl =
+dnl ========================================================
+MOZ_ARG_HEADER(Build dependencies)
+
+if test "$COMPILE_ENVIRONMENT"; then
+if test "$GNU_CC" -a "$GNU_CXX"; then
+  _DEPEND_CFLAGS='-MD -MP -MF $(MDDEPDIR)/$(@F).pp'
+else
+  dnl Don't override this for MSVC
+  if test -z "$_WIN32_MSVC"; then
+    _USE_CPP_INCLUDE_FLAG=
+    _DEFINES_CFLAGS='$(ACDEFINES) -D_MOZILLA_CONFIG_H_ -DMOZILLA_CLIENT'
+    _DEFINES_CXXFLAGS='$(ACDEFINES) -D_MOZILLA_CONFIG_H_ -DMOZILLA_CLIENT'
+  else
+    echo '#include <stdio.h>' > dummy-hello.c
+    changequote(,)
+    dnl This output is localized, split at the first double space or colon and space.
+    _CL_PREFIX_REGEX="^\([^:]*:.*[ :] \)\(.*\\\stdio.h\)$"
+    CL_INCLUDES_PREFIX=`${CC} -showIncludes -c -Fonul dummy-hello.c 2>&1 | sed -ne 's/'"$_CL_PREFIX_REGEX"'/\1/p'`
+    _CL_STDIO_PATH=`${CC} -showIncludes -c -Fonul dummy-hello.c 2>&1 | sed -ne 's/'"$_CL_PREFIX_REGEX"'/\2/p'`
+    changequote([,])
+    if ! test -e "$_CL_STDIO_PATH"; then
+        AC_MSG_ERROR([Unable to parse cl -showIncludes prefix. This compiler's locale has an unsupported formatting.])
+    fi
+    if test -z "$CL_INCLUDES_PREFIX"; then
+        AC_MSG_ERROR([Cannot find cl -showIncludes prefix.])
+    fi
+    AC_SUBST(CL_INCLUDES_PREFIX)
+    rm -f dummy-hello.c
+
+    dnl Make sure that the build system can handle non-ASCII characters
+    dnl in environment variables to prevent it from breaking silently on
+    dnl non-English systems.
+    NONASCII=$'\241\241'
+    AC_SUBST(NONASCII)
+  fi
+fi
+fi # COMPILE_ENVIRONMENT
+
+dnl ========================================================
+dnl =
 dnl = Static Build Options
 dnl =
 dnl ========================================================
 MOZ_ARG_HEADER(Static build options)
 
 if test -z "$MOZ_SYSTEM_ZLIB"; then
 if test -n "$JS_SHARED_LIBRARY" -o -n "$MOZ_LINKER"; then
   ZLIB_IN_MOZGLUE=1
@@ -4728,16 +4770,17 @@ COMPILE_CXXFLAGS=`echo \
     $COMPILE_CXXFLAGS`
 
 HOST_CFLAGS=`echo \
     $HOST_CFLAGS`
 
 HOST_CXXFLAGS=`echo \
     $HOST_CXXFLAGS`
 
+AC_SUBST(_DEPEND_CFLAGS)
 AC_SUBST(MOZ_SYSTEM_JPEG)
 AC_SUBST(MOZ_SYSTEM_PNG)
 AC_SUBST(MOZ_SYSTEM_BZ2)
 
 AC_SUBST_LIST(MOZ_JPEG_CFLAGS)
 AC_SUBST_LIST(MOZ_JPEG_LIBS)
 AC_SUBST_LIST(MOZ_BZ2_CFLAGS)
 AC_SUBST_LIST(MOZ_BZ2_LIBS)
--- a/testing/talos/talos/config.py
+++ b/testing/talos/talos/config.py
@@ -130,16 +130,17 @@ DEFAULTS = dict(
         'browser.safebrowsing.downloads.enabled': False,
         'browser.safebrowsing.passwords.enabled': False,
         'plugins.flashBlock.enabled': False,
         'privacy.trackingprotection.annotate_channels': False,
         'privacy.trackingprotection.enabled': False,
         'privacy.trackingprotection.pbmode.enabled': False,
         'browser.search.isUS': True,
         'browser.search.countryCode': 'US',
+        'browser.search.geoip.url': '',
         'browser.urlbar.userMadeSearchSuggestionsChoice': True,
         'extensions.update.url':
             'http://127.0.0.1/extensions-dummy/updateURL',
         'extensions.update.background.url':
             'http://127.0.0.1/extensions-dummy/updateBackgroundURL',
         'extensions.blocklist.enabled': False,
         'extensions.blocklist.url':
             'http://127.0.0.1/extensions-dummy/blocklistURL',
deleted file mode 100644
--- a/testing/web-platform/meta/custom-elements/adopted-callback.html.ini
+++ /dev/null
@@ -1,45 +0,0 @@
-[adopted-callback.html]
-  type: testharness
-  prefs: [dom.webcomponents.enabled:true]
-  [Inserting the shadow host of a custom element into the document of the template elements must enqueue and invoke adoptedCallback]
-    expected: FAIL
-
-  [Moving the shadow host of a custom element from the owner document into the document of the template elements must enqueue and invoke adoptedCallback]
-    expected: FAIL
-
-  [Inserting the shadow host of a custom element into a new document must enqueue and invoke adoptedCallback]
-    expected: FAIL
-
-  [Moving the shadow host of a custom element from the owner document into a new document must enqueue and invoke adoptedCallback]
-    expected: FAIL
-
-  [Inserting the shadow host of a custom element into a cloned document must enqueue and invoke adoptedCallback]
-    expected: FAIL
-
-  [Moving the shadow host of a custom element from the owner document into a cloned document must enqueue and invoke adoptedCallback]
-    expected: FAIL
-
-  [Inserting the shadow host of a custom element into a document created by createHTMLDocument must enqueue and invoke adoptedCallback]
-    expected: FAIL
-
-  [Moving the shadow host of a custom element from the owner document into a document created by createHTMLDocument must enqueue and invoke adoptedCallback]
-    expected: FAIL
-
-  [Inserting the shadow host of a custom element into an HTML document created by createDocument must enqueue and invoke adoptedCallback]
-    expected: FAIL
-
-  [Moving the shadow host of a custom element from the owner document into an HTML document created by createDocument must enqueue and invoke adoptedCallback]
-    expected: FAIL
-
-  [Inserting the shadow host of a custom element into the document of an iframe must enqueue and invoke adoptedCallback]
-    expected: FAIL
-
-  [Moving the shadow host of a custom element from the owner document into the document of an iframe must enqueue and invoke adoptedCallback]
-    expected: FAIL
-
-  [Inserting the shadow host of a custom element into an HTML document fetched by XHR must enqueue and invoke adoptedCallback]
-    expected: FAIL
-
-  [Moving the shadow host of a custom element from the owner document into an HTML document fetched by XHR must enqueue and invoke adoptedCallback]
-    expected: FAIL
-
--- a/toolkit/modules/tests/xpcshell/test_Log.js
+++ b/toolkit/modules/tests/xpcshell/test_Log.js
@@ -572,17 +572,17 @@ add_task(function* format_errors() {
 
   // Test that JS-generated Errors are recognized and formatted.
   try {
     yield Promise.resolve(); // Scrambles the stack
     // eslint-disable-next-line no-eval
     eval("javascript syntax error");
   } catch (e) {
     str = pFormat.format(e);
-    do_check_true(str.includes("SyntaxError: missing ;"));
+    do_check_true(str.includes("SyntaxError: unexpected token"));
     // Make sure we identified it as an Error and formatted the error location as
     // lineNumber:columnNumber.
     do_check_true(str.includes(":1:11)"));
     // Make sure that we use human-readable stack traces
     // Check that the error doesn't contain any reference to "Promise.jsm" or "Task.jsm"
     do_check_false(str.includes("Promise.jsm"));
     do_check_false(str.includes("Task.jsm"));
     do_check_true(str.includes("format_errors"));