Merge inbound to m-c. a=merge
authorRyan VanderMeulen <ryanvm@gmail.com>
Sat, 09 Aug 2014 11:19:46 -0400
changeset 198769 ad8cb646fad6841c5d48dda77e374498e56f8d71
parent 198676 8613e0929f200a8525b241db8938e0779ac3dcf0 (current diff)
parent 198768 7a51faeb82d838892b939cbed5c3def50421da0c (diff)
child 198770 d400055c9999e5c228a99a78e8efa5be18861000
child 198774 365a67a55dacde262e67f0202baf53b6bef963cd
push id27284
push userryanvm@gmail.com
push dateSat, 09 Aug 2014 15:25:31 +0000
treeherderautoland@ad8cb646fad6 [default view] [failures only]
perfherder[talos] [build metrics] [platform microbench] (compared to previous push)
reviewersmerge
milestone34.0a1
first release with
nightly linux32
nightly linux64
nightly mac
nightly win32
nightly win64
last release without
nightly linux32
nightly linux64
nightly mac
nightly win32
nightly win64
Merge inbound to m-c. a=merge
media/mtransport/test/Makefile.in
media/webrtc/signaling/test/Makefile.in
media/webrtc/webrtc-config.mk
testing/mochitest/mach_commands.py
xpcom/glue/DeadlockDetector.cpp
--- a/addon-sdk/mach_commands.py
+++ b/addon-sdk/mach_commands.py
@@ -21,17 +21,17 @@ from mach.decorators import (
 class JetpackRunner(MozbuildObject):
     """Run jetpack tests."""
     def run_tests(self, **kwargs):
         self._run_make(target='jetpack-tests')
 
 @CommandProvider
 class MachCommands(MachCommandBase):
     @Command('jetpack-test', category='testing',
-        description='Runs the jetpack test suite.')
+        description='Runs the jetpack test suite (Add-on SDK).')
     def run_jetpack_test(self, **params):
         # We should probably have a utility function to ensure the tree is
         # ready to run tests. Until then, we just create the state dir (in
         # case the tree wasn't built with mach).
         self._ensure_state_subdir_exists('.')
 
         jetpack = self._spawn(JetpackRunner)
 
--- a/build/valgrind/mach_commands.py
+++ b/build/valgrind/mach_commands.py
@@ -30,17 +30,17 @@ class MachCommands(MachCommandBase):
     '''
     Run Valgrind tests.
     '''
     def __init__(self, context):
         MachCommandBase.__init__(self, context)
 
     @Command('valgrind-test', category='testing',
         conditions=[conditions.is_firefox, is_valgrind_build],
-        description='Run the Valgrind test job.')
+        description='Run the Valgrind test job (memory-related errors).')
     @CommandArgument('--suppressions', default=[], action='append',
         metavar='FILENAME',
         help='Specify a suppression file for Valgrind to use. Use '
             '--suppression multiple times to specify multiple suppression '
             'files.')
     def valgrind_test(self, suppressions):
         import json
         import sys
--- a/config/external/icu/moz.build
+++ b/config/external/icu/moz.build
@@ -4,15 +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/.
 
 LIBRARY_NAME = 'icu'
 
 if CONFIG['MOZ_NATIVE_ICU']:
     OS_LIBS += CONFIG['MOZ_ICU_LIBS']
 else:
-    USE_LIBS += sorted(
-        '%s/intl/icu/target/lib/%s%s' % (
+    # Order needs to be preserved
+    for l in CONFIG['ICU_LIB_NAMES']:
+        USE_LIBS += ['%s/intl/icu/target/lib/%s%s' % (
             'static:' if not CONFIG['MOZ_SHARED_ICU'] else '',
             l,
             CONFIG['MOZ_ICU_DBG_SUFFIX']
-        ) for l in CONFIG['ICU_LIB_NAMES']
-    )
+        )]
--- a/configure.in
+++ b/configure.in
@@ -3812,16 +3812,17 @@ MOZ_PLACES=1
 MOZ_SOCIAL=1
 MOZ_PREF_EXTENSIONS=1
 MOZ_PROFILELOCKING=1
 MOZ_REFLOW_PERF=
 MOZ_SAFE_BROWSING=
 MOZ_HELP_VIEWER=
 MOZ_SPELLCHECK=1
 MOZ_ANDROID_OMTC=
+MOZ_ANDROID_APZ=
 MOZ_TOOLKIT_SEARCH=1
 MOZ_UI_LOCALE=en-US
 MOZ_UNIVERSALCHARDET=1
 MOZ_URL_CLASSIFIER=
 MOZ_XUL=1
 MOZ_ZIPWRITER=1
 NS_PRINTING=1
 MOZ_PDF_PRINTING=
@@ -4815,16 +4816,28 @@ dnl ====================================
 dnl = Build with the Android compositor
 dnl ========================================================
 if test -n "$MOZ_ANDROID_OMTC"; then
      dnl Do this if defined in confvars.sh
      AC_DEFINE(MOZ_ANDROID_OMTC)
 fi
 
 dnl ========================================================
+dnl = Enable the C++ async pan/zoom code instead of the Java version
+dnl ========================================================
+MOZ_ARG_ENABLE_BOOL(android-apz,
+[  --enable-android-apz      Switch to C++ pan/zoom code],
+    MOZ_ANDROID_APZ=1,
+    MOZ_ANDROID_APZ=)
+if test -n "$MOZ_ANDROID_APZ"; then
+     dnl Do this if defined in confvars.sh
+     AC_DEFINE(MOZ_ANDROID_APZ)
+fi
+
+dnl ========================================================
 dnl = Disable WebSMS backend
 dnl ========================================================
 MOZ_ARG_DISABLE_BOOL(websms-backend,
 [  --disable-websms-backend
                            Disable WebSMS backend],
     MOZ_WEBSMS_BACKEND=,
     MOZ_WEBSMS_BACKEND=1)
 
@@ -8392,16 +8405,17 @@ AC_SUBST(KEYTOOL)
 
 AC_SUBST(MOZ_PROFILELOCKING)
 
 AC_SUBST(ENABLE_TESTS)
 AC_SUBST(MOZ_UNIVERSALCHARDET)
 AC_SUBST(ACCESSIBILITY)
 AC_SUBST(MOZ_SPELLCHECK)
 AC_SUBST(MOZ_ANDROID_OMTC)
+AC_SUBST(MOZ_ANDROID_APZ)
 AC_SUBST(MOZ_ANDROID_ANR_REPORTER)
 AC_SUBST(MOZ_CRASHREPORTER)
 AC_SUBST(MOZ_CRASHREPORTER_INJECTOR)
 AC_SUBST(MOZ_CRASHREPORTER_UPLOAD_FULL_SYMBOLS)
 AC_SUBST(MOZ_MAINTENANCE_SERVICE)
 AC_SUBST(MOZ_STUB_INSTALLER)
 AC_SUBST(MOZ_VERIFY_MAR_SIGNATURE)
 AC_SUBST(MOZ_ENABLE_SIGNMAR)
--- a/content/base/src/ThirdPartyUtil.cpp
+++ b/content/base/src/ThirdPartyUtil.cpp
@@ -27,42 +27,47 @@ ThirdPartyUtil::Init()
 // Determine if aFirstDomain is a different base domain to aSecondURI; or, if
 // the concept of base domain does not apply, determine if the two hosts are not
 // string-identical.
 nsresult
 ThirdPartyUtil::IsThirdPartyInternal(const nsCString& aFirstDomain,
                                      nsIURI* aSecondURI,
                                      bool* aResult)
 {
-  NS_ASSERTION(aSecondURI, "null URI!");
+  NS_ENSURE_ARG(aSecondURI);
 
   // Get the base domain for aSecondURI.
   nsCString secondDomain;
   nsresult rv = GetBaseDomain(aSecondURI, secondDomain);
   if (NS_FAILED(rv))
     return rv;
 
   // Check strict equality.
   *aResult = aFirstDomain != secondDomain;
   return NS_OK;
 }
 
 // Get the URI associated with a window.
-already_AddRefed<nsIURI>
-ThirdPartyUtil::GetURIFromWindow(nsIDOMWindow* aWin)
+NS_IMETHODIMP
+ThirdPartyUtil::GetURIFromWindow(nsIDOMWindow* aWin, nsIURI** result)
 {
+  nsresult rv;
   nsCOMPtr<nsIScriptObjectPrincipal> scriptObjPrin = do_QueryInterface(aWin);
-  NS_ENSURE_TRUE(scriptObjPrin, nullptr);
+  if (!scriptObjPrin) {
+    return NS_ERROR_INVALID_ARG;
+  }
 
   nsIPrincipal* prin = scriptObjPrin->GetPrincipal();
-  NS_ENSURE_TRUE(prin, nullptr);
+  if (!prin) {
+    return NS_ERROR_INVALID_ARG;
+  }
 
-  nsCOMPtr<nsIURI> result;
-  prin->GetURI(getter_AddRefs(result));
-  return result.forget();
+  nsCOMPtr<nsIURI> uri;
+  rv = prin->GetURI(result);
+  return rv;
 }
 
 // Determine if aFirstURI is third party with respect to aSecondURI. See docs
 // for mozIThirdPartyUtil.
 NS_IMETHODIMP
 ThirdPartyUtil::IsThirdPartyURI(nsIURI* aFirstURI,
                                 nsIURI* aSecondURI,
                                 bool* aResult)
@@ -87,21 +92,23 @@ ThirdPartyUtil::IsThirdPartyWindow(nsIDO
                                    bool* aResult)
 {
   NS_ENSURE_ARG(aWindow);
   NS_ASSERTION(aResult, "null outparam pointer");
 
   bool result;
 
   // Get the URI of the window, and its base domain.
-  nsCOMPtr<nsIURI> currentURI = GetURIFromWindow(aWindow);
-  NS_ENSURE_TRUE(currentURI, NS_ERROR_INVALID_ARG);
+  nsresult rv;
+  nsCOMPtr<nsIURI> currentURI;
+  rv = GetURIFromWindow(aWindow, getter_AddRefs(currentURI));
+  NS_ENSURE_SUCCESS(rv, rv);
 
   nsCString bottomDomain;
-  nsresult rv = GetBaseDomain(currentURI, bottomDomain);
+  rv = GetBaseDomain(currentURI, bottomDomain);
   if (NS_FAILED(rv))
     return rv;
 
   if (aURI) {
     // Determine whether aURI is foreign with respect to currentURI.
     rv = IsThirdPartyInternal(bottomDomain, aURI, &result);
     if (NS_FAILED(rv))
       return rv;
@@ -121,18 +128,18 @@ ThirdPartyUtil::IsThirdPartyWindow(nsIDO
     NS_ENSURE_SUCCESS(rv, rv);
 
     if (SameCOMIdentity(parent, current)) {
       // We're at the topmost content window. We already know the answer.
       *aResult = false;
       return NS_OK;
     }
 
-    parentURI = GetURIFromWindow(parent);
-    NS_ENSURE_TRUE(parentURI, NS_ERROR_INVALID_ARG);
+    rv = GetURIFromWindow(parent, getter_AddRefs(parentURI));
+    NS_ENSURE_SUCCESS(rv, rv);
 
     rv = IsThirdPartyInternal(bottomDomain, parentURI, &result);
     if (NS_FAILED(rv))
       return rv;
 
     if (result) {
       *aResult = true;
       return NS_OK;
@@ -242,16 +249,39 @@ ThirdPartyUtil::IsThirdPartyChannel(nsIC
     ourWin = parentWin;
   }
 
   // Check the window hierarchy. This covers most cases for an ordinary page
   // load from the location bar.
   return IsThirdPartyWindow(ourWin, channelURI, aResult);
 }
 
+NS_IMETHODIMP
+ThirdPartyUtil::GetTopWindowForChannel(nsIChannel* aChannel, nsIDOMWindow** aWin)
+{
+  NS_ENSURE_ARG(aWin);
+
+  nsresult rv;
+  // Find the associated window and its parent window.
+  nsCOMPtr<nsILoadContext> ctx;
+  NS_QueryNotificationCallbacks(aChannel, ctx);
+  if (!ctx) {
+    return NS_ERROR_INVALID_ARG;
+  }
+
+  nsCOMPtr<nsIDOMWindow> window;
+  rv = ctx->GetAssociatedWindow(getter_AddRefs(window));
+  if (!window) {
+    return NS_ERROR_INVALID_ARG;
+  }
+
+  rv = window->GetTop(aWin);
+  return rv;
+}
+
 // Get the base domain for aHostURI; e.g. for "www.bbc.co.uk", this would be
 // "bbc.co.uk". Only properly-formed URI's are tolerated, though a trailing
 // dot may be present. If aHostURI is an IP address, an alias such as
 // 'localhost', an eTLD such as 'co.uk', or the empty string, aBaseDomain will
 // be the exact host. The result of this function should only be used in exact
 // string comparisons, since substring comparisons will not be valid for the
 // special cases elided above.
 NS_IMETHODIMP
--- a/content/base/src/ThirdPartyUtil.h
+++ b/content/base/src/ThirdPartyUtil.h
@@ -23,15 +23,14 @@ public:
 
   nsresult Init();
 
 private:
   ~ThirdPartyUtil() {}
 
   nsresult IsThirdPartyInternal(const nsCString& aFirstDomain,
     nsIURI* aSecondURI, bool* aResult);
-  static already_AddRefed<nsIURI> GetURIFromWindow(nsIDOMWindow* aWin);
 
   nsCOMPtr<nsIEffectiveTLDService> mTLDService;
 };
 
 #endif
 
--- a/content/base/src/nsObjectLoadingContent.cpp
+++ b/content/base/src/nsObjectLoadingContent.cpp
@@ -984,16 +984,27 @@ nsObjectLoadingContent::OnStartRequest(n
 NS_IMETHODIMP
 nsObjectLoadingContent::OnStopRequest(nsIRequest *aRequest,
                                       nsISupports *aContext,
                                       nsresult aStatusCode)
 {
   PROFILER_LABEL("nsObjectLoadingContent", "OnStopRequest",
     js::ProfileEntry::Category::NETWORK);
 
+  // Handle object not loading error because source was a tracking URL.
+  // We make a note of this object node by including it in a dedicated
+  // array of blocked tracking nodes under its parent document.
+  if (aStatusCode == NS_ERROR_TRACKING_URI) {
+    nsCOMPtr<nsIContent> thisNode =
+      do_QueryInterface(static_cast<nsIObjectLoadingContent*>(this));
+    if (thisNode) {
+      thisNode->GetCurrentDoc()->AddBlockedTrackingNode(thisNode);
+    }
+  }
+
   NS_ENSURE_TRUE(nsContentUtils::IsCallerChrome(), NS_ERROR_NOT_AVAILABLE);
 
   if (aRequest != mChannel) {
     return NS_BINDING_ABORTED;
   }
 
   mChannel = nullptr;
 
--- a/dom/base/URLSearchParams.cpp
+++ b/dom/base/URLSearchParams.cpp
@@ -176,40 +176,39 @@ URLSearchParams::ConvertString(const nsA
   if (!mDecoder) {
     mDecoder = EncodingUtils::DecoderForEncoding("UTF-8");
     if (!mDecoder) {
       MOZ_ASSERT(mDecoder, "Failed to create a decoder.");
       return;
     }
   }
 
-  nsACString::const_iterator iter;
-  aInput.BeginReading(iter);
-
   int32_t inputLength = aInput.Length();
   int32_t outputLength = 0;
 
-  nsresult rv = mDecoder->GetMaxLength(iter.get(), inputLength,
+  nsresult rv = mDecoder->GetMaxLength(aInput.BeginReading(), inputLength,
                                        &outputLength);
   if (NS_WARN_IF(NS_FAILED(rv))) {
     return;
   }
 
-  const mozilla::fallible_t fallible = mozilla::fallible_t();
-  nsAutoArrayPtr<char16_t> buf(new (fallible) char16_t[outputLength + 1]);
-  if (!buf) {
+  if (!aOutput.SetLength(outputLength, fallible_t())) {
     return;
   }
 
-  rv = mDecoder->Convert(iter.get(), &inputLength, buf, &outputLength);
-  if (NS_SUCCEEDED(rv)) {
-    buf[outputLength] = 0;
-    if (!aOutput.Assign(buf, outputLength, mozilla::fallible_t())) {
-      aOutput.Truncate();
-    }
+  int32_t newOutputLength = outputLength;
+  rv = mDecoder->Convert(aInput.BeginReading(), &inputLength,
+                         aOutput.BeginWriting(), &newOutputLength);
+  if (NS_FAILED(rv)) {
+    aOutput.Truncate();
+    return;
+  }
+
+  if (newOutputLength < outputLength) {
+    aOutput.Truncate(newOutputLength);
   }
 }
 
 /* static */ PLDHashOperator
 URLSearchParams::CopyEnumerator(const nsAString& aName,
                                 nsTArray<nsString>* aArray,
                                 void *userData)
 {
--- a/dom/bindings/mach_commands.py
+++ b/dom/bindings/mach_commands.py
@@ -25,17 +25,17 @@ class WebIDLProvider(MachCommandBase):
     def webidl_example(self, interface):
         from mozwebidlcodegen import BuildSystemWebIDL
 
         manager = self._spawn(BuildSystemWebIDL).manager
         for i in interface:
             manager.generate_example_files(i)
 
     @Command('webidl-parser-test', category='testing',
-        description='Run WebIDL tests.')
+        description='Run WebIDL tests (Interface Browser parser).')
     @CommandArgument('--verbose', '-v', action='store_true',
         help='Run tests in verbose mode.')
     def webidl_test(self, verbose=False):
         sys.path.insert(0, os.path.join(self.topsrcdir, 'other-licenses',
             'ply'))
 
         # Make sure we drop our cached grammar bits in the objdir, not
         # wherever we happen to be running from.
--- a/dom/ipc/CrashReporterParent.cpp
+++ b/dom/ipc/CrashReporterParent.cpp
@@ -163,28 +163,38 @@ CrashReporterParent::NotifyCrashService(
     MOZ_ASSERT(NS_IsMainThread());
 
     nsCOMPtr<nsICrashService> crashService =
         do_GetService("@mozilla.org/crashservice;1");
     if (!crashService) {
         return;
     }
 
-    if (mProcessType == GeckoProcessType_Content) {
-        crashService->AddCrash(nsICrashService::PROCESS_TYPE_CONTENT,
-                               nsICrashService::CRASH_TYPE_CRASH,
-                               mChildDumpID);
+    int32_t processType;
+    int32_t crashType = nsICrashService::CRASH_TYPE_CRASH;
+
+    switch (mProcessType) {
+        case GeckoProcessType_Content:
+            processType = nsICrashService::PROCESS_TYPE_CONTENT;
+            break;
+        case GeckoProcessType_Plugin: {
+            processType = nsICrashService::PROCESS_TYPE_PLUGIN;
+            nsAutoCString val;
+            if (mNotes.Get(NS_LITERAL_CSTRING("PluginHang"), &val) &&
+                val.Equals(NS_LITERAL_CSTRING("1"))) {
+                crashType = nsICrashService::CRASH_TYPE_HANG;
+            }
+            break;
+        }
+        case GeckoProcessType_GMPlugin:
+            processType = nsICrashService::PROCESS_TYPE_GMPLUGIN;
+            break;
+        default:
+            NS_ERROR("unknown process type");
+            return;
     }
-    else if (mProcessType == GeckoProcessType_Plugin) {
-        nsAutoCString val;
-        int32_t crashType = nsICrashService::CRASH_TYPE_CRASH;
-        if (mNotes.Get(NS_LITERAL_CSTRING("PluginHang"), &val) &&
-            val.Equals(NS_LITERAL_CSTRING("1"))) {
-            crashType = nsICrashService::CRASH_TYPE_HANG;
-        }
-        crashService->AddCrash(nsICrashService::PROCESS_TYPE_PLUGIN, crashType,
-                               mChildDumpID);
-    }
+
+    crashService->AddCrash(processType, crashType, mChildDumpID);
 }
 #endif
 
 } // namespace dom
 } // namespace mozilla
--- a/dom/media/tests/mochitest/long.js
+++ b/dom/media/tests/mochitest/long.js
@@ -54,16 +54,20 @@ function outputPcStats(stats, label) {
     }
   }
   outputStr += '\n\n';
   dump(outputStr);
 }
 
 
 var _lastStats = {};
+
+const MAX_ERROR_CYCLES = 5;
+var _errorCount = {};
+
 /**
  * Verifies the peer connection stats interval over interval
  *
  * @param {Object} stats
  *        Stats object to use for verification
  * @param {string} label
  *        Identifies the peer connection. Differentiates stats for
  *        interval-over-interval verification in cases where more than one set
@@ -76,38 +80,58 @@ function verifyPcStats(stats, label) {
   ];
 
   const INCREASING_OUTBOUND_STAT_NAMES = [
     'bytesSent',
     'packetsSent'
   ];
 
   if (_lastStats[label] !== undefined) {
+    var errorsInCycle = false;
+
     function verifyIncrease(rtpName, statNames) {
       var timestamp = new Date(stats[rtpName].timestamp).toISOString();
 
       statNames.forEach(function (statName) {
-        ok(stats[rtpName][statName] > _lastStats[label][rtpName][statName],
+        var passed = stats[rtpName][statName] >
+            _lastStats[label][rtpName][statName];
+        if (!passed) {
+          errorsInCycle = true;
+        }
+        ok(passed,
            timestamp + '.' + label + '.' + rtpName + '.' + statName,
            label + '.' + rtpName + '.' + statName + ' increased (value=' +
            stats[rtpName][statName] + ')');
       });
     }
 
     for (var prop in stats) {
       if (isLocalRtp(stats[prop])) {
         if (stats[prop].type === 'inboundrtp') {
           verifyIncrease(prop, INCREASING_INBOUND_STAT_NAMES);
         } else {
           verifyIncrease(prop, INCREASING_OUTBOUND_STAT_NAMES);
         }
       }
     }
+
+    if (errorsInCycle) {
+      _errorCount[label] += 1;
+      info(label +": increased error counter to " + _errorCount[label]);
+    } else {
+      // looks like we recovered from a temp glitch
+      if (_errorCount[label] > 0) {
+        info(label + ": reseting error counter to zero");
+      }
+      _errorCount[label] = 0;
+    }
+  } else {
+    _errorCount[label] = 0;
   }
-  
+
   _lastStats[label] = stats;
 }
 
 
 /**
  * Retrieves and performs a series of operations on PeerConnection stats
  *
  * @param {PeerConnectionWrapper} pc
@@ -170,18 +194,26 @@ function generateIntervalCommand(callbac
     name,
     function (test) {
       var startTime = Date.now();
       var intervalId = setInterval(function () {
         if (callback) {
           callback(test);
         }
 
+        var failed = false;
+        Object.keys(_errorCount).forEach(function (label) {
+          if (_errorCount[label] > MAX_ERROR_CYCLES) {
+            ok(false, "Encountered more then " + MAX_ERROR_CYCLES + " cycles" +
+              " with errors on " + label);
+            failed = true;
+          }
+        });
         var timeElapsed = Date.now() - startTime;
-        if (timeElapsed >= duration) {
+        if ((timeElapsed >= duration) || failed) {
           clearInterval(intervalId);
           test.next();
         }
       }, interval);
     }
   ]
 }
 
--- a/dom/media/tests/mochitest/steeplechase_long.ini
+++ b/dom/media/tests/mochitest/steeplechase_long.ini
@@ -2,10 +2,12 @@
 support-files =
   head.js
   long.js
   mediaStreamPlayback.js
   pc.js
   templates.js
   turnConfig.js
 
+[test_peerConnection_basicAudio_long.html]
+[test_peerConnection_basicVideo_long.html]
 [test_peerConnection_basicAudioVideoCombined_long.html]
 
--- a/dom/media/tests/mochitest/templates.js
+++ b/dom/media/tests/mochitest/templates.js
@@ -127,16 +127,19 @@ var commandsPeerConnection = [
     function (test) {
       test.createOffer(test.pcLocal, function (offer) {
         is(test.pcLocal.signalingState, STABLE,
            "Local create offer does not change signaling state");
         if (!test.pcRemote) {
           send_message({"offer": test.pcLocal._last_offer,
                         "offer_constraints": test.pcLocal.constraints,
                         "offer_options": test.pcLocal.offerOptions});
+          test._local_offer = test.pcLocal._last_offer;
+          test._offer_constraints = test.pcLocal.constraints;
+          test._offer_options = test.pcLocal.offerOptions;
         }
         test.next();
       });
     }
   ],
   [
     'PC_LOCAL_SET_LOCAL_DESCRIPTION',
     function (test) {
@@ -194,16 +197,18 @@ var commandsPeerConnection = [
     'PC_REMOTE_CREATE_ANSWER',
     function (test) {
       test.createAnswer(test.pcRemote, function (answer) {
         is(test.pcRemote.signalingState, HAVE_REMOTE_OFFER,
            "Remote createAnswer does not change signaling state");
         if (!test.pcLocal) {
           send_message({"answer": test.pcRemote._last_answer,
                         "answer_constraints": test.pcRemote.constraints});
+          test._remote_answer = test.pcRemote._last_answer;
+          test._answer_constraints = test.pcRemote.constraints;
         }
         test.next();
       });
     }
   ],
   [
     'PC_REMOTE_CHECK_FOR_DUPLICATED_PORTS_IN_SDP',
     function (test) {
--- a/dom/media/tests/mochitest/test_peerConnection_basicAudioVideoCombined_long.html
+++ b/dom/media/tests/mochitest/test_peerConnection_basicAudioVideoCombined_long.html
@@ -15,29 +15,30 @@
   <script type="application/javascript" src="templates.js"></script>
   <script type="application/javascript" src="turnConfig.js"></script>
 </head>
 <body>
 <pre id="test">
 <script type="application/javascript">
   createHTML({
     bug: "1014328",
-    title: "Basic audio/video (combined) peer connection, long running"
+    title: "Basic audio/video (combined) peer connection, long running",
+    visible: true
   });
 
-  FAKE_ENABLED = false;
-
   var test;
   runTest(function (options) {
     options = options || {};
     options.commands = commandsPeerConnection.slice(0);
-    options.commands.push(generateIntervalCommand(verifyConnectionStatus));
+    options.commands.push(generateIntervalCommand(verifyConnectionStatus,
+                                                  1000 * 10,
+                                                  1000 * 3600 * 3));
 
     test = new PeerConnectionTest(options);
-    test.setMediaConstraints([{audio: true, video: true}],
-                             [{audio: true, video: true}]);
+    test.setMediaConstraints([{audio: true, video: true, fake: false}],
+                             [{audio: true, video: true, fake: false}]);
     test.run();
   });
 </script>
 </pre>
 </body>
 </html>
 
new file mode 100644
--- /dev/null
+++ b/dom/media/tests/mochitest/test_peerConnection_basicAudio_long.html
@@ -0,0 +1,43 @@
+<!DOCTYPE HTML>
+
+<!-- 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/. -->
+
+<html>
+<head>
+  <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css"/>
+  <script type="application/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
+  <script type="application/javascript" src="head.js"></script>
+  <script type="application/javascript" src="long.js"></script>
+  <script type="application/javascript" src="mediaStreamPlayback.js"></script>
+  <script type="application/javascript" src="pc.js"></script>
+  <script type="application/javascript" src="templates.js"></script>
+  <script type="application/javascript" src="turnConfig.js"></script>
+</head>
+<body>
+<pre id="test">
+<script type="application/javascript">
+  createHTML({
+    bug: "796892",
+    title: "Basic audio-only peer connection",
+    visible: true
+  });
+
+  var test;
+  runNetworkTest(function (options) {
+    options = options || {};
+    options.commands = commandsPeerConnection.slice(0);
+    options.commands.push(generateIntervalCommand(verifyConnectionStatus,
+                                                  1000 * 10,
+                                                  1000 * 3600 * 3));
+
+    test = new PeerConnectionTest(options);
+    test.setMediaConstraints([{audio: true, fake: false}],
+                             [{audio: true, fake: false}]);
+    test.run();
+  });
+</script>
+</pre>
+</body>
+</html>
new file mode 100644
--- /dev/null
+++ b/dom/media/tests/mochitest/test_peerConnection_basicVideo_long.html
@@ -0,0 +1,43 @@
+<!DOCTYPE HTML>
+
+<!-- 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/. -->
+
+<html>
+<head>
+  <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css"/>
+  <script type="application/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
+  <script type="application/javascript" src="head.js"></script>
+  <script type="application/javascript" src="long.js"></script>
+  <script type="application/javascript" src="mediaStreamPlayback.js"></script>
+  <script type="application/javascript" src="pc.js"></script>
+  <script type="application/javascript" src="templates.js"></script>
+  <script type="application/javascript" src="turnConfig.js"></script>
+</head>
+<body>
+<pre id="test">
+<script type="application/javascript">
+  createHTML({
+    bug: "796888",
+    title: "Basic video-only peer connection",
+    visible: true
+  });
+
+  var test;
+  runNetworkTest(function (options) {
+    options = options || {};
+    options.commands = commandsPeerConnection.slice(0);
+    options.commands.push(generateIntervalCommand(verifyConnectionStatus,
+                                                  1000 * 10,
+                                                  1000 * 3600 * 3));
+
+    test = new PeerConnectionTest(options);
+    test.setMediaConstraints([{video: true, fake: false}],
+                             [{video: true, fake: false}]);
+    test.run();
+  });
+</script>
+</pre>
+</body>
+</html>
--- a/dom/plugins/base/nsJSNPRuntime.cpp
+++ b/dom/plugins/base/nsJSNPRuntime.cpp
@@ -7,16 +7,17 @@
 
 #include "jsfriendapi.h"
 #include "jswrapper.h"
 
 #include "nsIInterfaceRequestorUtils.h"
 #include "nsJSNPRuntime.h"
 #include "nsNPAPIPlugin.h"
 #include "nsNPAPIPluginInstance.h"
+#include "nsIGlobalObject.h"
 #include "nsIScriptGlobalObject.h"
 #include "nsIScriptContext.h"
 #include "nsDOMJSUtils.h"
 #include "nsJSUtils.h"
 #include "nsCxPusher.h"
 #include "nsIDocument.h"
 #include "nsIJSRuntimeService.h"
 #include "nsIXPConnect.h"
@@ -603,35 +604,38 @@ nsJSObjWrapper::NP_HasMethod(NPObject *n
     ::JS_ObjectIsFunction(cx, v.toObjectOrNull());
 }
 
 static bool
 doInvoke(NPObject *npobj, NPIdentifier method, const NPVariant *args,
          uint32_t argCount, bool ctorCall, NPVariant *result)
 {
   NPP npp = NPPStack::Peek();
-  JSContext *cx = GetJSContext(npp);
 
-  if (!cx) {
+  nsCOMPtr<nsIGlobalObject> globalObject = GetGlobalObject(npp);
+  if (NS_WARN_IF(!globalObject)) {
     return false;
   }
 
+  // We're about to run script via JS_CallFunctionValue, so we need an
+  // AutoEntryScript. NPAPI plugins are Gecko-specific and not in any spec.
+  dom::AutoEntryScript aes(globalObject);
+  JSContext *cx = aes.cx();
+
   if (!npobj || !result) {
     ThrowJSException(cx, "Null npobj, or result in doInvoke!");
 
     return false;
   }
 
   // Initialize *result
   VOID_TO_NPVARIANT(*result);
 
   nsJSObjWrapper *npjsobj = (nsJSObjWrapper *)npobj;
 
-  nsCxPusher pusher;
-  pusher.Push(cx);
   JS::Rooted<JSObject*> jsobj(cx, npjsobj->mJSObj);
   JSAutoCompartment ac(cx, jsobj);
   JS::Rooted<JS::Value> fv(cx);
 
   AutoJSExceptionReporter reporter(cx);
 
   if (method != NPIdentifier_VOID) {
     if (!GetProperty(cx, jsobj, method, &fv) ||
@@ -728,65 +732,71 @@ nsJSObjWrapper::NP_HasProperty(NPObject 
 }
 
 // static
 bool
 nsJSObjWrapper::NP_GetProperty(NPObject *npobj, NPIdentifier id,
                                NPVariant *result)
 {
   NPP npp = NPPStack::Peek();
-  JSContext *cx = GetJSContext(npp);
 
-  if (!cx) {
+  nsCOMPtr<nsIGlobalObject> globalObject = GetGlobalObject(npp);
+  if (NS_WARN_IF(!globalObject)) {
     return false;
   }
 
+  // We're about to run script via JS_CallFunctionValue, so we need an
+  // AutoEntryScript. NPAPI plugins are Gecko-specific and not in any spec.
+  dom::AutoEntryScript aes(globalObject);
+  JSContext *cx = aes.cx();
+
   if (!npobj) {
     ThrowJSException(cx,
                      "Null npobj in nsJSObjWrapper::NP_GetProperty!");
 
     return false;
   }
 
   nsJSObjWrapper *npjsobj = (nsJSObjWrapper *)npobj;
 
-  nsCxPusher pusher;
-  pusher.Push(cx);
   AutoJSExceptionReporter reporter(cx);
   JSAutoCompartment ac(cx, npjsobj->mJSObj);
 
   JS::Rooted<JS::Value> v(cx);
   return (GetProperty(cx, npjsobj->mJSObj, id, &v) &&
           JSValToNPVariant(npp, cx, v, result));
 }
 
 // static
 bool
 nsJSObjWrapper::NP_SetProperty(NPObject *npobj, NPIdentifier npid,
                                const NPVariant *value)
 {
   NPP npp = NPPStack::Peek();
-  JSContext *cx = GetJSContext(npp);
 
-  if (!cx) {
+  nsCOMPtr<nsIGlobalObject> globalObject = GetGlobalObject(npp);
+  if (NS_WARN_IF(!globalObject)) {
     return false;
   }
 
+  // We're about to run script via JS_CallFunctionValue, so we need an
+  // AutoEntryScript. NPAPI plugins are Gecko-specific and not in any spec.
+  dom::AutoEntryScript aes(globalObject);
+  JSContext *cx = aes.cx();
+
   if (!npobj) {
     ThrowJSException(cx,
                      "Null npobj in nsJSObjWrapper::NP_SetProperty!");
 
     return false;
   }
 
   nsJSObjWrapper *npjsobj = (nsJSObjWrapper *)npobj;
   bool ok = false;
 
-  nsCxPusher pusher;
-  pusher.Push(cx);
   AutoJSExceptionReporter reporter(cx);
   JS::Rooted<JSObject*> jsObj(cx, npjsobj->mJSObj);
   JSAutoCompartment ac(cx, jsObj);
 
   JS::Rooted<JS::Value> v(cx, NPVariantToJSVal(npp, cx, value));
 
   NS_ASSERTION(NPIdentifierIsInt(npid) || NPIdentifierIsString(npid),
                "id must be either string or int!\n");
--- a/gfx/layers/client/TiledContentClient.cpp
+++ b/gfx/layers/client/TiledContentClient.cpp
@@ -1387,17 +1387,17 @@ ClientTiledLayerBuffer::ComputeProgressi
 
   ContainerLayer* scrollAncestor = nullptr;
   mThebesLayer->GetAncestorLayers(&scrollAncestor, nullptr);
 
   // Find out the current view transform to determine which tiles to draw
   // first, and see if we should just abort this paint. Aborting is usually
   // caused by there being an incoming, more relevant paint.
   ViewTransform viewTransform;
-#if defined(MOZ_WIDGET_ANDROID)
+#if defined(MOZ_WIDGET_ANDROID) && !defined(MOZ_ANDROID_APZ)
   FrameMetrics compositorMetrics = scrollAncestor->GetFrameMetrics();
   bool abortPaint = false;
   // On Android, only the primary scrollable layer is async-scrolled, and the only one
   // that the Java-side code can provide details about. If we're tiling some other layer
   // then we already have all the information we need about it.
   if (scrollAncestor == mManager->GetPrimaryScrollableLayer()) {
     abortPaint = mManager->ProgressiveUpdateCallback(!staleRegion.Contains(aInvalidRegion),
                                                      compositorMetrics,
--- a/gfx/layers/ipc/CompositorParent.cpp
+++ b/gfx/layers/ipc/CompositorParent.cpp
@@ -140,19 +140,20 @@ CompositorThreadHolder::CreateCompositor
 
   Thread* compositorThread = new Thread("Compositor");
 
   Thread::Options options;
   /* Timeout values are powers-of-two to enable us get better data.
      128ms is chosen for transient hangs because 8Hz should be the minimally
      acceptable goal for Compositor responsiveness (normal goal is 60Hz). */
   options.transient_hang_timeout = 128; // milliseconds
-  /* 8192ms is chosen for permanent hangs because it's several seconds longer
-     than the default hang timeout on major platforms (about 5 seconds). */
-  options.permanent_hang_timeout = 8192; // milliseconds
+  /* 2048ms is chosen for permanent hangs because it's longer than most
+   * Compositor hangs seen in the wild, but is short enough to not miss getting
+   * native hang stacks. */
+  options.permanent_hang_timeout = 2048; // milliseconds
 
   if (!compositorThread->StartWithOptions(options)) {
     delete compositorThread;
     return nullptr;
   }
 
   CreateCompositorMap();
 
--- a/ipc/contentproc/plugin-container.cpp
+++ b/ipc/contentproc/plugin-container.cpp
@@ -78,16 +78,23 @@ void StartSandboxCallback()
         target_service->LowerToken();
     }
 }
 #endif
 
 int
 content_process_main(int argc, char* argv[])
 {
+    // Check for the absolute minimum number of args we need to move
+    // forward here. We expect the last arg to be the child process type.
+    if (argc < 1) {
+      return 3;
+    }
+    XRE_SetProcessType(argv[--argc]);
+
     bool isNuwa = false;
     for (int i = 1; i < argc; i++) {
         isNuwa |= strcmp(argv[i], "-nuwa") == 0;
 #if defined(XP_WIN)
         gIsSandboxEnabled |= strcmp(argv[i], "-sandbox") == 0;
 #endif
     }
 
@@ -109,27 +116,21 @@ content_process_main(int argc, char* arg
     } else {
         NuwaAddFinalConstructor(&InitializeBinder, nullptr);
     }
 #else
     InitializeBinder(nullptr);
 #endif
 #endif
 
-    // Check for the absolute minimum number of args we need to move
-    // forward here. We expect the last arg to be the child process type.
-    if (argc < 1)
-      return 3;
-    GeckoProcessType proctype = XRE_StringToChildProcessType(argv[--argc]);
-
 #ifdef XP_WIN
     // For plugins, this is done in PluginProcessChild::Init, as we need to
     // avoid it for unsupported plugins.  See PluginProcessChild::Init for
     // the details.
-    if (proctype != GeckoProcessType_Plugin) {
+    if (XRE_GetProcessType() != GeckoProcessType_Plugin) {
         mozilla::SanitizeEnvironmentVariables();
         SetDllDirectory(L"");
     }
 
     if (gIsSandboxEnabled) {
         sandbox::TargetServices* target_service =
             sandbox::SandboxFactory::GetTargetServices();
         if (!target_service) {
@@ -139,13 +140,13 @@ content_process_main(int argc, char* arg
         sandbox::ResultCode result = target_service->Init();
         if (result != sandbox::SBOX_ALL_OK) {
            return 2;
         }
         mozilla::SandboxTarget::Instance()->SetStartSandboxCallback(StartSandboxCallback);
     }
 #endif
 
-    nsresult rv = XRE_InitChildProcess(argc, argv, proctype);
+    nsresult rv = XRE_InitChildProcess(argc, argv);
     NS_ENSURE_SUCCESS(rv, 1);
 
     return 0;
 }
--- a/ipc/glue/MessageLink.cpp
+++ b/ipc/glue/MessageLink.cpp
@@ -10,16 +10,17 @@
 #include "mozilla/ipc/BrowserProcessSubThread.h"
 #include "mozilla/ipc/ProtocolUtils.h"
 
 #ifdef MOZ_NUWA_PROCESS
 #include "ipc/Nuwa.h"
 #include "mozilla/Preferences.h"
 #endif
 
+#include "mozilla/Assertions.h"
 #include "nsDebug.h"
 #include "nsISupportsImpl.h"
 #include "nsXULAppAPI.h"
 
 using namespace mozilla;
 using namespace std;
 
 template<>
@@ -53,35 +54,36 @@ namespace ipc {
 
 MessageLink::MessageLink(MessageChannel *aChan)
   : mChan(aChan)
 {
 }
 
 MessageLink::~MessageLink()
 {
+#ifdef DEBUG
     mChan = nullptr;
+#endif
 }
 
 ProcessLink::ProcessLink(MessageChannel *aChan)
-  : MessageLink(aChan),
-    mExistingListener(nullptr)
+  : MessageLink(aChan)
+  , mTransport(nullptr)
+  , mIOLoop(nullptr)
+  , mExistingListener(nullptr)
 {
 }
 
 ProcessLink::~ProcessLink()
 {
-    mIOLoop = 0;
-    if (mTransport) {
-        mTransport->set_listener(0);
-        
-        // we only hold a weak ref to the transport, which is "owned"
-        // by GeckoChildProcess/GeckoThread
-        mTransport = 0;
-    }
+#ifdef DEBUG
+    mTransport = nullptr;
+    mIOLoop = nullptr;
+    mExistingListener = nullptr;
+#endif
 }
 
 void 
 ProcessLink::Open(mozilla::ipc::Transport* aTransport, MessageLoop *aIOLoop, Side aSide)
 {
     NS_PRECONDITION(aTransport, "need transport layer");
 
     // FIXME need to check for valid channel
@@ -286,17 +288,18 @@ ProcessLink::OnEchoMessage(Message* msg)
     AssertIOThread();
     OnMessageReceived(*msg);
     delete msg;
 }
 
 void
 ProcessLink::OnChannelOpened()
 {
-    mChan->AssertLinkThread();
+    AssertIOThread();
+
     {
         MonitorAutoLock lock(*mChan->mMonitor);
 
         mExistingListener = mTransport->set_listener(this);
 #ifdef DEBUG
         if (mExistingListener) {
             queue<Message> pending;
             mExistingListener->GetQueuedMessages(pending);
@@ -351,28 +354,35 @@ ProcessLink::OnChannelConnected(int32_t 
 
     mChan->OnChannelConnected(peer_pid);
 }
 
 void
 ProcessLink::OnChannelError()
 {
     AssertIOThread();
+
     MonitorAutoLock lock(*mChan->mMonitor);
+
+    MOZ_ALWAYS_TRUE(this == mTransport->set_listener(mExistingListener));
+
     mChan->OnChannelErrorFromLink();
 }
 
 void
 ProcessLink::OnCloseChannel()
 {
     AssertIOThread();
 
     mTransport->Close();
 
     MonitorAutoLock lock(*mChan->mMonitor);
+
+    MOZ_ALWAYS_TRUE(this == mTransport->set_listener(mExistingListener));
+
     mChan->mChannelState = ChannelClosed;
     mChan->mMonitor->Notify();
 }
 
 bool
 ProcessLink::Unsound_IsClosed() const
 {
     return mTransport->Unsound_IsClosed();
--- a/ipc/glue/MessageLink.h
+++ b/ipc/glue/MessageLink.h
@@ -136,16 +136,24 @@ class ProcessLink
     {
         NS_ABORT_IF_FALSE(mIOLoop == MessageLoop::current(),
                           "not on I/O thread!");
     }
 
   public:
     explicit ProcessLink(MessageChannel *chan);
     virtual ~ProcessLink();
+
+    // The ProcessLink will register itself as the IPC::Channel::Listener on the
+    // transport passed here. If the transport already has a listener registered
+    // then a listener chain will be established (the ProcessLink listener
+    // methods will be called first and may call some methods on the original
+    // listener as well). Once the channel is closed (either via normal shutdown
+    // or a pipe error) the chain will be destroyed and the original listener
+    // will again be registered.
     void Open(Transport* aTransport, MessageLoop *aIOLoop, Side aSide);
     
     // Run on the I/O thread, only when using inter-process link.
     // These methods acquire the monitor and forward to the
     // similarly named methods in AsyncChannel below
     // (OnMessageReceivedFromLink(), etc)
     virtual void OnMessageReceived(const Message& msg) MOZ_OVERRIDE;
     virtual void OnChannelConnected(int32_t peer_pid) MOZ_OVERRIDE;
--- a/ipc/testshell/TestShellParent.cpp
+++ b/ipc/testshell/TestShellParent.cpp
@@ -1,21 +1,23 @@
 /* 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 "TestShellParent.h"
 
 /* This must occur *after* TestShellParent.h to avoid typedefs conflicts. */
+#include "jsfriendapi.h"
 #include "mozilla/ArrayUtils.h"
 
 #include "mozilla/dom/ContentParent.h"
+#include "mozilla/dom/ScriptSettings.h"
 
 #include "nsAutoPtr.h"
-#include "nsCxPusher.h"
+#include "xpcpublic.h"
 
 using namespace mozilla;
 using mozilla::ipc::TestShellParent;
 using mozilla::ipc::TestShellCommandParent;
 using mozilla::ipc::PTestShellCommandParent;
 using mozilla::dom::ContentParent;
 
 void
@@ -52,40 +54,39 @@ bool
 TestShellCommandParent::SetCallback(JSContext* aCx,
                                     JS::Value aCallback)
 {
   if (!mCallback.Hold(aCx)) {
     return false;
   }
 
   mCallback = aCallback;
-  mCx = aCx;
 
   return true;
 }
 
 bool
 TestShellCommandParent::RunCallback(const nsString& aResponse)
 {
-  NS_ENSURE_TRUE(!mCallback.get().isNull() && mCx, false);
+  NS_ENSURE_TRUE(mCallback.ToJSObject(), false);
 
-  // We're pulling a cx off the heap, so make sure it's stack-top.
-  AutoCxPusher pusher(mCx);
-  NS_ENSURE_TRUE(mCallback.ToJSObject(), false);
-  JSAutoCompartment ac(mCx, mCallback.ToJSObject());
-  JS::Rooted<JSObject*> global(mCx, JS::CurrentGlobalOrNull(mCx));
+  // We're about to run script via JS_CallFunctionValue, so we need an
+  // AutoEntryScript. This is just for testing and not in any spec.
+  dom::AutoEntryScript aes(xpc::GetNativeForGlobal(js::GetGlobalForObjectCrossCompartment(mCallback.ToJSObject())));
+  JSContext* cx = aes.cx();
+  JS::Rooted<JSObject*> global(cx, JS::CurrentGlobalOrNull(cx));
 
-  JSString* str = JS_NewUCStringCopyN(mCx, aResponse.get(), aResponse.Length());
+  JSString* str = JS_NewUCStringCopyN(cx, aResponse.get(), aResponse.Length());
   NS_ENSURE_TRUE(str, false);
 
-  JS::Rooted<JS::Value> strVal(mCx, JS::StringValue(str));
+  JS::Rooted<JS::Value> strVal(cx, JS::StringValue(str));
 
-  JS::Rooted<JS::Value> rval(mCx);
-  JS::Rooted<JS::Value> callback(mCx, mCallback);
-  bool ok = JS_CallFunctionValue(mCx, global, callback, JS::HandleValueArray(strVal), &rval);
+  JS::Rooted<JS::Value> rval(cx);
+  JS::Rooted<JS::Value> callback(cx, mCallback);
+  bool ok = JS_CallFunctionValue(cx, global, callback, JS::HandleValueArray(strVal), &rval);
   NS_ENSURE_TRUE(ok, false);
 
   return true;
 }
 
 void
 TestShellCommandParent::ReleaseCallback()
 {
--- a/ipc/testshell/TestShellParent.h
+++ b/ipc/testshell/TestShellParent.h
@@ -35,17 +35,17 @@ public:
   bool
   CommandDone(TestShellCommandParent* aActor, const nsString& aResponse);
 };
 
 
 class TestShellCommandParent : public PTestShellCommandParent
 {
 public:
-  TestShellCommandParent() : mCx(nullptr) { }
+  TestShellCommandParent() {}
 
   bool SetCallback(JSContext* aCx, JS::Value aCallback);
 
   bool RunCallback(const nsString& aResponse);
 
   void ReleaseCallback();
 
 protected:
@@ -53,17 +53,16 @@ protected:
 
   void ActorDestroy(ActorDestroyReason why);
 
   bool Recv__delete__(const nsString& aResponse) {
     return ExecuteCallback(aResponse);
   }
 
 private:
-  JSContext* mCx;
   nsAutoJSValHolder mCallback;
 };
 
 
 } /* namespace ipc */
 } /* namespace mozilla */
 
 #endif /* ipc_testshell_TestShellParent_h */
--- a/js/src/Makefile.in
+++ b/js/src/Makefile.in
@@ -309,16 +309,17 @@ endif
 export:: selfhosting
 selfhosting:: selfhosted.out.h
 
 selfhosting_srcs := \
   $(srcdir)/builtin/Utilities.js \
   $(srcdir)/builtin/ParallelUtilities.js \
   $(srcdir)/builtin/Array.js \
   $(srcdir)/builtin/Date.js \
+  $(srcdir)/builtin/Error.js \
   $(srcdir)/builtin/Intl.js \
   $(srcdir)/builtin/IntlData.js \
   $(srcdir)/builtin/Iterator.js \
   $(srcdir)/builtin/Map.js \
   $(srcdir)/builtin/Number.js \
   $(srcdir)/builtin/String.js \
   $(srcdir)/builtin/Set.js \
   $(srcdir)/builtin/TypedObject.js \
new file mode 100644
--- /dev/null
+++ b/js/src/builtin/Error.js
@@ -0,0 +1,31 @@
+/* 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/. */
+
+/* ES6 20140718 draft 19.5.3.4. */
+function ErrorToString()
+{
+  /* Steps 1-2. */
+  var obj = this;
+  if (!IsObject(obj))
+    ThrowError(JSMSG_INCOMPATIBLE_PROTO, "Error", "toString", "value");
+
+  /* Steps 3-5. */
+  var name = obj.name;
+  name = (name === undefined) ? "Error" : ToString(name);
+
+  /* Steps 6-8. */
+  var msg = obj.message;
+  msg = (msg === undefined) ? "" : ToString(msg);
+
+  /* Step 9. */
+  if (name === "")
+    return msg;
+
+  /* Step 10. */
+  if (msg === "")
+    return name;
+
+  /* Step 11. */
+  return name + ": " + msg;
+}
--- a/js/src/frontend/BytecodeEmitter.cpp
+++ b/js/src/frontend/BytecodeEmitter.cpp
@@ -3237,37 +3237,41 @@ EmitDestructuringOpsHelper(ExclusiveCont
         } else {
             JS_ASSERT(pn->isKind(PNK_OBJECT));
             JS_ASSERT(pn2->isKind(PNK_COLON) || pn2->isKind(PNK_SHORTHAND));
 
             ParseNode *key = pn2->pn_left;
             if (key->isKind(PNK_NUMBER)) {
                 if (!EmitNumberOp(cx, key->pn_dval, bce))
                     return false;
-            } else {
-                MOZ_ASSERT(key->isKind(PNK_STRING) || key->isKind(PNK_NAME));
+            } else if (key->isKind(PNK_NAME) || key->isKind(PNK_STRING)) {
                 PropertyName *name = key->pn_atom->asPropertyName();
 
                 // The parser already checked for atoms representing indexes and
                 // used PNK_NUMBER instead, but also watch for ids which TI treats
                 // as indexes for simplification of downstream analysis.
                 jsid id = NameToId(name);
                 if (id != types::IdToTypeId(id)) {
                     if (!EmitTree(cx, bce, key))
                         return false;
                 } else {
                     if (!EmitAtomOp(cx, name, JSOP_GETPROP, bce))
                         return false;
                     doElemOp = false;
                 }
+            } else {
+                JS_ASSERT(key->isKind(PNK_COMPUTED_NAME));
+                if (!EmitTree(cx, bce, key->pn_kid))
+                    return false;
             }
 
             pn3 = pn2->pn_right;
         }
 
+
         if (doElemOp) {
             /*
              * Ok, get the value of the matching property name.  This leaves
              * that value on top of the value being destructured, so the stack
              * is one deeper than when we started.
              */
             if (!EmitElemOpBase(cx, bce, JSOP_GETELEM))
                 return false;
@@ -5544,22 +5548,48 @@ EmitStatement(ExclusiveContext *cx, Byte
             return false;
         }
         if (op != JSOP_NOP) {
             if (!EmitTree(cx, bce, pn2))
                 return false;
             if (Emit1(cx, bce, op) < 0)
                 return false;
         }
-    } else if (!pn->isDirectivePrologueMember()) {
-        /* Don't complain about directive prologue members; just don't emit their code. */
-        bce->current->currentLine = bce->parser->tokenStream.srcCoords.lineNum(pn2->pn_pos.begin);
-        bce->current->lastColumn = 0;
-        if (!bce->reportStrictWarning(pn2, JSMSG_USELESS_EXPR))
-            return false;
+    } else if (pn->isDirectivePrologueMember()) {
+        // Don't complain about directive prologue members; just don't emit
+        // their code.
+    } else {
+        if (JSAtom *atom = pn->isStringExprStatement()) {
+            // Warn if encountering a non-directive prologue member string
+            // expression statement, that is inconsistent with the current
+            // directive prologue.  That is, a script *not* starting with
+            // "use strict" should warn for any "use strict" statements seen
+            // later in the script, because such statements are misleading.
+            const char *directive = nullptr;
+            if (atom == cx->names().useStrict) {
+                if (!bce->sc->strict)
+                    directive = js_useStrict_str;
+            } else if (atom == cx->names().useAsm) {
+                if (bce->sc->isFunctionBox()) {
+                    JSFunction *fun = bce->sc->asFunctionBox()->function();
+                    if (fun->isNative() && IsAsmJSModuleNative(fun->native()))
+                        directive = js_useAsm_str;
+                }
+            }
+
+            if (directive) {
+                if (!bce->reportStrictWarning(pn2, JSMSG_CONTRARY_NONDIRECTIVE, directive))
+                    return false;
+            }
+        } else {
+            bce->current->currentLine = bce->parser->tokenStream.srcCoords.lineNum(pn2->pn_pos.begin);
+            bce->current->lastColumn = 0;
+            if (!bce->reportStrictWarning(pn2, JSMSG_USELESS_EXPR))
+                return false;
+        }
     }
 
     return true;
 }
 
 static bool
 EmitDelete(ExclusiveContext *cx, BytecodeEmitter *bce, ParseNode *pn)
 {
@@ -6048,27 +6078,31 @@ EmitObject(ExclusiveContext *cx, Bytecod
 
         /* Emit an index for t[2] for later consumption by JSOP_INITELEM. */
         ParseNode *pn3 = pn2->pn_left;
         bool isIndex = false;
         if (pn3->isKind(PNK_NUMBER)) {
             if (!EmitNumberOp(cx, pn3->pn_dval, bce))
                 return false;
             isIndex = true;
-        } else {
+        } else if (pn3->isKind(PNK_NAME) || pn3->isKind(PNK_STRING)) {
             // The parser already checked for atoms representing indexes and
             // used PNK_NUMBER instead, but also watch for ids which TI treats
             // as indexes for simpliciation of downstream analysis.
-            JS_ASSERT(pn3->isKind(PNK_NAME) || pn3->isKind(PNK_STRING));
             jsid id = NameToId(pn3->pn_atom->asPropertyName());
             if (id != types::IdToTypeId(id)) {
                 if (!EmitTree(cx, bce, pn3))
                     return false;
                 isIndex = true;
             }
+        } else {
+            JS_ASSERT(pn3->isKind(PNK_COMPUTED_NAME));
+            if (!EmitTree(cx, bce, pn3->pn_kid))
+                return false;
+            isIndex = true;
         }
 
         /* Emit code for the property initializer. */
         if (!EmitTree(cx, bce, pn2->pn_right))
             return false;
 
         JSOp op = pn2->getOp();
         JS_ASSERT(op == JSOP_INITPROP ||
--- a/js/src/frontend/FullParseHandler.h
+++ b/js/src/frontend/FullParseHandler.h
@@ -85,16 +85,21 @@ class FullParseHandler
     ParseNode *freeTree(ParseNode *pn) { return allocator.freeTree(pn); }
     void prepareNodeForMutation(ParseNode *pn) { return allocator.prepareNodeForMutation(pn); }
     const Token &currentToken() { return tokenStream.currentToken(); }
 
     ParseNode *newName(PropertyName *name, uint32_t blockid, const TokenPos &pos) {
         return new_<NameNode>(PNK_NAME, JSOP_NAME, name, blockid, pos);
     }
 
+    ParseNode *newComputedName(ParseNode *expr, uint32_t begin, uint32_t end) {
+        TokenPos pos(begin, end);
+        return new_<UnaryNode>(PNK_COMPUTED_NAME, JSOP_NOP, pos, expr);
+    }
+
     Definition *newPlaceholder(JSAtom *atom, uint32_t blockid, const TokenPos &pos) {
         Definition *dn =
             (Definition *) new_<NameNode>(PNK_NAME, JSOP_NOP, atom, blockid, pos);
         if (!dn)
             return nullptr;
         dn->setDefn(true);
         dn->pn_dflags |= PND_PLACEHOLDER;
         return dn;
--- a/js/src/frontend/ParseNode.h
+++ b/js/src/frontend/ParseNode.h
@@ -84,16 +84,17 @@ class UpvarCookie
     F(ELEM) \
     F(ARRAY) \
     F(ELISION) \
     F(STATEMENTLIST) \
     F(LABEL) \
     F(OBJECT) \
     F(CALL) \
     F(NAME) \
+    F(COMPUTED_NAME) \
     F(NUMBER) \
     F(STRING) \
     F(TEMPLATE_STRING_LIST) \
     F(TEMPLATE_STRING) \
     F(TAGGED_TEMPLATE) \
     F(CALLSITEOBJ) \
     F(REGEXP) \
     F(TRUE) \
@@ -388,16 +389,18 @@ enum ParseNodeKind
  *                          [,,] holes are represented by PNK_ELISION nodes
  *                          pn_xflags: PN_ENDCOMMA if extra comma at end
  * PNK_OBJECT   list        pn_head: list of pn_count binary PNK_COLON nodes
  * PNK_COLON    binary      key-value pair in object initializer or
  *                          destructuring lhs
  *                          pn_left: property id, pn_right: value
  * PNK_SHORTHAND binary     Same fields as PNK_COLON. This is used for object
  *                          literal properties using shorthand ({x}).
+ * PNK_COMPUTED_NAME unary  ES6 ComputedPropertyName.
+ *                          pn_kid: the AssignmentExpression inside the square brackets
  * PNK_NAME,    name        pn_atom: name, string, or object atom
  * PNK_STRING               pn_op: JSOP_NAME, JSOP_STRING, or JSOP_OBJECT
  *                          If JSOP_NAME, pn_op may be JSOP_*ARG or JSOP_*VAR
  *                          with pn_cookie telling (staticLevel, slot) (see
  *                          jsscript.h's UPVAR macros) and pn_dflags telling
  *                          const-ness and static analysis results
  * PNK_TEMPLATE_STRING_LIST pn_head: list of alternating expr and template strings
  *              list
--- a/js/src/frontend/Parser.cpp
+++ b/js/src/frontend/Parser.cpp
@@ -7254,16 +7254,30 @@ Parser<ParseHandler>::objectLiteral()
         switch (ltok) {
           case TOK_NUMBER:
             atom = DoubleToAtom(context, tokenStream.currentToken().number());
             if (!atom)
                 return null();
             propname = newNumber(tokenStream.currentToken());
             break;
 
+          case TOK_LB: {
+              // Computed property name.
+              uint32_t begin = pos().begin;
+              Node assignNode = assignExpr();
+              if (!assignNode)
+                  return null();
+              MUST_MATCH_TOKEN(TOK_RB, JSMSG_COMP_PROP_UNTERM_EXPR);
+              propname = handler.newComputedName(assignNode, begin, pos().end);
+              if (!propname)
+                  return null();
+              handler.setListFlag(literal, PNX_NONCONST);
+              break;
+          }
+
           case TOK_NAME: {
             atom = tokenStream.currentName();
             if (atom == context->names().get) {
                 op = JSOP_INITPROP_GETTER;
             } else if (atom == context->names().set) {
                 op = JSOP_INITPROP_SETTER;
             } else {
                 propname = handler.newIdentifier(atom, pos());
--- a/js/src/frontend/SyntaxParseHandler.h
+++ b/js/src/frontend/SyntaxParseHandler.h
@@ -56,16 +56,20 @@ class SyntaxParseHandler
 
     void trace(JSTracer *trc) {}
 
     Node newName(PropertyName *name, uint32_t blockid, const TokenPos &pos) {
         lastAtom = name;
         return NodeName;
     }
 
+    Node newComputedName(Node expr, uint32_t start, uint32_t end) {
+        return NodeName;
+    }
+
     DefinitionNode newPlaceholder(JSAtom *atom, uint32_t blockid, const TokenPos &pos) {
         return Definition::PLACEHOLDER;
     }
 
     Node newIdentifier(JSAtom *atom, const TokenPos &pos) { return NodeString; }
     Node newNumber(double value, DecimalPoint decimalPoint, const TokenPos &pos) { return NodeGeneric; }
     Node newBooleanLiteral(bool cond, const TokenPos &pos) { return NodeGeneric; }
 
--- a/js/src/jit-test/tests/basic/error-toString.js
+++ b/js/src/jit-test/tests/basic/error-toString.js
@@ -1,9 +1,9 @@
 var errorToString = Error.prototype.toString;
 
 
-assertEq(errorToString.call({message: "", name: ""}), "Error");
+assertEq(errorToString.call({message: "", name: ""}), "");
 assertEq(errorToString.call({name: undefined, message: ""}), "Error");
 assertEq(errorToString.call({name: "Test", message: undefined}), "Test");
 assertEq(errorToString.call({name: "Test", message: ""}), "Test");
 assertEq(errorToString.call({name: "", message: "Test"}), "Test");
 assertEq(errorToString.call({name: "Test", message: "it!"}), "Test: it!");
new file mode 100644
--- /dev/null
+++ b/js/src/jit-test/tests/class/compProp.js
@@ -0,0 +1,15 @@
+load(libdir + "asserts.js");
+
+function f(tag) { return {[tag]: 1}; }
+a = [];
+for (var i = 0; i < 2000; i++)
+    a[i] = f("first");
+
+for (var i = 0; i < 2000; i++)
+    assertEq(a[i].first, 1);
+
+for (var i = 0; i < 2000; i++)
+    a[i] = f("second");
+
+for (var i = 0; i < 2000; i++)
+    assertEq(a[i].second, 1);
--- a/js/src/jit/x86/Assembler-x86.cpp
+++ b/js/src/jit/x86/Assembler-x86.cpp
@@ -25,17 +25,17 @@ ABIArgGenerator::next(MIRType type)
       case MIRType_Pointer:
         stackOffset_ += sizeof(uint32_t);
         break;
       case MIRType_Float32: // Float32 moves are actually double moves
       case MIRType_Double:
         stackOffset_ += sizeof(uint64_t);
         break;
       default:
-        MOZ_ASSUME_UNREACHABLE("Unexpected argument type");
+        MOZ_CRASH("Unexpected argument type");
     }
     return current_;
 }
 
 const Register ABIArgGenerator::NonArgReturnReg0 = ecx;
 const Register ABIArgGenerator::NonArgReturnReg1 = edx;
 const Register ABIArgGenerator::NonVolatileReg = ebx;
 const Register ABIArgGenerator::NonArg_VolatileReg = eax;
--- a/js/src/jit/x86/Assembler-x86.h
+++ b/js/src/jit/x86/Assembler-x86.h
@@ -243,17 +243,17 @@ class Assembler : public AssemblerX86Sha
             masm.movl_i32m(uintptr_t(ptr.value), dest.disp(), dest.base());
             writeDataRelocation(ptr);
             break;
           case Operand::MEM_SCALE:
             masm.movl_i32m(uintptr_t(ptr.value), dest.disp(), dest.base(), dest.index(), dest.scale());
             writeDataRelocation(ptr);
             break;
           default:
-            MOZ_ASSUME_UNREACHABLE("unexpected operand kind");
+            MOZ_CRASH("unexpected operand kind");
         }
     }
     void movl(ImmWord imm, Register dest) {
         masm.movl_i32r(imm.value, dest.code());
     }
     void movl(ImmPtr imm, Register dest) {
         movl(ImmWord(uintptr_t(imm.value)), dest);
     }
@@ -300,27 +300,27 @@ class Assembler : public AssemblerX86Sha
     }
 
     void fld32(const Operand &dest) {
         switch (dest.kind()) {
           case Operand::MEM_REG_DISP:
             masm.fld32_m(dest.disp(), dest.base());
             break;
           default:
-            MOZ_ASSUME_UNREACHABLE("unexpected operand kind");
+            MOZ_CRASH("unexpected operand kind");
         }
     }
 
     void fstp32(const Operand &src) {
         switch (src.kind()) {
           case Operand::MEM_REG_DISP:
             masm.fstp32_m(src.disp(), src.base());
             break;
           default:
-            MOZ_ASSUME_UNREACHABLE("unexpected operand kind");
+            MOZ_CRASH("unexpected operand kind");
         }
     }
 
     void cmpl(const Register src, ImmWord ptr) {
         masm.cmpl_ir(ptr.value, src.code());
     }
     void cmpl(const Register src, ImmPtr imm) {
         cmpl(src, ImmWord(uintptr_t(imm.value)));
@@ -342,17 +342,17 @@ class Assembler : public AssemblerX86Sha
             masm.cmpl_im_force32(uintptr_t(imm.value), op.disp(), op.base());
             writeDataRelocation(imm);
             break;
           case Operand::MEM_ADDRESS32:
             masm.cmpl_im(uintptr_t(imm.value), op.address());
             writeDataRelocation(imm);
             break;
           default:
-            MOZ_ASSUME_UNREACHABLE("unexpected operand kind");
+            MOZ_CRASH("unexpected operand kind");
         }
     }
     void cmpl(AsmJSAbsoluteAddress lhs, Register rhs) {
         masm.cmpl_rm_force32(rhs.code(), (void*)-1);
         append(AsmJSAbsoluteLink(CodeOffsetLabel(masm.currentOffset()), lhs.kind()));
     }
 
     void jmp(ImmPtr target, Relocation::Kind reloc = Relocation::HARDCODED) {
--- a/js/src/jit/x86/Bailouts-x86.cpp
+++ b/js/src/jit/x86/Bailouts-x86.cpp
@@ -75,17 +75,17 @@ IonBailoutIterator::IonBailoutIterator(c
 
     kind_ = Kind_BailoutIterator;
     current_ = fp;
     type_ = JitFrame_IonJS;
     topFrameSize_ = current_ - sp;
     switch (mode_) {
       case SequentialExecution: topIonScript_ = script()->ionScript(); break;
       case ParallelExecution: topIonScript_ = script()->parallelIonScript(); break;
-      default: MOZ_ASSUME_UNREACHABLE("No such execution mode");
+      default: MOZ_CRASH("No such execution mode");
     }
 
     if (bailout->frameClass() == FrameSizeClass::None()) {
         snapshotOffset_ = bailout->snapshotOffset();
         return;
     }
 
     // Compute the snapshot offset from the bailout ID.
--- a/js/src/jit/x86/BaselineIC-x86.cpp
+++ b/js/src/jit/x86/BaselineIC-x86.cpp
@@ -186,17 +186,17 @@ ICBinaryArith_Int32::Compiler::generateS
             masm.convertUInt32ToDouble(R0.payloadReg(), ScratchDoubleReg);
             masm.boxDouble(ScratchDoubleReg, R0);
         } else {
             masm.j(Assembler::Signed, &revertRegister);
             masm.tagValue(JSVAL_TYPE_INT32, R0.payloadReg(), R0);
         }
         break;
       default:
-       MOZ_ASSUME_UNREACHABLE("Unhandled op for BinaryArith_Int32.  ");
+       MOZ_CRASH("Unhandled op for BinaryArith_Int32.");
     }
 
     // Return.
     EmitReturnFromIC(masm);
 
     switch(op_) {
       case JSOP_MUL:
         masm.bind(&maybeNegZero);
@@ -247,17 +247,17 @@ ICUnaryArith_Int32::Compiler::generateSt
         masm.notl(R0.payloadReg());
         break;
       case JSOP_NEG:
         // Guard against 0 and MIN_INT, both result in a double.
         masm.branchTest32(Assembler::Zero, R0.payloadReg(), Imm32(0x7fffffff), &failure);
         masm.negl(R0.payloadReg());
         break;
       default:
-        MOZ_ASSUME_UNREACHABLE("Unexpected op");
+        MOZ_CRASH("Unexpected op");
     }
 
     EmitReturnFromIC(masm);
 
     masm.bind(&failure);
     EmitStubGuardFailure(masm);
     return true;
 }
--- a/js/src/jit/x86/CodeGenerator-x86.cpp
+++ b/js/src/jit/x86/CodeGenerator-x86.cpp
@@ -275,17 +275,17 @@ CodeGeneratorX86::loadViewTypeElement(Sc
       case Scalar::Uint8Clamped:
       case Scalar::Uint8:   masm.movzblWithPatch(srcAddr, ToRegister(out)); break;
       case Scalar::Int16:   masm.movswlWithPatch(srcAddr, ToRegister(out)); break;
       case Scalar::Uint16:  masm.movzwlWithPatch(srcAddr, ToRegister(out)); break;
       case Scalar::Int32:
       case Scalar::Uint32:  masm.movlWithPatch(srcAddr, ToRegister(out)); break;
       case Scalar::Float32: masm.movssWithPatch(srcAddr, ToFloatRegister(out)); break;
       case Scalar::Float64: masm.movsdWithPatch(srcAddr, ToFloatRegister(out)); break;
-      default: MOZ_ASSUME_UNREACHABLE("unexpected array type");
+      default: MOZ_CRASH("unexpected array type");
     }
 }
 
 template<typename T>
 bool
 CodeGeneratorX86::loadAndNoteViewTypeElement(Scalar::Type vt, const T &srcAddr,
                                              const LDefinition *out)
 {
@@ -380,17 +380,17 @@ CodeGeneratorX86::storeViewTypeElement(S
       case Scalar::Uint8Clamped:
       case Scalar::Uint8:   masm.movbWithPatch(ToRegister(value), dstAddr); break;
       case Scalar::Int16:
       case Scalar::Uint16:  masm.movwWithPatch(ToRegister(value), dstAddr); break;
       case Scalar::Int32:
       case Scalar::Uint32:  masm.movlWithPatch(ToRegister(value), dstAddr); break;
       case Scalar::Float32: masm.movssWithPatch(ToFloatRegister(value), dstAddr); break;
       case Scalar::Float64: masm.movsdWithPatch(ToFloatRegister(value), dstAddr); break;
-      default: MOZ_ASSUME_UNREACHABLE("unexpected array type");
+      default: MOZ_CRASH("unexpected array type");
     }
 }
 
 template<typename T>
 void
 CodeGeneratorX86::storeAndNoteViewTypeElement(Scalar::Type vt, const LAllocation *value,
                                               const T &dstAddr)
 {
@@ -539,17 +539,17 @@ CodeGeneratorX86::postAsmJSCall(LAsmJSCa
     }
 }
 
 void
 DispatchIonCache::initializeAddCacheState(LInstruction *ins, AddCacheState *addState)
 {
     // On x86, where there is no general purpose scratch register available,
     // child cache classes must manually specify a dispatch scratch register.
-    MOZ_ASSUME_UNREACHABLE("x86 needs manual assignment of dispatchScratch");
+    MOZ_CRASH("x86 needs manual assignment of dispatchScratch");
 }
 
 void
 GetPropertyParIC::initializeAddCacheState(LInstruction *ins, AddCacheState *addState)
 {
     // We don't have a scratch register, but only use the temp if we needed
     // one, it's BogusTemp otherwise.
     JS_ASSERT(ins->isGetPropertyCacheV() || ins->isGetPropertyCacheT());
--- a/js/src/jit/x86/Lowering-x86.cpp
+++ b/js/src/jit/x86/Lowering-x86.cpp
@@ -249,34 +249,34 @@ LIRGeneratorX86::visitAsmJSStoreHeap(MAs
             lir = new(alloc()) LAsmJSStoreHeap(ptrAlloc, useFixed(ins->value(), eax));
             break;
           case Scalar::Int16: case Scalar::Uint16:
           case Scalar::Int32: case Scalar::Uint32:
           case Scalar::Float32: case Scalar::Float64:
             // See comment below.
             lir = new(alloc()) LAsmJSStoreHeap(ptrAlloc, useRegisterAtStart(ins->value()));
             break;
-          default: MOZ_ASSUME_UNREACHABLE("unexpected array type");
+          default: MOZ_CRASH("unexpected array type");
         }
         return add(lir, ins);
     }
 
     switch (ins->viewType()) {
       case Scalar::Int8: case Scalar::Uint8:
         // See comment for LIRGeneratorX86::useByteOpRegister.
         lir = new(alloc()) LAsmJSStoreHeap(useRegister(ins->ptr()), useFixed(ins->value(), eax));
         break;
       case Scalar::Int16: case Scalar::Uint16:
       case Scalar::Int32: case Scalar::Uint32:
       case Scalar::Float32: case Scalar::Float64:
         // For now, don't allow constant values. The immediate operand
         // affects instruction layout which affects patching.
         lir = new(alloc()) LAsmJSStoreHeap(useRegisterAtStart(ptr), useRegisterAtStart(ins->value()));
         break;
-      default: MOZ_ASSUME_UNREACHABLE("unexpected array type");
+      default: MOZ_CRASH("unexpected array type");
     }
 
     return add(lir, ins);
 }
 
 bool
 LIRGeneratorX86::visitStoreTypedArrayElementStatic(MStoreTypedArrayElementStatic *ins)
 {
@@ -290,17 +290,17 @@ LIRGeneratorX86::visitStoreTypedArrayEle
                                                          useFixed(ins->value(), eax));
         break;
       case Scalar::Int16: case Scalar::Uint16:
       case Scalar::Int32: case Scalar::Uint32:
       case Scalar::Float32: case Scalar::Float64:
         lir = new(alloc()) LStoreTypedArrayElementStatic(useRegisterAtStart(ins->ptr()),
                                                          useRegisterAtStart(ins->value()));
         break;
-      default: MOZ_ASSUME_UNREACHABLE("unexpected array type");
+      default: MOZ_CRASH("unexpected array type");
     }
 
     return add(lir, ins);
 }
 
 bool
 LIRGeneratorX86::visitAsmJSLoadFuncPtr(MAsmJSLoadFuncPtr *ins)
 {
--- a/js/src/jit/x86/MacroAssembler-x86.cpp
+++ b/js/src/jit/x86/MacroAssembler-x86.cpp
@@ -168,17 +168,17 @@ MacroAssemblerX86::passABIArg(const Move
 {
     ++passedArgs_;
     MoveOperand to = MoveOperand(StackPointer, stackForCall_);
     switch (type) {
       case MoveOp::FLOAT32: stackForCall_ += sizeof(float); break;
       case MoveOp::DOUBLE:  stackForCall_ += sizeof(double); break;
       case MoveOp::INT32:   stackForCall_ += sizeof(int32_t); break;
       case MoveOp::GENERAL: stackForCall_ += sizeof(intptr_t); break;
-      default: MOZ_ASSUME_UNREACHABLE("Unexpected argument type");
+      default: MOZ_CRASH("Unexpected argument type");
     }
     enoughMemory_ &= moveResolver_.addMove(from, to, type);
 }
 
 void
 MacroAssemblerX86::passABIArg(Register reg)
 {
     passABIArg(MoveOperand(reg), MoveOp::GENERAL);
--- a/js/src/jit/x86/MacroAssembler-x86.h
+++ b/js/src/jit/x86/MacroAssembler-x86.h
@@ -97,17 +97,17 @@ class MacroAssemblerX86 : public MacroAs
           case Operand::MEM_REG_DISP:
             return Operand(Register::FromCode(base.base()), base.disp() + sizeof(void *));
 
           case Operand::MEM_SCALE:
             return Operand(Register::FromCode(base.base()), Register::FromCode(base.index()),
                            base.scale(), base.disp() + sizeof(void *));
 
           default:
-            MOZ_ASSUME_UNREACHABLE("unexpected operand kind");
+            MOZ_CRASH("unexpected operand kind");
         }
     }
     Address ToType(Address base) {
         return ToType(Operand(base)).toAddress();
     }
     void moveValue(const Value &val, Register type, Register data) {
         jsval_layout jv = JSVAL_TO_IMPL(val);
         movl(Imm32(jv.s.tag), type);
--- a/js/src/jit/x86/Trampoline-x86.cpp
+++ b/js/src/jit/x86/Trampoline-x86.cpp
@@ -570,17 +570,17 @@ JitRuntime::generateBailoutHandler(JSCon
     switch (mode) {
       case SequentialExecution:
         GenerateBailoutThunk(cx, masm, NO_FRAME_SIZE_CLASS_ID);
         break;
       case ParallelExecution:
         GenerateParallelBailoutThunk(masm, NO_FRAME_SIZE_CLASS_ID);
         break;
       default:
-        MOZ_ASSUME_UNREACHABLE("No such execution mode");
+        MOZ_CRASH("No such execution mode");
     }
 
     Linker linker(masm);
     JitCode *code = linker.newCode<NoGC>(cx, JSC::OTHER_CODE);
 
 #ifdef JS_ION_PERF
     writePerfSpewerJitCodeProfile(code, "BailoutHandler");
 #endif
@@ -706,17 +706,17 @@ JitRuntime::generateVMWrapper(JSContext 
       case Type_Object:
         masm.branchTestPtr(Assembler::Zero, eax, eax, masm.failureLabel(f.executionMode));
         break;
       case Type_Bool:
         masm.testb(eax, eax);
         masm.j(Assembler::Zero, masm.failureLabel(f.executionMode));
         break;
       default:
-        MOZ_ASSUME_UNREACHABLE("unknown failure kind");
+        MOZ_CRASH("unknown failure kind");
     }
 
     // Load the outparam and free any allocated stack.
     switch (f.outParam) {
       case Type_Handle:
         masm.popRooted(f.outParamRootType, ReturnReg, JSReturnOperand);
         break;
 
--- a/js/src/js.msg
+++ b/js/src/js.msg
@@ -269,17 +269,17 @@ MSG_DEF(JSMSG_BAD_GENERATOR_SYNTAX,   21
 MSG_DEF(JSMSG_ARRAY_COMP_LEFTSIDE,    216, 0, JSEXN_SYNTAXERR, "invalid array comprehension left-hand side")
 MSG_DEF(JSMSG_LET_COMP_BINDING,       217, 0, JSEXN_SYNTAXERR, "'let' is not a valid name for a comprehension variable")
 MSG_DEF(JSMSG_EMPTY_ARRAY_REDUCE,     218, 0, JSEXN_TYPEERR, "reduce of empty array with no initial value")
 MSG_DEF(JSMSG_BAD_SYMBOL,             219, 1, JSEXN_TYPEERR, "{0} is not a well-known @@-symbol")
 MSG_DEF(JSMSG_BAD_DELETE_OPERAND,     220, 0, JSEXN_REFERENCEERR, "invalid delete operand")
 MSG_DEF(JSMSG_BAD_INCOP_OPERAND,      221, 0, JSEXN_REFERENCEERR, "invalid increment/decrement operand")
 MSG_DEF(JSMSG_UNEXPECTED_TYPE,        222, 2, JSEXN_TYPEERR, "{0} is {1}")
 MSG_DEF(JSMSG_LET_DECL_NOT_IN_BLOCK,  223, 0, JSEXN_SYNTAXERR, "let declaration not directly within block")
-MSG_DEF(JSMSG_UNUSED224,              224, 0, JSEXN_NONE, "")
+MSG_DEF(JSMSG_CONTRARY_NONDIRECTIVE,  224, 1, JSEXN_SYNTAXERR, "'{0}' statement won't be enforced as a directive because it isn't in directive prologue position")
 MSG_DEF(JSMSG_CANT_SET_ARRAY_ATTRS,   225, 0, JSEXN_INTERNALERR, "can't set attributes on indexed array properties")
 MSG_DEF(JSMSG_EVAL_ARITY,             226, 0, JSEXN_TYPEERR, "eval accepts only one parameter")
 MSG_DEF(JSMSG_MISSING_FUN_ARG,        227, 2, JSEXN_TYPEERR, "missing argument {0} when calling function {1}")
 MSG_DEF(JSMSG_JSON_BAD_PARSE,         228, 3, JSEXN_SYNTAXERR, "JSON.parse: {0} at line {1} column {2} of the JSON data")
 MSG_DEF(JSMSG_JSON_BAD_STRINGIFY,     229, 0, JSEXN_ERR, "JSON.stringify")
 MSG_DEF(JSMSG_NOT_CALLABLE_OR_UNDEFINED, 230, 0, JSEXN_TYPEERR, "value is not a function or undefined")
 MSG_DEF(JSMSG_NOT_NONNULL_OBJECT,     231, 0, JSEXN_TYPEERR, "value is not a non-null object")
 MSG_DEF(JSMSG_DEPRECATED_OCTAL,       232, 0, JSEXN_SYNTAXERR, "octal literals and octal escape sequences are deprecated")
@@ -438,8 +438,9 @@ MSG_DEF(JSMSG_INVALID_ARG_TYPE,         
 MSG_DEF(JSMSG_TERMINATED,               384, 1, JSEXN_ERR, "Script terminated by timeout at:\n{0}")
 MSG_DEF(JSMSG_NO_SUCH_SELF_HOSTED_PROP, 385, 1, JSEXN_ERR, "No such property on self-hosted object: {0}")
 MSG_DEF(JSMSG_PROXY_EXTENSIBILITY,      386, 0, JSEXN_TYPEERR, "proxy must report same extensiblitity as target")
 MSG_DEF(JSMSG_PROXY_CONSTRUCT_OBJECT,   387, 0, JSEXN_TYPEERR, "proxy [[Construct]] must return an object")
 MSG_DEF(JSMSG_PROXY_GETOWN_OBJORUNDEF,  388, 0, JSEXN_TYPEERR, "proxy [[GetOwnProperty]] must return an object or undefined")
 MSG_DEF(JSMSG_CANT_REPORT_C_AS_NC,      389, 0, JSEXN_TYPEERR, "proxy can't report existing configurable property as non-configurable")
 MSG_DEF(JSMSG_PROXY_REVOKED,            390, 0, JSEXN_TYPEERR, "illegal operation attempted on a revoked proxy")
 MSG_DEF(JSMSG_TEMPLSTR_UNTERM_EXPR,     391, 0, JSEXN_SYNTAXERR, "missing } in template string")
+MSG_DEF(JSMSG_COMP_PROP_UNTERM_EXPR,    392, 0, JSEXN_SYNTAXERR, "missing ] in computed property name")
--- a/js/src/jsapi-tests/testChromeBuffer.cpp
+++ b/js/src/jsapi-tests/testChromeBuffer.cpp
@@ -107,17 +107,22 @@ BEGIN_TEST(testChromeBuffer)
      */
     {
         {
             JSAutoCompartment ac(cx, trusted_glob);
             const char *paramName = "untrusted";
             const char *bytes = "try {                                  "
                                 "  untrusted();                         "
                                 "} catch (e) {                          "
-                                "  return 'From trusted: ' + e;         "
+                                "  /*                                   "
+                                "   * Careful!  We must not reenter JS  "
+                                "   * that might try to push a frame.   "
+                                "   */                                  "
+                                "  return 'From trusted: ' +            "
+                                "         e.name + ': ' + e.message;    "
                                 "}                                      ";
             JS::HandleObject global = JS::HandleObject::fromMarkedLocation(trusted_glob.unsafeGet());
             JS::CompileOptions options(cx);
             options.setFileAndLine("", 0);
             CHECK(JS_CompileFunction(cx, global, "trusted", 1, &paramName,
                                      bytes, strlen(bytes), options, &fun));
             trusted_fun = JS_GetFunctionObject(fun);
         }
--- a/js/src/jsast.tbl
+++ b/js/src/jsast.tbl
@@ -68,10 +68,11 @@ ASTDEF(AST_CATCH,                 "Catch
 ASTDEF(AST_COMP_BLOCK,            "ComprehensionBlock",             "comprehensionBlock")
 
 ASTDEF(AST_ARRAY_PATT,            "ArrayPattern",                   "arrayPattern")
 ASTDEF(AST_OBJECT_PATT,           "ObjectPattern",                  "objectPattern")
 ASTDEF(AST_PROP_PATT,             "Property",                       "propertyPattern")
 ASTDEF(AST_TEMPLATE_LITERAL,      "TemplateLiteral",                "templateLiteral")
 ASTDEF(AST_TAGGED_TEMPLATE,       "TaggedTemplate",                 "taggedTemplate")
 ASTDEF(AST_CALL_SITE_OBJ,         "CallSiteObject",                 "callSiteObject")
+ASTDEF(AST_COMPUTED_NAME,         "ComputedName",                   "computedName")
 
 /* AST_LIMIT = last + 1 */
--- a/js/src/jsexn.cpp
+++ b/js/src/jsexn.cpp
@@ -46,24 +46,21 @@ static void
 exn_finalize(FreeOp *fop, JSObject *obj);
 
 bool
 Error(JSContext *cx, unsigned argc, Value *vp);
 
 static bool
 exn_toSource(JSContext *cx, unsigned argc, Value *vp);
 
-static bool
-exn_toString(JSContext *cx, unsigned argc, Value *vp);
-
 static const JSFunctionSpec exception_methods[] = {
 #if JS_HAS_TOSOURCE
     JS_FN(js_toSource_str, exn_toSource, 0, 0),
 #endif
-    JS_FN(js_toString_str, exn_toString, 0, 0),
+    JS_SELF_HOSTED_FN(js_toString_str, "ErrorToString", 0,0),
     JS_FS_END
 };
 
 
 const Class ErrorObject::class_ = {
     js_Error_str,
     JSCLASS_IMPLEMENTS_BARRIERS |
     JSCLASS_HAS_CACHED_PROTO(JSProto_Error) |
@@ -370,92 +367,16 @@ Error(JSContext *cx, unsigned argc, Valu
                                              lineNumber, columnNumber, nullptr, message));
     if (!obj)
         return false;
 
     args.rval().setObject(*obj);
     return true;
 }
 
-/* ES5 15.11.4.4 (NB: with subsequent errata). */
-static bool
-exn_toString(JSContext *cx, unsigned argc, Value *vp)
-{
-    JS_CHECK_RECURSION(cx, return false);
-    CallArgs args = CallArgsFromVp(argc, vp);
-
-    /* Step 2. */
-    if (!args.thisv().isObject()) {
-        JS_ReportErrorNumber(cx, js_GetErrorMessage, nullptr, JSMSG_BAD_PROTOTYPE, "Error");
-        return false;
-    }
-
-    /* Step 1. */
-    RootedObject obj(cx, &args.thisv().toObject());
-
-    /* Step 3. */
-    RootedValue nameVal(cx);
-    if (!JSObject::getProperty(cx, obj, obj, cx->names().name, &nameVal))
-        return false;
-
-    /* Step 4. */
-    RootedString name(cx);
-    if (nameVal.isUndefined()) {
-        name = cx->names().Error;
-    } else {
-        name = ToString<CanGC>(cx, nameVal);
-        if (!name)
-            return false;
-    }
-
-    /* Step 5. */
-    RootedValue msgVal(cx);
-    if (!JSObject::getProperty(cx, obj, obj, cx->names().message, &msgVal))
-        return false;
-
-    /* Step 6. */
-    RootedString message(cx);
-    if (msgVal.isUndefined()) {
-        message = cx->runtime()->emptyString;
-    } else {
-        message = ToString<CanGC>(cx, msgVal);
-        if (!message)
-            return false;
-    }
-
-    /* Step 7. */
-    if (name->empty() && message->empty()) {
-        args.rval().setString(cx->names().Error);
-        return true;
-    }
-
-    /* Step 8. */
-    if (name->empty()) {
-        args.rval().setString(message);
-        return true;
-    }
-
-    /* Step 9. */
-    if (message->empty()) {
-        args.rval().setString(name);
-        return true;
-    }
-
-    /* Step 10. */
-    StringBuffer sb(cx);
-    if (!sb.append(name) || !sb.append(": ") || !sb.append(message))
-        return false;
-
-    JSString *str = sb.finishString();
-    if (!str)
-        return false;
-    args.rval().setString(str);
-    return true;
-}
-
 #if JS_HAS_TOSOURCE
 /*
  * Return a string that may eval to something similar to the original object.
  */
 static bool
 exn_toSource(JSContext *cx, unsigned argc, Value *vp)
 {
     JS_CHECK_RECURSION(cx, return false);
--- a/js/src/jsreflect.cpp
+++ b/js/src/jsreflect.cpp
@@ -442,16 +442,35 @@ class NodeBuilder
 
     bool newNode(ASTType type, TokenPos *pos,
                  const char *childName1, HandleValue child1,
                  const char *childName2, HandleValue child2,
                  const char *childName3, HandleValue child3,
                  const char *childName4, HandleValue child4,
                  const char *childName5, HandleValue child5,
                  const char *childName6, HandleValue child6,
+                 MutableHandleValue dst) {
+        RootedObject node(cx);
+        return newNode(type, pos, &node) &&
+               setProperty(node, childName1, child1) &&
+               setProperty(node, childName2, child2) &&
+               setProperty(node, childName3, child3) &&
+               setProperty(node, childName4, child4) &&
+               setProperty(node, childName5, child5) &&
+               setProperty(node, childName6, child6) &&
+               setResult(node, dst);
+    }
+
+    bool newNode(ASTType type, TokenPos *pos,
+                 const char *childName1, HandleValue child1,
+                 const char *childName2, HandleValue child2,
+                 const char *childName3, HandleValue child3,
+                 const char *childName4, HandleValue child4,
+                 const char *childName5, HandleValue child5,
+                 const char *childName6, HandleValue child6,
                  const char *childName7, HandleValue child7,
                  MutableHandleValue dst) {
         RootedObject node(cx);
         return newNode(type, pos, &node) &&
                setProperty(node, childName1, child1) &&
                setProperty(node, childName2, child2) &&
                setProperty(node, childName3, child3) &&
                setProperty(node, childName4, child4) &&
@@ -633,16 +652,18 @@ class NodeBuilder
 
     bool taggedTemplate(HandleValue callee, NodeVector &args, TokenPos *pos,
                         MutableHandleValue dst);
 
     bool callSiteObj(NodeVector &raw, NodeVector &cooked, TokenPos *pos, MutableHandleValue dst);
 
     bool spreadExpression(HandleValue expr, TokenPos *pos, MutableHandleValue dst);
 
+    bool computedName(HandleValue name, TokenPos *pos, MutableHandleValue dst);
+
     bool objectExpression(NodeVector &elts, TokenPos *pos, MutableHandleValue dst);
 
     bool thisExpression(TokenPos *pos, MutableHandleValue dst);
 
     bool yieldExpression(HandleValue arg, YieldKind kind, TokenPos *pos, MutableHandleValue dst);
 
     bool comprehensionBlock(HandleValue patt, HandleValue src, bool isForEach, bool isForOf, TokenPos *pos,
                             MutableHandleValue dst);
@@ -1249,16 +1270,24 @@ NodeBuilder::taggedTemplate(HandleValue 
 
 bool
 NodeBuilder::templateLiteral(NodeVector &elts, TokenPos *pos, MutableHandleValue dst)
 {
     return listNode(AST_TEMPLATE_LITERAL, "elements", elts, pos, dst);
 }
 
 bool
+NodeBuilder::computedName(HandleValue name, TokenPos *pos, MutableHandleValue dst)
+{
+    return newNode(AST_COMPUTED_NAME, pos,
+                   "name", name,
+                   dst);
+}
+
+bool
 NodeBuilder::spreadExpression(HandleValue expr, TokenPos *pos, MutableHandleValue dst)
 {
     return newNode(AST_SPREAD_EXPR, pos,
                    "expression", expr,
                    dst);
 }
 
 bool
@@ -2868,16 +2897,23 @@ ASTSerializer::expression(ParseNode *pn,
 
       case PNK_SPREAD:
       {
           RootedValue expr(cx);
           return expression(pn->pn_kid, &expr) &&
                  builder.spreadExpression(expr, &pn->pn_pos, dst);
       }
 
+      case PNK_COMPUTED_NAME:
+      {
+         RootedValue name(cx);
+         return expression(pn->pn_kid, &name) &&
+                builder.computedName(name, &pn->pn_pos, dst);
+      }
+
       case PNK_OBJECT:
       {
         NodeVector elts(cx);
         if (!elts.reserve(pn->pn_count))
             return false;
 
         for (ParseNode *next = pn->pn_head; next; next = next->pn_next) {
             JS_ASSERT(pn->pn_pos.encloses(next->pn_pos));
@@ -2957,16 +2993,18 @@ ASTSerializer::expression(ParseNode *pn,
       default:
         LOCAL_NOT_REACHED("unexpected expression type");
     }
 }
 
 bool
 ASTSerializer::propertyName(ParseNode *pn, MutableHandleValue dst)
 {
+    if (pn->isKind(PNK_COMPUTED_NAME))
+        return expression(pn, dst);
     if (pn->isKind(PNK_NAME))
         return identifier(pn, dst);
 
     LOCAL_ASSERT(pn->isKind(PNK_STRING) || pn->isKind(PNK_NUMBER));
 
     return literal(pn, dst);
 }
 
--- a/js/src/jsstr.cpp
+++ b/js/src/jsstr.cpp
@@ -1,25 +1,14 @@
 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*-
  * vim: set ts=8 sts=4 et sw=4 tw=99:
  * 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/. */
 
-/*
- * JS string type implementation.
- *
- * In order to avoid unnecessary js_LockGCThing/js_UnlockGCThing calls, these
- * native methods store strings (possibly newborn) converted from their 'this'
- * parameter and arguments on the stack: 'this' conversions at argv[-1], arg
- * conversions at their index (argv[0], argv[1]).  This is a legitimate method
- * of rooting things that might lose their newborn root due to subsequent GC
- * allocations in the same native method.
- */
-
 #include "jsstr.h"
 
 #include "mozilla/Attributes.h"
 #include "mozilla/Casting.h"
 #include "mozilla/CheckedInt.h"
 #include "mozilla/FloatingPoint.h"
 #include "mozilla/PodOperations.h"
 #include "mozilla/Range.h"
new file mode 100644
--- /dev/null
+++ b/js/src/tests/ecma_5/extensions/error-tostring-function.js
@@ -0,0 +1,45 @@
+// Any copyright is dedicated to the Public Domain.
+// http://creativecommons.org/licenses/publicdomain/
+
+//-----------------------------------------------------------------------------
+var BUGNUMBER = 894653;
+var summary =
+  "Error.prototype.toString called on function objects should work as on any " +
+  "object";
+
+print(BUGNUMBER + ": " + summary);
+
+/**************
+ * BEGIN TEST *
+ **************/
+
+function ErrorToString(v)
+{
+  return Error.prototype.toString.call(v);
+}
+
+// The name property of function objects isn't standardized, so this must be an
+// extension-land test.
+
+assertEq(ErrorToString(function f(){}), "f");
+assertEq(ErrorToString(function g(){}), "g");
+assertEq(ErrorToString(function(){}), "");
+
+var fn1 = function() {};
+fn1.message = "ohai";
+assertEq(ErrorToString(fn1), "ohai");
+
+var fn2 = function blerch() {};
+fn2.message = "fnord";
+assertEq(ErrorToString(fn2), "blerch: fnord");
+
+var fn3 = function() {};
+fn3.message = "";
+assertEq(ErrorToString(fn3), "");
+
+/******************************************************************************/
+
+if (typeof reportCompare === "function")
+  reportCompare(true, true);
+
+print("Tests complete!");
new file mode 100644
--- /dev/null
+++ b/js/src/tests/ecma_5/extensions/misplaced-inconsistent-directive.js
@@ -0,0 +1,65 @@
+// |reftest| skip-if(!xulRuntime.shell) -- needs evaluate()
+/*
+ * Any copyright is dedicated to the Public Domain.
+ * http://creativecommons.org/licenses/publicdomain/
+ * Contributor:
+ *   Jeff Walden <jwalden+code@mit.edu>
+ */
+
+//-----------------------------------------------------------------------------
+var BUGNUMBER = 1046964;
+var summary =
+  "Misplaced directives (e.g. 'use strict') should trigger warnings if they " +
+  "contradict the actually-used semantics";
+
+print(BUGNUMBER + ": " + summary);
+
+/**************
+ * BEGIN TEST *
+ **************/
+
+options("strict");
+options("werror");
+
+function evaluateNoRval(code)
+{
+  evaluate(code, { compileAndGo: true, noScriptRval: true });
+}
+
+function expectSyntaxError(code)
+{
+  try
+  {
+    evaluateNoRval(code);
+    throw new Error("didn't throw");
+  }
+  catch (e)
+  {
+    assertEq(e instanceof SyntaxError, true,
+             "should have thrown a SyntaxError, instead got:\n" +
+             "    " + e + "\n" +
+             "when evaluating:\n" +
+             "    " + code);
+  }
+}
+
+expectSyntaxError("function f1() {} 'use strict'; function f2() {}");
+expectSyntaxError("function f3() { var x; 'use strict'; }");
+
+expectSyntaxError("function f4() {} 'use asm'; function f5() {}");
+expectSyntaxError("function f6() { var x; 'use strict'; }");
+expectSyntaxError("'use asm'; function f7() {}");
+
+// No errors expected -- useless non-directives, but not contrary to used
+// semantics.
+evaluateNoRval("'use strict'; function f8() {} 'use strict'; function f9() {}");
+evaluateNoRval("'use strict'; function f10() { var z; 'use strict' }");
+
+evaluateNoRval("function f11() { 'use asm'; return {}; }");
+
+/******************************************************************************/
+
+if (typeof reportCompare === "function")
+  reportCompare(true, true);
+
+print("Tests complete");
new file mode 100644
new file mode 100644
--- /dev/null
+++ b/js/src/tests/ecma_6/Class/compPropDestr.js
@@ -0,0 +1,11 @@
+var BUGNUMBER = 924688;
+var summary = 'Computed Property Names';
+
+print(BUGNUMBER + ": " + summary);
+
+var key = "z";
+var { [key]: foo } = { z: "bar" };
+assertEq(foo, "bar");
+
+
+reportCompare(0, 0, "ok");
new file mode 100644
--- /dev/null
+++ b/js/src/tests/ecma_6/Class/compPropNames.js
@@ -0,0 +1,181 @@
+var BUGNUMBER = 924688;
+var summary = 'Computed Property Names';
+
+print(BUGNUMBER + ": " + summary);
+
+// Function definitions.
+function syntaxError (script) {
+    try {
+        Function(script);
+    } catch (e) {
+        if (e instanceof SyntaxError) {
+            return;
+        }
+    }
+    throw new Error('Expected syntax error: ' + script);
+}
+
+
+// Tests begin.
+
+assertThrowsInstanceOf(function() { var a = {[field1]: "a", [field2]: "b"}; }, ReferenceError);
+
+assertThrowsInstanceOf(function() {
+                           field1 = 1;
+                           var a = {[field1]: "a", [field2]: "b"};
+                       }, ReferenceError);
+
+var f1 = 1;
+var f2 = 2;
+var a = {[f1]: "a", [f2]: "b"};
+assertEq(a[1], "a");
+assertEq(a[2], "b");
+
+var a = {[f1]: "a", f2: "b"};
+assertEq(a[1], "a");
+assertEq(a.f2, "b");
+
+var a = {["f1"]: "a", [++f2]: "b"};
+assertEq(a.f1, "a");
+assertEq(a[3], "b");
+
+var a = {["f1"]: "a", f2: "b"};
+assertEq(a.f1, "a");
+assertEq(a.f2, "b");
+
+
+var i = 0;
+var a = {
+    ["foo" + ++i]: i,
+    ["foo" + ++i]: i,
+    ["foo" + ++i]: i
+};
+assertEq(a.foo1, 1);
+assertEq(a.foo2, 2);
+assertEq(a.foo3, 3);
+
+syntaxError("({[");
+syntaxError("({[expr");
+syntaxError("({[expr]");
+syntaxError("({[expr]})");
+syntaxError("({[expr] 0})");
+syntaxError("({[expr], 0})");
+syntaxError("[[expr]: 0]");
+syntaxError("({[expr]: name: 0})");
+syntaxError("({[1, 2]: 3})");  // because '1,2' is an Expression but not an AssignmentExpression
+syntaxError("({[1;]: 1})");    // and not an ExpressionStatement
+syntaxError("({[if (0) 0;]})");  // much less a Statement
+syntaxError("function f() { {[x]: 1} }");  // that's not even an ObjectLiteral
+syntaxError("function f() { [x]: 1 }");    // or that
+syntaxError('a = {[f1@]: "a", [f2]: "b"}'); // unexpected symbol at end of AssignmentExpression
+try { JSON.parse('{["a"]:4}'); } catch(e) {
+    if (!(e instanceof SyntaxError)) throw new Error('Expected syntax error');
+}
+
+// Property characteristics.
+a = { ["b"] : 4 };
+b = Object.getOwnPropertyDescriptor(a, "b");
+assertEq(b.configurable, true);
+assertEq(b.enumerable, true);
+assertEq(b.writable, true);
+assertEq(b.value, 4);
+
+// Setter and getter are not hit.
+Object.defineProperty(Object.prototype, "x", { set: function (x) { throw "FAIL"; },
+                                               get: function (x) { throw "FAIL"; } });
+var a = {["x"]: 0};
+assertEq(a.x, 0);
+
+a = {["x"]: 1, ["x"]: 2};
+assertEq(a.x, 2);
+a = {x: 1, ["x"]: 2};
+assertEq(a.x, 2);
+a = {["x"]: 1, x: 2};
+assertEq(a.x, 2);
+
+// Symbols
+var unique_sym = Symbol("1"), registered_sym = Symbol.for("2");
+a = { [unique_sym] : 2, [registered_sym] : 3 };
+assertEq(a[unique_sym], 2);
+assertEq(a[registered_sym], 3);
+
+// Same expression can be run several times to build objects with different property names.
+a = [];
+for (var i = 0; i < 3; i++) {
+    a[i] = {["foo" + i]: i};
+}
+assertEq(a[0].foo0, 0);
+assertEq(a[1].foo1, 1);
+assertEq(a[2].foo2, 2);
+
+// Following are stored in object's elements rather than slots.
+var i = 0;
+a = { [++i] : i,
+      [++i] : i,
+      [++i] : i,
+      [++i] : i,
+      [++i] : i,
+      [++i] : i,
+      [++i] : i,
+      [++i] : i
+}
+for (var i = 1; i < 9; i++)
+    assertEq(a[i], i);
+syntaxError("a.1");
+syntaxError("a.2");
+syntaxError("a.3");
+syntaxError("a.4");
+syntaxError("a.5");
+syntaxError("a.6");
+syntaxError("a.7");
+syntaxError("a.8");
+
+// Adding a single large index.
+var i = 0;
+a = { [++i] : i,
+      [++i] : i,
+      [++i] : i,
+      [++i] : i,
+      [++i] : i,
+      [++i] : i,
+      [++i] : i,
+      [++i] : i,
+      [3000] : 2999
+}
+for (var i = 1; i < 9; i++)
+    assertEq(a[i], i);
+assertEq(a[3000], 2999);
+
+// Defining several properties using eval.
+var code = "({";
+for (i = 0; i < 1000; i++)
+    code += "['foo' + " + i + "]: 'ok', "
+code += "['bar']: 'ok'});";
+var obj = eval(code);
+for (i = 0; i < 1000; i++)
+    assertEq(obj["foo" + i], "ok");
+assertEq(obj["bar"], "ok");
+
+// Can yield in a computed property name which is in a generator.
+function* g() {
+    var a = { [yield 1]: 2, [yield 2]: 3};
+    return a;
+}
+
+var it = g();
+var next = it.next();
+assertEq(next.done, false);
+assertEq(next.value, 1);
+next = it.next("hello");
+assertEq(next.done, false);
+assertEq(next.value, 2);
+next = it.next("world");
+assertEq(next.done, true);
+assertEq(next.value.hello, 2);
+assertEq(next.value.world, 3);
+
+syntaxError("a = {get [expr]() { return 3; }, set[expr](v) { return 2; }}");
+
+
+
+reportCompare(0, 0, "ok");
new file mode 100644
--- a/js/src/tests/js1_8_5/extensions/reflect-parse.js
+++ b/js/src/tests/js1_8_5/extensions/reflect-parse.js
@@ -87,16 +87,17 @@ function updExpr(op, arg, prefix) Patter
 function logExpr(op, left, right) Pattern({ type: "LogicalExpression", operator: op, left: left, right: right })
 
 function condExpr(test, cons, alt) Pattern({ type: "ConditionalExpression", test: test, consequent: cons, alternate: alt })
 function seqExpr(exprs) Pattern({ type: "SequenceExpression", expressions: exprs })
 function newExpr(callee, args) Pattern({ type: "NewExpression", callee: callee, arguments: args })
 function callExpr(callee, args) Pattern({ type: "CallExpression", callee: callee, arguments: args })
 function arrExpr(elts) Pattern({ type: "ArrayExpression", elements: elts })
 function objExpr(elts) Pattern({ type: "ObjectExpression", properties: elts })
+function computedName(elts) Pattern({ type: "ComputedName", name: elts })
 function templateLit(elts) Pattern({ type: "TemplateLiteral", elements: elts })
 function taggedTemplate(tagPart, templatePart) Pattern({ type: "TaggedTemplate", callee: tagPart,
                 arguments : templatePart })
 function template(raw, cooked, ...args) Pattern([{ type: "CallSiteObject", raw: raw, cooked:
 cooked}, ...args])
 function compExpr(body, blocks, filter) Pattern({ type: "ComprehensionExpression", body: body, blocks: blocks, filter: filter })
 function genExpr(body, blocks, filter) Pattern({ type: "GeneratorExpression", body: body, blocks: blocks, filter: filter })
 function graphExpr(idx, body) Pattern({ type: "GraphExpression", index: idx, expression: body })
@@ -374,16 +375,39 @@ assertExpr("typeof(0?0:a)", unExpr("type
 assertExpr("[x for each (x in y) if (false)]", compExpr(ident("x"), [compEachBlock(ident("x"), ident("y"))], lit(false)));
 
 // Bug 632056: constant-folding
 program([exprStmt(ident("f")),
          ifStmt(lit(1),
                 funDecl(ident("f"), [], blockStmt([])),
                 null)]).assert(Reflect.parse("f; if (1) function f(){}"));
 
+// Bug 924688: computed property names
+assertExpr('a= {[field1]: "a", [field2=1]: "b"}',
+          aExpr("=", ident("a"),
+                objExpr([{ key: computedName(ident("field1")), value: lit("a")},
+                         { key: computedName(aExpr("=", ident("field2"), lit(1))),
+                           value: lit("b")}])));
+
+assertExpr('a= {["field1"]: "a", field2 : "b"}',
+          aExpr("=", ident("a"),
+                objExpr([{ key: computedName(lit("field1")), value: lit("a") },
+                         { key: ident("field2"), value: lit("b") }])));
+
+assertExpr('a= {[1]: 1, 2 : 2}',
+          aExpr("=", ident("a"),
+                objExpr([{ key: computedName(lit(1)), value: lit(1) },
+                         { key: lit(2), value: lit(2) }])));
+
+// Bug 924688: computed property names - location information
+var node = Reflect.parse("a = {[field1]: 5}");
+Pattern({ body: [ { expression: { right: { properties: [ {key: { loc:
+    { start: { line: 1, column: 5 }, end: { line: 1, column: 13 }}}}]}}}]}).match(node);
+
+
 // statements
 
 assertStmt("throw 42", throwStmt(lit(42)));
 assertStmt("for (;;) break", forStmt(null, null, null, breakStmt(null)));
 assertStmt("for (x; y; z) break", forStmt(ident("x"), ident("y"), ident("z"), breakStmt(null)));
 assertStmt("for (var x; y; z) break", forStmt(varDecl([{ id: ident("x"), init: null }]), ident("y"), ident("z")));
 assertStmt("for (var x = 42; y; z) break", forStmt(varDecl([{ id: ident("x"), init: lit(42) }]), ident("y"), ident("z")));
 assertStmt("for (x; ; z) break", forStmt(ident("x"), null, ident("z"), breakStmt(null)));
--- a/js/src/vm/RegExpObject.cpp
+++ b/js/src/vm/RegExpObject.cpp
@@ -2,16 +2,17 @@
  * vim: set ts=8 sts=4 et sw=4 tw=99:
  * 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 "vm/RegExpObject.h"
 
 #include "mozilla/MemoryReporting.h"
+#include "mozilla/PodOperations.h"
 
 #include "jsstr.h"
 
 #include "frontend/TokenStream.h"
 #include "irregexp/RegExpParser.h"
 #include "vm/MatchPairs.h"
 #include "vm/RegExpStatics.h"
 #include "vm/StringBuffer.h"
@@ -21,16 +22,17 @@
 #include "jsobjinlines.h"
 
 #include "vm/Shape-inl.h"
 
 using namespace js;
 
 using mozilla::DebugOnly;
 using mozilla::Maybe;
+using mozilla::PodCopy;
 using js::frontend::TokenStream;
 
 using JS::AutoCheckCannotGC;
 
 JS_STATIC_ASSERT(IgnoreCaseFlag == JSREG_FOLD);
 JS_STATIC_ASSERT(GlobalFlag == JSREG_GLOB);
 JS_STATIC_ASSERT(MultilineFlag == JSREG_MULTILINE);
 JS_STATIC_ASSERT(StickyFlag == JSREG_STICKY);
@@ -154,21 +156,17 @@ MatchPairs::initArray(size_t pairCount)
 bool
 MatchPairs::initArrayFrom(MatchPairs &copyFrom)
 {
     JS_ASSERT(copyFrom.pairCount() > 0);
 
     if (!allocOrExpandArray(copyFrom.pairCount()))
         return false;
 
-    for (size_t i = 0; i < pairCount_; i++) {
-        JS_ASSERT(copyFrom[i].check());
-        pairs_[i].start = copyFrom[i].start;
-        pairs_[i].limit = copyFrom[i].limit;
-    }
+    PodCopy(pairs_, copyFrom.pairs_, pairCount_);
 
     return true;
 }
 
 void
 MatchPairs::displace(size_t disp)
 {
     if (disp == 0)
@@ -547,18 +545,21 @@ RegExpShared::execute(JSContext *cx, Han
                       MatchPairs &matches)
 {
     TraceLogger *logger = TraceLoggerForMainThread(cx->runtime());
 
     /* Compile the code at point-of-use. */
     if (!compileIfNecessary(cx, input))
         return RegExpRunStatus_Error;
 
-    /* Ensure sufficient memory for output vector. */
-    if (!matches.initArray(pairCount()))
+    /*
+     * Ensure sufficient memory for output vector.
+     * No need to initialize it. The RegExp engine fills them in on a match.
+     */
+    if (!matches.allocOrExpandArray(pairCount()))
         return RegExpRunStatus_Error;
 
     /*
      * |displacement| emulates sticky mode by matching from this offset
      * into the char buffer and subtracting the delta off at the end.
      */
     size_t charsOffset = 0;
     size_t length = input->length();
@@ -572,16 +573,17 @@ RegExpShared::execute(JSContext *cx, Han
         length -= displacement;
         start = 0;
     }
 
     // Reset the Irregexp backtrack stack if it grows during execution.
     irregexp::RegExpStackScope stackScope(cx->runtime());
 
     if (canStringMatch) {
+        JS_ASSERT(pairCount() == 1);
         int res = StringFindPattern(input, source, start + charsOffset);
         if (res == -1)
             return RegExpRunStatus_Success_NotFound;
 
         matches[0].start = res;
         matches[0].limit = res + source->length();
 
         matches.checkAgainst(origLength);
--- a/js/src/vm/String.cpp
+++ b/js/src/vm/String.cpp
@@ -980,16 +980,26 @@ js::NewStringDontDeflate(ThreadSafeConte
         if (StaticStrings::hasUnit(c)) {
             // Free |chars| because we're taking possession of it, but it's no
             // longer needed because we use the static string instead.
             js_free(chars);
             return cx->staticStrings().getUnit(c);
         }
     }
 
+    if (JSFatInlineString::lengthFits<CharT>(length)) {
+        JSInlineString *str =
+            NewFatInlineString<allowGC>(cx, mozilla::Range<const CharT>(chars, length));
+        if (!str)
+            return nullptr;
+
+        js_free(chars);
+        return str;
+    }
+
     return JSFlatString::new_<allowGC>(cx, chars, length);
 }
 
 template JSFlatString *
 js::NewStringDontDeflate<CanGC>(ThreadSafeContext *cx, jschar *chars, size_t length);
 
 template JSFlatString *
 js::NewStringDontDeflate<NoGC>(ThreadSafeContext *cx, jschar *chars, size_t length);
--- a/js/xpconnect/loader/mozJSComponentLoader.cpp
+++ b/js/xpconnect/loader/mozJSComponentLoader.cpp
@@ -23,38 +23,37 @@
 #include "jsapi.h"
 #include "nsCOMPtr.h"
 #include "nsAutoPtr.h"
 #include "nsIComponentManager.h"
 #include "mozilla/Module.h"
 #include "nsIFile.h"
 #include "mozJSComponentLoader.h"
 #include "mozJSLoaderUtils.h"
-#include "nsIJSRuntimeService.h"
 #include "nsIXPConnect.h"
 #include "nsIObserverService.h"
 #include "nsIScriptSecurityManager.h"
 #include "nsIFileURL.h"
 #include "nsIJARURI.h"
 #include "nsNetUtil.h"
 #include "nsDOMBlobBuilder.h"
 #include "jsprf.h"
 #include "nsJSPrincipals.h"
 #include "nsJSUtils.h"
 #include "xpcprivate.h"
 #include "xpcpublic.h"
 #include "nsContentUtils.h"
-#include "nsCxPusher.h"
 #include "WrapperFactory.h"
 
 #include "mozilla/AddonPathService.h"
 #include "mozilla/scache/StartupCache.h"
 #include "mozilla/scache/StartupCacheUtils.h"
 #include "mozilla/MacroForEach.h"
 #include "mozilla/Preferences.h"
+#include "mozilla/dom/ScriptSettings.h"
 
 #include "js/OldDebugAPI.h"
 
 using namespace mozilla;
 using namespace mozilla::scache;
 using namespace xpc;
 using namespace JS;
 
@@ -69,17 +68,16 @@ static const JSClass kFakeBackstagePassJ
     JS_DeletePropertyStub,
     JS_PropertyStub,
     JS_StrictPropertyStub,
     JS_EnumerateStub,
     JS_ResolveStub,
     JS_ConvertStub
 };
 
-static const char kJSRuntimeServiceContractID[] = "@mozilla.org/js/xpc/RuntimeService;1";
 static const char kXPConnectServiceContractID[] = "@mozilla.org/js/xpc/XPConnect;1";
 static const char kObserverServiceContractID[] = "@mozilla.org/observer-service;1";
 static const char kJSCachePrefix[] = "jsloader";
 
 #define HAVE_PR_MEMMAP
 
 /**
  * Buffer sizes for serialization and deserialization of scripts.
@@ -234,45 +232,25 @@ static const JSFunctionSpec gGlobalFun[]
 class MOZ_STACK_CLASS JSCLContextHelper
 {
 public:
     JSCLContextHelper(JSContext* aCx);
     ~JSCLContextHelper();
 
     void reportErrorAfterPop(char *buf);
 
-    operator JSContext*() const {return mContext;}
-
 private:
-
     JSContext* mContext;
-    nsCxPusher mPusher;
     char*      mBuf;
 
     // prevent copying and assignment
     JSCLContextHelper(const JSCLContextHelper &) MOZ_DELETE;
     const JSCLContextHelper& operator=(const JSCLContextHelper &) MOZ_DELETE;
 };
 
-
-class JSCLAutoErrorReporterSetter
-{
-public:
-    JSCLAutoErrorReporterSetter(JSContext* cx, JSErrorReporter reporter)
-        {mContext = cx; mOldReporter = JS_SetErrorReporter(cx, reporter);}
-    ~JSCLAutoErrorReporterSetter()
-        {JS_SetErrorReporter(mContext, mOldReporter);}
-private:
-    JSContext* mContext;
-    JSErrorReporter mOldReporter;
-
-    JSCLAutoErrorReporterSetter(const JSCLAutoErrorReporterSetter &) MOZ_DELETE;
-    const JSCLAutoErrorReporterSetter& operator=(const JSCLAutoErrorReporterSetter &) MOZ_DELETE;
-};
-
 static nsresult
 ReportOnCaller(JSContext *callerContext,
                const char *format, ...) {
     if (!callerContext) {
         return NS_ERROR_FAILURE;
     }
 
     va_list ap;
@@ -302,19 +280,17 @@ ReportOnCaller(JSCLContextHelper &helper
     }
 
     helper.reportErrorAfterPop(buf);
 
     return NS_OK;
 }
 
 mozJSComponentLoader::mozJSComponentLoader()
-    : mRuntime(nullptr),
-      mContext(nullptr),
-      mModules(16),
+    : mModules(16),
       mImports(16),
       mInProgressImports(16),
       mInitialized(false),
       mReuseLoaderGlobal(false)
 {
     MOZ_ASSERT(!sSelf, "mozJSComponentLoader should be a singleton");
 
 #ifdef PR_LOGGING
@@ -412,32 +388,16 @@ mozJSComponentLoader::ReallyInit()
 
     // XXXkhuey B2G child processes have some sort of preferences race that
     // results in getting the wrong value.
     // But we don't want that on Firefox Mulet as it break most Firefox JSMs...
 #if defined(MOZ_B2G) && !defined(MOZ_MULET)
     mReuseLoaderGlobal = true;
 #endif
 
-    /*
-     * Get the JSRuntime from the runtime svc, if possible.
-     * We keep a reference around, because it's a Bad Thing if the runtime
-     * service gets shut down before we're done.  Bad!
-     */
-
-    mRuntimeService = do_GetService(kJSRuntimeServiceContractID, &rv);
-    if (NS_FAILED(rv) ||
-        NS_FAILED(rv = mRuntimeService->GetRuntime(&mRuntime)))
-        return rv;
-
-    // Create our compilation context.
-    mContext = JS_NewContext(mRuntime, 256);
-    if (!mContext)
-        return NS_ERROR_OUT_OF_MEMORY;
-
     nsCOMPtr<nsIScriptSecurityManager> secman =
         do_GetService(NS_SCRIPTSECURITYMANAGER_CONTRACTID);
     if (!secman)
         return NS_ERROR_FAILURE;
 
     rv = secman->GetSystemPrincipal(getter_AddRefs(mSystemPrincipal));
     if (NS_FAILED(rv) || !mSystemPrincipal)
         return NS_ERROR_FAILURE;
@@ -470,37 +430,38 @@ mozJSComponentLoader::LoadModule(FileLoc
         if (NS_FAILED(rv))
             return nullptr;
     }
 
     ModuleEntry* mod;
     if (mModules.Get(spec, &mod))
     return mod;
 
-    nsAutoPtr<ModuleEntry> entry(new ModuleEntry(mContext));
+    dom::AutoJSAPI jsapi;
+    jsapi.Init();
+    JSContext* cx = jsapi.cx();
 
-    JSAutoRequest ar(mContext);
-    RootedValue dummy(mContext);
+    nsAutoPtr<ModuleEntry> entry(new ModuleEntry(cx));
+    RootedValue dummy(cx);
     rv = ObjectForLocation(info, file, &entry->obj, &entry->thisObjectKey,
                            &entry->location, false, &dummy);
     if (NS_FAILED(rv)) {
         return nullptr;
     }
 
     nsCOMPtr<nsIXPConnect> xpc = do_GetService(kXPConnectServiceContractID,
                                                &rv);
     if (NS_FAILED(rv))
         return nullptr;
 
     nsCOMPtr<nsIComponentManager> cm;
     rv = NS_GetComponentManager(getter_AddRefs(cm));
     if (NS_FAILED(rv))
         return nullptr;
 
-    JSCLContextHelper cx(mContext);
     JSAutoCompartment ac(cx, entry->obj);
 
     nsCOMPtr<nsIXPConnectJSObjectHolder> cm_holder;
     rv = xpc->WrapNative(cx, entry->obj, cm,
                          NS_GET_IID(nsIComponentManager),
                          getter_AddRefs(cm_holder));
 
     if (NS_FAILED(rv)) {
@@ -522,18 +483,16 @@ mozJSComponentLoader::LoadModule(FileLoc
         return nullptr;
     }
 
     JSObject* file_jsobj = file_holder->GetJSObject();
     if (!file_jsobj) {
         return nullptr;
     }
 
-    JSCLAutoErrorReporterSetter aers(cx, xpc::SystemErrorReporter);
-
     RootedValue NSGetFactory_val(cx);
     if (!JS_GetProperty(cx, entryObj, "NSGetFactory", &NSGetFactory_val) ||
         NSGetFactory_val.isUndefined()) {
         return nullptr;
     }
 
     if (JS_TypeOfValue(cx, NSGetFactory_val) != JSTYPE_FUNCTION) {
         JS_ReportError(cx, "%s has NSGetFactory property that is not a function",
@@ -655,17 +614,17 @@ class ANSIFileAutoCloser
     explicit ANSIFileAutoCloser(FILE *file) : mFile(file) {}
     ~ANSIFileAutoCloser() { fclose(mFile); }
  private:
     FILE *mFile;
 };
 #endif
 
 JSObject*
-mozJSComponentLoader::PrepareObjectForLocation(JSCLContextHelper& aCx,
+mozJSComponentLoader::PrepareObjectForLocation(JSContext* aCx,
                                                nsIFile *aComponentFile,
                                                nsIURI *aURI,
                                                bool aReuseLoaderGlobal,
                                                bool *aRealFile)
 {
     nsCOMPtr<nsIXPConnectJSObjectHolder> holder;
     if (aReuseLoaderGlobal) {
         holder = mLoaderGlobal;
@@ -762,37 +721,40 @@ mozJSComponentLoader::PrepareObjectForLo
     // variable that we insert into the JSM.
     RootedString exposedUri(aCx, JS_NewStringCopyN(aCx, nativePath.get(), nativePath.Length()));
     NS_ENSURE_TRUE(exposedUri, nullptr);
 
     if (!JS_DefineProperty(aCx, obj, "__URI__", exposedUri, 0))
         return nullptr;
 
     if (createdNewGlobal) {
-        RootedObject global(aCx, holder->GetJSObject());
-        JS_FireOnNewGlobalObject(aCx, global);
+        // AutoEntryScript required to invoke debugger hook, which is a
+        // Gecko-specific concept at present.
+        dom::AutoEntryScript aes(GetNativeForGlobal(holder->GetJSObject()));
+        RootedObject global(aes.cx(), holder->GetJSObject());
+        JS_FireOnNewGlobalObject(aes.cx(), global);
     }
 
     return obj;
 }
 
 nsresult
 mozJSComponentLoader::ObjectForLocation(ComponentLoaderInfo &aInfo,
                                         nsIFile *aComponentFile,
                                         MutableHandleObject aObject,
                                         MutableHandleScript aTableScript,
                                         char **aLocation,
                                         bool aPropagateExceptions,
                                         MutableHandleValue aException)
 {
-    JSCLContextHelper cx(mContext);
+    MOZ_ASSERT(NS_IsMainThread(), "Must be on main thread.");
 
-    JS_AbortIfWrongThread(JS_GetRuntime(cx));
-
-    JSCLAutoErrorReporterSetter aers(cx, xpc::SystemErrorReporter);
+    dom::AutoJSAPI jsapi;
+    jsapi.Init();
+    JSContext* cx = jsapi.cx();
 
     bool realFile = false;
     nsresult rv = aInfo.EnsureURI();
     NS_ENSURE_SUCCESS(rv, rv);
     RootedObject obj(cx, PrepareObjectForLocation(cx, aComponentFile, aInfo.URI(),
                                                   mReuseLoaderGlobal, &realFile));
     NS_ENSURE_TRUE(obj, NS_ERROR_FAILURE);
 
@@ -1036,16 +998,20 @@ mozJSComponentLoader::ObjectForLocation(
         MOZ_ASSERT(tableScript);
     }
 
     aTableScript.set(tableScript);
 
     bool ok = false;
 
     {
+        // We're going to run script via JS_ExecuteScriptVersion or
+        // JS_CallFunction, so we need an AutoEntryScript.
+        // This is Gecko-specific and not in any spec.
+        dom::AutoEntryScript aes(GetNativeForGlobal(CurrentGlobalOrNull(cx)));
         AutoSaveContextOptions asco(cx);
         if (aPropagateExceptions)
             ContextOptionsRef(cx).setDontReportUncaught(true);
         if (script) {
             ok = JS_ExecuteScriptVersion(cx, obj, script, JSVERSION_LATEST);
         } else {
             RootedValue rval(cx);
             ok = JS_CallFunction(cx, obj, function, JS::HandleValueArray::empty(), &rval);
@@ -1083,37 +1049,34 @@ mozJSComponentLoader::ClearModules(const
 void
 mozJSComponentLoader::UnloadModules()
 {
     mInitialized = false;
 
     if (mLoaderGlobal) {
         MOZ_ASSERT(mReuseLoaderGlobal, "How did this happen?");
 
-        JSAutoRequest ar(mContext);
-        RootedObject global(mContext, mLoaderGlobal->GetJSObject());
+        dom::AutoJSAPI jsapi;
+        jsapi.Init();
+        JSContext* cx = jsapi.cx();
+        RootedObject global(cx, mLoaderGlobal->GetJSObject());
         if (global) {
-            JSAutoCompartment ac(mContext, global);
-            JS_SetAllNonReservedSlotsToUndefined(mContext, global);
+            JSAutoCompartment ac(cx, global);
+            JS_SetAllNonReservedSlotsToUndefined(cx, global);
         } else {
             NS_WARNING("Going to leak!");
         }
 
         mLoaderGlobal = nullptr;
     }
 
     mInProgressImports.Clear();
     mImports.Clear();
 
     mModules.Enumerate(ClearModules, nullptr);
-
-    JS_DestroyContextNoGC(mContext);
-    mContext = nullptr;
-
-    mRuntimeService = nullptr;
 }
 
 NS_IMETHODIMP
 mozJSComponentLoader::Import(const nsACString& registryLocation,
                              HandleValue targetValArg,
                              JSContext *cx,
                              uint8_t optionalArgc,
                              MutableHandleValue retval)
@@ -1293,82 +1256,91 @@ mozJSComponentLoader::ImportInto(const n
 
         mod = newEntry;
     }
 
     MOZ_ASSERT(mod->obj, "Import table contains entry with no object");
     vp.set(mod->obj);
 
     if (targetObj) {
-        JSCLContextHelper cxhelper(mContext);
-        JSAutoCompartment ac(mContext, mod->obj);
+        // cxhelper must be created before jsapi, so that jsapi is detroyed and
+        // pops any context it has pushed before we report to the caller context.
+        JSCLContextHelper cxhelper(callercx);
 
-        RootedValue symbols(mContext);
-        RootedObject modObj(mContext, mod->obj);
-        if (!JS_GetProperty(mContext, modObj,
+        // Even though we are calling JS_SetPropertyById on targetObj, we want
+        // to ensure that we never run script here, so we use an AutoJSAPI and
+        // not an AutoEntryScript.
+        dom::AutoJSAPI jsapi;
+        jsapi.Init();
+        JSContext* cx = jsapi.cx();
+        JSAutoCompartment ac(cx, mod->obj);
+
+        RootedValue symbols(cx);
+        RootedObject modObj(cx, mod->obj);
+        if (!JS_GetProperty(cx, modObj,
                             "EXPORTED_SYMBOLS", &symbols)) {
             return ReportOnCaller(cxhelper, ERROR_NOT_PRESENT,
                                   PromiseFlatCString(aLocation).get());
         }
 
-        if (!JS_IsArrayObject(mContext, symbols)) {
+        if (!JS_IsArrayObject(cx, symbols)) {
             return ReportOnCaller(cxhelper, ERROR_NOT_AN_ARRAY,
                                   PromiseFlatCString(aLocation).get());
         }
 
-        RootedObject symbolsObj(mContext, &symbols.toObject());
+        RootedObject symbolsObj(cx, &symbols.toObject());
 
         // Iterate over symbols array, installing symbols on targetObj:
 
         uint32_t symbolCount = 0;
-        if (!JS_GetArrayLength(mContext, symbolsObj, &symbolCount)) {
+        if (!JS_GetArrayLength(cx, symbolsObj, &symbolCount)) {
             return ReportOnCaller(cxhelper, ERROR_GETTING_ARRAY_LENGTH,
                                   PromiseFlatCString(aLocation).get());
         }
 
 #ifdef DEBUG
         nsAutoCString logBuffer;
 #endif
 
-        RootedValue value(mContext);
-        RootedId symbolId(mContext);
+        RootedValue value(cx);
+        RootedId symbolId(cx);
         for (uint32_t i = 0; i < symbolCount; ++i) {
-            if (!JS_GetElement(mContext, symbolsObj, i, &value) ||
+            if (!JS_GetElement(cx, symbolsObj, i, &value) ||
                 !value.isString() ||
-                !JS_ValueToId(mContext, value, &symbolId)) {
+                !JS_ValueToId(cx, value, &symbolId)) {
                 return ReportOnCaller(cxhelper, ERROR_ARRAY_ELEMENT,
                                       PromiseFlatCString(aLocation).get(), i);
             }
 
-            RootedObject modObj(mContext, mod->obj);
-            if (!JS_GetPropertyById(mContext, modObj, symbolId, &value)) {
-                JSAutoByteString bytes(mContext, JSID_TO_STRING(symbolId));
+            RootedObject modObj(cx, mod->obj);
+            if (!JS_GetPropertyById(cx, modObj, symbolId, &value)) {
+                JSAutoByteString bytes(cx, JSID_TO_STRING(symbolId));
                 if (!bytes)
                     return NS_ERROR_FAILURE;
                 return ReportOnCaller(cxhelper, ERROR_GETTING_SYMBOL,
                                       PromiseFlatCString(aLocation).get(),
                                       bytes.ptr());
             }
 
-            JSAutoCompartment target_ac(mContext, targetObj);
+            JSAutoCompartment target_ac(cx, targetObj);
 
-            if (!JS_WrapValue(mContext, &value) ||
-                !JS_SetPropertyById(mContext, targetObj, symbolId, value)) {
-                JSAutoByteString bytes(mContext, JSID_TO_STRING(symbolId));
+            if (!JS_WrapValue(cx, &value) ||
+                !JS_SetPropertyById(cx, targetObj, symbolId, value)) {
+                JSAutoByteString bytes(cx, JSID_TO_STRING(symbolId));
                 if (!bytes)
                     return NS_ERROR_FAILURE;
                 return ReportOnCaller(cxhelper, ERROR_SETTING_SYMBOL,
                                       PromiseFlatCString(aLocation).get(),
                                       bytes.ptr());
             }
 #ifdef DEBUG
             if (i == 0) {
                 logBuffer.AssignLiteral("Installing symbols [ ");
             }
-            JSAutoByteString bytes(mContext, JSID_TO_STRING(symbolId));
+            JSAutoByteString bytes(cx, JSID_TO_STRING(symbolId));
             if (!!bytes)
                 logBuffer.Append(bytes.ptr());
             logBuffer.Append(' ');
             if (i == symbolCount - 1) {
                 LOG(("%s] from %s\n", logBuffer.get(),
                      PromiseFlatCString(aLocation).get()));
             }
 #endif
@@ -1445,30 +1417,22 @@ mozJSComponentLoader::ModuleEntry::GetFa
 }
 
 //----------------------------------------------------------------------
 
 JSCLContextHelper::JSCLContextHelper(JSContext* aCx)
     : mContext(aCx)
     , mBuf(nullptr)
 {
-    mPusher.Push(mContext);
-    JS_BeginRequest(mContext);
 }
 
 JSCLContextHelper::~JSCLContextHelper()
 {
-    JS_EndRequest(mContext);
-    mPusher.Pop();
-    JSContext *restoredCx = nsContentUtils::GetCurrentJSContext();
-    if (restoredCx && mBuf) {
-        JS_ReportError(restoredCx, mBuf);
-    }
-
     if (mBuf) {
+        JS_ReportError(mContext, mBuf);
         JS_smprintf_free(mBuf);
     }
 }
 
 void
 JSCLContextHelper::reportErrorAfterPop(char *buf)
 {
     MOZ_ASSERT(!mBuf, "Already called reportErrorAfterPop");
--- a/js/xpconnect/loader/mozJSComponentLoader.h
+++ b/js/xpconnect/loader/mozJSComponentLoader.h
@@ -16,35 +16,31 @@
 #include "nsClassHashtable.h"
 #include "nsCxPusher.h"
 #include "nsDataHashtable.h"
 #include "jsapi.h"
 
 #include "xpcIJSGetFactory.h"
 
 class nsIFile;
-class nsIJSRuntimeService;
 class nsIPrincipal;
 class nsIXPConnectJSObjectHolder;
 class ComponentLoaderInfo;
 
 /* 6bd13476-1dd2-11b2-bbef-f0ccb5fa64b6 (thanks, mozbot) */
 
 #define MOZJSCOMPONENTLOADER_CID                                              \
   {0x6bd13476, 0x1dd2, 0x11b2,                                                \
     { 0xbb, 0xef, 0xf0, 0xcc, 0xb5, 0xfa, 0x64, 0xb6 }}
 #define MOZJSCOMPONENTLOADER_CONTRACTID "@mozilla.org/moz/jsloader;1"
 
-class JSCLContextHelper;
-
 class mozJSComponentLoader : public mozilla::ModuleLoader,
                              public xpcIJSModuleLoader,
                              public nsIObserver
 {
-    friend class JSCLContextHelper;
  public:
     NS_DECL_ISUPPORTS
     NS_DECL_XPCIJSMODULELOADER
     NS_DECL_NSIOBSERVER
 
     mozJSComponentLoader();
 
     // ModuleLoader
@@ -60,17 +56,17 @@ class mozJSComponentLoader : public mozi
  protected:
     virtual ~mozJSComponentLoader();
 
     static mozJSComponentLoader* sSelf;
 
     nsresult ReallyInit();
     void UnloadModules();
 
-    JSObject* PrepareObjectForLocation(JSCLContextHelper& aCx,
+    JSObject* PrepareObjectForLocation(JSContext* aCx,
                                        nsIFile* aComponentFile,
                                        nsIURI *aComponent,
                                        bool aReuseLoaderGlobal,
                                        bool *aRealFile);
 
     nsresult ObjectForLocation(ComponentLoaderInfo& aInfo,
                                nsIFile* aComponentFile,
                                JS::MutableHandleObject aObject,
@@ -80,21 +76,18 @@ class mozJSComponentLoader : public mozi
                                JS::MutableHandleValue aException);
 
     nsresult ImportInto(const nsACString &aLocation,
                         JS::HandleObject targetObj,
                         JSContext *callercx,
                         JS::MutableHandleObject vp);
 
     nsCOMPtr<nsIComponentManager> mCompMgr;
-    nsCOMPtr<nsIJSRuntimeService> mRuntimeService;
     nsCOMPtr<nsIPrincipal> mSystemPrincipal;
     nsCOMPtr<nsIXPConnectJSObjectHolder> mLoaderGlobal;
-    JSRuntime *mRuntime;
-    JSContext *mContext;
 
     class ModuleEntry : public mozilla::Module
     {
     public:
         ModuleEntry(JSContext* aCx)
           : mozilla::Module(), obj(aCx, nullptr), thisObjectKey(aCx, nullptr)
         {
             mVersion = mozilla::Module::kVersion;
--- a/js/xpconnect/src/XPCShellImpl.cpp
+++ b/js/xpconnect/src/XPCShellImpl.cpp
@@ -4,16 +4,17 @@
  * 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 "nsXULAppAPI.h"
 #include "jsapi.h"
 #include "jsfriendapi.h"
 #include "jsprf.h"
 #include "js/OldDebugAPI.h"
+#include "mozilla/dom/ScriptSettings.h"
 #include "nsServiceManagerUtils.h"
 #include "nsComponentManagerUtils.h"
 #include "nsIXPConnect.h"
 #include "nsIJSNativeInitializer.h"
 #include "nsIServiceManager.h"
 #include "nsIFile.h"
 #include "nsString.h"
 #include "nsIDirectoryService.h"
@@ -24,17 +25,16 @@
 #include "nsCOMArray.h"
 #include "nsDirectoryServiceUtils.h"
 #include "nsIJSRuntimeService.h"
 #include "nsCOMPtr.h"
 #include "nsAutoPtr.h"
 #include "nsJSPrincipals.h"
 #include "xpcpublic.h"
 #include "BackstagePass.h"
-#include "nsCxPusher.h"
 #include "nsIScriptSecurityManager.h"
 #include "nsIPrincipal.h"
 #include "nsJSUtils.h"
 
 #ifdef ANDROID
 #include <android/log.h>
 #endif
 
@@ -1456,21 +1456,19 @@ XRE_XPCShellMain(int argc, char **argv, 
         rtsvc->RegisterContextCallback(ContextCallback);
 
         // Override the default XPConnect interrupt callback. We could store the
         // old one and restore it before shutting down, but there's not really a
         // reason to bother.
         sScriptedInterruptCallback.construct(rt, UndefinedValue());
         JS_SetInterruptCallback(rt, XPCShellInterruptCallback);
 
-        cx = JS_NewContext(rt, 8192);
-        if (!cx) {
-            printf("JS_NewContext failed!\n");
-            return 1;
-        }
+        dom::AutoJSAPI jsapi;
+        jsapi.Init();
+        cx = jsapi.cx();
 
         argc--;
         argv++;
         ProcessArgsForCompartment(cx, argv, argc);
 
         nsCOMPtr<nsIXPConnect> xpc = do_GetService(nsIXPConnect::GetCID());
         if (!xpc) {
             printf("failed to get nsXPConnect service!\n");
@@ -1505,19 +1503,16 @@ XRE_XPCShellMain(int argc, char **argv, 
         JS_SetSecurityCallbacks(rt, &shellSecurityCallbacks);
 
 #ifdef TEST_TranslateThis
         nsCOMPtr<nsIXPCFunctionThisTranslator>
             translator(new nsXPCFunctionThisTranslator);
         xpc->SetFunctionThisTranslator(NS_GET_IID(nsITestXPCFunctionCallback), translator);
 #endif
 
-        nsCxPusher pusher;
-        pusher.Push(cx);
-
         nsRefPtr<BackstagePass> backstagePass;
         rv = NS_NewBackstagePass(getter_AddRefs(backstagePass));
         if (NS_FAILED(rv)) {
             fprintf(gErrFile, "+++ Failed to create BackstagePass: %8x\n",
                     static_cast<uint32_t>(rv));
             return 1;
         }
 
@@ -1547,51 +1542,49 @@ XRE_XPCShellMain(int argc, char **argv, 
             // might break various automation scripts.
             JS::CompartmentOptionsRef(glob).setDiscardSource(false);
 
             backstagePass->SetGlobalObject(glob);
 
             JSAutoCompartment ac(cx, glob);
 
             if (!JS_InitReflect(cx, glob)) {
-                JS_EndRequest(cx);
                 return 1;
             }
 
             if (!JS_DefineFunctions(cx, glob, glob_functions) ||
                 !JS_DefineProfilingFunctions(cx, glob)) {
-                JS_EndRequest(cx);
                 return 1;
             }
 
             JS::Rooted<JSObject*> envobj(cx);
             envobj = JS_DefineObject(cx, glob, "environment", &env_class);
             if (!envobj) {
-                JS_EndRequest(cx);
                 return 1;
             }
 
             JS_SetPrivate(envobj, envp);
 
             nsAutoString workingDirectory;
             if (GetCurrentWorkingDirectory(workingDirectory))
                 gWorkingDirectory = &workingDirectory;
 
             JS_DefineProperty(cx, glob, "__LOCATION__", JS::UndefinedHandleValue, 0,
                               GetLocationProperty, nullptr);
 
-            result = ProcessArgs(cx, glob, argv, argc, &dirprovider);
+            // We are almost certainly going to run script here, so we need an
+            // AutoEntryScript. This is Gecko-specific and not in any spec.
+            dom::AutoEntryScript aes(backstagePass);
+            result = ProcessArgs(aes.cx(), glob, argv, argc, &dirprovider);
 
             JS_DropPrincipals(rt, gJSPrincipals);
-            JS_SetAllNonReservedSlotsToUndefined(cx, glob);
+            JS_SetAllNonReservedSlotsToUndefined(aes.cx(), glob);
             JS_GC(rt);
         }
-        pusher.Pop();
         JS_GC(rt);
-        JS_DestroyContext(cx);
     } // this scopes the nsCOMPtrs
 
     if (!XRE_ShutdownTestShell())
         NS_ERROR("problem shutting down testshell");
 
     // no nsCOMPtrs are allowed to be alive when you call NS_ShutdownXPCOM
     rv = NS_ShutdownXPCOM( nullptr );
     MOZ_ASSERT(NS_SUCCEEDED(rv), "NS_ShutdownXPCOM failed");
--- a/layout/base/TouchCaret.cpp
+++ b/layout/base/TouchCaret.cpp
@@ -564,36 +564,38 @@ TouchCaret::HandleEvent(WidgetEvent* aEv
       status = HandleTouchDownEvent(aEvent->AsTouchEvent());
       break;
     case NS_MOUSE_BUTTON_DOWN:
       status = HandleMouseDownEvent(aEvent->AsMouseEvent());
       break;
     case NS_TOUCH_END:
       status = HandleTouchUpEvent(aEvent->AsTouchEvent());
       break;
-   case NS_MOUSE_BUTTON_UP:
+    case NS_MOUSE_BUTTON_UP:
       status = HandleMouseUpEvent(aEvent->AsMouseEvent());
       break;
     case NS_TOUCH_MOVE:
       status = HandleTouchMoveEvent(aEvent->AsTouchEvent());
       break;
     case NS_MOUSE_MOVE:
       status = HandleMouseMoveEvent(aEvent->AsMouseEvent());
       break;
     case NS_TOUCH_CANCEL:
       mTouchesId.Clear();
       SetState(TOUCHCARET_NONE);
       LaunchExpirationTimer();
       break;
     case NS_KEY_UP:
     case NS_KEY_DOWN:
     case NS_KEY_PRESS:
-    case NS_WHEEL_EVENT_START:
+    case NS_WHEEL_WHEEL:
+    case NS_WHEEL_START:
+    case NS_WHEEL_STOP:
       // Disable touch caret while key/wheel event is received.
-      TOUCHCARET_LOG("Receive key/wheel event");
+      TOUCHCARET_LOG("Receive key/wheel event %d", aEvent->message);
       SetVisibility(false);
       break;
     default:
       break;
   }
 
   return status;
 }
--- a/layout/base/nsLayoutUtils.cpp
+++ b/layout/base/nsLayoutUtils.cpp
@@ -6758,17 +6758,17 @@ nsLayoutUtils::CalculateScrollableRectFo
   if (aScrollableFrame) {
     contentBounds = aScrollableFrame->GetScrollRange();
 
     // We ifndef the below code for Fennec because it requires special behaviour
     // on the APZC side. Because Fennec has it's own PZC implementation which doesn't
     // provide the special behaviour, this code will cause it to break. We can remove
     // the ifndef once Fennec switches over to APZ or if we add the special handling
     // to Fennec
-#ifndef MOZ_WIDGET_ANDROID
+#if !defined(MOZ_WIDGET_ANDROID) || defined(MOZ_ANDROID_APZ)
     nsPoint scrollPosition = aScrollableFrame->GetScrollPosition();
     if (aScrollableFrame->GetScrollbarStyles().mVertical == NS_STYLE_OVERFLOW_HIDDEN) {
       contentBounds.y = scrollPosition.y;
       contentBounds.height = 0;
     }
     if (aScrollableFrame->GetScrollbarStyles().mHorizontal == NS_STYLE_OVERFLOW_HIDDEN) {
       contentBounds.x = scrollPosition.x;
       contentBounds.width = 0;
--- a/layout/base/nsPresContext.cpp
+++ b/layout/base/nsPresContext.cpp
@@ -57,17 +57,16 @@
 #include "nsRefreshDriver.h"
 #include "Layers.h"
 #include "nsIDOMEvent.h"
 #include "gfxPrefs.h"
 #include "nsIDOMChromeWindow.h"
 #include "nsFrameLoader.h"
 
 #include "nsContentUtils.h"
-#include "nsCxPusher.h"
 #include "nsPIWindowRoot.h"
 #include "mozilla/Preferences.h"
 
 // Needed for Start/Stop of Image Animation
 #include "imgIContainer.h"
 #include "nsIImageLoadingContent.h"
 
 #include "nsCSSParser.h"
@@ -1926,27 +1925,21 @@ nsPresContext::MediaFeatureValuesChanged
     MediaQueryList::NotifyList notifyList;
     for (PRCList *l = PR_LIST_HEAD(&mDOMMediaQueryLists);
          l != &mDOMMediaQueryLists; l = PR_NEXT_LINK(l)) {
       MediaQueryList *mql = static_cast<MediaQueryList*>(l);
       mql->MediumFeaturesChanged(notifyList);
     }
 
     if (!notifyList.IsEmpty()) {
-      nsPIDOMWindow *win = mDocument->GetInnerWindow();
-      nsCOMPtr<EventTarget> et = do_QueryInterface(win);
-      nsCxPusher pusher;
-
       for (uint32_t i = 0, i_end = notifyList.Length(); i != i_end; ++i) {
-        if (pusher.RePush(et)) {
-          nsAutoMicroTask mt;
-          MediaQueryList::HandleChangeData &d = notifyList[i];
-          ErrorResult result;
-          d.callback->Call(*d.mql, result);
-        }
+        nsAutoMicroTask mt;
+        MediaQueryList::HandleChangeData &d = notifyList[i];
+        ErrorResult result;
+        d.callback->Call(*d.mql, result);
       }
     }
 
     // NOTE:  When |notifyList| goes out of scope, our destructor could run.
   }
 }
 
 void
--- a/layout/base/tests/marionette/test_touchcaret.py
+++ b/layout/base/tests/marionette/test_touchcaret.py
@@ -142,16 +142,48 @@ class TouchCaretTest(MarionetteTestCase)
         # top-left corner of the input box.
         src_x, src_y = sel.touch_caret_location()
         dest_x, dest_y = 0, 0
         self.actions.wait(timeout).flick(el, src_x, src_y, dest_x, dest_y).perform()
 
         el.send_keys(content_to_add)
         assertFunc(non_target_content, sel.content)
 
+    def _test_touch_caret_hides_after_receiving_wheel_event(self, el, assertFunc):
+        sel = SelectionManager(el)
+        content_to_add = '!'
+        non_target_content = content_to_add + sel.content
+
+        # Tap to make touch caret appear. Note: it's strange that when the caret
+        # is at the end, the rect of the caret in <textarea> cannot be obtained.
+        # A bug perhaps.
+        el.tap()
+        sel.move_caret_to_end()
+        sel.move_caret_by_offset(1, backward=True)
+        el.tap(*sel.caret_location())
+
+        # Send an arbitrary scroll-down-10px wheel event to the center of the
+        # input box to hide touch caret. Then pretend to move it to the top-left
+        # corner of the input box.
+        src_x, src_y = sel.touch_caret_location()
+        dest_x, dest_y = 0, 0
+        el_center_x, el_center_y = el.rect['x'], el.rect['y']
+        self.marionette.execute_script(
+            '''var utils = SpecialPowers.getDOMWindowUtils(window);
+            utils.sendWheelEvent(arguments[0], arguments[1],
+                                 0, 10, 0, WheelEvent.DOM_DELTA_PIXEL,
+                                 0, 0, 0, 0);''',
+            script_args=[el_center_x, el_center_y]
+        )
+        self.actions.flick(el, src_x, src_y, dest_x, dest_y).perform()
+
+        el.send_keys(content_to_add)
+        assertFunc(non_target_content, sel.content)
+
+
     ########################################################################
     # <input> test cases with touch caret enabled
     ########################################################################
     def test_input_move_caret_to_the_right_by_one_character(self):
         self.openTestHtml(enabled=True, expiration_time=self._large_expiration_time)
         self._test_move_caret_to_the_right_by_one_character(self._input, self.assertEqual)
 
     def test_input_move_caret_to_end_by_dragging_touch_caret_to_bottom_right_corner(self):
@@ -161,16 +193,20 @@ class TouchCaretTest(MarionetteTestCase)
     def test_input_move_caret_to_front_by_dragging_touch_caret_to_top_left_corner(self):
         self.openTestHtml(enabled=True, expiration_time=self._large_expiration_time)
         self._test_move_caret_to_front_by_dragging_touch_caret_to_top_left_corner(self._input, self.assertEqual)
 
     def test_input_touch_caret_timeout(self):
         self.openTestHtml(enabled=True)
         self._test_touch_caret_timeout_by_dragging_it_to_top_left_corner_after_timout(self._input, self.assertNotEqual)
 
+    def test_input_touch_caret_hides_after_receiving_wheel_event(self):
+        self.openTestHtml(enabled=True, expiration_time=0)
+        self._test_touch_caret_hides_after_receiving_wheel_event(self._input, self.assertNotEqual)
+
     ########################################################################
     # <input> test cases with touch caret disabled
     ########################################################################
     def test_input_move_caret_to_the_right_by_one_character_disabled(self):
         self.openTestHtml(enabled=False)
         self._test_move_caret_to_the_right_by_one_character(self._input, self.assertNotEqual)
 
     def test_input_move_caret_to_front_by_dragging_touch_caret_to_top_left_corner_disabled(self):
@@ -191,16 +227,20 @@ class TouchCaretTest(MarionetteTestCase)
     def test_textarea_move_caret_to_front_by_dragging_touch_caret_to_top_left_corner(self):
         self.openTestHtml(enabled=True, expiration_time=self._large_expiration_time)
         self._test_move_caret_to_front_by_dragging_touch_caret_to_top_left_corner(self._textarea, self.assertEqual)
 
     def test_textarea_touch_caret_timeout(self):
         self.openTestHtml(enabled=True)
         self._test_touch_caret_timeout_by_dragging_it_to_top_left_corner_after_timout(self._textarea, self.assertNotEqual)
 
+    def test_textarea_touch_caret_hides_after_receiving_wheel_event(self):
+        self.openTestHtml(enabled=True, expiration_time=0)
+        self._test_touch_caret_hides_after_receiving_wheel_event(self._textarea, self.assertNotEqual)
+
     ########################################################################
     # <textarea> test cases with touch caret disabled
     ########################################################################
     def test_textarea_move_caret_to_the_right_by_one_character_disabled(self):
         self.openTestHtml(enabled=False)
         self._test_move_caret_to_the_right_by_one_character(self._textarea, self.assertNotEqual)
 
     def test_textarea_move_caret_to_front_by_dragging_touch_caret_to_top_left_corner_disabled(self):
@@ -221,16 +261,20 @@ class TouchCaretTest(MarionetteTestCase)
     def test_contenteditable_move_caret_to_front_by_dragging_touch_caret_to_top_left_corner(self):
         self.openTestHtml(enabled=True, expiration_time=self._large_expiration_time)
         self._test_move_caret_to_front_by_dragging_touch_caret_to_top_left_corner(self._contenteditable, self.assertEqual)
 
     def test_contenteditable_touch_caret_timeout(self):
         self.openTestHtml(enabled=True)
         self._test_touch_caret_timeout_by_dragging_it_to_top_left_corner_after_timout(self._contenteditable, self.assertNotEqual)
 
+    def test_contenteditable_touch_caret_hides_after_receiving_wheel_event(self):
+        self.openTestHtml(enabled=True, expiration_time=0)
+        self._test_touch_caret_hides_after_receiving_wheel_event(self._contenteditable, self.assertNotEqual)
+
     ########################################################################
     # <div> contenteditable test cases with touch caret disabled
     ########################################################################
     def test_contenteditable_move_caret_to_the_right_by_one_character_disabled(self):
         self.openTestHtml(enabled=False)
         self._test_move_caret_to_the_right_by_one_character(self._contenteditable, self.assertNotEqual)
 
     def test_contenteditable_move_caret_to_front_by_dragging_touch_caret_to_top_left_corner_disabled(self):
--- a/layout/reftests/w3c-css/submitted/flexbox/flexbox-abspos-child-1a.html
+++ b/layout/reftests/w3c-css/submitted/flexbox/flexbox-abspos-child-1a.html
@@ -2,17 +2,17 @@
 <!--
      Any copyright is dedicated to the Public Domain.
      http://creativecommons.org/publicdomain/zero/1.0/
 -->
 <html>
 <head>
   <title>CSS Test: Testing that "min-width", "max-width", "min-height", and "max-height" are applied on absolutely positioned children of a horizontal flex container</title>
   <link rel="author" title="Daniel Holbert" href="mailto:dholbert@mozilla.com">
-  <link rel="help" href="http://www.w3.org/TR/css3-flexbox/#abspos-items">
+  <link rel="help" href="http://www.w3.org/TR/css-flexbox-1/#abspos-items">
   <link rel="match" href="flexbox-abspos-child-1-ref.html">
   <meta charset="utf-8">
   <style>
     .flexContainer {
       display: flex;
       height: 10px;
       width: 10px;
       background: purple;
--- a/layout/reftests/w3c-css/submitted/flexbox/flexbox-abspos-child-1b.html
+++ b/layout/reftests/w3c-css/submitted/flexbox/flexbox-abspos-child-1b.html
@@ -2,17 +2,17 @@
 <!--
      Any copyright is dedicated to the Public Domain.
      http://creativecommons.org/publicdomain/zero/1.0/
 -->
 <html>
 <head>
   <title>CSS Test: Testing that "min-width", "max-width", "min-height", and "max-height" are applied on absolutely positioned children of a vertical flex container</title>
   <link rel="author" title="Daniel Holbert" href="mailto:dholbert@mozilla.com">
-  <link rel="help" href="http://www.w3.org/TR/css3-flexbox/#abspos-items">
+  <link rel="help" href="http://www.w3.org/TR/css-flexbox-1/#abspos-items">
   <link rel="match" href="flexbox-abspos-child-1-ref.html">
   <meta charset="utf-8">
   <style>
     .flexContainer {
       display: flex;
       flex-direction: column;
       height: 10px;
       width: 10px;
--- a/layout/reftests/w3c-css/submitted/flexbox/flexbox-align-content-horiz-1a.xhtml
+++ b/layout/reftests/w3c-css/submitted/flexbox/flexbox-align-content-horiz-1a.xhtml
@@ -4,17 +4,17 @@
      http://creativecommons.org/publicdomain/zero/1.0/
 -->
 <!-- Testcase with a series of horizontal flex containers, with 1-3 flex lines,
      testing each possible value of the 'align-content' property. -->
 <html xmlns="http://www.w3.org/1999/xhtml">
   <head>
     <title>CSS Test: Testing 'align-content' in a horizontal flex container</title>
     <link rel="author" title="Daniel Holbert" href="mailto:dholbert@mozilla.com"/>
-    <link rel="help" href="http://www.w3.org/TR/css3-flexbox/#align-content-property"/>
+    <link rel="help" href="http://www.w3.org/TR/css-flexbox-1/#align-content-property"/>
     <link rel="match" href="flexbox-align-content-horiz-1-ref.xhtml"/>
     <style>
       div.flexbox {
         width: 20px; /* Skinny, to force us to wrap */
         height: 200px;
         display: flex;
         flex-wrap: wrap;
         margin-right: 2px;
--- a/layout/reftests/w3c-css/submitted/flexbox/flexbox-align-content-horiz-1b.xhtml
+++ b/layout/reftests/w3c-css/submitted/flexbox/flexbox-align-content-horiz-1b.xhtml
@@ -5,17 +5,17 @@
 -->
 <!-- Testcase with a series of horizontal flex containers, with 1-3 flex lines,
      testing each possible value of the 'align-content' property. Additionally,
      the flex container derives its width from the "max-width" property. -->
 <html xmlns="http://www.w3.org/1999/xhtml">
   <head>
     <title>CSS Test: Testing 'align-content' in a horizontal flex container</title>
     <link rel="author" title="Daniel Holbert" href="mailto:dholbert@mozilla.com"/>
-    <link rel="help" href="http://www.w3.org/TR/css3-flexbox/#align-content-property"/>
+    <link rel="help" href="http://www.w3.org/TR/css-flexbox-1/#align-content-property"/>
     <link rel="match" href="flexbox-align-content-horiz-1-ref.xhtml"/>
     <style>
       div.flexbox {
         max-width: 20px; /* Skinny, to force us to wrap */
         height: 200px;
         display: flex;
         flex-wrap: wrap;
         margin-right: 2px;
--- a/layout/reftests/w3c-css/submitted/flexbox/flexbox-align-content-vert-1a.xhtml
+++ b/layout/reftests/w3c-css/submitted/flexbox/flexbox-align-content-vert-1a.xhtml
@@ -4,17 +4,17 @@
      http://creativecommons.org/publicdomain/zero/1.0/
 -->
 <!-- Testcase with a series of vertical flex containers, with 1-3 flex lines,
      testing each possible value of the 'align-content' property. -->
 <html xmlns="http://www.w3.org/1999/xhtml">
   <head>
     <title>CSS Test: Testing 'align-content' in a vertical flex container</title>
     <link rel="author" title="Daniel Holbert" href="mailto:dholbert@mozilla.com"/>
-    <link rel="help" href="http://www.w3.org/TR/css3-flexbox/#align-content-property"/>
+    <link rel="help" href="http://www.w3.org/TR/css-flexbox-1/#align-content-property"/>
     <link rel="match" href="flexbox-align-content-vert-1-ref.xhtml"/>
     <style>
       div.flexbox {
         width: 200px;
         height: 20px; /* Short, to force us to wrap */
         display: flex;
         flex-direction: column;
         flex-wrap: wrap;
--- a/layout/reftests/w3c-css/submitted/flexbox/flexbox-align-content-vert-1b.xhtml
+++ b/layout/reftests/w3c-css/submitted/flexbox/flexbox-align-content-vert-1b.xhtml
@@ -5,17 +5,17 @@
 -->
 <!-- Testcase with a series of vertical flex containers, with 1-3 flex lines,
      testing each possible value of the 'align-content' property. Additionally,
      the flex container derives its height from the "max-height" property.-->
 <html xmlns="http://www.w3.org/1999/xhtml">
   <head>
     <title>CSS Test: Testing 'align-content' in a vertical flex container</title>
     <link rel="author" title="Daniel Holbert" href="mailto:dholbert@mozilla.com"/>
-    <link rel="help" href="http://www.w3.org/TR/css3-flexbox/#align-content-property"/>
+    <link rel="help" href="http://www.w3.org/TR/css-flexbox-1/#align-content-property"/>
     <link rel="match" href="flexbox-align-content-vert-1-ref.xhtml"/>
     <style>
       div.flexbox {
         width: 200px;
         max-height: 20px; /* Short, to force us to wrap */
         display: flex;
         flex-direction: column;
         flex-wrap: wrap;
--- a/layout/reftests/w3c-css/submitted/flexbox/flexbox-align-self-baseline-horiz-1a.xhtml
+++ b/layout/reftests/w3c-css/submitted/flexbox/flexbox-align-self-baseline-horiz-1a.xhtml
@@ -7,17 +7,17 @@
      align-self, implicitly). This test baseline-aligns various types of
      content, and the flexbox's vertical size depends on the aggregate
      post-alignment height of its children.
 -->
 <html xmlns="http://www.w3.org/1999/xhtml">
   <head>
     <title>CSS Test: Baseline alignment of block flex items with 'baseline' value for 'align-items' / 'align-self'</title>
     <link rel="author" title="Daniel Holbert" href="mailto:dholbert@mozilla.com"/>
-    <link rel="help" href="http://www.w3.org/TR/css3-flexbox/#baseline-participation"/>
+    <link rel="help" href="http://www.w3.org/TR/css-flexbox-1/#baseline-participation"/>
     <link rel="match" href="flexbox-align-self-baseline-horiz-1-ref.xhtml"/>
     <style>
       .flexbox {
         display: flex;
         align-items: baseline;
         border: 1px dashed blue;
         font: 14px sans-serif;
       }
--- a/layout/reftests/w3c-css/submitted/flexbox/flexbox-align-self-baseline-horiz-1b.xhtml
+++ b/layout/reftests/w3c-css/submitted/flexbox/flexbox-align-self-baseline-horiz-1b.xhtml
@@ -9,17 +9,17 @@
      post-alignment height of its children. This test also uses
      "flex-wrap: wrap-reverse" to make the cross-axis bottom-to-top instead
      of top-to-bottom.
 -->
 <html xmlns="http://www.w3.org/1999/xhtml">
   <head>
     <title>CSS Test: Baseline alignment of block flex items with 'baseline' value for 'align-items' / 'align-self' in a wrap-reverse flex container</title>
     <link rel="author" title="Daniel Holbert" href="mailto:dholbert@mozilla.com"/>
-    <link rel="help" href="http://www.w3.org/TR/css3-flexbox/#baseline-participation"/>
+    <link rel="help" href="http://www.w3.org/TR/css-flexbox-1/#baseline-participation"/>
     <link rel="match" href="flexbox-align-self-baseline-horiz-1-ref.xhtml"/>
     <style>
       .flexbox {
         display: flex;
         align-items: baseline;
         flex-wrap: wrap-reverse;
         border: 1px dashed blue;
         font: 14px sans-serif;
--- a/layout/reftests/w3c-css/submitted/flexbox/flexbox-align-self-baseline-horiz-2.xhtml
+++ b/layout/reftests/w3c-css/submitted/flexbox/flexbox-align-self-baseline-horiz-2.xhtml
@@ -5,17 +5,17 @@
 -->
 <!-- Testcase for how a baseline-aligned flex item's position is impacted by
      cross-axis margins, in a fixed-size flex container.
   -->
 <html xmlns="http://www.w3.org/1999/xhtml">
   <head>
     <title>CSS Test: Baseline alignment of flex items in fixed-size single-line flex container</title>
     <link rel="author" title="Daniel Holbert" href="mailto:dholbert@mozilla.com"/>
-    <link rel="help" href="http://www.w3.org/TR/css3-flexbox/#baseline-participation"/>
+    <link rel="help" href="http://www.w3.org/TR/css-flexbox-1/#baseline-participation"/>
     <link rel="match" href="flexbox-align-self-baseline-horiz-2-ref.xhtml"/>
     <style>
       .flexbox {
         display: flex;
         align-items: baseline;
         width: 40px;
         height: 40px;
         border: 1px solid gray;
--- a/layout/reftests/w3c-css/submitted/flexbox/flexbox-align-self-baseline-horiz-3.xhtml
+++ b/layout/reftests/w3c-css/submitted/flexbox/flexbox-align-self-baseline-horiz-3.xhtml
@@ -6,17 +6,17 @@
 <!-- Testcase for how a baseline-aligned flex item's position is impacted by
      cross-axis margins, in a fixed-size flex container with the cross axis
      reversed via "flex-wrap: wrap-reverse".
   -->
 <html xmlns="http://www.w3.org/1999/xhtml">
   <head>
     <title>CSS Test: Baseline alignment of flex items in fixed-size single-line flex container, with cross axis reversed</title>
     <link rel="author" title="Daniel Holbert" href="mailto:dholbert@mozilla.com"/>
-    <link rel="help" href="http://www.w3.org/TR/css3-flexbox/#baseline-participation"/>
+    <link rel="help" href="http://www.w3.org/TR/css-flexbox-1/#baseline-participation"/>
     <link rel="match" href="flexbox-align-self-baseline-horiz-3-ref.xhtml"/>
     <style>
       .flexbox {
         display: flex;
         align-items: baseline;
         flex-wrap: wrap-reverse; /* Just to flip cross-axis */
         width: 40px;
         height: 40px;
--- a/layout/reftests/w3c-css/submitted/flexbox/flexbox-align-self-baseline-horiz-4.xhtml
+++ b/layout/reftests/w3c-css/submitted/flexbox/flexbox-align-self-baseline-horiz-4.xhtml
@@ -7,17 +7,17 @@
      align-self, implicitly), in a multi-line flex container.
      This test baseline-aligns variously-sized flex items, and the container's
      vertical size depends on the aggregate post-alignment height of its items.
   -->
 <html xmlns="http://www.w3.org/1999/xhtml">
   <head>
     <title>CSS Test: Baseline alignment of block flex items with 'baseline' value for 'align-items' / 'align-self' in a multi-line flex container</title>
     <link rel="author" title="Daniel Holbert" href="mailto:dholbert@mozilla.com"/>
-    <link rel="help" href="http://www.w3.org/TR/css3-flexbox/#baseline-participation"/>
+    <link rel="help" href="http://www.w3.org/TR/css-flexbox-1/#baseline-participation"/>
     <link rel="match" href="flexbox-align-self-baseline-horiz-4-ref.xhtml"/>
     <style>
       .flexbox {
         display: flex;
         flex-wrap: wrap;
         align-items: baseline;
         width: 90px;
       }
--- a/layout/reftests/w3c-css/submitted/flexbox/flexbox-align-self-baseline-horiz-5.xhtml
+++ b/layout/reftests/w3c-css/submitted/flexbox/flexbox-align-self-baseline-horiz-5.xhtml
@@ -7,17 +7,17 @@
      align-self, implicitly), in a wrap-reverse multi-line flex container.
      This test baseline-aligns variously-sized flex items, and the container's
      vertical size depends on the aggregate post-alignment height of its items.
   -->
 <html xmlns="http://www.w3.org/1999/xhtml">
   <head>
     <title>CSS Test: Baseline alignment of block flex items with 'baseline' value for 'align-items' / 'align-self' in a multi-line flex container</title>
     <link rel="author" title="Daniel Holbert" href="mailto:dholbert@mozilla.com"/>
-    <link rel="help" href="http://www.w3.org/TR/css3-flexbox/#baseline-participation"/>
+    <link rel="help" href="http://www.w3.org/TR/css-flexbox-1/#baseline-participation"/>
     <link rel="match" href="flexbox-align-self-baseline-horiz-5-ref.xhtml"/>
     <style>
       .flexbox {
         display: flex;
         flex-wrap: wrap-reverse;
         align-items: baseline;
         width: 90px;
       }
--- a/layout/reftests/w3c-css/submitted/flexbox/flexbox-align-self-horiz-1-block.xhtml
+++ b/layout/reftests/w3c-css/submitted/flexbox/flexbox-align-self-horiz-1-block.xhtml
@@ -4,17 +4,17 @@
      http://creativecommons.org/publicdomain/zero/1.0/
 -->
 <!-- Testcase for align-items / align-self behavior, with all the possible
      values included on different items within a flex container. -->
 <html xmlns="http://www.w3.org/1999/xhtml">
   <head>
     <title>CSS Test: Testing the behavior of 'align-self' property values on flex items that are blocks, in a horizontal flex container</title>
     <link rel="author" title="Daniel Holbert" href="mailto:dholbert@mozilla.com"/>
-    <link rel="help" href="http://www.w3.org/TR/css3-flexbox/#align-items-property"/>
+    <link rel="help" href="http://www.w3.org/TR/css-flexbox-1/#align-items-property"/>
     <link rel="match" href="flexbox-align-self-horiz-1-ref.xhtml"/>
     <style>
       .flexbox {
         border: 1px dashed blue;
         height: 200px;
         display: inline-flex;
         font-size: 10px;
         line-height: 10px;
--- a/layout/reftests/w3c-css/submitted/flexbox/flexbox-align-self-horiz-1-table.xhtml
+++ b/layout/reftests/w3c-css/submitted/flexbox/flexbox-align-self-horiz-1-table.xhtml
@@ -4,17 +4,17 @@
      http://creativecommons.org/publicdomain/zero/1.0/
 -->
 <!-- Testcase for align-items / align-self behavior, with all the possible
      values included on different items within a flex container. -->
 <html xmlns="http://www.w3.org/1999/xhtml">
   <head>
     <title>CSS Test: Testing the various 'align-self' property values on flex items that are tables</title>
     <link rel="author" title="Daniel Holbert" href="mailto:dholbert@mozilla.com"/>
-    <link rel="help" href="http://www.w3.org/TR/css3-flexbox/#align-items-property"/>
+    <link rel="help" href="http://www.w3.org/TR/css-flexbox-1/#align-items-property"/>
     <link rel="match" href="flexbox-align-self-horiz-1-ref.xhtml"/>
     <style>
       .flexbox {
         border: 1px dashed blue;
         height: 200px;
         display: inline-flex;
         font-size: 10px;
         line-height: 10px;
--- a/layout/reftests/w3c-css/submitted/flexbox/flexbox-align-self-horiz-2.xhtml
+++ b/layout/reftests/w3c-css/submitted/flexbox/flexbox-align-self-horiz-2.xhtml
@@ -5,17 +5,17 @@
 -->
 <!-- Testcase for align-items / align-self behavior, with all the possible
      values included on different items within a flex container, and with
      margin/border/padding values on each item. -->
 <html xmlns="http://www.w3.org/1999/xhtml">
   <head>
     <title>CSS Test: Testing the behavior of 'align-self' with a horizontal flex container, with margin/padding/border on the items</title>
     <link rel="author" title="Daniel Holbert" href="mailto:dholbert@mozilla.com"/>
-    <link rel="help" href="http://www.w3.org/TR/css3-flexbox/#align-items-property"/>
+    <link rel="help" href="http://www.w3.org/TR/css-flexbox-1/#align-items-property"/>
     <link rel="match" href="flexbox-align-self-horiz-2-ref.xhtml"/>
     <style>
       .flexbox {
         border: 1px dashed blue;
         height: 200px;
         display: inline-flex;
         font-size: 10px;
         line-height: 10px;
--- a/layout/reftests/w3c-css/submitted/flexbox/flexbox-align-self-horiz-3.xhtml
+++ b/layout/reftests/w3c-css/submitted/flexbox/flexbox-align-self-horiz-3.xhtml
@@ -5,17 +5,17 @@
 -->
 <!-- Testcase for align-items / align-self behavior, with all the possible
      values included on different items within a flex container, and with the
      flex container being shorter than its items. -->
 <html xmlns="http://www.w3.org/1999/xhtml">
   <head>
     <title>CSS Test: Testing the behavior of 'align-self' with a horizontal flex container that's shorter than its items</title>
     <link rel="author" title="Daniel Holbert" href="mailto:dholbert@mozilla.com"/>
-    <link rel="help" href="http://www.w3.org/TR/css3-flexbox/#align-items-property"/>
+    <link rel="help" href="http://www.w3.org/TR/css-flexbox-1/#align-items-property"/>
     <link rel="match" href="flexbox-align-self-horiz-3-ref.xhtml"/>
     <style>
       .flexbox {
         border: 1px dashed blue;
         padding: 3px;
         height: 4px;
         display: inline-flex;
         font-size: 10px;
--- a/layout/reftests/w3c-css/submitted/flexbox/flexbox-align-self-horiz-4.xhtml
+++ b/layout/reftests/w3c-css/submitted/flexbox/flexbox-align-self-horiz-4.xhtml
@@ -5,17 +5,17 @@
 -->
 <!-- Testcase for align-items / align-self behavior, with all the possible
      values included on different items within a flex container, and with the
      flex container being shorter than its items. -->
 <html xmlns="http://www.w3.org/1999/xhtml">
   <head>
     <title>CSS Test: Testing the behavior of 'align-self' with a horizontal flex container that's shorter than its items, with margin/padding/border on the items</title>
     <link rel="author" title="Daniel Holbert" href="mailto:dholbert@mozilla.com"/>
-    <link rel="help" href="http://www.w3.org/TR/css3-flexbox/#align-items-property"/>
+    <link rel="help" href="http://www.w3.org/TR/css-flexbox-1/#align-items-property"/>
     <link rel="match" href="flexbox-align-self-horiz-4-ref.xhtml"/>
     <style>
       .flexbox {
         border: 1px dashed blue;
         padding: 3px;
         height: 4px;
         display: inline-flex;
         font-size: 10px;
--- a/layout/reftests/w3c-css/submitted/flexbox/flexbox-align-self-horiz-5.xhtml
+++ b/layout/reftests/w3c-css/submitted/flexbox/flexbox-align-self-horiz-5.xhtml
@@ -6,17 +6,17 @@
 <!-- Testcase for align-items / align-self behavior with auto margins in
      play (which should negate the effects of align-items / align-self,
      because there won't be any available space in which to align the item
      after the auto margins are resolved).  -->
 <html xmlns="http://www.w3.org/1999/xhtml">
   <head>
     <title>CSS Test: Testing the behavior of 'align-self' with auto margins in play, in a horizontal flex container</title>
     <link rel="author" title="Daniel Holbert" href="mailto:dholbert@mozilla.com"/>
-    <link rel="help" href="http://www.w3.org/TR/css3-flexbox/#auto-margins"/>
+    <link rel="help" href="http://www.w3.org/TR/css-flexbox-1/#auto-margins"/>
     <link rel="match" href="flexbox-align-self-horiz-5-ref.xhtml"/>
     <style>
       .flexbox {
         border: 1px dashed blue;
         height: 140px;
         width: 400px;
         display: flex;
         font-size: 10px;
--- a/layout/reftests/w3c-css/submitted/flexbox/flexbox-align-self-stretch-vert-1.html
+++ b/layout/reftests/w3c-css/submitted/flexbox/flexbox-align-self-stretch-vert-1.html
@@ -2,17 +2,17 @@
 <!--
      Any copyright is dedicated to the Public Domain.
      http://creativecommons.org/publicdomain/zero/1.0/
 -->
 <html>
 <head>
   <title>CSS Test: Testing the sizing of a stretched horizontal flex container in a vertical flex container</title>
   <link rel="author" title="Daniel Holbert" href="mailto:dholbert@mozilla.com">
-  <link rel="help" href="http://www.w3.org/TR/css3-flexbox/#layout-algorithm">
+  <link rel="help" href="http://www.w3.org/TR/css-flexbox-1/#layout-algorithm">
   <link rel="match" href="flexbox-align-self-stretch-vert-1-ref.html">
   <meta name="assert" content="If a stretched flex item's main size is influenced by its cross size, and the flex container has a definite cross size, then the item's cross size should be resolved early so that it can be used when determining the item's main size">
   <meta name="assert" content="http://dev.w3.org/csswg/css-flexbox/issues-cr-2012#issue-23">
   <meta charset="utf-8">
   <style>
     div.fixedWidthWrapper {
       width: 200px;
       /* Small enough that 3 characters can _easily_ fit in our width */
--- a/layout/reftests/w3c-css/submitted/flexbox/flexbox-align-self-stretch-vert-2.html
+++ b/layout/reftests/w3c-css/submitted/flexbox/flexbox-align-self-stretch-vert-2.html
@@ -2,17 +2,17 @@
 <!--
      Any copyright is dedicated to the Public Domain.
      http://creativecommons.org/publicdomain/zero/1.0/
 -->
 <html>
 <head>
   <title>CSS Test: Testing the sizing of stretched flex items in a vertical multi-line flex container</title>
   <link rel="author" title="Daniel Holbert" href="mailto:dholbert@mozilla.com">
-  <link rel="help" href="http://www.w3.org/TR/css3-flexbox/#layout-algorithm">
+  <link rel="help" href="http://www.w3.org/TR/css-flexbox-1/#layout-algorithm">
   <link rel="match" href="flexbox-align-self-stretch-vert-2-ref.html">
   <meta name="assert" content="In a multi-line flex container, flex items should not be stretched (in the cross axis) until after wrapping has been performed.">
   <meta charset="utf-8">
   <style>
     div.container {
       display: flex;
       flex-flow: column wrap;
       width: 100px;
--- a/layout/reftests/w3c-css/submitted/flexbox/flexbox-align-self-vert-1.xhtml
+++ b/layout/reftests/w3c-css/submitted/flexbox/flexbox-align-self-vert-1.xhtml
@@ -4,17 +4,17 @@
      http://creativecommons.org/publicdomain/zero/1.0/
 -->
 <!-- Testcase for align-items / align-self behavior, with all the possible
      values included on different items within a flex container. -->
 <html xmlns="http://www.w3.org/1999/xhtml">
   <head>
     <title>CSS Test: Testing the behavior of 'align-self' property values on flex items that are blocks, in a vertical flex container</title>
     <link rel="author" title="Daniel Holbert" href="mailto:dholbert@mozilla.com"/>
-    <link rel="help" href="http://www.w3.org/TR/css3-flexbox/#align-items-property"/>
+    <link rel="help" href="http://www.w3.org/TR/css-flexbox-1/#align-items-property"/>
     <link rel="match" href="flexbox-align-self-vert-1-ref.xhtml"/>
     <style>
       .flexbox {
         border: 1px dashed blue;
         width: 200px;
         display: flex;
         flex-direction: column;
         font-size: 10px;
--- a/layout/reftests/w3c-css/submitted/flexbox/flexbox-align-self-vert-2.xhtml
+++ b/layout/reftests/w3c-css/submitted/flexbox/flexbox-align-self-vert-2.xhtml
@@ -5,17 +5,17 @@
 -->
 <!-- Testcase for align-items / align-self behavior, with all the possible
      values included on different items within a flex container, and with
      margin/border/padding values on each item. -->
 <html xmlns="http://www.w3.org/1999/xhtml">
   <head>
     <title>CSS Test: Testing the behavior of 'align-self' with a vertical flex container, with margin/padding/border on the items</title>
     <link rel="author" title="Daniel Holbert" href="mailto:dholbert@mozilla.com"/>
-    <link rel="help" href="http://www.w3.org/TR/css3-flexbox/#align-items-property"/>
+    <link rel="help" href="http://www.w3.org/TR/css-flexbox-1/#align-items-property"/>
     <link rel="match" href="flexbox-align-self-vert-2-ref.xhtml"/>
     <style>
       .flexbox {
         border: 1px dashed blue;
         width: 200px;
         display: flex;
         flex-direction: column;
         float: left;
--- a/layout/reftests/w3c-css/submitted/flexbox/flexbox-align-self-vert-3.xhtml
+++ b/layout/reftests/w3c-css/submitted/flexbox/flexbox-align-self-vert-3.xhtml
@@ -5,17 +5,17 @@
 -->
 <!-- Testcase for align-items / align-self behavior, with all the possible
      values included on different items within a flex container, and with the
      flex container being skinnier than its items. -->
 <html xmlns="http://www.w3.org/1999/xhtml">
   <head>
     <title>CSS Test: Testing the behavior of 'align-self' with a vertical flex container that's skinnier than its items</title>
     <link rel="author" title="Daniel Holbert" href="mailto:dholbert@mozilla.com"/>
-    <link rel="help" href="http://www.w3.org/TR/css3-flexbox/#align-items-property"/>
+    <link rel="help" href="http://www.w3.org/TR/css-flexbox-1/#align-items-property"/>
     <link rel="match" href="flexbox-align-self-vert-3-ref.xhtml"/>
     <style>
       .flexbox {
         border: 1px dashed blue;
         width: 4px;
         display: flex;
         flex-direction: column;
         font-family: sans-serif;
--- a/layout/reftests/w3c-css/submitted/flexbox/flexbox-align-self-vert-4.xhtml
+++ b/layout/reftests/w3c-css/submitted/flexbox/flexbox-align-self-vert-4.xhtml
@@ -5,17 +5,17 @@
 -->
 <!-- Testcase for align-items / align-self behavior, with all the possible
      values included on different items within a flex container, and with the
      flex container being skinnier than its items. -->
 <html xmlns="http://www.w3.org/1999/xhtml">
   <head>
     <title>CSS Test: Testing the behavior of 'align-self' with a vertical flex container that's skinnier than its items, with margin/padding/border on the items</title>
     <link rel="author" title="Daniel Holbert" href="mailto:dholbert@mozilla.com"/>
-    <link rel="help" href="http://www.w3.org/TR/css3-flexbox/#align-items-property"/>
+    <link rel="help" href="http://www.w3.org/TR/css-flexbox-1/#align-items-property"/>
     <link rel="match" href="flexbox-align-self-vert-4-ref.xhtml"/>
     <style>
       .flexbox {
         border: 1px dashed blue;
         width: 4px;
         display: flex;
         flex-direction: column;
         float: left;
--- a/layout/reftests/w3c-css/submitted/flexbox/flexbox-align-self-vert-rtl-1.xhtml
+++ b/layout/reftests/w3c-css/submitted/flexbox/flexbox-align-self-vert-rtl-1.xhtml
@@ -5,17 +5,17 @@
 -->
 <!-- Testcase for align-items / align-self behavior, with all the possible
      values included on different items within a flex container, and with
      "direction: rtl" to swap the horizontal (cross) axis. -->
 <html xmlns="http://www.w3.org/1999/xhtml">
   <head>
     <title>CSS Test: Testing the behavior of 'align-self' property values on flex items that are blocks, in a vertical flex container with 'direction: rtl'</title>
     <link rel="author" title="Daniel Holbert" href="mailto:dholbert@mozilla.com"/>
-    <link rel="help" href="http://www.w3.org/TR/css3-flexbox/#align-items-property"/>
+    <link rel="help" href="http://www.w3.org/TR/css-flexbox-1/#align-items-property"/>
     <link rel="match" href="flexbox-align-self-vert-rtl-1-ref.xhtml"/>
     <style>
       .flexbox {
         border: 1px dashed blue;
         width: 200px;
         display: flex;
         flex-direction: column;
         direction: rtl;
--- a/layout/reftests/w3c-css/submitted/flexbox/flexbox-align-self-vert-rtl-2.xhtml
+++ b/layout/reftests/w3c-css/submitted/flexbox/flexbox-align-self-vert-rtl-2.xhtml
@@ -6,17 +6,17 @@
 <!-- Testcase for align-items / align-self behavior, with all the possible
      values included on different items within a flex container, and with
      margin/border/padding values on each, and with "direction: rtl" to swap
      the horizontal (cross) axis item. -->
 <html xmlns="http://www.w3.org/1999/xhtml">
   <head>
     <title>CSS Test: Testing the behavior of 'align-self' with a vertical flex container, with margin/padding/border on the items and with 'direction: rtl'</title>
     <link rel="author" title="Daniel Holbert" href="mailto:dholbert@mozilla.com"/>
-    <link rel="help" href="http://www.w3.org/TR/css3-flexbox/#align-items-property"/>
+    <link rel="help" href="http://www.w3.org/TR/css-flexbox-1/#align-items-property"/>
     <link rel="match" href="flexbox-align-self-vert-rtl-2-ref.xhtml"/>
     <style>
       .flexbox {
         border: 1px dashed blue;
         width: 200px;
         display: flex;
         flex-direction: column;
         direction: rtl;
--- a/layout/reftests/w3c-css/submitted/flexbox/flexbox-align-self-vert-rtl-3.xhtml
+++ b/layout/reftests/w3c-css/submitted/flexbox/flexbox-align-self-vert-rtl-3.xhtml
@@ -6,17 +6,17 @@
 <!-- Testcase for align-items / align-self behavior, with all the possible
      values included on different items within a flex container, and with the
      flex container being skinnier than its items, and with "direction: rtl" to
      swap the horizontal (cross) axis. -->
 <html xmlns="http://www.w3.org/1999/xhtml">
   <head>
     <title>CSS Test: Testing the behavior of 'align-self' with a vertical flex container that's skinnier than its items and  with 'direction: rtl'</title>
     <link rel="author" title="Daniel Holbert" href="mailto:dholbert@mozilla.com"/>
-    <link rel="help" href="http://www.w3.org/TR/css3-flexbox/#align-items-property"/>
+    <link rel="help" href="http://www.w3.org/TR/css-flexbox-1/#align-items-property"/>
     <link rel="match" href="flexbox-align-self-vert-rtl-3-ref.xhtml"/>
     <style>
       .flexbox {
         border: 1px dashed blue;
         width: 4px;
         display: flex;
         flex-direction: column;
         direction: rtl;
--- a/layout/reftests/w3c-css/submitted/flexbox/flexbox-align-self-vert-rtl-4.xhtml
+++ b/layout/reftests/w3c-css/submitted/flexbox/flexbox-align-self-vert-rtl-4.xhtml
@@ -6,17 +6,17 @@
 <!-- Testcase for align-items / align-self behavior, with all the possible
      values included on different items within a flex container, and with the
      flex container being skinnier than its items, and with "direction: rtl" to
      swap the horizontal (cross) axis. -->
 <html xmlns="http://www.w3.org/1999/xhtml">
   <head>
     <title>CSS Test: Testing the behavior of 'align-self' with a vertical flex container that's skinnier than its items, with margin/padding/border on the items and with 'direction: rtl'</title>
     <link rel="author" title="Daniel Holbert" href="mailto:dholbert@mozilla.com"/>
-    <link rel="help" href="http://www.w3.org/TR/css3-flexbox/#align-items-property"/>
+    <link rel="help" href="http://www.w3.org/TR/css-flexbox-1/#align-items-property"/>
     <link rel="match" href="flexbox-align-self-vert-rtl-4-ref.xhtml"/>
     <style>
       .flexbox {
         border: 1px dashed blue;
         width: 4px;
         display: flex;
         flex-direction: column;
         direction: rtl;
--- a/layout/reftests/w3c-css/submitted/flexbox/flexbox-anonymous-items-1.html
+++ b/layout/reftests/w3c-css/submitted/flexbox/flexbox-anonymous-items-1.html
@@ -2,17 +2,17 @@
 <!--
      Any copyright is dedicated to the Public Domain.
      http://creativecommons.org/publicdomain/zero/1.0/
 -->
 <html>
 <head>
   <title>CSS Test: Testing that we gracefully handle cases where two anonymous flex items become adjacent due to "order" reordering</title>
   <link rel="author" title="Daniel Holbert" href="mailto:dholbert@mozilla.com">
-  <link rel="help" href="http://www.w3.org/TR/css3-flexbox/#flex-items">
+  <link rel="help" href="http://www.w3.org/TR/css-flexbox-1/#flex-items">
   <link rel="match" href="flexbox-anonymous-items-1-ref.html">
   <meta charset="utf-8">
   <style>
     .flexContainer {
       display: flex;
     }
   </style>
 </head>
--- a/layout/reftests/w3c-css/submitted/flexbox/flexbox-baseline-align-self-baseline-horiz-1.html
+++ b/layout/reftests/w3c-css/submitted/flexbox/flexbox-baseline-align-self-baseline-horiz-1.html
@@ -9,17 +9,17 @@
        If any of the flex items on the flex container's first line
        participate in baseline alignment, the flex container's
        main-axis baseline is the baseline of those flex items.
 -->
 <html>
 <head>
   <title>CSS Test: Testing the baseline of a horizontal flex container with baseline-aligned flex items</title>
   <link rel="author" title="Daniel Holbert" href="mailto:dholbert@mozilla.com">
-  <link rel="help" href="http://www.w3.org/TR/css3-flexbox/#flex-baselines">
+  <link rel="help" href="http://www.w3.org/TR/css-flexbox-1/#flex-baselines">
   <link rel="match" href="flexbox-baseline-align-self-baseline-horiz-1-ref.html">
   <meta charset="utf-8">
   <style>
     body {
       margin: 0;
       font-size: 20px;
       line-height: 20px;
     }
--- a/layout/reftests/w3c-css/submitted/flexbox/flexbox-baseline-align-self-baseline-vert-1.html
+++ b/layout/reftests/w3c-css/submitted/flexbox/flexbox-baseline-align-self-baseline-vert-1.html
@@ -9,17 +9,17 @@
      participating in baseline alignment, so their "align-self:baseline"
      computed style doesn't have any special effect on the container's
      baseline.
 -->
 <html>
 <head>
   <title>CSS Test: Testing the baseline of a vertical flex container with baseline-aligned flex items</title>
   <link rel="author" title="Daniel Holbert" href="mailto:dholbert@mozilla.com">
-  <link rel="help" href="http://www.w3.org/TR/css3-flexbox/#flex-baselines">
+  <link rel="help" href="http://www.w3.org/TR/css-flexbox-1/#flex-baselines">
   <link rel="match" href="flexbox-baseline-align-self-baseline-vert-1-ref.html">
   <meta charset="utf-8">
   <link rel="stylesheet" type="text/css" href="support/ahem.css" />
   <style>
     body {
       margin: 0;
       font: 20px Ahem;
       line-height: 20px;
--- a/layout/reftests/w3c-css/submitted/flexbox/flexbox-baseline-empty-1a.html
+++ b/layout/reftests/w3c-css/submitted/flexbox/flexbox-baseline-empty-1a.html
@@ -11,17 +11,17 @@
        from ... the flex container's content box.
 
      I'm taking that to mean the baseline is the bottom of the content box.
 -->
 <html>
 <head>
   <title>CSS Test: Testing the baseline of an empty horizontal flex container</title>
   <link rel="author" title="Daniel Holbert" href="mailto:dholbert@mozilla.com">
-  <link rel="help" href="http://www.w3.org/TR/css3-flexbox/#flex-baselines">
+  <link rel="help" href="http://www.w3.org/TR/css-flexbox-1/#flex-baselines">
   <link rel="match" href="flexbox-baseline-empty-1-ref.html">
   <meta charset="utf-8">
   <link rel="stylesheet" type="text/css" href="support/ahem.css" />
   <style>
     body {
       font: 20px Ahem;
     }
     .flexContainer {
--- a/layout/reftests/w3c-css/submitted/flexbox/flexbox-baseline-empty-1b.html
+++ b/layout/reftests/w3c-css/submitted/flexbox/flexbox-baseline-empty-1b.html
@@ -11,17 +11,17 @@
        from ... the flex container's content box.
 
      I'm taking that to mean the baseline is the bottom of the content box.
 -->
 <html>
 <head>
   <title>CSS Test: Testing the baseline of an empty vertical flex container</title>
   <link rel="author" title="Daniel Holbert" href="mailto:dholbert@mozilla.com">
-  <link rel="help" href="http://www.w3.org/TR/css3-flexbox/#flex-baselines">
+  <link rel="help" href="http://www.w3.org/TR/css-flexbox-1/#flex-baselines">
   <link rel="match" href="flexbox-baseline-empty-1-ref.html">
   <meta charset="utf-8">
   <link rel="stylesheet" type="text/css" href="support/ahem.css" />
   <style>
     body {
       font: 20px Ahem;
     }
     .flexContainer {
--- a/layout/reftests/w3c-css/submitted/flexbox/flexbox-baseline-multi-item-horiz-1.html
+++ b/layout/reftests/w3c-css/submitted/flexbox/flexbox-baseline-multi-item-horiz-1.html
@@ -10,17 +10,17 @@
        first flex item has a baseline parallel to the flex
        container's main axis, the flex container's main-axis
        baseline is that baseline.
 -->
 <html>
 <head>
   <title>CSS Test: Testing the baseline of a horizontal flex container whose flex items are not baseline-aligned</title>
   <link rel="author" title="Daniel Holbert" href="mailto:dholbert@mozilla.com">
-  <link rel="help" href="http://www.w3.org/TR/css3-flexbox/#flex-baselines">
+  <link rel="help" href="http://www.w3.org/TR/css-flexbox-1/#flex-baselines">
   <link rel="match" href="flexbox-baseline-multi-item-horiz-1-ref.html">
   <meta charset="utf-8">
   <style>
     .flexContainer {
       display: inline-flex;
       background: lightblue;
     }
     .smallFont {
--- a/layout/reftests/w3c-css/submitted/flexbox/flexbox-baseline-multi-item-vert-1.html
+++ b/layout/reftests/w3c-css/submitted/flexbox/flexbox-baseline-multi-item-vert-1.html
@@ -10,17 +10,17 @@
        first flex item has a baseline parallel to the flex
        container's main axis, the flex container's main-axis
        baseline is that baseline.
 -->
 <html>
 <head>
   <title>CSS Test: Testing the baseline of a vertical flex container whose flex items are not baseline-aligned</title>
   <link rel="author" title="Daniel Holbert" href="mailto:dholbert@mozilla.com">
-  <link rel="help" href="http://www.w3.org/TR/css3-flexbox/#flex-baselines">
+  <link rel="help" href="http://www.w3.org/TR/css-flexbox-1/#flex-baselines">
   <link rel="match" href="flexbox-baseline-multi-item-vert-1-ref.html">
   <meta charset="utf-8">
   <link rel="stylesheet" type="text/css" href="support/ahem.css" />
   <style>
     body {
       margin: 0;
       font: 20px Ahem;
       line-height: 20px;
--- a/layout/reftests/w3c-css/submitted/flexbox/flexbox-baseline-multi-line-horiz-1.html
+++ b/layout/reftests/w3c-css/submitted/flexbox/flexbox-baseline-multi-line-horiz-1.html
@@ -11,17 +11,17 @@
        first flex item has a baseline parallel to the flex
        container's main axis, the flex container's main-axis
        baseline is that baseline.
 -->
 <html>
 <head>
   <title>CSS Test: Testing the baseline of a horizontal flex container with multiple flex lines</title>
   <link rel="author" title="Daniel Holbert" href="mailto:dholbert@mozilla.com">
-  <link rel="help" href="http://www.w3.org/TR/css3-flexbox/#flex-baselines">
+  <link rel="help" href="http://www.w3.org/TR/css-flexbox-1/#flex-baselines">
   <link rel="match" href="flexbox-baseline-multi-line-horiz-1-ref.html">
   <meta charset="utf-8">
   <style>
     .flexContainer {
       display: inline-flex;
       flex-wrap: wrap;
       width: 40px;
       height: 40px;
--- a/layout/reftests/w3c-css/submitted/flexbox/flexbox-baseline-multi-line-horiz-2.html
+++ b/layout/reftests/w3c-css/submitted/flexbox/flexbox-baseline-multi-line-horiz-2.html
@@ -11,17 +11,17 @@
        first flex item has a baseline parallel to the flex
        container's main axis, the flex container's main-axis
        baseline is that baseline.
 -->
 <html>
 <head>
   <title>CSS Test: Testing the baseline of a horizontal flex container with multiple flex lines</title>
   <link rel="author" title="Daniel Holbert" href="mailto:dholbert@mozilla.com">
-  <link rel="help" href="http://www.w3.org/TR/css3-flexbox/#flex-baselines">
+  <link rel="help" href="http://www.w3.org/TR/css-flexbox-1/#flex-baselines">
   <link rel="match" href="flexbox-baseline-multi-line-horiz-2-ref.html">
   <meta charset="utf-8">
   <style>
     .flexContainer {
       display: inline-flex;
       flex-wrap: wrap-reverse;
       width: 40px;
       height: 40px;
--- a/layout/reftests/w3c-css/submitted/flexbox/flexbox-baseline-multi-line-horiz-3.html
+++ b/layout/reftests/w3c-css/submitted/flexbox/flexbox-baseline-multi-line-horiz-3.html
@@ -2,17 +2,17 @@
 <!--
      Any copyright is dedicated to the Public Domain.
      http://creativecommons.org/publicdomain/zero/1.0/
 -->
 <html>
 <head>
   <title>CSS Test: Testing the baseline of a horizontal multi-line (wrap) flex container with baseline-aligned items on first line</title>
   <link rel="author" title="Daniel Holbert" href="mailto:dholbert@mozilla.com">
-  <link rel="help" href="http://www.w3.org/TR/css3-flexbox/#flex-baselines">
+  <link rel="help" href="http://www.w3.org/TR/css-flexbox-1/#flex-baselines">
   <link rel="match" href="flexbox-baseline-multi-line-horiz-3-ref.html">
   <meta charset="utf-8">
   <style>
     .flexContainer {
       display: inline-flex;
       flex-wrap: wrap;
       width: 40px;
       height: 100px;
--- a/layout/reftests/w3c-css/submitted/flexbox/flexbox-baseline-multi-line-horiz-4.html
+++ b/layout/reftests/w3c-css/submitted/flexbox/flexbox-baseline-multi-line-horiz-4.html
@@ -2,17 +2,17 @@
 <!--
      Any copyright is dedicated to the Public Domain.
      http://creativecommons.org/publicdomain/zero/1.0/
 -->
 <html>
 <head>
   <title>CSS Test: Testing the baseline of a horizontal multi-line (wrap-reverse) flex container with baseline-aligned items on first line</title>
   <link rel="author" title="Daniel Holbert" href="mailto:dholbert@mozilla.com">
-  <link rel="help" href="http://www.w3.org/TR/css3-flexbox/#flex-baselines">
+  <link rel="help" href="http://www.w3.org/TR/css-flexbox-1/#flex-baselines">
   <link rel="match" href="flexbox-baseline-multi-line-horiz-4-ref.html">
   <meta charset="utf-8">
   <style>
     .flexContainer {
       display: inline-flex;
       flex-wrap: wrap-reverse;
       width: 40px;
       height: 100px;
--- a/layout/reftests/w3c-css/submitted/flexbox/flexbox-baseline-multi-line-vert-1.html
+++ b/layout/reftests/w3c-css/submitted/flexbox/flexbox-baseline-multi-line-vert-1.html
@@ -11,17 +11,17 @@
        first flex item has a baseline parallel to the flex
        container's main axis, the flex container's main-axis
        baseline is that baseline.
 -->
 <html>
 <head>
   <title>CSS Test: Testing the baseline of a vertical flex container with multiple flex lines</title>
   <link rel="author" title="Daniel Holbert" href="mailto:dholbert@mozilla.com">
-  <link rel="help" href="http://www.w3.org/TR/css3-flexbox/#flex-baselines">
+  <link rel="help" href="http://www.w3.org/TR/css-flexbox-1/#flex-baselines">
   <link rel="match" href="flexbox-baseline-multi-line-vert-1-ref.html">
   <meta charset="utf-8">
   <style>
     .flexContainer {
       display: inline-flex;
       flex-direction: column;
       flex-wrap: wrap;
       width: 40px;
--- a/layout/reftests/w3c-css/submitted/flexbox/flexbox-baseline-multi-line-vert-2.html
+++ b/layout/reftests/w3c-css/submitted/flexbox/flexbox-baseline-multi-line-vert-2.html
@@ -11,17 +11,17 @@
        first flex item has a baseline parallel to the flex
        container's main axis, the flex container's main-axis
        baseline is that baseline.
 -->
 <html>
 <head>
   <title>CSS Test: Testing the baseline of a vertical flex container with multiple flex lines</title>
   <link rel="author" title="Daniel Holbert" href="mailto:dholbert@mozilla.com">
-  <link rel="help" href="http://www.w3.org/TR/css3-flexbox/#flex-baselines">
+  <link rel="help" href="http://www.w3.org/TR/css-flexbox-1/#flex-baselines">
   <link rel="match" href="flexbox-baseline-multi-line-vert-2-ref.html">
   <meta charset="utf-8">
   <style>
     .flexContainer {
       display: inline-flex;
       flex-direction: column;
       flex-wrap: wrap-reverse;
       width: 40px;
--- a/layout/reftests/w3c-css/submitted/flexbox/flexbox-baseline-single-item-1a.html
+++ b/layout/reftests/w3c-css/submitted/flexbox/flexbox-baseline-single-item-1a.html
@@ -10,17 +10,17 @@
        first flex item has a baseline parallel to the flex
        container's main axis, the flex container's main-axis
        baseline is that baseline.
 -->
 <html>
 <head>
   <title>CSS Test: Testing the baseline of a horizontal flex container with one flex item</title>
   <link rel="author" title="Daniel Holbert" href="mailto:dholbert@mozilla.com">
-  <link rel="help" href="http://www.w3.org/TR/css3-flexbox/#flex-baselines">
+  <link rel="help" href="http://www.w3.org/TR/css-flexbox-1/#flex-baselines">
   <link rel="match" href="flexbox-baseline-single-item-1-ref.html">
   <meta charset="utf-8">
   <style>
     .flexContainer {
       display: inline-flex;
       height: 16px;
       width: 16px;
       background: purple;
--- a/layout/reftests/w3c-css/submitted/flexbox/flexbox-baseline-single-item-1b.html
+++ b/layout/reftests/w3c-css/submitted/flexbox/flexbox-baseline-single-item-1b.html
@@ -10,17 +10,17 @@
        first flex item has a baseline parallel to the flex
        container's cross axis, the flex container's cross-axis
        baseline is that baseline.
 -->
 <html>
 <head>
   <title>CSS Test: Testing the baseline of a vertical flex container with one flex item</title>
   <link rel="author" title="Daniel Holbert" href="mailto:dholbert@mozilla.com">
-  <link rel="help" href="http://www.w3.org/TR/css3-flexbox/#flex-baselines">
+  <link rel="help" href="http://www.w3.org/TR/css-flexbox-1/#flex-baselines">
   <link rel="match" href="flexbox-baseline-single-item-1-ref.html">
   <meta charset="utf-8">
   <style>
     .flexContainer {
       display: inline-flex;
       flex-direction: column;
       height: 16px;
       width: 16px;
--- a/layout/reftests/w3c-css/submitted/flexbox/flexbox-basic-block-horiz-1.xhtml
+++ b/layout/reftests/w3c-css/submitted/flexbox/flexbox-basic-block-horiz-1.xhtml
@@ -4,17 +4,17 @@
      http://creativecommons.org/publicdomain/zero/1.0/
 -->
 <!-- Testcase with blocks as flex items in a horizontal flex container, with
      various "flex" values and various combinations of the items. -->
 <html xmlns="http://www.w3.org/1999/xhtml">
   <head>
     <title>CSS Test: Testing flexbox layout algorithm property on block flex items in a horizontal flex container</title>
     <link rel="author" title="Daniel Holbert" href="mailto:dholbert@mozilla.com"/>
-    <link rel="help" href="http://www.w3.org/TR/css3-flexbox/#layout-algorithm"/>
+    <link rel="help" href="http://www.w3.org/TR/css-flexbox-1/#layout-algorithm"/>
     <link rel="match" href="flexbox-basic-block-horiz-1-ref.xhtml"/>
     <style>
       div { height: 100px; }
       div.flexbox {
         border: 1px dashed blue;
         width: 200px;
         font-size: 10px;
         display: flex;
--- a/layout/reftests/w3c-css/submitted/flexbox/flexbox-basic-block-vert-1.xhtml
+++ b/layout/reftests/w3c-css/submitted/flexbox/flexbox-basic-block-vert-1.xhtml
@@ -4,17 +4,17 @@
      http://creativecommons.org/publicdomain/zero/1.0/
 -->
 <!-- Testcase with blocks as flex items in a vertical flex container, with
      various "flex" values and various combinations of the items. -->
 <html xmlns="http://www.w3.org/1999/xhtml">
   <head>
     <title>CSS Test: Testing flexbox layout algorithm property on block flex items in a vertical flex container</title>
     <link rel="author" title="Daniel Holbert" href="mailto:dholbert@mozilla.com"/>
-    <link rel="help" href="http://www.w3.org/TR/css3-flexbox/#layout-algorithm"/>
+    <link rel="help" href="http://www.w3.org/TR/css-flexbox-1/#layout-algorithm"/>
     <link rel="match" href="flexbox-basic-block-vert-1-ref.xhtml"/>
     <style>
       div { width: 50px; }
       div.flexbox {
         float: left;
         border: 1px dashed blue;
         height: 200px;
         font-size: 10px;
--- a/layout/reftests/w3c-css/submitted/flexbox/flexbox-basic-canvas-horiz-1.xhtml
+++ b/layout/reftests/w3c-css/submitted/flexbox/flexbox-basic-canvas-horiz-1.xhtml
@@ -5,17 +5,17 @@
 -->
 <!--
      This test checks that canvas elements behave correctly as flex items.
 -->
 <html xmlns="http://www.w3.org/1999/xhtml">
   <head>
     <title>CSS Test: Testing flexbox layout algorithm property on canvas flex items in a horizontal flex container</title>
     <link rel="author" title="Daniel Holbert" href="mailto:dholbert@mozilla.com"/>
-    <link rel="help" href="http://www.w3.org/TR/css3-flexbox/#layout-algorithm"/>
+    <link rel="help" href="http://www.w3.org/TR/css-flexbox-1/#layout-algorithm"/>
     <link rel="match" href="flexbox-basic-canvas-horiz-1-ref.xhtml"/>
     <style>
       div.flexbox {
         width: 200px;
         background: lightgreen;
         display: flex;
         justify-content: space-between;
         margin-bottom: 5px;
--- a/layout/reftests/w3c-css/submitted/flexbox/flexbox-basic-canvas-vert-1.xhtml
+++ b/layout/reftests/w3c-css/submitted/flexbox/flexbox-basic-canvas-vert-1.xhtml
@@ -5,17 +5,17 @@
 -->
 <!--
      This test checks that canvas elements behave correctly as flex items.
 -->
 <html xmlns="http://www.w3.org/1999/xhtml">
   <head>
     <title>CSS Test: Testing flexbox layout algorithm property on canvas flex items in a vertical flex container</title>
     <link rel="author" title="Daniel Holbert" href="mailto:dholbert@mozilla.com"/>
-    <link rel="help" href="http://www.w3.org/TR/css3-flexbox/#layout-algorithm"/>
+    <link rel="help" href="http://www.w3.org/TR/css-flexbox-1/#layout-algorithm"/>
     <link rel="match" href="flexbox-basic-canvas-vert-1-ref.xhtml"/>
     <style>
       div.flexbox {
         height: 200px;
         background: lightgreen;
         display: flex;
         justify-content: space-between;
         flex-direction: column;
--- a/layout/reftests/w3c-css/submitted/flexbox/flexbox-basic-fieldset-horiz-1.xhtml
+++ b/layout/reftests/w3c-css/submitted/flexbox/flexbox-basic-fieldset-horiz-1.xhtml
@@ -5,17 +5,17 @@
 -->
 <!--
      This test checks that fieldset elements behave correctly as flex items.
 -->
 <html xmlns="http://www.w3.org/1999/xhtml">
   <head>
     <title>CSS Test: Testing flexbox layout algorithm property on fieldset flex items in a horizontal flex container</title>
     <link rel="author" title="Daniel Holbert" href="mailto:dholbert@mozilla.com"/>
-    <link rel="help" href="http://www.w3.org/TR/css3-flexbox/#layout-algorithm"/>
+    <link rel="help" href="http://www.w3.org/TR/css-flexbox-1/#layout-algorithm"/>
     <link rel="match" href="flexbox-basic-fieldset-horiz-1-ref.xhtml"/>
     <style>
       div.flexbox {
         width: 200px;
         background: lightgreen;
         display: flex;
         justify-content: space-between;
         margin-bottom: 5px;
--- a/layout/reftests/w3c-css/submitted/flexbox/flexbox-basic-fieldset-vert-1.xhtml
+++ b/layout/reftests/w3c-css/submitted/flexbox/flexbox-basic-fieldset-vert-1.xhtml
@@ -5,17 +5,17 @@
 -->
 <!--
      This test checks that fieldset elements behave correctly as flex items.
 -->
 <html xmlns="http://www.w3.org/1999/xhtml">
   <head>
     <title>CSS Test: Testing flexbox layout algorithm property on fieldset flex items in a vertical flex container</title>
     <link rel="author" title="Daniel Holbert" href="mailto:dholbert@mozilla.com"/>
-    <link rel="help" href="http://www.w3.org/TR/css3-flexbox/#layout-algorithm"/>
+    <link rel="help" href="http://www.w3.org/TR/css-flexbox-1/#layout-algorithm"/>
     <link rel="match" href="flexbox-basic-fieldset-vert-1-ref.xhtml"/>
     <style>
       div.flexbox {
         height: 200px;
         background: lightgreen;
         display: flex;
         justify-content: space-between;
         flex-direction: column;
--- a/layout/reftests/w3c-css/submitted/flexbox/flexbox-basic-iframe-horiz-1.xhtml
+++ b/layout/reftests/w3c-css/submitted/flexbox/flexbox-basic-iframe-horiz-1.xhtml
@@ -5,17 +5,17 @@
 -->
 <!--
      This test checks that iframe elements behave correctly as flex items.
 -->
 <html xmlns="http://www.w3.org/1999/xhtml">
   <head>
     <title>CSS Test: Testing flexbox layout algorithm property on iframe flex items in a horizontal flex container</title>
     <link rel="author" title="Daniel Holbert" href="mailto:dholbert@mozilla.com"/>
-    <link rel="help" href="http://www.w3.org/TR/css3-flexbox/#layout-algorithm"/>
+    <link rel="help" href="http://www.w3.org/TR/css-flexbox-1/#layout-algorithm"/>
     <link rel="match" href="flexbox-basic-iframe-horiz-1-ref.xhtml"/>
     <style>
       div.flexbox {
         width: 200px;
         background: lightgreen;
         display: flex;
         justify-content: space-between;
         margin-bottom: 5px;
--- a/layout/reftests/w3c-css/submitted/flexbox/flexbox-basic-iframe-vert-1.xhtml
+++ b/layout/reftests/w3c-css/submitted/flexbox/flexbox-basic-iframe-vert-1.xhtml
@@ -5,17 +5,17 @@
 -->
 <!--
      This test checks that iframe elements behave correctly as flex items.
 -->
 <html xmlns="http://www.w3.org/1999/xhtml">
   <head>
     <title>CSS Test: Testing flexbox layout algorithm property on iframe flex items in a vertical flex container</title>
     <link rel="author" title="Daniel Holbert" href="mailto:dholbert@mozilla.com"/>
-    <link rel="help" href="http://www.w3.org/TR/css3-flexbox/#layout-algorithm"/>
+    <link rel="help" href="http://www.w3.org/TR/css-flexbox-1/#layout-algorithm"/>
     <link rel="match" href="flexbox-basic-iframe-vert-1-ref.xhtml"/>
     <style>
       div.flexbox {
         height: 200px;
         background: lightgreen;
         display: flex;
         justify-content: space-between;
         flex-direction: column;
--- a/layout/reftests/w3c-css/submitted/flexbox/flexbox-basic-img-horiz-1.xhtml
+++ b/layout/reftests/w3c-css/submitted/flexbox/flexbox-basic-img-horiz-1.xhtml
@@ -5,17 +5,17 @@
 -->
 <!--
      This test checks that img elements behave correctly as flex items.
 -->
 <html xmlns="http://www.w3.org/1999/xhtml">
   <head>
     <title>CSS Test: Testing flexbox layout algorithm property on img flex items in a horizontal flex container</title>
     <link rel="author" title="Daniel Holbert" href="mailto:dholbert@mozilla.com"/>
-    <link rel="help" href="http://www.w3.org/TR/css3-flexbox/#layout-algorithm"/>
+    <link rel="help" href="http://www.w3.org/TR/css-flexbox-1/#layout-algorithm"/>
     <link rel="match" href="flexbox-basic-img-horiz-1-ref.xhtml"/>
     <style>
       div.flexbox {
         width: 200px;
         background: lightgreen;
         display: flex;
         justify-content: space-between;
         margin-bottom: 5px;
--- a/layout/reftests/w3c-css/submitted/flexbox/flexbox-basic-img-vert-1.xhtml
+++ b/layout/reftests/w3c-css/submitted/flexbox/flexbox-basic-img-vert-1.xhtml
@@ -5,17 +5,17 @@
 -->
 <!--
      This test checks that img elements behave correctly as flex items.
 -->
 <html xmlns="http://www.w3.org/1999/xhtml">
   <head>
     <title>CSS Test: Testing flexbox layout algorithm property on img flex items in a vertical flex container</title>
     <link rel="author" title="Daniel Holbert" href="mailto:dholbert@mozilla.com"/>
-    <link rel="help" href="http://www.w3.org/TR/css3-flexbox/#layout-algorithm"/>
+    <link rel="help" href="http://www.w3.org/TR/css-flexbox-1/#layout-algorithm"/>
     <link rel="match" href="flexbox-basic-img-vert-1-ref.xhtml"/>
     <style>
       div.flexbox {
         height: 200px;
         background: lightgreen;
         display: flex;
         justify-content: space-between;
         flex-direction: column;
--- a/layout/reftests/w3c-css/submitted/flexbox/flexbox-basic-textarea-horiz-1.xhtml
+++ b/layout/reftests/w3c-css/submitted/flexbox/flexbox-basic-textarea-horiz-1.xhtml
@@ -5,17 +5,17 @@
 -->
 <!--
      This test checks that textarea elements behave correctly as flex items.
 -->
 <html xmlns="http://www.w3.org/1999/xhtml">
   <head>
     <title>CSS Test: Testing flexbox layout algorithm property on textarea flex items in a horizontal flex container</title>
     <link rel="author" title="Daniel Holbert" href="mailto:dholbert@mozilla.com"/>
-    <link rel="help" href="http://www.w3.org/TR/css3-flexbox/#layout-algorithm"/>
+    <link rel="help" href="http://www.w3.org/TR/css-flexbox-1/#layout-algorithm"/>
     <link rel="match" href="flexbox-basic-textarea-horiz-1-ref.xhtml"/>
     <style>
       div.flexbox {
         width: 200px;
         background: lightgreen;
         display: flex;
         justify-content: space-between;
         margin-bottom: 5px;
--- a/layout/reftests/w3c-css/submitted/flexbox/flexbox-basic-textarea-vert-1.xhtml
+++ b/layout/reftests/w3c-css/submitted/flexbox/flexbox-basic-textarea-vert-1.xhtml
@@ -5,17 +5,17 @@
 -->
 <!--
      This test checks that textarea elements behave correctly as flex items.
 -->
 <html xmlns="http://www.w3.org/1999/xhtml">
   <head>
     <title>CSS Test: Testing flexbox layout algorithm property on textarea flex items in a vertical flex container</title>
     <link rel="author" title="Daniel Holbert" href="mailto:dholbert@mozilla.com"/>
-    <link rel="help" href="http://www.w3.org/TR/css3-flexbox/#layout-algorithm"/>
+    <link rel="help" href="http://www.w3.org/TR/css-flexbox-1/#layout-algorithm"/>
     <link rel="match" href="flexbox-basic-textarea-vert-1-ref.xhtml"/>
     <style>
       div.flexbox {
         height: 200px;
         background: lightgreen;
         display: flex;
         justify-content: space-between;
         flex-direction: column;
--- a/layout/reftests/w3c-css/submitted/flexbox/flexbox-basic-video-horiz-1.xhtml
+++ b/layout/reftests/w3c-css/submitted/flexbox/flexbox-basic-video-horiz-1.xhtml
@@ -5,17 +5,17 @@
 -->
 <!--
      This test checks that video elements behave correctly as flex items.
 -->
 <html xmlns="http://www.w3.org/1999/xhtml">
   <head>
     <title>CSS Test: Testing flexbox layout algorithm property on video flex items in a horizontal flex container</title>
     <link rel="author" title="Daniel Holbert" href="mailto:dholbert@mozilla.com"/>
-    <link rel="help" href="http://www.w3.org/TR/css3-flexbox/#layout-algorithm"/>
+    <link rel="help" href="http://www.w3.org/TR/css-flexbox-1/#layout-algorithm"/>
     <link rel="match" href="flexbox-basic-video-horiz-1-ref.xhtml"/>
     <style>
       div.flexbox {
         width: 200px;
         background: lightgreen;
         display: flex;
         justify-content: space-between;
         margin-bottom: 5px;
--- a/layout/reftests/w3c-css/submitted/flexbox/flexbox-basic-video-vert-1.xhtml
+++ b/layout/reftests/w3c-css/submitted/flexbox/flexbox-basic-video-vert-1.xhtml
@@ -5,17 +5,17 @@
 -->
 <!--
      This test checks that video elements behave correctly as flex items.
 -->
 <html xmlns="http://www.w3.org/1999/xhtml">
   <head>
     <title>CSS Test: Testing flexbox layout algorithm property on video flex items in a vertical flex container</title>
     <link rel="author" title="Daniel Holbert" href="mailto:dholbert@mozilla.com"/>
-    <link rel="help" href="http://www.w3.org/TR/css3-flexbox/#layout-algorithm"/>
+    <link rel="help" href="http://www.w3.org/TR/css-flexbox-1/#layout-algorithm"/>
     <link rel="match" href="flexbox-basic-video-vert-1-ref.xhtml"/>
     <style>
       div.flexbox {
         height: 200px;
         background: lightgreen;
         display: flex;
         justify-content: space-between;
         flex-direction: column;
--- a/layout/reftests/w3c-css/submitted/flexbox/flexbox-break-request-horiz-1a.html
+++ b/layout/reftests/w3c-css/submitted/flexbox/flexbox-break-request-horiz-1a.html
@@ -2,17 +2,17 @@
 <!--
      Any copyright is dedicated to the Public Domain.
      http://creativecommons.org/publicdomain/zero/1.0/
 -->
 <html>
 <head>
   <title>CSS Test: Testing page-break-before in horizontal multi-line flex containers</title>
   <link rel="author" title="Daniel Holbert" href="mailto:dholbert@mozilla.com">
-  <link rel="help" href="http://www.w3.org/TR/css3-flexbox/#algo-line-break">
+  <link rel="help" href="http://www.w3.org/TR/css-flexbox-1/#algo-line-break">
   <link rel="match" href="flexbox-break-request-horiz-1-ref.html">
   <meta charset="utf-8">
   <style>
     div.flexbox {
       display: flex;
       flex-wrap: wrap;
       border: 1px dashed black;
       width: 60px;
--- a/layout/reftests/w3c-css/submitted/flexbox/flexbox-break-request-horiz-1b.html
+++ b/layout/reftests/w3c-css/submitted/flexbox/flexbox-break-request-horiz-1b.html
@@ -2,17 +2,17 @@
 <!--
      Any copyright is dedicated to the Public Domain.
      http://creativecommons.org/publicdomain/zero/1.0/
 -->
 <html>
 <head>
   <title>CSS Test: Testing page-break-after in horizontal multi-line flex containers</title>
   <link rel="author" title="Daniel Holbert" href="mailto:dholbert@mozilla.com">
-  <link rel="help" href="http://www.w3.org/TR/css3-flexbox/#algo-line-break">
+  <link rel="help" href="http://www.w3.org/TR/css-flexbox-1/#algo-line-break">
   <link rel="match" href="flexbox-break-request-horiz-1-ref.html">
   <meta charset="utf-8">
   <style>
     div.flexbox {
       display: flex;
       flex-wrap: wrap;
       border: 1px dashed black;
       width: 60px;
--- a/layout/reftests/w3c-css/submitted/flexbox/flexbox-break-request-horiz-2a.html
+++ b/layout/reftests/w3c-css/submitted/flexbox/flexbox-break-request-horiz-2a.html
@@ -2,17 +2,17 @@
 <!--
      Any copyright is dedicated to the Public Domain.
      http://creativecommons.org/publicdomain/zero/1.0/
 -->
 <html>
 <head>
   <title>CSS Test: Testing page-break-before in horizontal single-line flex containers (should have no effect)</title>
   <link rel="author" title="Daniel Holbert" href="mailto:dholbert@mozilla.com">
-  <link rel="help" href="http://www.w3.org/TR/css3-flexbox/#algo-line-break">
+  <link rel="help" href="http://www.w3.org/TR/css-flexbox-1/#algo-line-break">
   <link rel="match" href="flexbox-break-request-horiz-2-ref.html">
   <meta charset="utf-8">
   <style>
     div.flexbox {
       display: flex;
       border: 1px dashed black;
       width: 60px;
       height: 20px;
--- a/layout/reftests/w3c-css/submitted/flexbox/flexbox-break-request-horiz-2b.html
+++ b/layout/reftests/w3c-css/submitted/flexbox/flexbox-break-request-horiz-2b.html
@@ -2,17 +2,17 @@
 <!--
      Any copyright is dedicated to the Public Domain.
      http://creativecommons.org/publicdomain/zero/1.0/
 -->
 <html>
 <head>
   <title>CSS Test: Testing page-break-after in horizontal single-line flex containers (should have no effect)</title>
   <link rel="author" title="Daniel Holbert" href="mailto:dholbert@mozilla.com">
-  <link rel="help" href="http://www.w3.org/TR/css3-flexbox/#algo-line-break">
+  <link rel="help" href="http://www.w3.org/TR/css-flexbox-1/#algo-line-break">
   <link rel="match" href="flexbox-break-request-horiz-2-ref.html">
   <meta charset="utf-8">
   <style>
     div.flexbox {
       display: flex;
       border: 1px dashed black;
       width: 60px;
       height: 20px;
--- a/layout/reftests/w3c-css/submitted/flexbox/flexbox-break-request-vert-1a.html
+++ b/layout/reftests/w3c-css/submitted/flexbox/flexbox-break-request-vert-1a.html
@@ -2,17 +2,17 @@
 <!--
      Any copyright is dedicated to the Public Domain.
      http://creativecommons.org/publicdomain/zero/1.0/
 -->
 <html>
 <head>
   <title>CSS Test: Testing page-break-before in vertical multi-line flex containers</title>
   <link rel="author" title="Daniel Holbert" href="mailto:dholbert@mozilla.com">
-  <link rel="help" href="http://www.w3.org/TR/css3-flexbox/#algo-line-break">
+  <link rel="help" href="http://www.w3.org/TR/css-flexbox-1/#algo-line-break">
   <link rel="match" href="flexbox-break-request-vert-1-ref.html">
   <meta charset="utf-8">
   <style>
     div.flexbox {
       display: flex;
       flex-direction: column;
       flex-wrap: wrap;
       border: 1px dashed black;
--- a/layout/reftests/w3c-css/submitted/flexbox/flexbox-break-request-vert-1b.html
+++ b/layout/reftests/w3c-css/submitted/flexbox/flexbox-break-request-vert-1b.html
@@ -2,17 +2,17 @@
 <!--
      Any copyright is dedicated to the Public Domain.
      http://creativecommons.org/publicdomain/zero/1.0/
 -->
 <html>
 <head>
   <title>CSS Test: Testing page-break-after in vertical multi-line flex containers</title>
   <link rel="author" title="Daniel Holbert" href="mailto:dholbert@mozilla.com">
-  <link rel="help" href="http://www.w3.org/TR/css3-flexbox/#algo-line-break">
+  <link rel="help" href="http://www.w3.org/TR/css-flexbox-1/#algo-line-break">
   <link rel="match" href="flexbox-break-request-vert-1-ref.html">
   <meta charset="utf-8">
   <style>
     div.flexbox {
       display: flex;
       flex-direction: column;
       flex-wrap: wrap;
       border: 1px dashed black;
--- a/layout/reftests/w3c-css/submitted/flexbox/flexbox-break-request-vert-2a.html
+++ b/layout/reftests/w3c-css/submitted/flexbox/flexbox-break-request-vert-2a.html
@@ -2,17 +2,17 @@
 <!--
      Any copyright is dedicated to the Public Domain.
      http://creativecommons.org/publicdomain/zero/1.0/
 -->
 <html>
 <head>
   <title>CSS Test: Testing page-break-before in vertical single-line flex containers (should have no effect)</title>
   <link rel="author" title="Daniel Holbert" href="mailto:dholbert@mozilla.com">
-  <link rel="help" href="http://www.w3.org/TR/css3-flexbox/#algo-line-break">
+  <link rel="help" href="http://www.w3.org/TR/css-flexbox-1/#algo-line-break">
   <link rel="match" href="flexbox-break-request-vert-2-ref.html">
   <meta charset="utf-8">
   <style>
     div.flexbox {
       display: flex;
       flex-direction: column;
       border: 1px dashed black;
       width: 20px;
--- a/layout/reftests/w3c-css/submitted/flexbox/flexbox-break-request-vert-2b.html
+++ b/layout/reftests/w3c-css/submitted/flexbox/flexbox-break-request-vert-2b.html
@@ -2,17 +2,17 @@
 <!--
      Any copyright is dedicated to the Public Domain.
      http://creativecommons.org/publicdomain/zero/1.0/
 -->
 <html>
 <head>
   <title>CSS Test: Testing page-break-after in vertical single-line flex containers (should have no effect)</title>
   <link rel="author" title="Daniel Holbert" href="mailto:dholbert@mozilla.com">
-  <link rel="help" href="http://www.w3.org/TR/css3-flexbox/#algo-line-break">
+  <link rel="help" href="http://www.w3.org/TR/css-flexbox-1/#algo-line-break">
   <link rel="match" href="flexbox-break-request-vert-2-ref.html">
   <meta charset="utf-8">
   <style>
     div.flexbox {
       display: flex;
       flex-direction: column;
       border: 1px dashed black;
       width: 20px;
--- a/layout/reftests/w3c-css/submitted/flexbox/flexbox-collapsed-item-baseline-1.html
+++ b/layout/reftests/w3c-css/submitted/flexbox/flexbox-collapsed-item-baseline-1.html
@@ -2,17 +2,17 @@
 <!--
      Any copyright is dedicated to the Public Domain.
      http://creativecommons.org/publicdomain/zero/1.0/
 -->
 <html>
 <head>
   <title>CSS Test: Testing that a collapsed flex item participates in baseline alignment only for the purpose of establishing container's cross size</title>
   <link rel="author" title="Daniel Holbert" href="mailto:dholbert@mozilla.com">
-  <link rel="help" href="http://www.w3.org/TR/css3-flexbox/#algo-visibility">
+  <link rel="help" href="http://www.w3.org/TR/css-flexbox-1/#algo-visibility">
   <link rel="match" href="flexbox-collapsed-item-baseline-1-ref.html">
   <meta charset="utf-8">
   <style>
     .flexContainer {
       display: flex;
       width: 50px;
       background: yellow;
       border: 1px dotted black;
--- a/layout/reftests/w3c-css/submitted/flexbox/flexbox-collapsed-item-horiz-1.html
+++ b/layout/reftests/w3c-css/submitted/flexbox/flexbox-collapsed-item-horiz-1.html
@@ -2,17 +2,17 @@
 <!--
      Any copyright is dedicated to the Public Domain.
      http://creativecommons.org/publicdomain/zero/1.0/
 -->
 <html>
 <head>
   <title>CSS Test: Testing that visibility:collapse on a flex item in a single-line flex container maintains the containers's cross size, but doesn't otherwise impact flex layout</title>
   <link rel="author" title="Daniel Holbert" href="mailto:dholbert@mozilla.com">
-  <link rel="help" href="http://www.w3.org/TR/css3-flexbox/#algo-visibility">
+  <link rel="help" href="http://www.w3.org/TR/css-flexbox-1/#algo-visibility">
   <link rel="match" href="flexbox-collapsed-item-horiz-1-ref.html">
   <meta charset="utf-8">
   <style>
     .flexContainer {
       display: flex;
       background: yellow;
       border: 1px dotted black;
       float: left;
--- a/layout/reftests/w3c-css/submitted/flexbox/flexbox-collapsed-item-horiz-2.html
+++ b/layout/reftests/w3c-css/submitted/flexbox/flexbox-collapsed-item-horiz-2.html
@@ -2,17 +2,17 @@
 <!--
      Any copyright is dedicated to the Public Domain.
      http://creativecommons.org/publicdomain/zero/1.0/
 -->
 <html>
 <head>
   <title>CSS Test: Testing that visibility:collapse on a flex item in a multi-line flex container creates struts, and that they can migrate between lines</title>
   <link rel="author" title="Daniel Holbert" href="mailto:dholbert@mozilla.com">
-  <link rel="help" href="http://www.w3.org/TR/css3-flexbox/#algo-visibility">
+  <link rel="help" href="http://www.w3.org/TR/css-flexbox-1/#algo-visibility">
   <link rel="match" href="flexbox-collapsed-item-horiz-2-ref.html">
   <meta charset="utf-8">
   <style>
     .flexContainer {
       display: flex;
       flex-wrap: wrap;
 
       /* These let us show where each flex line begins (and hence, how tall
--- a/layout/reftests/w3c-css/submitted/flexbox/flexbox-collapsed-item-horiz-3.html
+++ b/layout/reftests/w3c-css/submitted/flexbox/flexbox-collapsed-item-horiz-3.html
@@ -2,17 +2,17 @@
 <!--
      Any copyright is dedicated to the Public Domain.
      http://creativecommons.org/publicdomain/zero/1.0/
 -->
 <html>
 <head>
   <title>CSS Test: Testing that strut formation (from visibility:collapse) happens *after* lines have been stretched</title>
   <link rel="author" title="Daniel Holbert" href="mailto:dholbert@mozilla.com">
-  <link rel="help" href="http://www.w3.org/TR/css3-flexbox/#algo-visibility">
+  <link rel="help" href="http://www.w3.org/TR/css-flexbox-1/#algo-visibility">
   <link rel="match" href="flexbox-collapsed-item-horiz-3-ref.html">
   <meta charset="utf-8">
   <style>
     .flexContainer {
       display: flex;
       flex-wrap: wrap;
       align-content: stretch; /* Initial value; just here for emphasis */
       width: 25px;
--- a/layout/reftests/w3c-css/submitted/flexbox/flexbox-flex-flow-1.html
+++ b/layout/reftests/w3c-css/submitted/flexbox/flexbox-flex-flow-1.html
@@ -2,17 +2,17 @@
 <!--
      Any copyright is dedicated to the Public Domain.
      http://creativecommons.org/publicdomain/zero/1.0/
 -->
 <html>
 <head>
   <title>CSS Test: Testing all the values of the "flex-flow" shorthand property, with 4 flex items in each container</title>
   <link rel="author" title="Daniel Holbert" href="mailto:dholbert@mozilla.com">
-  <link rel="help" href="http://www.w3.org/TR/css3-flexbox/#flex-flow-property">
+  <link rel="help" href="http://www.w3.org/TR/css-flexbox-1/#flex-flow-property">
   <link rel="match" href="flexbox-flex-flow-1-ref.html">
   <meta charset="utf-8">
   <style>
     .flexContainer {
       display: flex;
       height: 60px;
       width: 60px;
       font: 10px sans-serif;
--- a/layout/reftests/w3c-css/submitted/flexbox/flexbox-flex-flow-2.html
+++ b/layout/reftests/w3c-css/submitted/flexbox/flexbox-flex-flow-2.html
@@ -2,17 +2,17 @@
 <!--
      Any copyright is dedicated to the Public Domain.
      http://creativecommons.org/publicdomain/zero/1.0/
 -->
 <html>
 <head>
   <title>CSS Test: Testing all the values of the "flex-flow" shorthand property, with 3 flex items in each container</title>
   <link rel="author" title="Daniel Holbert" href="mailto:dholbert@mozilla.com">
-  <link rel="help" href="http://www.w3.org/TR/css3-flexbox/#flex-flow-property">
+  <link rel="help" href="http://www.w3.org/TR/css-flexbox-1/#flex-flow-property">
   <link rel="match" href="flexbox-flex-flow-2-ref.html">
   <meta charset="utf-8">
   <style>
     .flexContainer {
       display: flex;
       height: 60px;
       width: 60px;
       font: 10px sans-serif;
--- a/layout/reftests/w3c-css/submitted/flexbox/flexbox-flex-wrap-horiz-1.html
+++ b/layout/reftests/w3c-css/submitted/flexbox/flexbox-flex-wrap-horiz-1.html
@@ -2,17 +2,17 @@
 <!--
      Any copyright is dedicated to the Public Domain.
      http://creativecommons.org/publicdomain/zero/1.0/
 -->
 <html>
 <head>
   <title>CSS Test: Testing flex-wrap in horizontal flex containers</title>
   <link rel="author" title="Daniel Holbert" href="mailto:dholbert@mozilla.com">
-  <link rel="help" href="http://www.w3.org/TR/css3-flexbox/#flex-wrap-property">
+  <link rel="help" href="http://www.w3.org/TR/css-flexbox-1/#flex-wrap-property">
   <link rel="match" href="flexbox-flex-wrap-horiz-1-ref.html">
   <meta charset="utf-8">
   <style>
     div.flexbox {
       display: flex;
       flex-wrap: wrap;
       border: 1px dashed black;
       width: 100px;
--- a/layout/reftests/w3c-css/submitted/flexbox/flexbox-flex-wrap-horiz-2.html
+++ b/layout/reftests/w3c-css/submitted/flexbox/flexbox-flex-wrap-horiz-2.html
@@ -2,17 +2,17 @@
 <!--
      Any copyright is dedicated to the Public Domain.
      http://creativecommons.org/publicdomain/zero/1.0/
 -->
 <html>
 <head>
   <title>CSS Test: Ensure that min-width is honored for horizontal multi-line flex containers</title>
   <link rel="author" title="Daniel Holbert" href="mailto:dholbert@mozilla.com">
-  <link rel="help" href="http://www.w3.org/TR/css3-flexbox/#flex-wrap-property">
+  <link rel="help" href="http://www.w3.org/TR/css-flexbox-1/#flex-wrap-property">
   <link rel="match" href="flexbox-flex-wrap-horiz-2-ref.html">
   <meta charset="utf-8">
   <style>
     div.flexbox {
       display: flex;
       flex-wrap: wrap;
       border: 1px dashed black;
       min-width: 100px;
--- a/layout/reftests/w3c-css/submitted/flexbox/flexbox-flex-wrap-vert-1.html
+++ b/layout/reftests/w3c-css/submitted/flexbox/flexbox-flex-wrap-vert-1.html
@@ -2,17 +2,17 @@
 <!--
      Any copyright is dedicated to the Public Domain.
      http://creativecommons.org/publicdomain/zero/1.0/
 -->
 <html>
 <head>
   <title>CSS Test: Testing flex-wrap in vertical flex containers</title>
   <link rel="author" title="Daniel Holbert" href="mailto:dholbert@mozilla.com">
-  <link rel="help" href="http://www.w3.org/TR/css3-flexbox/#flex-wrap-property">
+  <link rel="help" href="http://www.w3.org/TR/css-flexbox-1/#flex-wrap-property">
   <link rel="match" href="flexbox-flex-wrap-vert-1-ref.html">
   <meta charset="utf-8">
   <style>
     div.flexbox {
       display: flex;
       flex-direction: column;
       flex-wrap: wrap;
       border: 1px dashed black;
--- a/layout/reftests/w3c-css/submitted/flexbox/flexbox-flex-wrap-vert-2.html
+++ b/layout/reftests/w3c-css/submitted/flexbox/flexbox-flex-wrap-vert-2.html
@@ -2,17 +2,17 @@
 <!--
      Any copyright is dedicated to the Public Domain.
      http://creativecommons.org/publicdomain/zero/1.0/
 -->
 <html>
 <head>
   <title>CSS Test: Ensure that min-height is honored for vertical multi-line flex containers</title>
   <link rel="author" title="Daniel Holbert" href="mailto:dholbert@mozilla.com">
-  <link rel="help" href="http://www.w3.org/TR/css3-flexbox/#flex-wrap-property">
+  <link rel="help" href="http://www.w3.org/TR/css-flexbox-1/#flex-wrap-property">
   <link rel="match" href="flexbox-flex-wrap-vert-2-ref.html">
   <meta charset="utf-8">
   <style>
     div.flexbox {
       display: flex;
       flex-direction: column;
       flex-wrap: wrap;
       border: 1px dashed black;
--- a/layout/reftests/w3c-css/submitted/flexbox/flexbox-items-as-stacking-contexts-1.xhtml
+++ b/layout/reftests/w3c-css/submitted/flexbox/flexbox-items-as-stacking-contexts-1.xhtml
@@ -5,17 +5,17 @@
 -->
 <!-- Testcase with flex items containing overlapping content, with
      "z-index" set on some of them, which should make them create
      stacking contexts. -->
 <html xmlns="http://www.w3.org/1999/xhtml">
   <head>
     <title>CSS Test: Testing that 'z-index' property makes flex items form stacking contexts</title>
     <link rel="author" title="Daniel Holbert" href="mailto:dholbert@mozilla.com"/>
-    <link rel="help" href="http://www.w3.org/TR/css3-flexbox/#painting"/>
+    <link rel="help" href="http://www.w3.org/TR/css-flexbox-1/#painting"/>
     <link rel="match" href="flexbox-items-as-stacking-contexts-1-ref.xhtml"/>
     <style>
       .flexbox {
         width: 90px;
         height: 10px;
         border: 2px solid gray;
         display: flex;
         margin-bottom: 10px;
--- a/layout/reftests/w3c-css/submitted/flexbox/flexbox-items-as-stacking-contexts-2.html
+++ b/layout/reftests/w3c-css/submitted/flexbox/flexbox-items-as-stacking-contexts-2.html
@@ -13,17 +13,17 @@
      "order" on flex items.
  -->
 <!-- This was resolved by the CSSWG in April 2013:
      http://krijnhoetmer.nl/irc-logs/css/20130403#l-455 -->
 <html>
 <head>
   <title>CSS Test: Testing that flex items paint as pseudo-stacking contexts (like inline-blocks): atomically, in the absence of 'z-index' on descendants</title>
   <link rel="author" title="Daniel Holbert" href="mailto:dholbert@mozilla.com">
-  <link rel="help" href="http://www.w3.org/TR/css3-flexbox/#painting">
+  <link rel="help" href="http://www.w3.org/TR/css-flexbox-1/#painting">
   <link rel="match" href="flexbox-items-as-stacking-contexts-2-ref.html">
   <style>
     body { font: 10px sans-serif }
     .flexContainer {
       background: orange;
       display: flex;
       justify-content: space-between;
       width: 70px;
--- a/layout/reftests/w3c-css/submitted/flexbox/flexbox-items-as-stacking-contexts-3.html
+++ b/layout/reftests/w3c-css/submitted/flexbox/flexbox-items-as-stacking-contexts-3.html
@@ -9,17 +9,17 @@
      content in another flex item, if we set appropriately interleaving
      "z-index" values. -->
 <!-- This was resolved by the CSSWG in April 2013:
      http://krijnhoetmer.nl/irc-logs/css/20130403#l-455 -->
 <html>
 <head>
   <title>CSS Test: Testing that flex items paint as pseudo-stacking contexts (like inline-blocks), instead of full stacking contexts: 'z-index' should let descendants interleave</title>
   <link rel="author" title="Daniel Holbert" href="mailto:dholbert@mozilla.com">
-  <link rel="help" href="http://www.w3.org/TR/css3-flexbox/#painting">
+  <link rel="help" href="http://www.w3.org/TR/css-flexbox-1/#painting">
   <link rel="match" href="flexbox-items-as-stacking-contexts-3-ref.html">
   <style>
     .flexContainer {
       background: orange;
       display: flex;
       justify-content: space-between;
       width: 70px;
       height: 20px;
--- a/layout/reftests/w3c-css/submitted/flexbox/flexbox-justify-content-horiz-1a.xhtml
+++ b/layout/reftests/w3c-css/submitted/flexbox/flexbox-justify-content-horiz-1a.xhtml
@@ -4,17 +4,17 @@
      http://creativecommons.org/publicdomain/zero/1.0/
 -->
 <!-- Testcase with a series of horizontal flex containers, testing each
      possible value of the 'justify-content' property. -->
 <html xmlns="http://www.w3.org/1999/xhtml">
   <head>
     <title>CSS Test: Testing 'justify-content' in a horizontal flex container</title>
     <link rel="author" title="Daniel Holbert" href="mailto:dholbert@mozilla.com"/>
-    <link rel="help" href="http://www.w3.org/TR/css3-flexbox/#justify-content-property"/>
+    <link rel="help" href="http://www.w3.org/TR/css-flexbox-1/#justify-content-property"/>
     <link rel="match" href="flexbox-justify-content-horiz-1-ref.xhtml"/>
     <style>
       div.flexbox {
         width: 200px;
         display: flex;
         margin-bottom: 2px;
       }
       div.a {
--- a/layout/reftests/w3c-css/submitted/flexbox/flexbox-justify-content-horiz-1b.xhtml
+++ b/layout/reftests/w3c-css/submitted/flexbox/flexbox-justify-content-horiz-1b.xhtml
@@ -5,17 +5,17 @@
 -->
 <!-- Testcase with a series of horizontal flex containers, testing each
      possible value of the 'justify-content' property. The flex containers'
      widths are determined by their "min-width" property. -->
 <html xmlns="http://www.w3.org/1999/xhtml">
   <head>
     <title>CSS Test: Testing 'justify-content' in a horizontal flex container with "min-width"</title>
     <link rel="author" title="Daniel Holbert" href="mailto:dholbert@mozilla.com"/>
-    <link rel="help" href="http://www.w3.org/TR/css3-flexbox/#justify-content-property"/>
+    <link rel="help" href="http://www.w3.org/TR/css-flexbox-1/#justify-content-property"/>
     <link rel="match" href="flexbox-justify-content-horiz-1-ref.xhtml"/>
     <style>
       div.flexbox {
         min-width: 200px;
         display: flex;
         margin-bottom: 2px;
 
         /* Use "float" to trigger intrinsic sizing, which in this case will
--- a/layout/reftests/w3c-css/submitted/flexbox/flexbox-justify-content-horiz-2.xhtml
+++ b/layout/reftests/w3c-css/submitted/flexbox/flexbox-justify-content-horiz-2.xhtml
@@ -5,17 +5,17 @@
 -->
 <!-- Testcase with a series of flex containers testing each possible value of
      the 'justify-content' property, with margin/border/padding on the
      flex items. -->
 <html xmlns="http://www.w3.org/1999/xhtml">
   <head>
     <title>CSS Test: Testing 'justify-content' in a horizontal flex container, with margins/border/padding on flex items</title>
     <link rel="author" title="Daniel Holbert" href="mailto:dholbert@mozilla.com"/>
-    <link rel="help" href="http://www.w3.org/TR/css3-flexbox/#justify-content-property"/>
+    <link rel="help" href="http://www.w3.org/TR/css-flexbox-1/#justify-content-property"/>
     <link rel="match" href="flexbox-justify-content-horiz-2-ref.xhtml"/>
     <style>
       div.flexbox {
         width: 200px;
         display: flex;
         margin-bottom: 4px;
         border: 1px dotted black;
       }
--- a/layout/reftests/w3c-css/submitted/flexbox/flexbox-justify-content-horiz-3.xhtml
+++ b/layout/reftests/w3c-css/submitted/flexbox/flexbox-justify-content-horiz-3.xhtml
@@ -11,17 +11,17 @@
          (right) side.
        * For 'flex-end', we should overflow on the start (left) side.
        * For 'center'/'space-around', we should overflow equally on both sides.
 -->
 <html xmlns="http://www.w3.org/1999/xhtml">
   <head>
     <title>CSS Test: Testing 'justify-content' in a horizontal flex container, and its effects on flex items that overflow</title>
     <link rel="author" title="Daniel Holbert" href="mailto:dholbert@mozilla.com"/>
-    <link rel="help" href="http://www.w3.org/TR/css3-flexbox/#justify-content-property"/>
+    <link rel="help" href="http://www.w3.org/TR/css-flexbox-1/#justify-content-property"/>
     <link rel="match" href="flexbox-justify-content-horiz-3-ref.xhtml"/>
     <style>
       body { margin-left: 100px; } /* So we can see left-overflowed stuff */
       div.flexbox {
         width: 30px;
         display: flex;
         margin-bottom: 2px;
       }
--- a/layout/reftests/w3c-css/submitted/flexbox/flexbox-justify-content-horiz-4.xhtml
+++ b/layout/reftests/w3c-css/submitted/flexbox/flexbox-justify-content-horiz-4.xhtml
@@ -11,17 +11,17 @@
          (right) side.
        * For 'flex-end', we should overflow on the start (left) side.
        * For 'center'/'space-around', we should overflow equally on both sides.
 -->
 <html xmlns="http://www.w3.org/1999/xhtml">
   <head>
     <title>CSS Test: Testing 'justify-content' in a horizontal flex container, and its effects on flex items that overflow, with margins/border/padding on flex items</title>
     <link rel="author" title="Daniel Holbert" href="mailto:dholbert@mozilla.com"/>
-    <link rel="help" href="http://www.w3.org/TR/css3-flexbox/#justify-content-property"/>
+    <link rel="help" href="http://www.w3.org/TR/css-flexbox-1/#justify-content-property"/>
     <link rel="match" href="flexbox-justify-content-horiz-4-ref.xhtml"/>
     <style>
       body { margin-left: 100px; } /* So we can see left-overflowed stuff */
       div.flexbox {
         width: 30px;
         display: flex;
         margin-bottom: 4px;
       }
--- a/layout/reftests/w3c-css/submitted/flexbox/flexbox-justify-content-horiz-5.xhtml
+++ b/layout/reftests/w3c-css/submitted/flexbox/flexbox-justify-content-horiz-5.xhtml
@@ -4,17 +4,17 @@
      http://creativecommons.org/publicdomain/zero/1.0/
 -->
 <!-- Testcase to exercise each possible value of the 'justify-content'
      property, in an auto-sized horizontal flex container. -->
 <html xmlns="http://www.w3.org/1999/xhtml">
   <head>
     <title>CSS Test: Testing 'justify-content' in an auto-sized horizontal flex container</title>
     <link rel="author" title="Daniel Holbert" href="mailto:dholbert@mozilla.com"/>
-    <link rel="help" href="http://www.w3.org/TR/css3-flexbox/#justify-content-property"/>
+    <link rel="help" href="http://www.w3.org/TR/css-flexbox-1/#justify-content-property"/>
     <link rel="match" href="flexbox-justify-content-horiz-5-ref.xhtml"/>
     <style>
       div.flexbox {
         display: flex;
       }
       div.a {
         height: 20px;
         flex: 0 10px;
--- a/layout/reftests/w3c-css/submitted/flexbox/flexbox-justify-content-vert-1a.xhtml
+++ b/layout/reftests/w3c-css/submitted/flexbox/flexbox-justify-content-vert-1a.xhtml
@@ -4,17 +4,17 @@
      http://creativecommons.org/publicdomain/zero/1.0/
 -->
 <!-- Testcase with a series of vertical flex containers, testing each
      possible value of the 'justify-content' property. -->
 <html xmlns="http://www.w3.org/1999/xhtml">
   <head>
     <title>CSS Test: Testing 'justify-content' in a vertical flex container</title>
     <link rel="author" title="Daniel Holbert" href="mailto:dholbert@mozilla.com"/>
-    <link rel="help" href="http://www.w3.org/TR/css3-flexbox/#justify-content-property"/>
+    <link rel="help" href="http://www.w3.org/TR/css-flexbox-1/#justify-content-property"/>
     <link rel="match" href="flexbox-justify-content-vert-1-ref.xhtml"/>
     <style>
       div.flexbox {
         height: 200px;
         display: flex;
         flex-direction: column;
         margin-right: 2px;
         float: left;
--- a/layout/reftests/w3c-css/submitted/flexbox/flexbox-justify-content-vert-1b.xhtml
+++ b/layout/reftests/w3c-css/submitted/flexbox/flexbox-justify-content-vert-1b.xhtml
@@ -5,17 +5,17 @@
 -->
 <!-- Testcase with a series of vertical flex containers, testing each
      possible value of the 'justify-content' property. The flex containers'
      heights are determined by their "min-height" property. -->
 <html xmlns="http://www.w3.org/1999/xhtml">
   <head>
     <title>CSS Test: Testing 'justify-content' in a vertical flex container with "min-height"</title>
     <link rel="author" title="Daniel Holbert" href="mailto:dholbert@mozilla.com"/>
-    <link rel="help" href="http://www.w3.org/TR/css3-flexbox/#justify-content-property"/>
+    <link rel="help" href="http://www.w3.org/TR/css-flexbox-1/#justify-content-property"/>
     <link rel="match" href="flexbox-justify-content-vert-1-ref.xhtml"/>
     <style>
       div.flexbox {
         min-height: 200px;
         display: flex;
         flex-direction: column;
         margin-right: 2px;
         float: left;
--- a/layout/reftests/w3c-css/submitted/flexbox/flexbox-justify-content-vert-2.xhtml
+++ b/layout/reftests/w3c-css/submitted/flexbox/flexbox-justify-content-vert-2.xhtml
@@ -5,17 +5,17 @@
 -->
 <!-- Testcase with a series of flex containers testing each possible value of
      the 'justify-content' property, with margin/border/padding on the
      flex items. -->
 <html xmlns="http://www.w3.org/1999/xhtml">
   <head>
     <title>CSS Test: Testing 'justify-content' in a vertical flex container, with margins/border/padding on flex items</title>
     <link rel="author" title="Daniel Holbert" href="mailto:dholbert@mozilla.com"/>
-    <link rel="help" href="http://www.w3.org/TR/css3-flexbox/#justify-content-property"/>
+    <link rel="help" href="http://www.w3.org/TR/css-flexbox-1/#justify-content-property"/>
     <link rel="match" href="flexbox-justify-content-vert-2-ref.xhtml"/>
     <style>
       div.flexbox {
         height: 200px;
         display: flex;
         flex-direction: column;
         margin-right: 2px;
         float: left;
--- a/layout/reftests/w3c-css/submitted/flexbox/flexbox-justify-content-vert-3.xhtml
+++ b/layout/reftests/w3c-css/submitted/flexbox/flexbox-justify-content-vert-3.xhtml
@@ -12,17 +12,17 @@
          (bottom) side.
        * For 'flex-end', we should overflow on the start (top) side.
        * For 'center'/'space-around', we should overflow equally on both sides.
 -->
 <html xmlns="http://www.w3.org/1999/xhtml">
   <head>
     <title>CSS Test: Testing 'justify-content' in a vertical flex container, and its effects on flex items that overflow</title>
     <link rel="author" title="Daniel Holbert" href="mailto:dholbert@mozilla.com"/>
-    <link rel="help" href="http://www.w3.org/TR/css3-flexbox/#justify-content-property"/>
+    <link rel="help" href="http://www.w3.org/TR/css-flexbox-1/#justify-content-property"/>
     <link rel="match" href="flexbox-justify-content-vert-3-ref.xhtml"/>
     <style>
       body { margin-top: 100px; } /* So we can see top-overflowed stuff */
       div.flexbox {
         height: 30px;
         display: flex;
         flex-direction: column;
         margin-right: 2px;
--- a/layout/reftests/w3c-css/submitted/flexbox/flexbox-justify-content-vert-4.xhtml
+++ b/layout/reftests/w3c-css/submitted/flexbox/flexbox-justify-content-vert-4.xhtml
@@ -12,17 +12,17 @@
          (bottom) side.
        * For 'flex-end', we should overflow on the start (top) side.
        * For 'center'/'space-around', we should overflow equally on both sides.
 -->
 <html xmlns="http://www.w3.org/1999/xhtml">
   <head>
     <title>CSS Test: Testing 'justify-content' in a vertical flex container, and its effects on flex items that overflow, with margins/border/padding on flex items</title>
     <link rel="author" title="Daniel Holbert" href="mailto:dholbert@mozilla.com"/>
-    <link rel="help" href="http://www.w3.org/TR/css3-flexbox/#justify-content-property"/>
+    <link rel="help" href="http://www.w3.org/TR/css-flexbox-1/#justify-content-property"/>
     <link rel="match" href="flexbox-justify-content-vert-4-ref.xhtml"/>
     <style>
       body { margin-top: 100px; } /* So we can see top-overflowed stuff */
       div.flexbox {
         height: 30px;
         display: flex;
         flex-direction: column;
         margin-right: 4px;
--- a/layout/reftests/w3c-css/submitted/flexbox/flexbox-justify-content-vert-5.xhtml
+++ b/layout/reftests/w3c-css/submitted/flexbox/flexbox-justify-content-vert-5.xhtml
@@ -7,17 +7,17 @@
      property, in an auto-sized vertical flex container.  The flex container
      should shrink-wrap its contents' heights, leaving no packing space
      available.  So, the "justify-content" values should have no effect
      in this testcase. -->
 <html xmlns="http://www.w3.org/1999/xhtml">
   <head>
     <title>CSS Test: Testing 'justify-content' in an auto-sized vertical flex container</title>
     <link rel="author" title="Daniel Holbert" href="mailto:dholbert@mozilla.com"/>
-    <link rel="help" href="http://www.w3.org/TR/css3-flexbox/#justify-content-property"/>
+    <link rel="help" href="http://www.w3.org/TR/css-flexbox-1/#justify-content-property"/>
     <link rel="match" href="flexbox-justify-content-vert-5-ref.xhtml"/>
     <style>
       div.flexbox {
         display: flex;
         flex-direction: column;
         margin-right: 2px;
         float: left;
         border: 1px dotted black;
--- a/layout/reftests/w3c-css/submitted/flexbox/flexbox-margin-auto-horiz-1.xhtml
+++ b/layout/reftests/w3c-css/submitted/flexbox/flexbox-margin-auto-horiz-1.xhtml
@@ -4,17 +4,17 @@
      http://creativecommons.org/publicdomain/zero/1.0/
 -->
 <!-- Testcase with a variety of 'display: flex' examples
      with margin-left and/or margin-right set to 'auto'. -->
 <html xmlns="http://www.w3.org/1999/xhtml">
   <head>
     <title>CSS Test: Testing horizontal auto margins on flex items in a horizontal flex container</title>
     <link rel="author" title="Daniel Holbert" href="mailto:dholbert@mozilla.com"/>
-    <link rel="help" href="http://www.w3.org/TR/css3-flexbox/#auto-margins"/>
+    <link rel="help" href="http://www.w3.org/TR/css-flexbox-1/#auto-margins"/>
     <link rel="match" href="flexbox-margin-auto-horiz-1-ref.xhtml"/>
     <style>
       div.flexbox {
         width: 200px;
         height: 20px;
         background: lightgray;
         display: flex;
         margin-bottom: 2px;
--- a/layout/reftests/w3c-css/submitted/flexbox/flexbox-margin-auto-horiz-2.xhtml
+++ b/layout/reftests/w3c-css/submitted/flexbox/flexbox-margin-auto-horiz-2.xhtml
@@ -4,17 +4,17 @@
      http://creativecommons.org/publicdomain/zero/1.0/
 -->
 <!-- Testcase with a variety of 'display: flex' examples
      with margin-top and/or margin-bottom set to 'auto' on flex items. -->
 <html xmlns="http://www.w3.org/1999/xhtml">
   <head>
     <title>CSS Test: Testing vertical auto margins on flex items in a horizontal flex container</title>
     <link rel="author" title="Daniel Holbert" href="mailto:dholbert@mozilla.com"/>
-    <link rel="help" href="http://www.w3.org/TR/css3-flexbox/#auto-margins"/>
+    <link rel="help" href="http://www.w3.org/TR/css-flexbox-1/#auto-margins"/>
     <link rel="match" href="flexbox-margin-auto-horiz-2-ref.xhtml"/>
     <style>
       div.flexbox {
         border: 2px dotted black;
         display: flex;
         margin-bottom: 2px;
         width: 100px;
       }
--- a/layout/reftests/w3c-css/submitted/flexbox/flexbox-mbp-horiz-1-reverse.xhtml
+++ b/layout/reftests/w3c-css/submitted/flexbox/flexbox-mbp-horiz-1-reverse.xhtml
@@ -4,17 +4,17 @@
      http://creativecommons.org/publicdomain/zero/1.0/
 -->
 <!-- Testcase with borders on flex items, and "flex-direction: row-reverse" to
      reverse the flex container's main axis. -->
 <html xmlns="http://www.w3.org/1999/xhtml">
   <head>
     <title>CSS Test: Testing borders on flex items in a row-reverse horizontal flex container</title>
     <link rel="author" title="Daniel Holbert" href="mailto:dholbert@mozilla.com"/>
-    <link rel="help" href="http://www.w3.org/TR/css3-flexbox/#layout-algorithm"/>
+    <link rel="help" href="http://www.w3.org/TR/css-flexbox-1/#layout-algorithm"/>
     <link rel="match" href="flexbox-mbp-horiz-1-reverse-ref.xhtml"/>
     <style>
       div { height: 100px; border: 0; }
       div.flexbox {
         width: 200px;
         font-size: 10px;
         display: flex;
         flex-direction: row-reverse;
--- a/layout/reftests/w3c-css/submitted/flexbox/flexbox-mbp-horiz-1-rtl-reverse.xhtml
+++ b/layout/reftests/w3c-css/submitted/flexbox/flexbox-mbp-horiz-1-rtl-reverse.xhtml
@@ -5,17 +5,17 @@
 -->
 <!-- Testcase with borders on flex items, and "direction: rtl" and
      "flex-direction: row-reverse" to *doubly* reverse the flex container's
      main axis. --> 
 <html xmlns="http://www.w3.org/1999/xhtml">
   <head>
     <title>CSS Test: Testing borders on flex items in a row-reverse horizontal flex container, with 'direction: rtl'</title>
     <link rel="author" title="Daniel Holbert" href="mailto:dholbert@mozilla.com"/>
-    <link rel="help" href="http://www.w3.org/TR/css3-flexbox/#layout-algorithm"/>
+    <link rel="help" href="http://www.w3.org/TR/css-flexbox-1/#layout-algorithm"/>
     <link rel="match" href="flexbox-mbp-horiz-1-ref.xhtml"/>
     <style>
       div { height: 100px; border: 0; }
       div.flexbox {
         width: 200px;
         font-size: 10px;
         display: flex;
         flex-direction: row-reverse;
--- a/layout/reftests/w3c-css/submitted/flexbox/flexbox-mbp-horiz-1-rtl.xhtml
+++ b/layout/reftests/w3c-css/submitted/flexbox/flexbox-mbp-horiz-1-rtl.xhtml
@@ -4,17 +4,17 @@
      http://creativecommons.org/publicdomain/zero/1.0/
 -->
 <!-- Testcase with borders on flex items, and "direction: rtl" to reverse
      the flex container's main axis. -->
 <html xmlns="http://www.w3.org/1999/xhtml">
   <head>
     <title>CSS Test: Testing borders on flex items in a horizontal flex container with 'direction: rtl'</title>
     <link rel="author" title="Daniel Holbert" href="mailto:dholbert@mozilla.com"/>
-    <link rel="help" href="http://www.w3.org/TR/css3-flexbox/#layout-algorithm"/>
+    <link rel="help" href="http://www.w3.org/TR/css-flexbox-1/#layout-algorithm"/>
     <link rel="match" href="flexbox-mbp-horiz-1-reverse-ref.xhtml"/>
     <style>
       div { height: 100px; border: 0; }
       div.flexbox {
         width: 200px;
         font-size: 10px;
         display: flex;
         direction: rtl;
--- a/layout/reftests/w3c-css/submitted/flexbox/flexbox-mbp-horiz-1.xhtml
+++ b/layout/reftests/w3c-css/submitted/flexbox/flexbox-mbp-horiz-1.xhtml
@@ -3,17 +3,17 @@
      Any copyright is dedicated to the Public Domain.
      http://creativecommons.org/publicdomain/zero/1.0/
 -->
 <!-- Testcase with borders on flex items. -->
 <html xmlns="http://www.w3.org/1999/xhtml">
   <head>
     <title>CSS Test: Testing borders on flex items in a horizontal flex container</title>
     <link rel="author" title="Daniel Holbert" href="mailto:dholbert@mozilla.com"/>
-    <link rel="help" href="http://www.w3.org/TR/css3-flexbox/#layout-algorithm"/>
+    <link rel="help" href="http://www.w3.org/TR/css-flexbox-1/#layout-algorithm"/>
     <link rel="match" href="flexbox-mbp-horiz-1-ref.xhtml"/>
     <style>
       div { height: 100px; border: 0; }
       div.flexbox {
         width: 200px;
         font-size: 10px;
         display: flex;
       }
--- a/layout/reftests/w3c-css/submitted/flexbox/flexbox-mbp-horiz-2a.xhtml
+++ b/layout/reftests/w3c-css/submitted/flexbox/flexbox-mbp-horiz-2a.xhtml
@@ -3,17 +3,17 @@
      Any copyright is dedicated to the Public Domain.
      http://creativecommons.org/publicdomain/zero/1.0/
 -->
 <!-- Testcase with margin/border on flex items. -->
 <html xmlns="http://www.w3.org/1999/xhtml">
   <head>
     <title>CSS Test: Testing margins and borders on flex items in a horizontal flex container</title>
     <link rel="author" title="Daniel Holbert" href="mailto:dholbert@mozilla.com"/>
-    <link rel="help" href="http://www.w3.org/TR/css3-flexbox/#layout-algorithm"/>
+    <link rel="help" href="http://www.w3.org/TR/css-flexbox-1/#layout-algorithm"/>
     <link rel="match" href="flexbox-mbp-horiz-2-ref.xhtml"/>
     <style>
       div { height: 100px; border: 0; }
       div.flexbox {
         width: 200px;
         font-size: 10px;
         display: flex;
       }
--- a/layout/reftests/w3c-css/submitted/flexbox/flexbox-mbp-horiz-2b.xhtml
+++ b/layout/reftests/w3c-css/submitted/flexbox/flexbox-mbp-horiz-2b.xhtml
@@ -6,17 +6,17 @@
 <!-- Testcase with margin/border/padding on flex items. (NOTE: This renders
      the same as the "-2a" variant, which lacks padding, because we've
      just replaced some of the "-2a" variant's content-box area with
      padding-box area in this test.) -->
 <html xmlns="http://www.w3.org/1999/xhtml">
   <head>
     <title>CSS Test: Testing margins, borders, and padding on flex items in a horizontal flex container</title>
     <link rel="author" title="Daniel Holbert" href="mailto:dholbert@mozilla.com"/>
-    <link rel="help" href="http://www.w3.org/TR/css3-flexbox/#layout-algorithm"/>
+    <link rel="help" href="http://www.w3.org/TR/css-flexbox-1/#layout-algorithm"/>
     <link rel="match" href="flexbox-mbp-horiz-2-ref.xhtml"/>
     <style>
       div { height: 100px; border: 0; }
       div.flexbox {
         width: 200px;
         font-size: 10px;
         display: flex;
       }
--- a/layout/reftests/w3c-css/submitted/flexbox/flexbox-mbp-horiz-3-reverse.xhtml
+++ b/layout/reftests/w3c-css/submitted/flexbox/flexbox-mbp-horiz-3-reverse.xhtml
@@ -3,17 +3,17 @@
      Any copyright is dedicated to the Public Domain.
      http://creativecommons.org/publicdomain/zero/1.0/
 -->
 <!-- Testcase with border/padding on a row-reverse flex container and on its children -->
 <html xmlns="http://www.w3.org/1999/xhtml">
   <head>
     <title>CSS Test: Testing borders and padding on a row-reverse horizontal flex container and its flex items</title>
     <link rel="author" title="Daniel Holbert" href="mailto:dholbert@mozilla.com"/>
-    <link rel="help" href="http://www.w3.org/TR/css3-flexbox/#layout-algorithm"/>
+    <link rel="help" href="http://www.w3.org/TR/css-flexbox-1/#layout-algorithm"/>
     <link rel="match" href="flexbox-mbp-horiz-3-reverse-ref.xhtml"/>
     <style>
       div { height: 20px; border: 0; }
       div.flexbox {
         width: 200px;
         display: flex;
         flex-direction: row-reverse;
         margin-bottom: 2px;
--- a/layout/reftests/w3c-css/submitted/flexbox/flexbox-mbp-horiz-3.xhtml
+++ b/layout/reftests/w3c-css/submitted/flexbox/flexbox-mbp-horiz-3.xhtml
@@ -3,17 +3,17 @@
      Any copyright is dedicated to the Public Domain.
      http://creativecommons.org/publicdomain/zero/1.0/
 -->
 <!-- Testcase with border/padding on a flex container and on its children -->
 <html xmlns="http://www.w3.org/1999/xhtml">
   <head>
     <title>CSS Test: Testing borders and padding on a horizontal flex container and its flex items</title>
     <link rel="author" title="Daniel Holbert" href="mailto:dholbert@mozilla.com"/>
-    <link rel="help" href="http://www.w3.org/TR/css3-flexbox/#layout-algorithm"/>
+    <link rel="help" href="http://www.w3.org/TR/css-flexbox-1/#layout-algorithm"/>
     <link rel="match" href="flexbox-mbp-horiz-3-ref.xhtml"/>
     <style>
       div { height: 20px; border: 0; }
       div.flexbox {
         width: 200px;
         display: flex;
         margin-bottom: 2px;
       }
--- a/layout/reftests/w3c-css/submitted/flexbox/flexbox-mbp-horiz-4.xhtml
+++ b/layout/reftests/w3c-css/submitted/flexbox/flexbox-mbp-horiz-4.xhtml
@@ -7,17 +7,17 @@
      says that percentage values on padding/margin-top and -bottom should be
      resolved against the flex container's height (not its width, as would
      be the case in a block).
 -->
 <html xmlns="http://www.w3.org/1999/xhtml">
   <head>
     <title>CSS Test: Testing percent-valued padding and margin on flex items</title>
     <link rel="author" title="Daniel Holbert" href="mailto:dholbert@mozilla.com"/>
-    <link rel="help" href="http://www.w3.org/TR/css3-flexbox/#layout-algorithm"/>
+    <link rel="help" href="http://www.w3.org/TR/css-flexbox-1/#layout-algorithm"/>
     <link rel="match" href="flexbox-mbp-horiz-4-ref.xhtml"/>
     <style>
       div { border: 0; }
       div.flexbox {
         width: 200px;
         display: flex;
         margin-bottom: 2px;
         border: 1px dotted black;
--- a/layout/reftests/w3c-css/submitted/flexbox/flexbox-min-height-auto-001.html
+++ b/layout/reftests/w3c-css/submitted/flexbox/flexbox-min-height-auto-001.html
@@ -3,17 +3,17 @@
      Any copyright is dedicated to the Public Domain.
      http://creativecommons.org/publicdomain/zero/1.0/
 -->
 <html>
   <head>
     <meta charset="utf-8">
     <title>CSS Test: Testing min-height:auto</title>
     <link rel="author" title="Daniel Holbert" href="mailto:dholbert@mozilla.com">
-    <link rel="help" href="http://www.w3.org/TR/css3-flexbox/#min-size-auto">
+    <link rel="help" href="http://www.w3.org/TR/css-flexbox-1/#min-size-auto">
     <link rel="match" href="flexbox-min-height-auto-001-ref.html">
 <!--
      This testcase tests the used value of "min-height:auto" (the property's
      initial value) on flex items in a vertical flex container.
 
      It's supposed to resolve to the smallest of:
       a) The used 'flex-basis' (taken from 'height'), if 'flex-basis' is at its
          initial value.
--- a/layout/reftests/w3c-css/submitted/flexbox/flexbox-min-height-auto-002a.html
+++ b/layout/reftests/w3c-css/submitted/flexbox/flexbox-min-height-auto-002a.html
@@ -3,17 +3,17 @@
      Any copyright is dedicated to the Public Domain.
      http://creativecommons.org/publicdomain/zero/1.0/
 -->
 <html>
   <head>
     <meta charset="utf-8">
     <title>CSS Test: Testing min-height:auto</title>
     <link rel="author" title="Daniel Holbert" href="mailto:dholbert@mozilla.com">
-    <link rel="help" href="http://www.w3.org/TR/css3-flexbox/#min-size-auto">
+    <link rel="help" href="http://www.w3.org/TR/css-flexbox-1/#min-size-auto">
     <link rel="match" href="flexbox-min-height-auto-002-ref.html">
 <!--
      This testcase tests the used value of "min-height:auto" (the property's
      initial value) on flex items in a vertical flex container.
 
      It's supposed to resolve to the smallest of:
       a) The used 'flex-basis' (taken from 'height'), if 'flex-basis' is at its
          initial value.
--- a/layout/reftests/w3c-css/submitted/flexbox/flexbox-min-height-auto-002b.html
+++ b/layout/reftests/w3c-css/submitted/flexbox/flexbox-min-height-auto-002b.html
@@ -3,17 +3,17 @@
      Any copyright is dedicated to the Public Domain.
      http://creativecommons.org/publicdomain/zero/1.0/
 -->
 <html>
   <head>
     <meta charset="utf-8">
     <title>CSS Test: Testing min-height:auto</title>
     <link rel="author" title="Daniel Holbert" href="mailto:dholbert@mozilla.com">
-    <link rel="help" href="http://www.w3.org/TR/css3-flexbox/#min-size-auto">
+    <link rel="help" href="http://www.w3.org/TR/css-flexbox-1/#min-size-auto">
     <link rel="match" href="flexbox-min-height-auto-002-ref.html">
 <!--
      This testcase tests the used value of "min-height:auto" (the property's
      initial value) on flex items in a vertical flex container.
 
      It's supposed to resolve to the smallest of:
       a) The used 'flex-basis' (taken from 'height'), if 'flex-basis' is at its
          initial value.
--- a/layout/reftests/w3c-css/submitted/flexbox/flexbox-min-height-auto-002c.html
+++ b/layout/reftests/w3c-css/submitted/flexbox/flexbox-min-height-auto-002c.html
@@ -3,17 +3,17 @@
      Any copyright is dedicated to the Public Domain.
      http://creativecommons.org/publicdomain/zero/1.0/
 -->
 <html>
   <head>
     <meta charset="utf-8">
     <title>CSS Test: Testing min-height:auto</title>
     <link rel="author" title="Daniel Holbert" href="mailto:dholbert@mozilla.com">
-    <link rel="help" href="http://www.w3.org/TR/css3-flexbox/#min-size-auto">
+    <link rel="help" href="http://www.w3.org/TR/css-flexbox-1/#min-size-auto">
     <link rel="match" href="flexbox-min-height-auto-002-ref.html">
 <!--
      This testcase tests the used value of "min-height:auto" (the property's
      initial value) on flex items in a vertical flex container.
 
      It's supposed to resolve to the smallest of:
       a) The used 'flex-basis' (taken from 'height'), if 'flex-basis' is at its
          initial value.
--- a/layout/reftests/w3c-css/submitted/flexbox/flexbox-min-height-auto-003.html
+++ b/layout/reftests/w3c-css/submitted/flexbox/flexbox-min-height-auto-003.html
@@ -3,17 +3,17 @@
      Any copyright is dedicated to the Public Domain.
      http://creativecommons.org/publicdomain/zero/1.0/
 -->
 <html>
   <head>
     <meta charset="utf-8">
     <title>CSS Test: Testing min-height:auto & 'overflow' interaction</title>
     <link rel="author" title="Daniel Holbert" href="mailto:dholbert@mozilla.com">
-    <link rel="help" href="http://www.w3.org/TR/css3-flexbox/#min-size-auto">
+    <link rel="help" href="http://www.w3.org/TR/css-flexbox-1/#min-size-auto">
     <link rel="match" href="flexbox-min-height-auto-003-ref.html">
 <!--
      This testcase checks how "overflow-y" impacts the sizing behavior of flex
      items with "min-height:auto" (the new initial value for "min-height").
 
      In particular, the flex-item-specific "min-height:auto" behavior is
      supposed to be disabled (e.g. we end up with min-height:0) when
      "overflow-y" is non-"visible".
--- a/layout/reftests/w3c-css/submitted/flexbox/flexbox-min-height-auto-004.html
+++ b/layout/reftests/w3c-css/submitted/flexbox/flexbox-min-height-auto-004.html
@@ -3,17 +3,17 @@
      Any copyright is dedicated to the Public Domain.
      http://creativecommons.org/publicdomain/zero/1.0/
 -->
 <html>
   <head>
     <meta charset="utf-8">
     <title>CSS Test: Testing min-height:auto & 'overflow' interaction</title>
     <link rel="author" title="Daniel Holbert" href="mailto:dholbert@mozilla.com">
-    <link rel="help" href="http://www.w3.org/TR/css3-flexbox/#min-size-auto">
+    <link rel="help" href="http://www.w3.org/TR/css-flexbox-1/#min-size-auto">
     <link rel="match" href="flexbox-min-height-auto-004-ref.html">
 <!--
      This testcase checks how "overflow-x" indirectly impacts the sizing
      behavior of flex items with "min-height:auto" (the new initial value
      for "min-height"), via its influence on "overflow-y".
 
      In particular, the flex-item-specific "min-height:auto" behavior is
      supposed to be disabled (e.g. we end up with min-height:0) when
--- a/layout/reftests/w3c-css/submitted/flexbox/flexbox-min-width-auto-001.html
+++ b/layout/reftests/w3c-css/submitted/flexbox/flexbox-min-width-auto-001.html
@@ -3,17 +3,17 @@
      Any copyright is dedicated to the Public Domain.
      http://creativecommons.org/publicdomain/zero/1.0/
 -->
 <html>
   <head>
     <meta charset="utf-8">
     <title>CSS Test: Testing min-width:auto</title>
     <link rel="author" title="Daniel Holbert" href="mailto:dholbert@mozilla.com">
-    <link rel="help" href="http://www.w3.org/TR/css3-flexbox/#min-size-auto">
+    <link rel="help" href="http://www.w3.org/TR/css-flexbox-1/#min-size-auto">
     <link rel="match" href="flexbox-min-width-auto-001-ref.html">
 <!--
      This testcase tests the used value of "min-width:auto" (the property's
      initial value) on flex items in a horizontal flex container.
 
      It's supposed to resolve to the smallest of:
       a) The used 'flex-basis' (taken from 'width'), if 'flex-basis' is at its
          initial value.
--- a/layout/reftests/w3c-css/submitted/flexbox/flexbox-min-width-auto-002a.html
+++ b/layout/reftests/w3c-css/submitted/flexbox/flexbox-min-width-auto-002a.html
@@ -3,17 +3,17 @@
      Any copyright is dedicated to the Public Domain.
      http://creativecommons.org/publicdomain/zero/1.0/
 -->
 <html>
   <head>
     <meta charset="utf-8">
     <title>CSS Test: Testing min-width:auto</title>
     <link rel="author" title="Daniel Holbert" href="mailto:dholbert@mozilla.com">
-    <link rel="help" href="http://www.w3.org/TR/css3-flexbox/#min-size-auto">
+    <link rel="help" href="http://www.w3.org/TR/css-flexbox-1/#min-size-auto">
     <link rel="match" href="flexbox-min-width-auto-002-ref.html">
 <!--
      This testcase tests the used value of "min-width:auto" (the property's
      initial value) on flex items in a horizontal flex container.
 
      It's supposed to resolve to the smallest of:
       a) The used 'flex-basis' (taken from 'width'), if 'flex-basis' is at its
          initial value.
--- a/layout/reftests/w3c-css/submitted/flexbox/flexbox-min-width-auto-002b.html
+++ b/layout/reftests/w3c-css/submitted/flexbox/flexbox-min-width-auto-002b.html
@@ -3,17 +3,17 @@
      Any copyright is dedicated to the Public Domain.
      http://creativecommons.org/publicdomain/zero/1.0/
 -->
 <html>
   <head>
     <meta charset="utf-8">
     <title>CSS Test: Testing min-width:auto</title>
     <link rel="author" title="Daniel Holbert" href="mailto:dholbert@mozilla.com">
-    <link rel="help" href="http://www.w3.org/TR/css3-flexbox/#min-size-auto">
+    <link rel="help" href="http://www.w3.org/TR/css-flexbox-1/#min-size-auto">
     <link rel="match" href="flexbox-min-width-auto-002-ref.html">
 <!--
      This testcase tests the used value of "min-width:auto" (the property's
      initial value) on flex items in a horizontal flex container.
 
      It's supposed to resolve to the smallest of:
       a) The used 'flex-basis' (taken from 'width'), if 'flex-basis' is at its
          initial value.
--- a/layout/reftests/w3c-css/submitted/flexbox/flexbox-min-width-auto-002c.html
+++ b/layout/reftests/w3c-css/submitted/flexbox/flexbox-min-width-auto-002c.html
@@ -3,17 +3,17 @@
      Any copyright is dedicated to the Public Domain.
      http://creativecommons.org/publicdomain/zero/1.0/
 -->
 <html>
   <head>
     <meta charset="utf-8">
     <title>CSS Test: Testing min-width:auto</title>
     <link rel="author" title="Daniel Holbert" href="mailto:dholbert@mozilla.com">
-    <link rel="help" href="http://www.w3.org/TR/css3-flexbox/#min-size-auto">
+    <link rel="help" href="http://www.w3.org/TR/css-flexbox-1/#min-size-auto">
     <link rel="match" href="flexbox-min-width-auto-002-ref.html">
 <!--
      This testcase tests the used value of "min-width:auto" (the property's
      initial value) on flex items in a horizontal flex container.
 
      It's supposed to resolve to the smallest of:
       a) The used 'flex-basis' (taken from 'width'), if 'flex-basis' is at its
          initial value.
--- a/layout/reftests/w3c-css/submitted/flexbox/flexbox-min-width-auto-003.html
+++ b/layout/reftests/w3c-css/submitted/flexbox/flexbox-min-width-auto-003.html
@@ -3,17 +3,17 @@
      Any copyright is dedicated to the Public Domain.
      http://creativecommons.org/publicdomain/zero/1.0/
 -->
 <html>
   <head>
     <meta charset="utf-8">
     <title>CSS Test: Testing min-width:auto & 'overflow' interaction</title>
     <link rel="author" title="Daniel Holbert" href="mailto:dholbert@mozilla.com">
-    <link rel="help" href="http://www.w3.org/TR/css3-flexbox/#min-size-auto">
+    <link rel="help" href="http://www.w3.org/TR/css-flexbox-1/#min-size-auto">
     <link rel="match" href="flexbox-min-width-auto-003-ref.html">
 <!--
      This testcase checks how "overflow-x" impacts the sizing behavior of flex
      items with "min-width:auto" (the new initial value for "min-width").
 
      In particular, the flex-item-specific "min-width:auto" behavior is
      supposed to be disabled (e.g. we end up with min-width:0) when
      "overflow-x" is non-"visible".
--- a/layout/reftests/w3c-css/submitted/flexbox/flexbox-min-width-auto-004.html
+++ b/layout/reftests/w3c-css/submitted/flexbox/flexbox-min-width-auto-004.html
@@ -3,17 +3,17 @@
      Any copyright is dedicated to the Public Domain.
      http://creativecommons.org/publicdomain/zero/1.0/
 -->
 <html>
   <head>
     <meta charset="utf-8">
     <title>CSS Test: Testing min-width:auto & 'overflow' interaction</title>
     <link rel="author" title="Daniel Holbert" href="mailto:dholbert@mozilla.com">
-    <link rel="help" href="http://www.w3.org/TR/css3-flexbox/#min-size-auto">
+    <link rel="help" href="http://www.w3.org/TR/css-flexbox-1/#min-size-auto">
     <link rel="match" href="flexbox-min-width-auto-004-ref.html">
 <!--
      This testcase checks how "overflow-y" indirectly impacts the sizing
      behavior of flex items with "min-width:auto" (the new initial value
      for "min-width"), via its influence on "overflow-x".
 
      In particular, the flex-item-specific "min-width:auto" behavior is
      supposed to be disabled (e.g. we end up with min-width:0) when
--- a/layout/reftests/w3c-css/submitted/flexbox/flexbox-overflow-horiz-1.html
+++ b/layout/reftests/w3c-css/submitted/flexbox/flexbox-overflow-horiz-1.html
@@ -4,17 +4,17 @@
      http://creativecommons.org/publicdomain/zero/1.0/
 -->
 <!-- This testcase checks that we correctly handle the "overflow" property on
      a horizontal flex container. -->
 <html>
 <head>
   <title>CSS Test: Testing 'overflow' property on a horizontal flex container, with contents not overflowing</title>
   <link rel="author" title="Daniel Holbert" href="mailto:dholbert@mozilla.com">
-  <link rel="help" href="http://www.w3.org/TR/css3-flexbox/#flex-containers">
+  <link rel="help" href="http://www.w3.org/TR/css-flexbox-1/#flex-containers">
   <link rel="match" href="flexbox-overflow-horiz-1-ref.html">
   <style>
     .flexContainer {
       background: purple;
       display: flex;
       width: 70px;
       height: 70px;
       float: left;
--- a/layout/reftests/w3c-css/submitted/flexbox/flexbox-overflow-horiz-2.html
+++ b/layout/reftests/w3c-css/submitted/flexbox/flexbox-overflow-horiz-2.html
@@ -6,17 +6,17 @@
 <!-- This testcase checks that we honor "align-items" on a horizontal
      flex container that has "overflow: hidden".  We use a huge border on
      one of the flex items, large enough that it overflows the container,
      to be sure that "overflow: hidden" is actually applying. -->
 <html>
 <head>
   <title>CSS Test: Testing 'overflow' property on a horizontal flex container, with 'align-items: center'</title>
   <link rel="author" title="Daniel Holbert" href="mailto:dholbert@mozilla.com">
-  <link rel="help" href="http://www.w3.org/TR/css3-flexbox/#flex-containers">
+  <link rel="help" href="http://www.w3.org/TR/css-flexbox-1/#flex-containers">
   <link rel="match" href="flexbox-overflow-horiz-2-ref.html">
   <style>
     .flexContainer {
       background: purple;
       display: flex;
       align-items: center;
       width: 70px;
       height: 70px;
--- a/layout/reftests/w3c-css/submitted/flexbox/flexbox-overflow-horiz-3.html
+++ b/layout/reftests/w3c-css/submitted/flexbox/flexbox-overflow-horiz-3.html
@@ -6,17 +6,17 @@
 <!-- This testcase checks that we honor "justify-content" on a horizontal
      flex container that has "overflow:hidden".  We use a large flex item,
      large enough that it overflows the container, to be sure that
      "overflow: hidden" is actually applying. -->
 <html>
 <head>
   <title>CSS Test: Testing 'overflow' property on a horizontal flex container, with 'justify-content: space-around'</title>
   <link rel="author" title="Daniel Holbert" href="mailto:dholbert@mozilla.com">
-  <link rel="help" href="http://www.w3.org/TR/css3-flexbox/#flex-containers">
+  <link rel="help" href="http://www.w3.org/TR/css-flexbox-1/#flex-containers">
   <link rel="match" href="flexbox-overflow-horiz-3-ref.html">
   <style>
     .flexContainer {
       background: purple;
       display: flex;
       justify-content: space-around;
       width: 70px;
       height: 70px;
--- a/layout/reftests/w3c-css/submitted/flexbox/flexbox-overflow-horiz-4.html
+++ b/layout/reftests/w3c-css/submitted/flexbox/flexbox-overflow-horiz-4.html
@@ -6,17 +6,17 @@
 <!-- This testcase checks that we honor "flex-wrap" on a horizontal
      flex container that has "overflow:hidden".  We use a large flex item,
      large enough that it overflows the container in the cross axis, to be
      sure that "overflow: hidden" is actually applying. -->
 <html>
 <head>
   <title>CSS Test: Testing 'overflow' property on a horizontal flex container, with 'flex-wrap: wrap'</title>
   <link rel="author" title="Daniel Holbert" href="mailto:dholbert@mozilla.com">
-  <link rel="help" href="http://www.w3.org/TR/css3-flexbox/#flex-wrap-property">
+  <link rel="help" href="http://www.w3.org/TR/css-flexbox-1/#flex-wrap-property">
   <link rel="match" href="flexbox-overflow-horiz-4-ref.html">
   <style>
     .flexContainer {
       background: purple;
       display: flex;
       flex-wrap: wrap;
       width: 70px;
       height: 70px;
--- a/layout/reftests/w3c-css/submitted/flexbox/flexbox-overflow-horiz-5.html
+++ b/layout/reftests/w3c-css/submitted/flexbox/flexbox-overflow-horiz-5.html
@@ -6,17 +6,17 @@
 <!-- This testcase checks that we honor "align-content" on a horizontal
      flex container that has "overflow:hidden".  We use a large flex item,
      large enough that it overflows the container in the main axis, to be
      sure that "overflow: hidden" is actually applying. -->
 <html>
 <head>
   <title>CSS Test: Testing 'overflow' property on a horizontal flex container, with 'align-content: space-around'</title>
   <link rel="author" title="Daniel Holbert" href="mailto:dholbert@mozilla.com">
-  <link rel="help" href="http://www.w3.org/TR/css3-flexbox/#align-content-property">
+  <link rel="help" href="http://www.w3.org/TR/css-flexbox-1/#align-content-property">
   <link rel="match" href="flexbox-overflow-horiz-5-ref.html">
   <style>
     .flexContainer {
       background: purple;
       display: flex;
       flex-wrap: wrap;
       align-content: space-around;
       width: 70px;
--- a/layout/reftests/w3c-css/submitted/flexbox/flexbox-overflow-vert-1.html
+++ b/layout/reftests/w3c-css/submitted/flexbox/flexbox-overflow-vert-1.html
@@ -4,17 +4,17 @@
      http://creativecommons.org/publicdomain/zero/1.0/
 -->
 <!-- This testcase checks that we correctly handle the "overflow" property on
      a vertical flex container with overflowing contents. -->
 <html>
 <head>
   <title>CSS Test: Testing 'overflow' property on a vertical flex container</title>
   <link rel="author" title="Daniel Holbert" href="mailto:dholbert@mozilla.com">
-  <link rel="help" href="http://www.w3.org/TR/css3-flexbox/#flex-containers">
+  <link rel="help" href="http://www.w3.org/TR/css-flexbox-1/#flex-containers">
   <link rel="match" href="flexbox-overflow-vert-1-ref.html">
   <style>
     .flexContainer {
       background: purple;
       display: flex;
       flex-direction: column;
       width: 70px;
       height: 70px;
--- a/layout/reftests/w3c-css/submitted/flexbox/flexbox-overflow-vert-2.html
+++ b/layout/reftests/w3c-css/submitted/flexbox/flexbox-overflow-vert-2.html
@@ -6,17 +6,17 @@
 <!-- This testcase checks that we honor "align-items" on a vertical
      flex container that has "overflow: hidden".  We use a huge border on
      one of the flex items, large enough that it overflows the container,
      to be sure that "overflow: hidden" is actually applying. -->
 <html>
 <head>
   <title>CSS Test: Testing 'overflow' property on a vertical flex container, with 'align-items: center'</title>
   <link rel="author" title="Daniel Holbert" href="mailto:dholbert@mozilla.com">
-  <link rel="help" href="http://www.w3.org/TR/css3-flexbox/#flex-containers">
+  <link rel="help" href="http://www.w3.org/TR/css-flexbox-1/#flex-containers">
   <link rel="match" href="flexbox-overflow-vert-2-ref.html">
   <style>
     .flexContainer {
       background: purple;
       display: flex;
       flex-direction: column;
       align-items: center;
       width: 70px;
--- a/layout/reftests/w3c-css/submitted/flexbox/flexbox-overflow-vert-3.html
+++ b/layout/reftests/w3c-css/submitted/flexbox/flexbox-overflow-vert-3.html
@@ -6,17 +6,17 @@
 <!-- This testcase checks that we honor "justify-content" on a vertical
      flex container that has "overflow:hidden".  We use a large flex item,
      large enough that it overflows the container, to be sure that
      "overflow: hidden" is actually applying. -->
 <html>
 <head>
   <title>CSS Test: Testing 'overflow' property on a vertical flex container, with 'justify-content: space-around'</title>
   <link rel="author" title="Daniel Holbert" href="mailto:dholbert@mozilla.com">
-  <link rel="help" href="http://www.w3.org/TR/css3-flexbox/#flex-containers">
+  <link rel="help" href="http://www.w3.org/TR/css-flexbox-1/#flex-containers">
   <link rel="match" href="flexbox-overflow-vert-3-ref.html">
   <style>
     .flexContainer {
       background: purple;
       display: flex;
       flex-direction: column;
       justify-content: space-around;
       width: 70px;
--- a/layout/reftests/w3c-css/submitted/flexbox/flexbox-overflow-vert-4.html
+++ b/layout/reftests/w3c-css/submitted/flexbox/flexbox-overflow-vert-4.html
@@ -6,17 +6,17 @@
 <!-- This testcase checks that we honor "flex-wrap" on a vertical
      flex container that has "overflow:hidden".  We use a large flex item,
      large enough that it overflows the container in the cross axis, to be
      sure that "overflow: hidden" is actually applying. -->
 <html>
 <head>
   <title>CSS Test: Testing 'overflow' property on a vertical flex container, with 'flex-wrap: wrap'</title>
   <link rel="author" title="Daniel Holbert" href="mailto:dholbert@mozilla.com">
-  <link rel="help" href="http://www.w3.org/TR/css3-flexbox/#flex-wrap-property">
+  <link rel="help" href="http://www.w3.org/TR/css-flexbox-1/#flex-wrap-property">
   <link rel="match" href="flexbox-overflow-vert-4-ref.html">
   <style>
     .flexContainer {
       background: purple;
       display: flex;
       flex-direction: column;
       flex-wrap: wrap;
       width: 70px;
--- a/layout/reftests/w3c-css/submitted/flexbox/flexbox-overflow-vert-5.html
+++ b/layout/reftests/w3c-css/submitted/flexbox/flexbox-overflow-vert-5.html
@@ -6,17 +6,17 @@
 <!-- This testcase checks that we honor "align-content" on a vertical
      flex container that has "overflow:hidden".  We use a large flex item,
      large enough that it overflows the container in the main axis, to be
      sure that "overflow: hidden" is actually applying. -->
 <html>
 <head>
   <title>CSS Test: Testing 'overflow' property on a vertical flex container, with 'align-content: space-around'</title>
   <link rel="author" title="Daniel Holbert" href="mailto:dholbert@mozilla.com">
-  <link rel="help" href="http://www.w3.org/TR/css3-flexbox/#align-content-property">
+  <link rel="help" href="http://www.w3.org/TR/css-flexbox-1/#align-content-property">
   <link rel="match" href="flexbox-overflow-vert-5-ref.html">
   <style>
     .flexContainer {
       background: purple;
       display: flex;
       flex-direction: column;
       flex-wrap: wrap;
       align-content: space-around;
--- a/layout/reftests/w3c-css/submitted/flexbox/flexbox-paint-ordering-1.xhtml
+++ b/layout/reftests/w3c-css/submitted/flexbox/flexbox-paint-ordering-1.xhtml
@@ -4,17 +4,17 @@
      http://creativecommons.org/publicdomain/zero/1.0/
 -->
 <!-- Testcase with flex items containing overlapping content, to test
      their paint-order. -->
 <html xmlns="http://www.w3.org/1999/xhtml">
   <head>
     <title>CSS Test: Testing the paint-order of overlapping flex items, with varying tweaks on the container</title>
     <link rel="author" title="Daniel Holbert" href="mailto:dholbert@mozilla.com"/>
-    <link rel="help" href="http://www.w3.org/TR/css3-flexbox/#painting"/>
+    <link rel="help" href="http://www.w3.org/TR/css-flexbox-1/#painting"/>
     <link rel="match" href="flexbox-paint-ordering-1-ref.xhtml"/>
     <style>
       body {
         line-height: 0;
       }
       .container {
         width: 40px;
         height: 14px;
--- a/layout/reftests/w3c-css/submitted/flexbox/flexbox-paint-ordering-2.xhtml
+++ b/layout/reftests/w3c-css/submitted/flexbox/flexbox-paint-ordering-2.xhtml
@@ -5,17 +5,17 @@
 -->
 <!-- Testcase with flex items containing overlapping content, with
      "order" and "z-index" set on some of them, to test how that affects
      paint-order. -->
 <html xmlns="http://www.w3.org/1999/xhtml">
   <head>
     <title>CSS Test: Testing the paint-order of overlapping flex items with 'order' and 'z-index' set</title>
     <link rel="author" title="Daniel Holbert" href="mailto:dholbert@mozilla.com"/>
-    <link rel="help" href="http://www.w3.org/TR/css3-flexbox/#painting"/>
+    <link rel="help" href="http://www.w3.org/TR/css-flexbox-1/#painting"/>
     <link rel="match" href="flexbox-paint-ordering-2-ref.xhtml"/>
     <style>
       body {
         line-height: 0;
       }
 
       .flexbox {
         display: inline-flex;
--- a/layout/reftests/w3c-css/submitted/flexbox/flexbox-root-node-1a.html
+++ b/layout/reftests/w3c-css/submitted/flexbox/flexbox-root-node-1a.html
@@ -4,17 +4,17 @@
      http://creativecommons.org/publicdomain/zero/1.0/
 -->
 <!-- This testcase checks that we correctly handle 'display:flex' property on
      the root <html> element, with the <body> as the sole flex item. -->
 <html style="display: flex; justify-content: center">
 <head>
   <title>CSS Test: Testing 'display:flex' on root node</title>
   <link rel="author" title="Daniel Holbert" href="mailto:dholbert@mozilla.com">
-  <link rel="help" href="http://www.w3.org/TR/css3-flexbox/#flex-containers">
+  <link rel="help" href="http://www.w3.org/TR/css-flexbox-1/#flex-containers">
   <link rel="match" href="flexbox-root-node-1-ref.html">
   <style>
     html {
       display: flex;
       justify-content: center;
     }
   </style>
 </head>
--- a/layout/reftests/w3c-css/submitted/flexbox/flexbox-root-node-1b.html
+++ b/layout/reftests/w3c-css/submitted/flexbox/flexbox-root-node-1b.html
@@ -4,17 +4,17 @@
      http://creativecommons.org/publicdomain/zero/1.0/
 -->
 <!-- This testcase checks that we correctly handle 'display:flex' property on
      the root <html> element, with no explicit <body>. -->
 <html style="display: flex; justify-content: center">
 <head>
   <title>CSS Test: Testing 'display:flex' on root node</title>
   <link rel="author" title="Daniel Holbert" href="mailto:dholbert@mozilla.com">
-  <link rel="help" href="http://www.w3.org/TR/css3-flexbox/#flex-containers">
+  <link rel="help" href="http://www.w3.org/TR/css-flexbox-1/#flex-containers">
   <link rel="match" href="flexbox-root-node-1-ref.html">
   <style>
     html {
       display: flex;
       justify-content: center;
     }
   </style>
 </head>
--- a/layout/reftests/w3c-css/submitted/flexbox/flexbox-sizing-horiz-1.xhtml
+++ b/layout/reftests/w3c-css/submitted/flexbox/flexbox-sizing-horiz-1.xhtml
@@ -6,17 +6,17 @@
 <!--
      This testcase checks how "min-width" and "max-width" affect the sizing
      of horizontal flex containers that have no explicit "width" property.
 -->
 <html xmlns="http://www.w3.org/1999/xhtml">
   <head>
     <title>CSS Test: Testing sizing of an auto-sized horizontal flex container with min-width and max-width constraints</title>
     <link rel="author" title="Daniel Holbert" href="mailto:dholbert@mozilla.com"/>
-    <link rel="help" href="http://www.w3.org/TR/css3-flexbox/#layout-algorithm"/>
+    <link rel="help" href="http://www.w3.org/TR/css-flexbox-1/#layout-algorithm"/>
     <link rel="match" href="flexbox-sizing-horiz-1-ref.xhtml"/>
     <style>
       div { height: 10px; }
       div.flexbox {
         border: 1px dashed blue;
         font-size: 10px;
         display: flex;
         margin-bottom: 2px;
--- a/layout/reftests/w3c-css/submitted/flexbox/flexbox-sizing-horiz-2.xhtml
+++ b/layout/reftests/w3c-css/submitted/flexbox/flexbox-sizing-horiz-2.xhtml
@@ -6,17 +6,17 @@
 <!--
      This testcase checks how "min-height" and "max-height" affect the sizing
      of horizontal flex containers that have no explicit "height" property.
 -->
 <html xmlns="http://www.w3.org/1999/xhtml">
   <head>
     <title>CSS Test: Testing sizing of an auto-sized horizontal flex container with min-height and max-height constraints</title>
     <link rel="author" title="Daniel Holbert" href="mailto:dholbert@mozilla.com"/>
-    <link rel="help" href="http://www.w3.org/TR/css3-flexbox/#layout-algorithm"/>
+    <link rel="help" href="http://www.w3.org/TR/css-flexbox-1/#layout-algorithm"/>
     <link rel="match" href="flexbox-sizing-horiz-2-ref.xhtml"/>
     <style>
       div { width: 200px; }
       div.flexbox {
         border: 1px dashed blue;
         background: lightgreen;
         font-size: 10px;
         display: flex;
--- a/layout/reftests/w3c-css/submitted/flexbox/flexbox-sizing-vert-1.xhtml
+++ b/layout/reftests/w3c-css/submitted/flexbox/flexbox-sizing-vert-1.xhtml
@@ -6,17 +6,17 @@
 <!--
      This testcase checks how "min-height" and "max-height" affect the sizing
      of vertical flex containers that have no explicit "height" property.
 -->
 <html xmlns="http://www.w3.org/1999/xhtml">
   <head>
     <title>CSS Test: Testing sizing of an auto-sized vertical flex container with min-height and max-height constraints</title>
     <link rel="author" title="Daniel Holbert" href="mailto:dholbert@mozilla.com"/>
-    <link rel="help" href="http://www.w3.org/TR/css3-flexbox/#layout-algorithm"/>
+    <link rel="help" href="http://www.w3.org/TR/css-flexbox-1/#layout-algorithm"/>
     <link rel="match" href="flexbox-sizing-vert-1-ref.xhtml"/>
     <style>
       div { width: 10px; }
       div.flexbox {
         float: left;
         border: 1px dashed blue;
         font-size: 10px;
         display: flex;
--- a/layout/reftests/w3c-css/submitted/flexbox/flexbox-sizing-vert-2.xhtml
+++ b/layout/reftests/w3c-css/submitted/flexbox/flexbox-sizing-vert-2.xhtml
@@ -6,17 +6,17 @@
 <!--
      This testcase checks how "min-width" and "max-width" affect the sizing
      of vertical flex containers that have no explicit "width" property.
 -->
 <html xmlns="http://www.w3.org/1999/xhtml">
   <head>
     <title>CSS Test: Testing sizing of an auto-sized vertical flex container with min-width and max-width constraints</title>
     <link rel="author" title="Daniel Holbert" href="mailto:dholbert@mozilla.com"/>
-    <link rel="help" href="http://www.w3.org/TR/css3-flexbox/#layout-algorithm"/>
+    <link rel="help" href="http://www.w3.org/TR/css-flexbox-1/#layout-algorithm"/>
     <link rel="match" href="flexbox-sizing-vert-2-ref.xhtml"/>
     <style>
       div { height: 100px; }
       div.flexbox {
         float: left;
         border: 1px dashed blue;
         background: lightgreen;
         font-size: 10px;
--- a/layout/reftests/w3c-css/submitted/flexbox/flexbox-table-fixup-1a.xhtml
+++ b/layout/reftests/w3c-css/submitted/flexbox/flexbox-table-fixup-1a.xhtml
@@ -8,17 +8,17 @@
      table-fixup.  We use justify-content:space-between to stick packing
      space between flex items, so that we can verify that e.g. a contiguous
      run of <td>s will end up in the same flex item (wrapped in a table).
 -->
 <html xmlns="http://www.w3.org/1999/xhtml">
   <head>
     <title>CSS Test: Testing that table cells in a flex container get an anonymous table wrapper that forms the flex item</title>
     <link rel="author" title="Daniel Holbert" href="mailto:dholbert@mozilla.com"/>
-    <link rel="help" href="http://www.w3.org/TR/css3-flexbox/#flex-items"/>
+    <link rel="help" href="http://www.w3.org/TR/css-flexbox-1/#flex-items"/>
     <link rel="match" href="flexbox-table-fixup-1-ref.xhtml"/>
     <style>
       div.flexbox {
         border: 1px dashed blue;
         width: 200px;
         display: flex;
         justify-content: space-around;
       }
--- a/layout/reftests/w3c-css/submitted/flexbox/flexbox-table-fixup-1b.xhtml
+++ b/layout/reftests/w3c-css/submitted/flexbox/flexbox-table-fixup-1b.xhtml
@@ -14,17 +14,17 @@
      don't themselves form flex items.  The flex property _is_ honored on
      the <div class="c">, though, because _its_ box _is_ a direct child of a
      flexbox, so it _is_ a flex item.
 -->
 <html xmlns="http://www.w3.org/1999/xhtml">
   <head>
     <title>CSS Test: Testing that the 'flex' shorthand has no effect on table cells in a flex container, since they aren't flex items</title>
     <link rel="author" title="Daniel Holbert" href="mailto:dholbert@mozilla.com"/>
-    <link rel="help" href="http://www.w3.org/TR/css3-flexbox/#flex-items"/>
+    <link rel="help" href="http://www.w3.org/TR/css-flexbox-1/#flex-items"/>
     <link rel="match" href="flexbox-table-fixup-1-ref.xhtml"/>
     <style>
       div.flexbox {
         border: 1px dashed blue;
         width: 200px;
         display: flex;
         justify-content: space-around;
       }
--- a/layout/reftests/w3c-css/submitted/flexbox/flexbox-whitespace-handling-1a.xhtml
+++ b/layout/reftests/w3c-css/submitted/flexbox/flexbox-whitespace-handling-1a.xhtml
@@ -13,17 +13,17 @@
      The test also uses 'justify-content: space-around' to be sure we can
      tell whether anonymous flex items are being created around the whitespace
      (since they'd claim a share of the packing space if they were there).
 -->
 <html xmlns="http://www.w3.org/1999/xhtml">
   <head>
     <title>CSS Test: Test that anonymous flex items aren't created for pure-whitespace inline content</title>
     <link rel="author" title="Daniel Holbert" href="mailto:dholbert@mozilla.com"/>
-    <link rel="help" href="http://www.w3.org/TR/css3-flexbox/#flex-items"/>
+    <link rel="help" href="http://www.w3.org/TR/css-flexbox-1/#flex-items"/>
     <link rel="match" href="flexbox-whitespace-handling-1-ref.xhtml"/>
     <style>
       div { height: 100px; }
       div.flexbox {
         white-space: pre;
         border: 1px dashed blue;
         width: 200px;
         display: flex;
--- a/layout/reftests/w3c-css/submitted/flexbox/flexbox-whitespace-handling-1b.xhtml
+++ b/layout/reftests/w3c-css/submitted/flexbox/flexbox-whitespace-handling-1b.xhtml
@@ -9,17 +9,17 @@
      doing things right).
 -->
 <!-- XXXdholbert Does this testcase add value?
     (Maybe it should be an alternate reference case.) -->
 <html xmlns="http://www.w3.org/1999/xhtml">
   <head>
     <title>CSS Test: Test that flex items are created correctly</title>
     <link rel="author" title="Daniel Holbert" href="mailto:dholbert@mozilla.com"/>
-    <link rel="help" href="http://www.w3.org/TR/css3-flexbox/#flex-items"/>
+    <link rel="help" href="http://www.w3.org/TR/css-flexbox-1/#flex-items"/>
     <link rel="match" href="flexbox-whitespace-handling-1-ref.xhtml"/>
     <style>
       div { height: 100px; }
       div.flexbox {
         border: 1px dashed blue;
         width: 200px;
         display: flex;
         justify-content: space-around;
--- a/layout/reftests/w3c-css/submitted/flexbox/flexbox-whitespace-handling-2.xhtml
+++ b/layout/reftests/w3c-css/submitted/flexbox/flexbox-whitespace-handling-2.xhtml
@@ -7,17 +7,17 @@
      This test verifies that we preserve whitespace at the beginning & end of
      anonymous flex items (using "white-space: pre" so that it actually
      occupies space and affects the rendering).
 -->
 <html xmlns="http://www.w3.org/1999/xhtml">
   <head>
     <title>CSS Test: Test that whitespace is preserved at the edges of anonymous flex items if 'white-space: pre' is set</title>
     <link rel="author" title="Daniel Holbert" href="mailto:dholbert@mozilla.com"/>
-    <link rel="help" href="http://www.w3.org/TR/css3-flexbox/#flex-items"/>
+    <link rel="help" href="http://www.w3.org/TR/css-flexbox-1/#flex-items"/>
     <link rel="match" href="flexbox-whitespace-handling-2-ref.xhtml"/>
     <link rel="stylesheet" type="text/css" href="support/ahem.css" />
     <style>
       div { height: 100px; }
       div.flexbox {
         white-space: pre;
         border: 1px dashed blue;
         width: 200px;
--- a/layout/reftests/w3c-css/submitted/flexbox/flexbox-with-pseudo-elements-1.html
+++ b/layout/reftests/w3c-css/submitted/flexbox/flexbox-with-pseudo-elements-1.html
@@ -6,17 +6,17 @@
 <!-- Testcase to ensure we handle ::before and ::after pseudo-elements on
      a flex container and treat them as flex items (e.g. honoring "align-self",
      and not merging them into anonymous flex items formed around text).
 -->
 <html>
 <head>
   <title>CSS Test: Testing that generated content nodes are treated as a flex items</title>
   <link rel="author" title="Daniel Holbert" href="mailto:dholbert@mozilla.com">
-  <link rel="help" href="http://www.w3.org/TR/css3-flexbox/#flex-items">
+  <link rel="help" href="http://www.w3.org/TR/css-flexbox-1/#flex-items">
   <link rel="match" href="flexbox-with-pseudo-elements-1-ref.html">
   <meta charset="utf-8">
   <style>
     .flexContainer {
       display: flex;
       align-items: flex-end;
       justify-content: space-between;
       height: 50px;
--- a/layout/reftests/w3c-css/submitted/flexbox/flexbox-with-pseudo-elements-2.html
+++ b/layout/reftests/w3c-css/submitted/flexbox/flexbox-with-pseudo-elements-2.html
@@ -5,17 +5,17 @@
 -->
 <!-- Testcase to ensure we handle ::before and ::after pseudo-elements on
      a flex container and treat them as flex items (e.g. honoring "order").
 -->
 <html>
 <head>
   <title>CSS Test: Testing that generated content nodes are treated as a flex items, and honor 'order'</title>
   <link rel="author" title="Daniel Holbert" href="mailto:dholbert@mozilla.com">
-  <link rel="help" href="http://www.w3.org/TR/css3-flexbox/#flex-items">
+  <link rel="help" href="http://www.w3.org/TR/css-flexbox-1/#flex-items">
   <link rel="match" href="flexbox-with-pseudo-elements-2-ref.html">
   <meta charset="utf-8">
   <style>
     .flexContainer {
       display: flex;
       margin-bottom: 2px;
       background: lightgray;
     }
--- a/layout/reftests/w3c-css/submitted/flexbox/flexbox-with-pseudo-elements-3.html
+++ b/layout/reftests/w3c-css/submitted/flexbox/flexbox-with-pseudo-elements-3.html
@@ -10,17 +10,17 @@
      Note that we *don't* treat the table row or cell frames themselves as flex
      items, because they get wrapped in an anonymous table box, and *that* is
      the flex item.  So, "align-self" and "order" have no effect on the
      row/cell. -->
 <html>
 <head>
   <title>CSS Test: Testing that generated content nodes with table-part display types are wrapped with an anonymous table, which forms a flex item</title>
   <link rel="author" title="Daniel Holbert" href="mailto:dholbert@mozilla.com">
-  <link rel="help" href="http://www.w3.org/TR/css3-flexbox/#flex-items">
+  <link rel="help" href="http://www.w3.org/TR/css-flexbox-1/#flex-items">
   <link rel="match" href="flexbox-with-pseudo-elements-3-ref.html">
   <meta charset="utf-8">
   <style>
     .flexContainer {
       display: flex;
       align-items: flex-end;
       justify-content: space-between;
       height: 50px;
--- a/layout/style/Loader.cpp
+++ b/layout/style/Loader.cpp
@@ -803,16 +803,32 @@ SheetLoadData::OnStreamComplete(nsIUnich
     // Sorry, we don't care about this load anymore
     LOG_WARN(("  No document and not non-document sheet; dropping load"));
     mLoader->SheetComplete(this, NS_BINDING_ABORTED);
     return NS_OK;
   }
 
   if (NS_FAILED(aStatus)) {
     LOG_WARN(("  Load failed: status 0x%x", aStatus));
+    // Handle sheet not loading error because source was a tracking URL.
+    // We make a note of this sheet node by including it in a dedicated
+    // array of blocked tracking nodes under its parent document.
+    //
+    // Multiple sheet load instances might be tied to this request,
+    // we annotate each one linked to a valid owning element (node).
+    if (aStatus == NS_ERROR_TRACKING_URI) {
+      nsIDocument* doc = mLoader->GetDocument();
+      if (doc) {
+        for (SheetLoadData* data = this; data; data = data->mNext) {
+          // mOwningElement may be null but AddBlockTrackingNode can cope
+          nsCOMPtr<nsIContent> content = do_QueryInterface(data->mOwningElement);
+          doc->AddBlockedTrackingNode(content);
+        }
+      }
+    }
     mLoader->SheetComplete(this, aStatus);
     return NS_OK;
   }
 
   nsCOMPtr<nsIChannel> channel;
   nsresult result = aLoader->GetChannel(getter_AddRefs(channel));
   if (NS_FAILED(result)) {
     LOG_WARN(("  No channel from loader"));
--- a/layout/style/full-screen-override.css
+++ b/layout/style/full-screen-override.css
@@ -14,10 +14,11 @@
   opacity: 1;
   /* Ancestors of a full-screen element should not apply SVG masking, clipping, or
      filtering, since that would affect the full-screen element and create a pseudo-
      stacking context. */
   mask: none;
   clip: auto;
   filter: none;
   -moz-transform: none;
+  will-change: auto;
 }
 
--- a/layout/tools/reftest/mach_commands.py
+++ b/layout/tools/reftest/mach_commands.py
@@ -385,41 +385,41 @@ def B2GCommand(func):
             'executed.')
     func = path(func)
 
     return func
 
 
 @CommandProvider
 class MachCommands(MachCommandBase):
-    @Command('reftest', category='testing', description='Run reftests.')
+    @Command('reftest', category='testing', description='Run reftests (layout and graphics correctness).')
     @ReftestCommand
     def run_reftest(self, test_file, **kwargs):
         return self._run_reftest(test_file, suite='reftest', **kwargs)
 
     @Command('jstestbrowser', category='testing',
         description='Run js/src/tests in the browser.')
     @ReftestCommand
     def run_jstestbrowser(self, test_file, **kwargs):
         return self._run_reftest(test_file, suite='jstestbrowser', **kwargs)
 
     @Command('reftest-ipc', category='testing',
-        description='Run IPC reftests.')
+        description='Run IPC reftests (layout and graphics correctness, separate process).')
     @ReftestCommand
     def run_ipc(self, test_file, **kwargs):
         return self._run_reftest(test_file, suite='reftest-ipc', **kwargs)
 
     @Command('crashtest', category='testing',
-        description='Run crashtests.')
+        description='Run crashtests (Check if crashes on a page).')
     @ReftestCommand
     def run_crashtest(self, test_file, **kwargs):
         return self._run_reftest(test_file, suite='crashtest', **kwargs)
 
     @Command('crashtest-ipc', category='testing',
-        description='Run IPC crashtests.')
+        description='Run IPC crashtests (Check if crashes on a page, separate process).')
     @ReftestCommand
     def run_crashtest_ipc(self, test_file, **kwargs):
         return self._run_reftest(test_file, suite='crashtest-ipc', **kwargs)
 
     def _run_reftest(self, test_file=None, suite=None, **kwargs):
         reftest = self._spawn(ReftestRunner)
         return reftest.run_desktop_test(test_file, suite=suite, **kwargs)
 
@@ -435,31 +435,31 @@ def is_emulator(cls):
 class B2GCommands(MachCommandBase):
     def __init__(self, context):
         MachCommandBase.__init__(self, context)
 
         for attr in ('b2g_home', 'xre_path', 'device_name'):
             setattr(self, attr, getattr(context, attr, None))
 
     @Command('reftest-remote', category='testing',
-        description='Run a remote reftest.',
+        description='Run a remote reftest (b2g layout and graphics correctness, remote device).',
         conditions=[conditions.is_b2g, is_emulator])
     @B2GCommand
     def run_reftest_remote(self, test_file, **kwargs):
         return self._run_reftest(test_file, suite='reftest', **kwargs)
 
     @Command('reftest-b2g-desktop', category='testing',
-        description='Run a b2g desktop reftest.',
+        description='Run a b2g desktop reftest (b2g desktop layout and graphics correctness).',
         conditions=[conditions.is_b2g_desktop])
     @B2GCommand
     def run_reftest_b2g_desktop(self, test_file, **kwargs):
         return self._run_reftest(test_file, suite='reftest', **kwargs)
 
     @Command('crashtest-remote', category='testing',
-        description='Run a remote crashtest.',
+        description='Run a remote crashtest (Check if b2g crashes on a page, remote device).',
         conditions=[conditions.is_b2g, is_emulator])
     @B2GCommand
     def run_crashtest_remote(self, test_file, **kwargs):
         return self._run_reftest(test_file, suite='crashtest', **kwargs)
 
     def _run_reftest(self, test_file=None, suite=None, **kwargs):
         if self.device_name:
             if self.device_name.startswith('emulator'):
--- a/layout/xul/grid/nsGridCell.h
+++ b/layout/xul/grid/nsGridCell.h
@@ -8,33 +8,35 @@
   Author:
   Eric D Vaughan
 
 **/
 
 #ifndef nsGridCell_h___
 #define nsGridCell_h___
 
+#include "mozilla/Attributes.h"
+
 class nsBoxLayoutState;
 struct nsSize;
 class nsIFrame;
 
 /*
  * Grid cell is what makes up the cellmap in the grid. Each GridCell contains
  * 2 pointers. One to the matching box in the columns and one to the matching box
  * in the rows. Remember that you can put content in both rows and columns.
  * When asked for preferred/min/max sizes it works like a stack and takes the 
  * biggest sizes.
  */
 
-class nsGridCell
+class nsGridCell MOZ_FINAL
 {
 public:
     nsGridCell();
-    virtual ~nsGridCell();
+    ~nsGridCell();
 
     nsSize      GetPrefSize(nsBoxLayoutState& aBoxLayoutState);
     nsSize      GetMinSize(nsBoxLayoutState& aBoxLayoutState);
     nsSize      GetMaxSize(nsBoxLayoutState& aBoxLayoutState);
     bool        IsCollapsed();
 
 // accessors
     nsIFrame*   GetBoxInColumn()               { return mBoxInColumn; }
--- a/layout/xul/nsTextBoxFrame.cpp
+++ b/layout/xul/nsTextBoxFrame.cpp
@@ -18,17 +18,16 @@
 #include "nsXPIDLString.h"
 #include "nsIServiceManager.h"
 #include "nsIDOMElement.h"
 #include "nsIDOMXULLabelElement.h"
 #include "mozilla/EventStateManager.h"
 #include "nsITheme.h"
 #include "nsUnicharUtils.h"
 #include "nsContentUtils.h"
-#include "nsCxPusher.h"
 #include "nsDisplayList.h"
 #include "nsCSSRendering.h"
 #include "nsIReflowCallback.h"
 #include "nsBoxFrame.h"
 #include "mozilla/Preferences.h"
 #include "nsLayoutUtils.h"
 #include "mozilla/Attributes.h"
 
@@ -187,25 +186,18 @@ public:
 bool
 nsTextBoxFrame::UpdateAccesskey(nsWeakFrame& aWeakThis)
 {
     nsAutoString accesskey;
     nsCOMPtr<nsIDOMXULLabelElement> labelElement = do_QueryInterface(mContent);
     NS_ENSURE_TRUE(aWeakThis.IsAlive(), false);
     if (labelElement) {
         // Accesskey may be stored on control.
-        // Because this method is called by the reflow callback, current context
-        // may not be the right one. Pushing the context of mContent so that
-        // if nsIDOMXULLabelElement is implemented in XBL, we don't get a
-        // security exception.
-        nsCxPusher cx;
-        if (cx.Push(mContent)) {
-          labelElement->GetAccessKey(accesskey);
-          NS_ENSURE_TRUE(aWeakThis.IsAlive(), false);
-        }
+        labelElement->GetAccessKey(accesskey);
+        NS_ENSURE_TRUE(aWeakThis.IsAlive(), false);
     }
     else {
         mContent->GetAttr(kNameSpaceID_None, nsGkAtoms::accesskey, accesskey);
     }
 
     if (!accesskey.Equals(mAccessKey)) {
         // Need to get clean mTitle.
         RecomputeTitle();
deleted file mode 100644
--- a/media/mtransport/test/Makefile.in
+++ /dev/null
@@ -1,10 +0,0 @@
-# -*- Mode: makefile; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- #
-# This Source Code Form is subject to the terms of the Mozilla Public
-# License, v. 2.0. If a copy of the MPL was not distributed with this
-# file, You can obtain one at http://mozilla.org/MPL/2.0/.
-
-ifeq ($(OS_TARGET), Android)
-CPPFLAGS += \
-  $(STLPORT_CPPFLAGS) \
-  $(NULL)
-endif
deleted file mode 100644
--- a/media/webrtc/signaling/test/Makefile.in
+++ /dev/null
@@ -1,12 +0,0 @@
-# This Source Code Form is subject to the terms of the Mozilla Public
-# License, v. 2.0. If a copy of the MPL was not distributed with this file,
-# You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-ifeq ($(OS_TARGET),Android)
-CPPFLAGS += \
-  $(STLPORT_CPPFLAGS) \
-  $(NULL)
-endif
-
-include $(topsrcdir)/config/config.mk
-include $(topsrcdir)/media/webrtc/webrtc-config.mk
deleted file mode 100644
--- a/media/webrtc/webrtc-config.mk
+++ /dev/null
@@ -1,19 +0,0 @@
-# This Source Code Form is subject to the terms of the Mozilla Public
-# License, v. 2.0. If a copy of the MPL was not distributed with this
-# file, You can obtain one at http://mozilla.org/MPL/2.0/.
-
-ifndef INCLUDED_CONFIG_MK
-$(error Must include config.mk before this file.)
-endif
-
-ifdef WEBRTC_CONFIG_INCLUDED
-$(error Must not include webrtc-config.mk twice.)
-endif
-
-WEBRTC_CONFIG_INCLUDED = 1
-
-EXTRA_DEPS += $(topsrcdir)/media/webrtc/webrtc-config.mk
-
-LOCAL_INCLUDES += \
-  -I$(topsrcdir)/media/webrtc/trunk/webrtc \
-  $(NULL)
--- a/mobile/android/app/mobile.js
+++ b/mobile/android/app/mobile.js
@@ -559,16 +559,19 @@ pref("editor.singleLine.pasteNewlines", 
 // threshold where a tap becomes a drag, in 1/240" reference pixels
 // The names of the preferences are to be in sync with EventStateManager.cpp
 pref("ui.dragThresholdX", 25);
 pref("ui.dragThresholdY", 25);
 
 pref("layers.acceleration.disabled", false);
 pref("layers.offmainthreadcomposition.enabled", true);
 pref("layers.async-video.enabled", true);
+#ifdef MOZ_ANDROID_APZ
+pref("layers.async-pan-zoom.enabled", true);
+#endif
 pref("layers.progressive-paint", true);
 pref("layers.low-precision-buffer", true);
 pref("layers.low-precision-resolution", "0.25");
 pref("layers.low-precision-opacity", "1.0");
 // We want to limit layers for two reasons:
 // 1) We can't scroll smoothly if we have to many draw calls
 // 2) Pages that have too many layers consume too much memory and crash.
 // By limiting the number of layers on mobile we're making the main thread
--- a/mobile/android/base/AppConstants.java.in
+++ b/mobile/android/base/AppConstants.java.in
@@ -191,16 +191,23 @@ public class AppConstants {
     // it if this APK doesn't include API14 support.
     public static final boolean MOZ_ANDROID_BEAM =
 #ifdef MOZ_ANDROID_BEAM
     Versions.feature14Plus;
 #else
     false;
 #endif
 
+    public static final boolean MOZ_ANDROID_APZ =
+#ifdef MOZ_ANDROID_APZ
+    true;
+#else
+    false;
+#endif
+
     // See this wiki page for more details about channel specific build defines:
     // https://wiki.mozilla.org/Platform/Channel-specific_build_defines
     public static final boolean RELEASE_BUILD =
 #ifdef RELEASE_BUILD
     true;
 #else
     false;
 #endif
--- a/mobile/android/base/GeckoAppShell.java
+++ b/mobile/android/base/GeckoAppShell.java
@@ -178,16 +178,17 @@ public class GeckoAppShell
     static public final int LINK_TYPE_WIMAX = 4;
     static public final int LINK_TYPE_2G = 5;
     static public final int LINK_TYPE_3G = 6;
     static public final int LINK_TYPE_4G = 7;
 
     /* The Android-side API: API methods that Android calls */
 
     // Initialization methods
+    public static native void registerJavaUiThread();
     public static native void nativeInit();
 
     // helper methods
     //    public static native void setSurfaceView(GeckoSurfaceView sv);
     public static native void setLayerClient(Object client);
     public static native void onResume();
     public static void callObserver(String observerKey, String topic, String data) {
         sendEventToGecko(GeckoEvent.createCallObserverEvent(observerKey, topic, data));
@@ -515,16 +516,34 @@ public class GeckoAppShell
     @WrapElementForJNI
     public static void acknowledgeEvent() {
         synchronized (sEventAckLock) {
             sWaitingForEventAck = false;
             sEventAckLock.notifyAll();
         }
     }
 
+    private static Runnable sCallbackRunnable = new Runnable() {
+        @Override
+        public void run() {
+            ThreadUtils.assertOnUiThread();
+            long nextDelay = runUiThreadCallback();
+            if (nextDelay >= 0) {
+                ThreadUtils.getUiHandler().postDelayed(this, nextDelay);
+            }
+        }
+    };
+
+    private static native long runUiThreadCallback();
+
+    @WrapElementForJNI(allowMultithread = true)
+    private static void requestUiThreadCallback(long delay) {
+        ThreadUtils.getUiHandler().postDelayed(sCallbackRunnable, delay);
+    }
+
     private static float getLocationAccuracy(Location location) {
         float radius = location.getAccuracy();
         return (location.hasAccuracy() && radius > 0) ? radius : 1001;
     }
 
     private static Location getLastKnownLocation(LocationManager lm) {
         Location lastKnownLocation = null;
         List<String> providers = lm.getAllProviders();
--- a/mobile/android/base/GeckoThread.java
+++ b/mobile/android/base/GeckoThread.java
@@ -161,16 +161,24 @@ public class GeckoThread extends Thread 
     public void run() {
         Looper.prepare();
         ThreadUtils.sGeckoThread = this;
         ThreadUtils.sGeckoHandler = new Handler();
         ThreadUtils.sGeckoQueue = Looper.myQueue();
 
         String path = initGeckoEnvironment();
 
+        // This can only happen after the call to initGeckoEnvironment
+        // above, because otherwise the JNI code hasn't been loaded yet.
+        ThreadUtils.postToUiThread(new Runnable() {
+            @Override public void run() {
+                GeckoAppShell.registerJavaUiThread();
+            }
+        });
+
         Log.w(LOGTAG, "zerdatime " + SystemClock.uptimeMillis() + " - runGecko");
 
         String args = addCustomProfileArg(mArgs);
         String type = getTypeFromAction(mAction);
 
         if (!AppConstants.MOZILLA_OFFICIAL) {
             Log.i(LOGTAG, "RunGecko - args = " + args);
         }
--- a/mobile/android/base/gfx/GeckoLayerClient.java
+++ b/mobile/android/base/gfx/GeckoLayerClient.java
@@ -934,23 +934,16 @@ class GeckoLayerClient implements LayerV
     }
 
     /** Implementation of PanZoomTarget */
     @Override
     public void removeRenderTask(RenderTask task) {
         mView.removeRenderTask(task);
     }
 
-
-    /** Implementation of PanZoomTarget */
-    @Override
-    public boolean postDelayed(Runnable action, long delayMillis) {
-        return mView.postDelayed(action, delayMillis);
-    }
-
     /** Implementation of PanZoomTarget */
     @Override
     public Object getLock() {
         return this;
     }
 
     /** Implementation of PanZoomTarget
      * Converts a point from layer view coordinates to layer coordinates. In other words, given a
--- a/mobile/android/base/gfx/LayerMarginsAnimator.java
+++ b/mobile/android/base/gfx/LayerMarginsAnimator.java
@@ -3,29 +3,28 @@
  * 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/. */
 
 package org.mozilla.gecko.gfx;
 
 import org.mozilla.gecko.GeckoAppShell;
 import org.mozilla.gecko.GeckoEvent;
 import org.mozilla.gecko.PrefsHelper;
-import org.mozilla.gecko.TouchEventInterceptor;
 import org.mozilla.gecko.util.FloatUtils;
 import org.mozilla.gecko.util.ThreadUtils;
 
 import android.graphics.PointF;
 import android.graphics.RectF;
 import android.os.SystemClock;
 import android.util.Log;
 import android.view.animation.DecelerateInterpolator;
 import android.view.MotionEvent;
 import android.view.View;
 
-public class LayerMarginsAnimator implements TouchEventInterceptor {
+public class LayerMarginsAnimator {
     private static final String LOGTAG = "GeckoLayerMarginsAnimator";
     // The duration of the animation in ns
     private static final long MARGIN_ANIMATION_DURATION = 250000000;
     private static final String PREF_SHOW_MARGINS_THRESHOLD = "browser.ui.show-margins-threshold";
 
     /* This is the proportion of the viewport rect, minus maximum margins,
      * that needs to be travelled before margins will be exposed.
      */
@@ -65,19 +64,16 @@ public class LayerMarginsAnimator implem
                 SHOW_MARGINS_THRESHOLD = (float)value / 100.0f;
             }
 
             @Override
             public boolean isObserver() {
                 return true;
             }
         });
-
-        // Listen to touch events, for auto-pinning
-        aView.addTouchInterceptor(this);
     }
 
     public void destroy() {
         if (mPrefObserverId != null) {
             PrefsHelper.removeObserver(mPrefObserverId);
             mPrefObserverId = null;
         }
     }
@@ -242,25 +238,17 @@ public class LayerMarginsAnimator implem
                                    mMaxMargins.top, mMaxMargins.bottom,
                                    false);
             }
         }
 
         return aMetrics.setMargins(newMarginsX[0], newMarginsY[0], newMarginsX[1], newMarginsY[1]).offsetViewportBy(aDx, aDy);
     }
 
-    /** Implementation of TouchEventInterceptor */
-    @Override
-    public boolean onTouch(View view, MotionEvent event) {
-        return false;
-    }
-
-    /** Implementation of TouchEventInterceptor */
-    @Override
-    public boolean onInterceptTouchEvent(View view, MotionEvent event) {
+    boolean onInterceptTouchEvent(MotionEvent event) {
         int action = event.getActionMasked();
         if (action == MotionEvent.ACTION_DOWN && event.getPointerCount() == 1) {
             mTouchTravelDistance.set(0.0f, 0.0f);
         }
 
         return false;
     }
 
--- a/mobile/android/base/gfx/LayerRenderer.java
+++ b/mobile/android/base/gfx/LayerRenderer.java
@@ -538,55 +538,16 @@ public class LayerRenderer implements Ta
             mUpdated &= mVertScrollLayer.update(mPageContext);  // called on compositor thread
             mUpdated &= mHorizScrollLayer.update(mPageContext); // called on compositor thread
 
             for (Layer layer : mExtraLayers) {
                 mUpdated &= layer.update(mPageContext); // called on compositor thread
             }
         }
 
-        /** Retrieves the bounds for the layer, rounded in such a way that it
-         * can be used as a mask for something that will render underneath it.
-         * This will round the bounds inwards, but stretch the mask towards any
-         * near page edge, where near is considered to be 'within 2 pixels'.
-         * Returns null if the given layer is null.
-         */
-        private Rect getMaskForLayer(Layer layer) {
-            if (layer == null) {
-                return null;
-            }
-
-            RectF bounds = RectUtils.contract(layer.getBounds(mPageContext), 1.0f, 1.0f);
-            Rect mask = RectUtils.roundIn(bounds);
-
-            // If the mask is within two pixels of any page edge, stretch it over
-            // that edge. This is to avoid drawing thin slivers when masking
-            // layers.
-            if (mask.top <= 2) {
-                mask.top = -1;
-            }
-            if (mask.left <= 2) {
-                mask.left = -1;
-            }
-
-            // Because we're drawing relative to the page-rect, we only need to
-            // take into account its width and height (and not its origin)
-            int pageRight = mPageRect.width();
-            int pageBottom = mPageRect.height();
-
-            if (mask.right >= pageRight - 2) {
-                mask.right = pageRight + 1;
-            }
-            if (mask.bottom >= pageBottom - 2) {
-                mask.bottom = pageBottom + 1;
-            }
-
-            return mask;
-        }
-
         private void clear(int color) {
             GLES20.glClearColor(((color >> 16) & 0xFF) / 255.0f,
                                 ((color >> 8) & 0xFF) / 255.0f,
                                 (color & 0xFF) / 255.0f,
                                 0.0f);
             // The bits set here need to match up with those used
             // in gfx/layers/opengl/LayerManagerOGL.cpp.
             GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT |
@@ -608,26 +569,16 @@ public class LayerRenderer implements Ta
             mBackgroundColor = mView.getBackgroundColor();
 
             // Clear the page area to the page background colour.
             setScissorRect();
             clear(mBackgroundColor);
             GLES20.glDisable(GLES20.GL_SCISSOR_TEST);
         }
 
-        // Draws the layer the client added to us.
-        void drawRootLayer() {
-            Layer rootLayer = mView.getLayerClient().getRoot();
-            if (rootLayer == null) {
-                return;
-            }
-
-            rootLayer.draw(mPageContext);
-        }
-
         @JNITarget
         public void drawForeground() {
             // Any GL state which is changed here must be restored in
             // CompositorOGL::RestoreState
 
             /* Draw any extra layers that were added (likely plugins) */
             if (mExtraLayers.size() > 0) {
                 for (Layer layer : mExtraLayers) {
--- a/mobile/android/base/gfx/LayerView.java
+++ b/mobile/android/base/gfx/LayerView.java
@@ -12,17 +12,16 @@ import org.mozilla.gecko.AndroidGamepadM
 import org.mozilla.gecko.AppConstants.Versions;
 import org.mozilla.gecko.EventDispatcher;
 import org.mozilla.gecko.GeckoAccessibility;
 import org.mozilla.gecko.GeckoAppShell;
 import org.mozilla.gecko.GeckoEvent;
 import org.mozilla.gecko.PrefsHelper;
 import org.mozilla.gecko.Tab;
 import org.mozilla.gecko.Tabs;
-import org.mozilla.gecko.TouchEventInterceptor;
 import org.mozilla.gecko.ZoomConstraints;
 import org.mozilla.gecko.mozglue.RobocopTarget;
 import org.mozilla.gecko.mozglue.generatorannotations.WrapElementForJNI;
 
 import android.content.Context;
 import android.graphics.Bitmap;
 import android.graphics.BitmapFactory;
 import android.graphics.Canvas;
@@ -64,18 +63,20 @@ public class LayerView extends FrameLayo
     private int mBackgroundColor;
     private FullScreenState mFullScreenState;
 
     private SurfaceView mSurfaceView;
     private TextureView mTextureView;
 
     private Listener mListener;
 
+    private PointF mInitialTouchPoint;
+    private boolean mGeckoIsReady;
+
     /* This should only be modified on the Java UI thread. */
-    private final ArrayList<TouchEventInterceptor> mTouchInterceptors;
     private final Overscroll mOverscroll;
 
     /* Flags used to determine when to show the painted surface. */
     public static final int PAINT_START = 0;
     public static final int PAINT_BEFORE_FIRST = 1;
     public static final int PAINT_AFTER_FIRST = 2;
 
     public boolean shouldUseTextureView() {
@@ -104,17 +105,16 @@ public class LayerView extends FrameLayo
     public LayerView(Context context, AttributeSet attrs) {
         super(context, attrs);
 
         mGLController = GLController.getInstance(this);
         mPaintState = PAINT_START;
         mBackgroundColor = Color.WHITE;
         mFullScreenState = FullScreenState.NONE;
 
-        mTouchInterceptors = new ArrayList<TouchEventInterceptor>();
         if (Versions.feature14Plus) {
             mOverscroll = new OverscrollEdgeEffect(this);
         } else {
             mOverscroll = null;
         }
         Tabs.registerOnTabsChangedListener(this);
     }
 
@@ -151,53 +151,46 @@ public class LayerView extends FrameLayo
             @Override public void prefValue(String pref, boolean force16bit) {
                 if (force16bit) {
                     GeckoAppShell.setScreenDepthOverride(16);
                 }
             }
         });
 
         mLayerClient.notifyGeckoReady();
-        addTouchInterceptor(new TouchEventInterceptor() {
-            private PointF mInitialTouchPoint;
+        mInitialTouchPoint = null;
+        mGeckoIsReady = true;
+    }
 
-            @Override
-            public boolean onInterceptTouchEvent(View view, MotionEvent event) {
-                return false;
-            }
+    private boolean sendEventToGecko(MotionEvent event) {
+        if (!mGeckoIsReady) {
+            return false;
+        }
 
-            @Override
-            public boolean onTouch(View view, MotionEvent event) {
-                if (event == null) {
-                    return true;
-                }
+        int action = event.getActionMasked();
+        PointF point = new PointF(event.getX(), event.getY());
+        if (action == MotionEvent.ACTION_DOWN) {
+            mInitialTouchPoint = point;
+        }
 
-                int action = event.getActionMasked();
-                PointF point = new PointF(event.getX(), event.getY());
-                if (action == MotionEvent.ACTION_DOWN) {
-                    mInitialTouchPoint = point;
-                }
-
-                if (mInitialTouchPoint != null && action == MotionEvent.ACTION_MOVE) {
-                    Point p = getEventRadius(event);
+        if (mInitialTouchPoint != null && action == MotionEvent.ACTION_MOVE) {
+            Point p = getEventRadius(event);
 
-                    if (PointUtils.subtract(point, mInitialTouchPoint).length() <
-                        Math.max(PanZoomController.CLICK_THRESHOLD, Math.min(Math.min(p.x, p.y), PanZoomController.PAN_THRESHOLD))) {
-                        // Don't send the touchmove event if if the users finger hasn't moved far.
-                        // Necessary for Google Maps to work correctly. See bug 771099.
-                        return true;
-                    } else {
-                        mInitialTouchPoint = null;
-                    }
-                }
+            if (PointUtils.subtract(point, mInitialTouchPoint).length() <
+                Math.max(PanZoomController.CLICK_THRESHOLD, Math.min(Math.min(p.x, p.y), PanZoomController.PAN_THRESHOLD))) {
+                // Don't send the touchmove event if if the users finger hasn't moved far.
+                // Necessary for Google Maps to work correctly. See bug 771099.
+                return true;
+            } else {
+                mInitialTouchPoint = null;
+            }
+        }
 
-                GeckoAppShell.sendEventToGecko(GeckoEvent.createMotionEvent(event, false));
-                return true;
-            }
-        });
+        GeckoAppShell.sendEventToGecko(GeckoEvent.createMotionEvent(event, false));
+        return true;
     }
 
     public void showSurface() {
         // Fix this if TextureView support is turned back on above
         mSurfaceView.setVisibility(View.VISIBLE);
     }
 
     public void hideSurface() {
@@ -210,81 +203,44 @@ public class LayerView extends FrameLayo
             mLayerClient.destroy();
         }
         if (mRenderer != null) {
             mRenderer.destroy();
         }
         Tabs.unregisterOnTabsChangedListener(this);
     }
 
-    public void addTouchInterceptor(final TouchEventInterceptor aTouchInterceptor) {
-        post(new Runnable() {
-            @Override
-            public void run() {
-                mTouchInterceptors.add(aTouchInterceptor);
-            }
-        });
-    }
-
-    public void removeTouchInterceptor(final TouchEventInterceptor aTouchInterceptor) {
-        post(new Runnable() {
-            @Override
-            public void run() {
-                mTouchInterceptors.remove(aTouchInterceptor);
-            }
-        });
-    }
-
-    private boolean runTouchInterceptors(MotionEvent event, boolean aOnTouch) {
-        boolean result = false;
-        for (TouchEventInterceptor i : mTouchInterceptors) {
-            if (aOnTouch) {
-                result |= i.onTouch(this, event);
-            } else {
-                result |= i.onInterceptTouchEvent(this, event);
-            }
-        }
-
-        return result;
-    }
-
     @Override
     public void dispatchDraw(final Canvas canvas) {
         super.dispatchDraw(canvas);
 
         // We must have a layer client to get valid viewport metrics
         if (mLayerClient != null && mOverscroll != null) {
             mOverscroll.draw(canvas, getViewportMetrics());
         }
     }
 
     @Override
     public boolean onTouchEvent(MotionEvent event) {
         if (event.getActionMasked() == MotionEvent.ACTION_DOWN) {
             requestFocus();
         }
 
-        if (runTouchInterceptors(event, false)) {
+        if (mMarginsAnimator != null && mMarginsAnimator.onInterceptTouchEvent(event)) {
             return true;
         }
         if (mPanZoomController != null && mPanZoomController.onTouchEvent(event)) {
             return true;
         }
-        if (runTouchInterceptors(event, true)) {
-            return true;
-        }
-        return false;
+        return sendEventToGecko(event);
     }
 
     @Override
     public boolean onHoverEvent(MotionEvent event) {
-        if (runTouchInterceptors(event, true)) {
-            return true;
-        }
-        return false;
+        return sendEventToGecko(event);
     }
 
     @Override
     public boolean onGenericMotionEvent(MotionEvent event) {
         if (AndroidGamepadManager.handleMotionEvent(event)) {
             return true;
         }
         if (mPanZoomController != null && mPanZoomController.onMotionEvent(event)) {
--- a/mobile/android/base/gfx/NativePanZoomController.java
+++ b/mobile/android/base/gfx/NativePanZoomController.java
@@ -16,40 +16,37 @@ import org.json.JSONObject;
 import android.graphics.PointF;
 import android.view.KeyEvent;
 import android.view.MotionEvent;
 import android.view.View;
 
 class NativePanZoomController implements PanZoomController, GeckoEventListener {
     private final PanZoomTarget mTarget;
     private final EventDispatcher mDispatcher;
-    private final CallbackRunnable mCallbackRunnable;
 
     NativePanZoomController(PanZoomTarget target, View view, EventDispatcher dispatcher) {
         mTarget = target;
         mDispatcher = dispatcher;
-        mCallbackRunnable = new CallbackRunnable();
         if (GeckoThread.checkLaunchState(GeckoThread.LaunchState.GeckoRunning)) {
             init();
         } else {
             mDispatcher.registerGeckoThreadListener(this, "Gecko:Ready");
         }
     }
 
     public void handleMessage(String event, JSONObject message) {
         if ("Gecko:Ready".equals(event)) {
             mDispatcher.unregisterGeckoThreadListener(this, "Gecko:Ready");
             init();
         }
     }
 
     public boolean onTouchEvent(MotionEvent event) {
         GeckoEvent wrapped = GeckoEvent.createMotionEvent(event, true);
-        handleTouchEvent(wrapped);
-        return false;
+        return handleTouchEvent(wrapped);
     }
 
     public boolean onMotionEvent(MotionEvent event) {
         // FIXME implement this
         return false;
     }
 
     public boolean onKeyEvent(KeyEvent event) {
@@ -65,44 +62,33 @@ class NativePanZoomController implements
     public void pageRectUpdated() {
         // no-op in APZC, I think
     }
 
     public void abortPanning() {
         // no-op in APZC, I think
     }
 
+    public void notifyDefaultActionPrevented(boolean prevented) {
+        // This should never get called; there is a different
+        // codepath that notifies the APZ code of this.
+        throw new IllegalStateException("APZCCallbackHandler::NotifyDefaultPrevented should be getting called, not this!");
+    }
+
     public native void abortAnimation();
 
     private native void init();
-    private native void handleTouchEvent(GeckoEvent event);
+    private native boolean handleTouchEvent(GeckoEvent event);
     private native void handleMotionEvent(GeckoEvent event);
-    private native long runDelayedCallback();
 
     public native void destroy();
-    public native void notifyDefaultActionPrevented(boolean prevented);
     public native boolean getRedrawHint();
     public native void setOverScrollMode(int overscrollMode);
     public native int getOverScrollMode();
 
     @WrapElementForJNI(allowMultithread = true, stubName = "RequestContentRepaintWrapper")
     private void requestContentRepaint(float x, float y, float width, float height, float resolution) {
         mTarget.forceRedraw(new DisplayPortMetrics(x, y, x + width, y + height, resolution));
     }
 
-    @WrapElementForJNI(allowMultithread = true, stubName = "PostDelayedCallbackWrapper")
-    private void postDelayedCallback(long delay) {
-        mTarget.postDelayed(mCallbackRunnable, delay);
-    }
-
-    class CallbackRunnable implements Runnable {
-        @Override
-        public void run() {
-            long nextDelay = runDelayedCallback();
-            if (nextDelay >= 0) {
-                mTarget.postDelayed(this, nextDelay);
-            }
-        }
-    }
-
     public void setOverscrollHandler(final Overscroll listener) {
     }
 }
--- a/mobile/android/base/gfx/PanZoomController.java
+++ b/mobile/android/base/gfx/PanZoomController.java
@@ -18,17 +18,21 @@ public interface PanZoomController {
     // between the touch-down and touch-up of a click). In units of density-independent pixels.
     public static final float PAN_THRESHOLD = 1/16f * GeckoAppShell.getDpi();
 
     // Threshold for sending touch move events to content
     public static final float CLICK_THRESHOLD = 1/50f * GeckoAppShell.getDpi();
 
     static class Factory {
         static PanZoomController create(PanZoomTarget target, View view, EventDispatcher dispatcher) {
-            return new JavaPanZoomController(target, view, dispatcher);
+            if (org.mozilla.gecko.AppConstants.MOZ_ANDROID_APZ) {
+                return new NativePanZoomController(target, view, dispatcher);
+            } else {
+                return new JavaPanZoomController(target, view, dispatcher);
+            }
         }
     }
 
     public void destroy();
 
     public boolean onTouchEvent(MotionEvent event);
     public boolean onMotionEvent(MotionEvent event);
     public boolean onKeyEvent(KeyEvent event);
--- a/mobile/android/base/gfx/PanZoomTarget.java
+++ b/mobile/android/base/gfx/PanZoomTarget.java
@@ -20,14 +20,13 @@ public interface PanZoomTarget {
     public void setViewportMetrics(ImmutableViewportMetrics viewport);
     public void scrollBy(float dx, float dy);
     public void scrollMarginsBy(float dx, float dy);
     public void panZoomStopped();
     /** This triggers an (asynchronous) viewport update/redraw. */
     public void forceRedraw(DisplayPortMetrics displayPort);
 
     public boolean post(Runnable action);
-    public boolean postDelayed(Runnable action, long delayMillis);
     public void postRenderTask(RenderTask task);
     public void removeRenderTask(RenderTask task);
     public Object getLock();
     public PointF convertViewPointToLayerPoint(PointF viewPoint);
 }
--- a/mobile/android/base/toolbar/ToolbarEditText.java
+++ b/mobile/android/base/toolbar/ToolbarEditText.java
@@ -27,16 +27,17 @@ import android.util.AttributeSet;
 import android.util.Log;
 import android.view.KeyEvent;
 import android.view.View;
 import android.view.inputmethod.BaseInputConnection;
 import android.view.inputmethod.EditorInfo;
 import android.view.inputmethod.InputConnection;
 import android.view.inputmethod.InputConnectionWrapper;
 import android.view.inputmethod.InputMethodManager;
+import android.widget.TextView;
 
 /**
 * {@code ToolbarEditText} is the text entry used when the toolbar
 * is in edit state. It handles all the necessary input method machinery.
 * It's meant to be owned by {@code ToolbarEditLayout}.
 */
 public class ToolbarEditText extends CustomEditText
                              implements AutocompleteHandler {
@@ -102,16 +103,24 @@ public class ToolbarEditText extends Cus
             imm.restartInput(this);
             imm.hideSoftInputFromWindow(getWindowToken(), 0);
         } catch (NullPointerException e) {
             Log.e(LOGTAG, "InputMethodManagerService, why are you throwing"
                           + " a NullPointerException? See bug 782096", e);
         }
     }
 
+    @Override
+    public void setText(final CharSequence text, final TextView.BufferType type) {
+        super.setText(text, type);
+
+        // Any autocomplete text would have been overwritten, so reset our autocomplete states.
+        resetAutocompleteState();
+    }
+
     /**
      * Mark the start of autocomplete changes so our text change
      * listener does not react to changes in autocomplete text
      */
     private void beginSettingAutocomplete() {
         beginBatchEdit();
         mSettingAutoComplete = true;
     }
@@ -131,17 +140,23 @@ public class ToolbarEditText extends Cus
         mAutoCompleteSpans = new Object[] {
             // Span to mark the autocomplete text
             AUTOCOMPLETE_SPAN,
             // Span to change the autocomplete text color
             new BackgroundColorSpan(getHighlightColor())
         };
 
         mAutoCompleteResult = "";
-        mAutoCompletePrefixLength = 0;
+
+        // Pretend we already autocompleted the existing text,
+        // so that actions like backspacing don't trigger autocompletion.
+        mAutoCompletePrefixLength = getText().length();
+
+        // Show the cursor.
+        setCursorVisible(true);
     }
 
     /**
      * Get the portion of text that is not marked as autocomplete text.
      *
      * @param text Current text content that may include autocomplete text
      */
     private static String getNonAutocompleteText(final Editable text) {
--- a/mobile/android/chrome/content/browser.js
+++ b/mobile/android/chrome/content/browser.js
@@ -851,20 +851,16 @@ var BrowserApp = {
     window.top.QueryInterface(Ci.nsIInterfaceRequestor).getInterface(Ci.nsIDOMWindowUtils).isFirstPaint = true;
     Services.androidBridge.contentDocumentChanged();
   },
 
   get tabs() {
     return this._tabs;
   },
 
-  get selectedTab() {
-    return this._selectedTab;
-  },
-
   set selectedTab(aTab) {
     if (this._selectedTab == aTab)
       return;
 
     if (this._selectedTab) {
       this._selectedTab.setActive(false);
     }
 
@@ -1757,16 +1753,21 @@ var BrowserApp = {
 
   get layersTileHeight() {
     delete this.layersTileHeight;
     let height = Services.prefs.getIntPref("layers.tile-height");
     return this.layersTileHeight = height;
   },
 
   // nsIAndroidBrowserApp
+  get selectedTab() {
+    return this._selectedTab;
+  },
+
+  // nsIAndroidBrowserApp
   getBrowserTab: function(tabId) {
     return this.getTabForId(tabId);
   },
 
   getUITelemetryObserver: function() {
     return UITelemetry;
   },
 
--- a/mozglue/android/APKOpen.cpp
+++ b/mozglue/android/APKOpen.cpp
@@ -399,19 +399,19 @@ ChildProcessInit(int argc, char* argv[])
   }
   if (loadSQLiteLibs(argv[i]) != SUCCESS) {
     return FAILURE;
   }
   if (loadGeckoLibs(argv[i]) != SUCCESS) {
     return FAILURE;
   }
 
-  GeckoProcessType (*fXRE_StringToChildProcessType)(char*);
-  xul_dlsym("XRE_StringToChildProcessType", &fXRE_StringToChildProcessType);
+  void (*fXRE_SetProcessType)(char*);
+  xul_dlsym("XRE_SetProcessType", &fXRE_SetProcessType);
 
-  mozglueresult (*fXRE_InitChildProcess)(int, char**, GeckoProcessType);
+  mozglueresult (*fXRE_InitChildProcess)(int, char**);
   xul_dlsym("XRE_InitChildProcess", &fXRE_InitChildProcess);
 
-  GeckoProcessType proctype = fXRE_StringToChildProcessType(argv[--argc]);
+  fXRE_SetProcessType(argv[--argc]);
 
-  return fXRE_InitChildProcess(argc, argv, proctype);
+  return fXRE_InitChildProcess(argc, argv);
 }
 
--- a/mozglue/android/jni-stubs.inc
+++ b/mozglue/android/jni-stubs.inc
@@ -53,16 +53,35 @@ Java_org_mozilla_gecko_ANRReporter_relea
 #endif
 
 #ifdef JNI_BINDINGS
   xul_dlsym("Java_org_mozilla_gecko_ANRReporter_releaseNativeStack", &f_Java_org_mozilla_gecko_ANRReporter_releaseNativeStack);
 #endif
 
 #ifdef JNI_STUBS
 
+typedef void (*Java_org_mozilla_gecko_GeckoAppShell_registerJavaUiThread_t)(JNIEnv *, jclass);
+static Java_org_mozilla_gecko_GeckoAppShell_registerJavaUiThread_t f_Java_org_mozilla_gecko_GeckoAppShell_registerJavaUiThread;
+extern "C" NS_EXPORT void JNICALL
+Java_org_mozilla_gecko_GeckoAppShell_registerJavaUiThread(JNIEnv * arg0, jclass arg1) {
+    if (!f_Java_org_mozilla_gecko_GeckoAppShell_registerJavaUiThread) {
+        arg0->ThrowNew(arg0->FindClass("java/lang/UnsupportedOperationException"),
+                       "JNI Function called before it was loaded");
+        return ;
+    }
+     f_Java_org_mozilla_gecko_GeckoAppShell_registerJavaUiThread(arg0, arg1);
+}
+#endif
+
+#ifdef JNI_BINDINGS
+  xul_dlsym("Java_org_mozilla_gecko_GeckoAppShell_registerJavaUiThread", &f_Java_org_mozilla_gecko_GeckoAppShell_registerJavaUiThread);
+#endif
+
+#ifdef JNI_STUBS
+
 typedef void (*Java_org_mozilla_gecko_GeckoAppShell_nativeInit_t)(JNIEnv *, jclass);
 static Java_org_mozilla_gecko_GeckoAppShell_nativeInit_t f_Java_org_mozilla_gecko_GeckoAppShell_nativeInit;
 extern "C" NS_EXPORT void JNICALL
 Java_org_mozilla_gecko_GeckoAppShell_nativeInit(JNIEnv * arg0, jclass arg1) {
     if (!f_Java_org_mozilla_gecko_GeckoAppShell_nativeInit) {
         arg0->ThrowNew(arg0->FindClass("java/lang/UnsupportedOperationException"),
                        "JNI Function called before it was loaded");
         return ;
@@ -338,16 +357,35 @@ Java_org_mozilla_gecko_GeckoAppShell_not
 #endif
 
 #ifdef JNI_BINDINGS
   xul_dlsym("Java_org_mozilla_gecko_GeckoAppShell_notifyGeckoOfEvent", &f_Java_org_mozilla_gecko_GeckoAppShell_notifyGeckoOfEvent);
 #endif
 
 #ifdef JNI_STUBS
 
+typedef jlong (*Java_org_mozilla_gecko_GeckoAppShell_runUiThreadCallback_t)(JNIEnv *, jclass);
+static Java_org_mozilla_gecko_GeckoAppShell_runUiThreadCallback_t f_Java_org_mozilla_gecko_GeckoAppShell_runUiThreadCallback;
+extern "C" NS_EXPORT jlong JNICALL
+Java_org_mozilla_gecko_GeckoAppShell_runUiThreadCallback(JNIEnv * arg0, jclass arg1) {
+    if (!f_Java_org_mozilla_gecko_GeckoAppShell_runUiThreadCallback) {
+        arg0->ThrowNew(arg0->FindClass("java/lang/UnsupportedOperationException"),
+                       "JNI Function called before it was loaded");
+        return 0;
+    }
+    return f_Java_org_mozilla_gecko_GeckoAppShell_runUiThreadCallback(arg0, arg1);
+}
+#endif
+
+#ifdef JNI_BINDINGS
+  xul_dlsym("Java_org_mozilla_gecko_GeckoAppShell_runUiThreadCallback", &f_Java_org_mozilla_gecko_GeckoAppShell_runUiThreadCallback);
+#endif
+
+#ifdef JNI_STUBS
+
 typedef void (*Java_org_mozilla_gecko_GeckoAppShell_cameraCallbackBridge_t)(JNIEnv *, jclass, jbyteArray);
 static Java_org_mozilla_gecko_GeckoAppShell_cameraCallbackBridge_t f_Java_org_mozilla_gecko_GeckoAppShell_cameraCallbackBridge;
 extern "C" NS_EXPORT void JNICALL
 Java_org_mozilla_gecko_GeckoAppShell_cameraCallbackBridge(JNIEnv * arg0, jclass arg1, jbyteArray arg2) {
     if (!f_Java_org_mozilla_gecko_GeckoAppShell_cameraCallbackBridge) {
         arg0->ThrowNew(arg0->FindClass("java/lang/UnsupportedOperationException"),
                        "JNI Function called before it was loaded");
         return ;
@@ -414,26 +452,26 @@ Java_org_mozilla_gecko_gfx_NativePanZoom
 #endif
 
 #ifdef JNI_BINDINGS
   xul_dlsym("Java_org_mozilla_gecko_gfx_NativePanZoomController_init", &f_Java_org_mozilla_gecko_gfx_NativePanZoomController_init);
 #endif
 
 #ifdef JNI_STUBS
 
-typedef void (*Java_org_mozilla_gecko_gfx_NativePanZoomController_handleTouchEvent_t)(JNIEnv *, jobject, jobject);
+typedef jboolean (*Java_org_mozilla_gecko_gfx_NativePanZoomController_handleTouchEvent_t)(JNIEnv *, jobject, jobject);
 static Java_org_mozilla_gecko_gfx_NativePanZoomController_handleTouchEvent_t f_Java_org_mozilla_gecko_gfx_NativePanZoomController_handleTouchEvent;
-extern "C" NS_EXPORT void JNICALL
+extern "C" NS_EXPORT jboolean JNICALL
 Java_org_mozilla_gecko_gfx_NativePanZoomController_handleTouchEvent(JNIEnv * arg0, jobject arg1, jobject arg2) {
     if (!f_Java_org_mozilla_gecko_gfx_NativePanZoomController_handleTouchEvent) {
         arg0->ThrowNew(arg0->FindClass("java/lang/UnsupportedOperationException"),
                        "JNI Function called before it was loaded");
-        return ;
+        return false;
     }
-     f_Java_org_mozilla_gecko_gfx_NativePanZoomController_handleTouchEvent(arg0, arg1, arg2);
+    return f_Java_org_mozilla_gecko_gfx_NativePanZoomController_handleTouchEvent(arg0, arg1, arg2);
 }
 #endif
 
 #ifdef JNI_BINDINGS
   xul_dlsym("Java_org_mozilla_gecko_gfx_NativePanZoomController_handleTouchEvent", &f_Java_org_mozilla_gecko_gfx_NativePanZoomController_handleTouchEvent);
 #endif
 
 #ifdef JNI_STUBS
@@ -452,35 +490,16 @@ Java_org_mozilla_gecko_gfx_NativePanZoom
 #endif
 
 #ifdef JNI_BINDINGS
   xul_dlsym("Java_org_mozilla_gecko_gfx_NativePanZoomController_handleMotionEvent", &f_Java_org_mozilla_gecko_gfx_NativePanZoomController_handleMotionEvent);
 #endif
 
 #ifdef JNI_STUBS
 
-typedef jlong (*Java_org_mozilla_gecko_gfx_NativePanZoomController_runDelayedCallback_t)(JNIEnv *, jobject);
-static Java_org_mozilla_gecko_gfx_NativePanZoomController_runDelayedCallback_t f_Java_org_mozilla_gecko_gfx_NativePanZoomController_runDelayedCallback;
-extern "C" NS_EXPORT jlong JNICALL
-Java_org_mozilla_gecko_gfx_NativePanZoomController_runDelayedCallback(JNIEnv * arg0, jobject arg1) {
-    if (!f_Java_org_mozilla_gecko_gfx_NativePanZoomController_runDelayedCallback) {
-        arg0->ThrowNew(arg0->FindClass("java/lang/UnsupportedOperationException"),
-                       "JNI Function called before it was loaded");
-        return 0;
-    }
-    return f_Java_org_mozilla_gecko_gfx_NativePanZoomController_runDelayedCallback(arg0, arg1);
-}
-#endif
-
-#ifdef JNI_BINDINGS
-  xul_dlsym("Java_org_mozilla_gecko_gfx_NativePanZoomController_runDelayedCallback", &f_Java_org_mozilla_gecko_gfx_NativePanZoomController_runDelayedCallback);
-#endif
-
-#ifdef JNI_STUBS
-
 typedef void (*Java_org_mozilla_gecko_gfx_NativePanZoomController_destroy_t)(JNIEnv *, jobject);
 static Java_org_mozilla_gecko_gfx_NativePanZoomController_destroy_t f_Java_org_mozilla_gecko_gfx_NativePanZoomController_destroy;
 extern "C" NS_EXPORT void JNICALL
 Java_org_mozilla_gecko_gfx_NativePanZoomController_destroy(JNIEnv * arg0, jobject arg1) {
     if (!f_Java_org_mozilla_gecko_gfx_NativePanZoomController_destroy) {
         arg0->ThrowNew(arg0->FindClass("java/lang/UnsupportedOperationException"),
                        "JNI Function called before it was loaded");
         return ;
@@ -490,35 +509,16 @@ Java_org_mozilla_gecko_gfx_NativePanZoom
 #endif
 
 #ifdef JNI_BINDINGS
   xul_dlsym("Java_org_mozilla_gecko_gfx_NativePanZoomController_destroy", &f_Java_org_mozilla_gecko_gfx_NativePanZoomController_destroy);
 #endif
 
 #ifdef JNI_STUBS
 
-typedef void (*Java_org_mozilla_gecko_gfx_NativePanZoomController_notifyDefaultActionPrevented_t)(JNIEnv *, jobject, jboolean);
-static Java_org_mozilla_gecko_gfx_NativePanZoomController_notifyDefaultActionPrevented_t f_Java_org_mozilla_gecko_gfx_NativePanZoomController_notifyDefaultActionPrevented;
-extern "C" NS_EXPORT void JNICALL
-Java_org_mozilla_gecko_gfx_NativePanZoomController_notifyDefaultActionPrevented(JNIEnv * arg0, jobject arg1, jboolean arg2) {
-    if (!f_Java_org_mozilla_gecko_gfx_NativePanZoomController_notifyDefaultActionPrevented) {
-        arg0->ThrowNew(arg0->FindClass("java/lang/UnsupportedOperationException"),
-                       "JNI Function called before it was loaded");
-        return ;
-    }
-     f_Java_org_mozilla_gecko_gfx_NativePanZoomController_notifyDefaultActionPrevented(arg0, arg1, arg2);
-}
-#endif
-
-#ifdef JNI_BINDINGS
-  xul_dlsym("Java_org_mozilla_gecko_gfx_NativePanZoomController_notifyDefaultActionPrevented", &f_Java_org_mozilla_gecko_gfx_NativePanZoomController_notifyDefaultActionPrevented);
-#endif
-
-#ifdef JNI_STUBS
-
 typedef jboolean (*Java_org_mozilla_gecko_gfx_NativePanZoomController_getRedrawHint_t)(JNIEnv *, jobject);
 static Java_org_mozilla_gecko_gfx_NativePanZoomController_getRedrawHint_t f_Java_org_mozilla_gecko_gfx_NativePanZoomController_getRedrawHint;
 extern "C" NS_EXPORT jboolean JNICALL
 Java_org_mozilla_gecko_gfx_NativePanZoomController_getRedrawHint(JNIEnv * arg0, jobject arg1) {
     if (!f_Java_org_mozilla_gecko_gfx_NativePanZoomController_getRedrawHint) {
         arg0->ThrowNew(arg0->FindClass("java/lang/UnsupportedOperationException"),
                        "JNI Function called before it was loaded");
         return false;
--- a/netwerk/base/public/mozIThirdPartyUtil.idl
+++ b/netwerk/base/public/mozIThirdPartyUtil.idl
@@ -7,17 +7,17 @@
 interface nsIURI;
 interface nsIDOMWindow;
 interface nsIChannel;
 
 /**
  * Utility functions for determining whether a given URI, channel, or window
  * hierarchy is third party with respect to a known URI.
  */
-[scriptable, uuid(d994fd1d-d2fe-4372-9ae7-88b08b7d9d90)]
+[scriptable, uuid(b711bd7f-0674-49be-ae77-f221db5f7b6c)]
 interface mozIThirdPartyUtil : nsISupports
 {
   /**
    * isThirdPartyURI
    *
    * Determine whether two URIs are third party with respect to each other.
    * This is determined by computing the base domain for both URIs. If they can
    * be determined, and the base domains match, the request is defined as first
@@ -135,16 +135,31 @@ interface mozIThirdPartyUtil : nsISuppor
    * special cases elided above.
    *
    * @param aHostURI
    *        The URI to analyze.
    *
    * @return the base domain.
    */
   AUTF8String getBaseDomain(in nsIURI aHostURI);
+
+  /**
+   * getURIFromWindow
+   *
+   * Returns the URI associated with the script object principal for the
+   * window.
+   */
+  nsIURI getURIFromWindow(in nsIDOMWindow aWindow);
+
+  /**
+   * getTopWindowForChannel
+   *
+   * Returns the top-level window associated with the given channel.
+   */
+  nsIDOMWindow getTopWindowForChannel(in nsIChannel aChannel);
 };
 
 %{ C++
 /**
  * The mozIThirdPartyUtil implementation is an XPCOM service registered
  * under the ContractID:
  */
 #define THIRDPARTYUTIL_CONTRACTID "@mozilla.org/thirdpartyutil;1"
--- a/netwerk/base/src/ProxyAutoConfig.cpp
+++ b/netwerk/base/src/ProxyAutoConfig.cpp
@@ -239,17 +239,28 @@ static const char *sPacUtils =
   "    }\n"
   "    return ((date1 <= date) && (date <= date2));\n"
   "}\n"
   "";
 
 // sRunning is defined for the helper functions only while the
 // Javascript engine is running and the PAC object cannot be deleted
 // or reset.
-static ProxyAutoConfig *sRunning = nullptr;
+static uint32_t sRunningIndex = 0xdeadbeef;
+static ProxyAutoConfig *GetRunning()
+{
+  MOZ_ASSERT(sRunningIndex != 0xdeadbeef);
+  return static_cast<ProxyAutoConfig *>(PR_GetThreadPrivate(sRunningIndex));
+}
+
+static void SetRunning(ProxyAutoConfig *arg)
+{
+  MOZ_ASSERT(sRunningIndex != 0xdeadbeef);
+  PR_SetThreadPrivate(sRunningIndex, arg);
+}
 
 // The PACResolver is used for dnsResolve()
 class PACResolver MOZ_FINAL : public nsIDNSListener
                             , public nsITimerCallback
 {
 public:
   NS_DECL_THREADSAFE_ISUPPORTS
 
@@ -317,22 +328,22 @@ PACErrorReporter(JSContext *cx, const ch
 }
 
 // timeout of 0 means the normal necko timeout strategy, otherwise the dns request
 // will be canceled after aTimeout milliseconds
 static
 bool PACResolve(const nsCString &aHostName, NetAddr *aNetAddr,
                 unsigned int aTimeout)
 {
-  if (!sRunning) {
+  if (!GetRunning()) {
     NS_WARNING("PACResolve without a running ProxyAutoConfig object");
     return false;
   }
 
-  return sRunning->ResolveAddress(aHostName, aNetAddr, aTimeout);
+  return GetRunning()->ResolveAddress(aHostName, aNetAddr, aTimeout);
 }
 
 ProxyAutoConfig::ProxyAutoConfig()
   : mJSRuntime(nullptr)
   , mJSNeedsSetup(false)
   , mShutdown(false)
 {
   MOZ_COUNT_CTOR(ProxyAutoConfig);
@@ -435,22 +446,22 @@ bool PACMyIpAddress(JSContext *cx, unsig
 {
   JS::CallArgs args = JS::CallArgsFromVp(argc, vp);
 
   if (NS_IsMainThread()) {
     NS_WARNING("DNS Resolution From PAC on Main Thread. How did that happen?");
     return false;
   }
 
-  if (!sRunning) {
+  if (!GetRunning()) {
     NS_WARNING("PAC myIPAddress without a running ProxyAutoConfig object");
     return false;
   }
 
-  return sRunning->MyIPAddress(args);
+  return GetRunning()->MyIPAddress(args);
 }
 
 // proxyAlert(msg) javascript implementation
 static
 bool PACProxyAlert(JSContext *cx, unsigned int argc, JS::Value *vp)
 {
   JS::CallArgs args = CallArgsFromVp(argc, vp);
 
@@ -588,36 +599,42 @@ const JSClass JSRuntimeWrapper::sGlobalC
   "PACResolutionThreadGlobal",
   JSCLASS_GLOBAL_FLAGS,
   JS_PropertyStub, JS_DeletePropertyStub, JS_PropertyStub, JS_StrictPropertyStub,
   JS_EnumerateStub, JS_ResolveStub, JS_ConvertStub,
   nullptr, nullptr, nullptr, nullptr,
   JS_GlobalObjectTraceHook
 };
 
+void
+ProxyAutoConfig::SetThreadLocalIndex(uint32_t index)
+{
+  sRunningIndex = index;
+}
+
 nsresult
 ProxyAutoConfig::Init(const nsCString &aPACURI,
                       const nsCString &aPACScript)
 {
   mPACURI = aPACURI;
   mPACScript = sPacUtils;
   mPACScript.Append(aPACScript);
 
-  if (!sRunning)
+  if (!GetRunning())
     return SetupJS();
 
   mJSNeedsSetup = true;
   return NS_OK;
 }
 
 nsresult
 ProxyAutoConfig::SetupJS()
 {
   mJSNeedsSetup = false;
-  NS_ABORT_IF_FALSE(!sRunning, "JIT is running");
+  NS_ABORT_IF_FALSE(!GetRunning(), "JIT is running");
 
   delete mJSRuntime;
   mJSRuntime = nullptr;
 
   if (mPACScript.IsEmpty())
     return NS_ERROR_FAILURE;
 
   mJSRuntime = JSRuntimeWrapper::Create();
@@ -628,37 +645,37 @@ ProxyAutoConfig::SetupJS()
   JSAutoRequest ar(cx);
   JSAutoCompartment ac(cx, mJSRuntime->Global());
 
   // check if this is a data: uri so that we don't spam the js console with
   // huge meaningless strings. this is not on the main thread, so it can't
   // use nsIRUI scheme methods
   bool isDataURI = nsDependentCSubstring(mPACURI, 0, 5).LowerCaseEqualsASCII("data:", 5);
 
-  sRunning = this;
+  SetRunning(this);
   JS::Rooted<JSObject*> global(cx, mJSRuntime->Global());
   JS::CompileOptions options(cx);
   options.setFileAndLine(mPACURI.get(), 1);
   JS::Rooted<JSScript*> script(cx);
   if (!JS_CompileScript(cx, global, mPACScript.get(),
                         mPACScript.Length(), options, &script) ||
       !JS_ExecuteScript(cx, global, script))
   {
     nsString alertMessage(NS_LITERAL_STRING("PAC file failed to install from "));
     if (isDataURI) {
       alertMessage += NS_LITERAL_STRING("data: URI");
     }
     else {
       alertMessage += NS_ConvertUTF8toUTF16(mPACURI);
     }
     PACLogToConsole(alertMessage);
-    sRunning = nullptr;
+    SetRunning(nullptr);
     return NS_ERROR_FAILURE;
   }
-  sRunning = nullptr;
+  SetRunning(nullptr);
 
   mJSRuntime->SetOK();
   nsString alertMessage(NS_LITERAL_STRING("PAC file installed from "));
   if (isDataURI) {
     alertMessage += NS_LITERAL_STRING("data: URI");
   }
   else {
     alertMessage += NS_ConvertUTF8toUTF16(mPACURI);
@@ -684,17 +701,17 @@ ProxyAutoConfig::GetProxyForURI(const ns
     return NS_ERROR_NOT_AVAILABLE;
 
   JSContext *cx = mJSRuntime->Context();
   JSAutoRequest ar(cx);
   JSAutoCompartment ac(cx, mJSRuntime->Global());
 
   // the sRunning flag keeps a new PAC file from being installed
   // while the event loop is spinning on a DNS function. Don't early return.
-  sRunning = this;
+  SetRunning(this);
   mRunningHost = aTestHost;
 
   nsresult rv = NS_ERROR_FAILURE;
   JS::RootedString uriString(cx, JS_NewStringCopyZ(cx, aTestURI.get()));
   JS::RootedString hostString(cx, JS_NewStringCopyZ(cx, aTestHost.get()));
 
   if (uriString && hostString) {
     JS::AutoValueArray<2> args(cx);
@@ -710,17 +727,17 @@ ProxyAutoConfig::GetProxyForURI(const ns
       if (pacString.init(cx, rval.toString())) {
         CopyUTF16toUTF8(pacString, result);
         rv = NS_OK;
       }
     }
   }
 
   mRunningHost.Truncate();
-  sRunning = nullptr;
+  SetRunning(nullptr);
   return rv;
 }
 
 void
 ProxyAutoConfig::GC()
 {
   if (!mJSRuntime || !mJSRuntime->IsOK())
     return;
@@ -737,17 +754,17 @@ ProxyAutoConfig::~ProxyAutoConfig()
                "should have been deleted on pac thread");
 }
 
 void
 ProxyAutoConfig::Shutdown()
 {
   NS_ABORT_IF_FALSE(!NS_IsMainThread(), "wrong thread for shutdown");
 
-  if (sRunning || mShutdown)
+  if (GetRunning() || mShutdown)
     return;
 
   mShutdown = true;
   delete mJSRuntime;
   mJSRuntime = nullptr;
 }
 
 bool
--- a/netwerk/base/src/ProxyAutoConfig.h
+++ b/netwerk/base/src/ProxyAutoConfig.h
@@ -26,16 +26,17 @@ union NetAddr;
 
 class ProxyAutoConfig  {
 public:
   ProxyAutoConfig();
   ~ProxyAutoConfig();
 
   nsresult Init(const nsCString &aPACURI,
                 const nsCString &aPACScript);
+  void     SetThreadLocalIndex(uint32_t index);
   void     Shutdown();
   void     GC();
   bool     MyIPAddress(const JS::CallArgs &aArgs);
   bool     ResolveAddress(const nsCString &aHostName,
                           NetAddr *aNetAddr, unsigned int aTimeout);
 
   /**
    * Get the proxy string for the specified URI.  The proxy string is
--- a/netwerk/base/src/nsChannelClassifier.cpp
+++ b/netwerk/base/src/nsChannelClassifier.cpp
@@ -1,22 +1,31 @@
 /* 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 "nsChannelClassifier.h"
 
+#include "mozIThirdPartyUtil.h"
 #include "nsNetUtil.h"
-#include "nsIChannel.h"
-#include "nsIProtocolHandler.h"
+#include "nsICacheEntryDescriptor.h"
 #include "nsICachingChannel.h"
-#include "nsICacheEntryDescriptor.h"
+#include "nsIChannel.h"
+#include "nsIDOMDocument.h"
+#include "nsIDOMWindow.h"
+#include "nsIIOService.h"
+#include "nsIPermissionManager.h"
+#include "nsIProtocolHandler.h"
+#include "nsIScriptSecurityManager.h"
+
+#include "mozilla/Preferences.h"
+
 #include "prlog.h"
-#include "nsIScriptSecurityManager.h"
-#include "mozIThirdPartyUtil.h"
+
+using mozilla::Preferences;
 
 #if defined(PR_LOGGING)
 //
 // NSPR_LOG_MODULES=nsChannelClassifier:5
 //
 static PRLogModuleInfo *gChannelClassifierLog;
 #endif
 #undef LOG
@@ -28,32 +37,88 @@ NS_IMPL_ISUPPORTS(nsChannelClassifier,
 nsChannelClassifier::nsChannelClassifier()
 {
 #if defined(PR_LOGGING)
     if (!gChannelClassifierLog)
         gChannelClassifierLog = PR_NewLogModule("nsChannelClassifier");
 #endif
 }
 
-bool
-nsChannelClassifier::ShouldEnableTrackingProtection(nsIChannel* aChannel)
+nsresult
+nsChannelClassifier::ShouldEnableTrackingProtection(nsIChannel* aChannel,
+                                                    bool *result)
 {
+    NS_ENSURE_ARG(result);
+    *result = false;
+
     nsresult rv;
-
     nsCOMPtr<mozIThirdPartyUtil> thirdPartyUtil =
         do_GetService(THIRDPARTYUTIL_CONTRACTID, &rv);
-    if (NS_FAILED(rv)) {
-      return false;
-    }
-
+    NS_ENSURE_SUCCESS(rv, rv);
     // Third party checks don't work for chrome:// URIs in mochitests, so just
     // default to isThirdParty = true
     bool isThirdParty = true;
     (void)thirdPartyUtil->IsThirdPartyChannel(aChannel, nullptr, &isThirdParty);
-    return isThirdParty;
+    if (!isThirdParty) {
+        *result = false;
+        return NS_OK;
+    }
+
+    nsCOMPtr<nsIDOMWindow> win;
+    rv = thirdPartyUtil->GetTopWindowForChannel(aChannel, getter_AddRefs(win));
+    NS_ENSURE_SUCCESS(rv, rv);
+
+    nsCOMPtr<nsIURI> uri;
+    rv = thirdPartyUtil->GetURIFromWindow(win, getter_AddRefs(uri));
+    NS_ENSURE_SUCCESS(rv, rv);
+
+    nsCOMPtr<nsIIOService> ios = do_GetService(NS_IOSERVICE_CONTRACTID, &rv);
+    NS_ENSURE_SUCCESS(rv, rv);
+
+    const char ALLOWLIST_EXAMPLE_PREF[] = "channelclassifier.allowlist_example";
+    if (!uri && Preferences::GetBool(ALLOWLIST_EXAMPLE_PREF, false)) {
+      LOG(("nsChannelClassifier[%p]: Allowlisting test domain", this));
+      rv = ios->NewURI(NS_LITERAL_CSTRING("http://allowlisted.example.com"),
+                       nullptr, nullptr, getter_AddRefs(uri));
+      NS_ENSURE_SUCCESS(rv, rv);
+    }
+
+    // Take the host/port portion so we can allowlist by site. Also ignore the
+    // scheme, since users who put sites on the allowlist probably don't expect
+    // allowlisting to depend on scheme.
+    nsCOMPtr<nsIURL> url = do_QueryInterface(uri, &rv);
+    NS_ENSURE_SUCCESS(rv, rv);
+
+    nsCString escaped(NS_LITERAL_CSTRING("https://"));
+    nsAutoCString temp;
+    rv = url->GetHostPort(temp);
+    NS_ENSURE_SUCCESS(rv, rv);
+    escaped.Append(temp);
+
+    // Stuff the whole thing back into a URI for the permission manager.
+    rv = ios->NewURI(escaped, nullptr, nullptr, getter_AddRefs(uri));
+    NS_ENSURE_SUCCESS(rv, rv);
+
+    nsCOMPtr<nsIPermissionManager> permMgr =
+        do_GetService(NS_PERMISSIONMANAGER_CONTRACTID, &rv);
+    NS_ENSURE_SUCCESS(rv, rv);
+
+    uint32_t permissions = nsIPermissionManager::UNKNOWN_ACTION;
+    rv = permMgr->TestPermission(uri, "trackingprotection", &permissions);
+    NS_ENSURE_SUCCESS(rv, rv);
+
+#ifdef DEBUG
+    if (permissions == nsIPermissionManager::ALLOW_ACTION) {
+        LOG(("nsChannelClassifier[%p]: Allowlisting channel[%p] for %s", this,
+             aChannel, escaped.get()));
+    }
+#endif
+
+    *result = permissions != nsIPermissionManager::ALLOW_ACTION;
+    return NS_OK;
 }
 
 nsresult
 nsChannelClassifier::Start(nsIChannel *aChannel)
 {
     // Don't bother to run the classifier on a load that has already failed.
     // (this might happen after a redirect)
     nsresult status;
@@ -111,17 +176,19 @@ nsChannelClassifier::Start(nsIChannel *a
     NS_ENSURE_SUCCESS(rv, rv);
 
     nsCOMPtr<nsIPrincipal> principal;
     rv = securityManager->GetChannelPrincipal(aChannel,
                                               getter_AddRefs(principal));
     NS_ENSURE_SUCCESS(rv, rv);
 
     bool expectCallback;
-    bool trackingProtectionEnabled = ShouldEnableTrackingProtection(aChannel);
+    bool trackingProtectionEnabled = false;
+    (void)ShouldEnableTrackingProtection(aChannel, &trackingProtectionEnabled);
+
     rv = uriClassifier->Classify(principal, trackingProtectionEnabled, this,
                                  &expectCallback);
     if (NS_FAILED(rv)) return rv;
 
     if (expectCallback) {
         // Suspend the channel, it will be resumed when we get the classifier
         // callback.
         rv = aChannel->Suspend();
@@ -142,16 +209,21 @@ nsChannelClassifier::Start(nsIChannel *a
     return NS_OK;
 }
 
 // Note in the cache entry that this URL was classified, so that future
 // cached loads don't need to be checked.
 void
 nsChannelClassifier::MarkEntryClassified(nsresult status)
 {
+    // Don't cache tracking classifications because we support allowlisting.
+    if (status == NS_ERROR_TRACKING_URI) {
+        return;
+    }
+
     nsCOMPtr<nsICachingChannel> cachingChannel =
         do_QueryInterface(mSuspendedChannel);
     if (!cachingChannel) {
         return;
     }
 
     nsCOMPtr<nsISupports> cacheToken;
     cachingChannel->GetCacheToken(getter_AddRefs(cacheToken));
@@ -205,18 +277,23 @@ nsChannelClassifier::HasBeenClassified(n
 NS_IMETHODIMP
 nsChannelClassifier::OnClassifyComplete(nsresult aErrorCode)
 {
     if (mSuspendedChannel) {
         MarkEntryClassified(aErrorCode);
 
         if (NS_FAILED(aErrorCode)) {
 #ifdef DEBUG
-            LOG(("nsChannelClassifier[%p]: cancelling channel %p with error "
-                 "code: %x", this, mSuspendedChannel.get(), aErrorCode));
+            nsCOMPtr<nsIURI> uri;
+            mSuspendedChannel->GetURI(getter_AddRefs(uri));
+            nsCString spec;
+            uri->GetSpec(spec);
+            LOG(("nsChannelClassifier[%p]: cancelling channel %p for %s "
+                 "with error code: %x", this, mSuspendedChannel.get(),
+                 spec.get(), aErrorCode));
 #endif
             mSuspendedChannel->Cancel(aErrorCode);
         }
 #ifdef DEBUG
         LOG(("nsChannelClassifier[%p]: resuming channel %p from "
              "OnClassifyComplete", this, mSuspendedChannel.get()));
 #endif
         mSuspendedChannel->Resume();
--- a/netwerk/base/src/nsChannelClassifier.h
+++ b/netwerk/base/src/nsChannelClassifier.h
@@ -24,12 +24,12 @@ public:
 
 private:
     nsCOMPtr<nsIChannel> mSuspendedChannel;
 
     ~nsChannelClassifier() {}
     void MarkEntryClassified(nsresult status);
     bool HasBeenClassified(nsIChannel *aChannel);
     // Whether or not tracking protection should be enabled on this channel.
-    bool ShouldEnableTrackingProtection(nsIChannel* aChannel);
+    nsresult ShouldEnableTrackingProtection(nsIChannel *aChannel, bool *result);
 };
 
 #endif
--- a/netwerk/base/src/nsPACMan.cpp
+++ b/netwerk/base/src/nsPACMan.cpp
@@ -250,23 +250,31 @@ PendingPACQuery::Run()
 {
   NS_ABORT_IF_FALSE(!NS_IsMainThread(), "wrong thread");
   mPACMan->PostQuery(this);
   return NS_OK;
 }
 
 //-----------------------------------------------------------------------------
 
+static bool sThreadLocalSetup = false;
+static uint32_t sThreadLocalIndex = 0xdeadbeef; // out of range
+
 nsPACMan::nsPACMan()
   : mLoadPending(false)
   , mShutdown(false)
   , mLoadFailureCount(0)
   , mInProgress(false)
 {
   NS_ABORT_IF_FALSE(NS_IsMainThread(), "pacman must be created on main thread");
+  if (!sThreadLocalSetup){
+    sThreadLocalSetup = true;
+    PR_NewThreadPrivateIndex(&sThreadLocalIndex, nullptr);
+  }
+  mPAC.SetThreadLocalIndex(sThreadLocalIndex);
 }
 
 nsPACMan::~nsPACMan()
 {
   if (mPACThread) {
     if (NS_IsMainThread()) {
       mPACThread->Shutdown();
     }
--- a/netwerk/base/src/nsProtocolProxyService.cpp
+++ b/netwerk/base/src/nsProtocolProxyService.cpp
@@ -560,16 +560,20 @@ nsProtocolProxyService::PrefsChanged(nsI
     if (!pref || !strcmp(pref, PROXY_PREF("autoconfig_url")))
         reloadPAC = true;
 
     if (reloadPAC) {
         tempString.Truncate();
         if (mProxyConfig == PROXYCONFIG_PAC) {
             prefBranch->GetCharPref(PROXY_PREF("autoconfig_url"),
                                     getter_Copies(tempString));
+            if (mPACMan && !mPACMan->IsPACURI(tempString)) {
+                LOG(("PAC Thread URI Changed - Reset Pac Thread"));
+                ResetPACThread();
+            }
         } else if (mProxyConfig == PROXYCONFIG_WPAD) {
             // We diverge from the WPAD spec here in that we don't walk the
             // hosts's FQDN, stripping components until we hit a TLD.  Doing so
             // is dangerous in the face of an incomplete list of TLDs, and TLDs
             // get added over time.  We could consider doing only a single
             // substitution of the first component, if that proves to help
             // compatibility.
             tempString.AssignLiteral(WPAD_URL);
@@ -938,17 +942,17 @@ nsProtocolProxyService::ProcessPACString
         return;
     }
 
     const char *proxies = pacString.get();
 
     nsProxyInfo *pi = nullptr, *first = nullptr, *last = nullptr;
     while (*proxies) {
         proxies = ExtractProxyInfo(proxies, aResolveFlags, &pi);
-        if (pi && !mProxyOverTLS) {
+        if (pi && (pi->mType == kProxyType_HTTPS) && !mProxyOverTLS) {
             delete pi;
             pi = nullptr;
         }
 
         if (pi) {
             if (last) {
                 NS_ASSERTION(last->mNext == nullptr, "leaking nsProxyInfo");
                 last->mNext = pi;
--- a/netwerk/socket/nsISSLSocketControl.idl
+++ b/netwerk/socket/nsISSLSocketControl.idl
@@ -2,24 +2,25 @@
  *
  * 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"
 
 interface nsIInterfaceRequestor;
+interface nsIX509Cert;
 
 %{C++
 template<class T> class nsTArray;
 class nsCString;
 %}
 [ref] native nsCStringTArrayRef(nsTArray<nsCString>);
 
-[scriptable, builtinclass, uuid(2032ad83-229f-4ddb-818a-59b9ae4ecd4b)]
+[scriptable, builtinclass, uuid(7836a872-e50c-4e43-8224-fd08a8d09699)]
 interface nsISSLSocketControl : nsISupports {
     attribute nsIInterfaceRequestor     notificationCallbacks;
 
     void proxyStartSSL();
     void StartTLS();
 
     /* NPN (Next Protocol Negotiation) is a mechanism for
        negotiating the protocol to be spoken inside the SSL
@@ -89,10 +90,17 @@ interface nsISSLSocketControl : nsISuppo
     const short SSL_MAC_MD5     = 1;
     const short SSL_MAC_SHA     = 2;
     const short SSL_HMAC_MD5    = 3;
     const short SSL_HMAC_SHA    = 4;
     const short SSL_HMAC_SHA256 = 5;
     const short SSL_MAC_AEAD    = 6;
 
     [infallible] readonly attribute short MACAlgorithmUsed;
+
+    /**
+     * If set before the server requests a client cert (assuming it does so at
+     * all), then this cert will be presented to the server, instead of asking
+     * the user or searching the set of rememebered user cert decisions.
+     */
+    attribute nsIX509Cert clientCert;
 };
 
--- a/netwerk/test/unit/test_protocolproxyservice.js
+++ b/netwerk/test/unit/test_protocolproxyservice.js
@@ -358,56 +358,97 @@ function protocol_handler_test_1(pi)
 {
   do_check_eq(pi, null);
   prefs.setCharPref("network.proxy.autoconfig_url", "");
   prefs.setIntPref("network.proxy.type", 0);
 
   run_pac_cancel_test();
 }
 
-function TestResolveCallback() {
+function TestResolveCallback(type, nexttest) {
+  this.type = type;
+  this.nexttest = nexttest;
 }
 TestResolveCallback.prototype = {
   QueryInterface:
   function TestResolveCallback_QueryInterface(iid) {
     if (iid.equals(Components.interfaces.nsIProtocolProxyCallback) ||
         iid.equals(Components.interfaces.nsISupports))
       return this;
     throw Components.results.NS_ERROR_NO_INTERFACE;
   },
 
   onProxyAvailable:
   function TestResolveCallback_onProxyAvailable(req, uri, pi, status) {
     dump("*** uri=" + uri.spec + ", status=" + status + "\n");
 
-    do_check_neq(req, null);
-    do_check_neq(uri, null);
-    do_check_eq(status, 0);
-    do_check_neq(pi, null);
+    if (this.type == null) {
+      do_check_eq(pi, null);
+    } else {
+      do_check_neq(req, null);
+      do_check_neq(uri, null);
+      do_check_eq(status, 0);
+      do_check_neq(pi, null);
+      check_proxy(pi, this.type, "foopy", 8080, 0, -1, true);
+      check_proxy(pi.failoverProxy, "direct", "", -1, -1, -1, false);
+    }
 
-    check_proxy(pi, "http", "foopy", 8080, 0, -1, true);
-    check_proxy(pi.failoverProxy, "direct", "", -1, -1, -1, false);
-
-    run_protocol_handler_test();
+    this.nexttest();
   }
 };
 
+var originalTLSProxy;
+
 function run_pac_test() {
   var pac = 'data:text/plain,' +
             'function FindProxyForURL(url, host) {' +
             '  return "PROXY foopy:8080; DIRECT";' +
             '}';
   var uri = ios.newURI("http://www.mozilla.org/", null, null);
 
   // Configure PAC
 
   prefs.setIntPref("network.proxy.type", 2);
   prefs.setCharPref("network.proxy.autoconfig_url", pac);
+  var req = pps.asyncResolve(uri, 0, new TestResolveCallback("http", run_pac2_test));
+}
 
-  var req = pps.asyncResolve(uri, 0, new TestResolveCallback());
+function run_pac2_test() {
+  var pac = 'data:text/plain,' +
+            'function FindProxyForURL(url, host) {' +
+            '  return "HTTPS foopy:8080; DIRECT";' +
+            '}';
+  var uri = ios.newURI("http://www.mozilla.org/", null, null);
+
+  // Configure PAC
+  originalTLSProxy = prefs.getBoolPref("network.proxy.proxy_over_tls");
+
+  prefs.setCharPref("network.proxy.autoconfig_url", pac);
+  prefs.setBoolPref("network.proxy.proxy_over_tls", true);
+
+  var req = pps.asyncResolve(uri, 0, new TestResolveCallback("https", run_pac3_test));
+}
+
+function run_pac3_test() {
+  var pac = 'data:text/plain,' +
+            'function FindProxyForURL(url, host) {' +
+            '  return "HTTPS foopy:8080; DIRECT";' +
+            '}';
+  var uri = ios.newURI("http://www.mozilla.org/", null, null);
+
+  // Configure PAC
+  prefs.setCharPref("network.proxy.autoconfig_url", pac);
+  prefs.setBoolPref("network.proxy.proxy_over_tls", false);
+
+  var req = pps.asyncResolve(uri, 0, new TestResolveCallback(null, finish_pac_test));
+}
+
+function finish_pac_test() {
+  prefs.setBoolPref("network.proxy.proxy_over_tls", originalTLSProxy);
+  run_protocol_handler_test();
 }
 
 function TestResolveCancelationCallback() {
 }
 TestResolveCancelationCallback.prototype = {
   QueryInterface:
   function TestResolveCallback_QueryInterface(iid) {
     if (iid.equals(Components.interfaces.nsIProtocolProxyCallback) ||
--- a/nsprpub/TAG-INFO
+++ b/nsprpub/TAG-INFO
@@ -1,1 +1,1 @@
-NSPR_4_10_7_BETA4
+NSPR_4_10_7_BETA5
--- a/nsprpub/config/prdepend.h
+++ b/nsprpub/config/prdepend.h
@@ -5,9 +5,8 @@
 
 /*
  * A dummy header file that is a dependency for all the object files.
  * Used to force a full recompilation of NSPR in Mozilla's Tinderbox
  * depend builds.  See comments in rules.mk.
  */
 
 #error "Do not include this header file."
-
--- a/nsprpub/configure
+++ b/nsprpub/configure
@@ -790,16 +790,17 @@ with_dist_includedir
 with_dist_libdir
 with_mozilla
 enable_optimize
 enable_debug
 enable_debug_symbols
 enable_win32_target
 enable_symbian_target
 enable_debug_rtl
+enable_static_rtl
 enable_n32
 enable_x32
 enable_64bit
 enable_mdupdate
 enable_cplus
 with_arm_kuser
 with_macos_sdk
 enable_macos_target
@@ -1450,16 +1451,17 @@ Optional Features:
   --enable-debug=DBG    Enable debugging (using compiler flags DBG)
   --enable-debug-symbols=DBG    Enable debugging symbols
                                        (using compiler flags DBG)
   --enable-win32-target=\$t
                           Specify win32 flavor. (WIN95 or WINNT)
   --enable-symbian-target=\$t
                           Specify symbian flavor. (WINSCW or GCCE)
   --enable-debug-rtl      Use the MSVC debug runtime library
+  --enable-static-rtl     Use the MSVC static runtime library
   --enable-n32            Enable n32 ABI support (IRIX only)
   --enable-x32            Enable x32 ABI support (x86_64 only)
   --enable-64bit          Enable 64-bit support (on certain platforms)
   --enable-mdupdate       Enable use of certain compilers' mdupdate feature
   --enable-cplus          Enable some c++ api routines
   --enable-macos-target=VER
                           Set the minimum MacOS version needed at runtime
                           10.2 for ppc, 10.4 for x86
@@ -2905,16 +2907,24 @@ if test "${enable_debug_rtl+set}" = set;
   enableval=$enable_debug_rtl;  if test "$enableval" = "yes"; then
 	    USE_DEBUG_RTL=1
       else
 	    USE_DEBUG_RTL=0
       fi
 fi
 
 
+# Check whether --enable-static-rtl was given.
+if test "${enable_static_rtl+set}" = set; then :
+  enableval=$enable_static_rtl;  if test "$enableval" = "yes"; then
+	    USE_STATIC_RTL=1
+      fi
+fi
+
+
 # Check whether --enable-n32 was given.
 if test "${enable_n32+set}" = set; then :
   enableval=$enable_n32;  if test "$enableval" = "yes"; then
 	USE_N32=1
       else if test "$enableval" = "no"; then
 	USE_N32=
       fi
     fi
@@ -7180,19 +7190,27 @@ tools are selected during the Xcode/Deve
             PROFILE_USE_CFLAGS="$PROFILE_USE_CFLAGS -Gw"
         fi
 
         if test -z "$MOZ_OPTIMIZE"; then
             CFLAGS="$CFLAGS -Od"
         fi
 
         if test "$USE_DEBUG_RTL" = 1; then
-            CFLAGS="$CFLAGS -MDd"
+            if test -n "$USE_STATIC_RTL"; then
+                CFLAGS="$CFLAGS -MTd"
+            else
+                CFLAGS="$CFLAGS -MDd"
+            fi
         else
-            CFLAGS="$CFLAGS -MD"
+            if test -n "$USE_STATIC_RTL"; then
+                CFLAGS="$CFLAGS -MT"
+            else
+                CFLAGS="$CFLAGS -MD"
+            fi
         fi
 
         if test -n "$MOZ_DEBUG"; then
             $as_echo "#define _DEBUG 1" >>confdefs.h
 
         else
             DEFINES="$DEFINES -U_DEBUG"
         fi
--- a/nsprpub/configure.in
+++ b/nsprpub/configure.in
@@ -385,16 +385,22 @@ AC_ARG_ENABLE(symbian-target,
 AC_ARG_ENABLE(debug-rtl,
     [  --enable-debug-rtl      Use the MSVC debug runtime library],
     [ if test "$enableval" = "yes"; then
 	    USE_DEBUG_RTL=1
       else
 	    USE_DEBUG_RTL=0
       fi ])
 
+AC_ARG_ENABLE(static-rtl,
+    [  --enable-static-rtl     Use the MSVC static runtime library],
+    [ if test "$enableval" = "yes"; then
+	    USE_STATIC_RTL=1
+      fi ])
+
 AC_ARG_ENABLE(n32,
     [  --enable-n32            Enable n32 ABI support (IRIX only)],
     [ if test "$enableval" = "yes"; then
 	USE_N32=1
       else if test "$enableval" = "no"; then
 	USE_N32=
       fi
     fi ])
@@ -1999,19 +2005,27 @@ tools are selected during the Xcode/Deve
             PROFILE_USE_CFLAGS="$PROFILE_USE_CFLAGS -Gw"
         fi
 
         if test -z "$MOZ_OPTIMIZE"; then
             CFLAGS="$CFLAGS -Od"
         fi
 
         if test "$USE_DEBUG_RTL" = 1; then
-            CFLAGS="$CFLAGS -MDd"
+            if test -n "$USE_STATIC_RTL"; then
+                CFLAGS="$CFLAGS -MTd"
+            else
+                CFLAGS="$CFLAGS -MDd"
+            fi
         else
-            CFLAGS="$CFLAGS -MD"
+            if test -n "$USE_STATIC_RTL"; then
+                CFLAGS="$CFLAGS -MT"
+            else
+                CFLAGS="$CFLAGS -MD"
+            fi
         fi
 
         if test -n "$MOZ_DEBUG"; then
             AC_DEFINE(_DEBUG)
         else
             DEFINES="$DEFINES -U_DEBUG"
         fi
 
--- a/python/mozbuild/mozbuild/mach_commands.py
+++ b/python/mozbuild/mozbuild/mach_commands.py
@@ -613,17 +613,17 @@ class Warnings(MachCommandBase):
                     warning['column'], warning['flag'], warning['message']))
             else:
                 print('%s:%d [%s] %s' % (filename, warning['line'],
                     warning['flag'], warning['message']))
 
 @CommandProvider
 class GTestCommands(MachCommandBase):
     @Command('gtest', category='testing',
-        description='Run GTest unit tests.')
+        description='Run GTest unit tests (C++ tests).')
     @CommandArgument('gtest_filter', default=b"*", nargs='?', metavar='gtest_filter',
         help="test_filter is a ':'-separated list of wildcard patterns (called the positive patterns),"
              "optionally followed by a '-' and another ':'-separated pattern list (called the negative patterns).")
     @CommandArgument('--jobs', '-j', default='1', nargs='?', metavar='jobs', type=int,
         help='Run the tests in parallel using multiple processes.')
     @CommandArgument('--tbpl-parser', '-t', action='store_true',
         help='Output test results in a format that can be parsed by TBPL.')
     @CommandArgument('--shuffle', '-s', action='store_true',
--- a/security/manager/ssl/src/nsNSSComponent.cpp
+++ b/security/manager/ssl/src/nsNSSComponent.cpp
@@ -19,27 +19,17 @@
 #include "nsDirectoryServiceDefs.h"
 #include "nsICertOverrideService.h"
 #include "mozilla/Preferences.h"
 #include "nsThreadUtils.h"
 #include "mozilla/PublicSSL.h"
 #include "mozilla/StaticPtr.h"
 
 #ifndef MOZ_DISABLE_CRYPTOLEGACY
-#include "nsIDOMNode.h"
-#include "nsIDOMEvent.h"
-#include "nsIDOMDocument.h"
-#include "nsIDOMWindow.h"
-#include "nsIDOMWindowCollection.h"
-#include "nsIDocument.h"
-#include "mozilla/dom/SmartCardEvent.h"
 #include "nsSmartCardMonitor.h"
-#include "nsIDOMCryptoLegacy.h"
-#else
-#include "nsIDOMCrypto.h"
 #endif
 
 #include "nsCRT.h"
 #include "nsNTLMAuthModule.h"
 #include "nsIFile.h"
 #include "nsIProperties.h"
 #include "nsIWindowWatcher.h"
 #include "nsIPrompt.h"
@@ -62,72 +52,24 @@
 
 #ifdef XP_WIN
 #include "nsILocalFileWin.h"
 #endif
 
 #include "p12plcy.h"
 
 using namespace mozilla;
-using namespace mozilla::dom;
 using namespace mozilla::psm;
 
 #ifdef PR_LOGGING
 PRLogModuleInfo* gPIPNSSLog = nullptr;
 #endif
 
 int nsNSSComponent::mInstanceCount = 0;
 
-// XXX tmp callback for slot password
-extern char* pk11PasswordPrompt(PK11SlotInfo* slot, PRBool retry, void* arg);
-
-#ifndef MOZ_DISABLE_CRYPTOLEGACY
-//This class is used to run the callback code
-//passed to the event handlers for smart card notification
-class nsTokenEventRunnable : public nsIRunnable {
-public:
-  nsTokenEventRunnable(const nsAString& aType, const nsAString& aTokenName);
-
-  NS_IMETHOD Run ();
-  NS_DECL_THREADSAFE_ISUPPORTS
-protected:
-  virtual ~nsTokenEventRunnable();
-private:
-  nsString mType;
-  nsString mTokenName;
-};
-
-// ISuuports implementation for nsTokenEventRunnable
-NS_IMPL_ISUPPORTS(nsTokenEventRunnable, nsIRunnable)
-
-nsTokenEventRunnable::nsTokenEventRunnable(const nsAString& aType,
-                                           const nsAString& aTokenName)
-  : mType(aType)
-  , mTokenName(aTokenName)
-{
-}
-
-nsTokenEventRunnable::~nsTokenEventRunnable() { }
-
-//Implementation that runs the callback passed to
-//crypto.generateCRMFRequest as an event.
-NS_IMETHODIMP
-nsTokenEventRunnable::Run()
-{
-  static NS_DEFINE_CID(kNSSComponentCID, NS_NSSCOMPONENT_CID);
-
-  nsresult rv;
-  nsCOMPtr<nsINSSComponent> nssComponent(do_GetService(kNSSComponentCID, &rv));
-  if (NS_FAILED(rv))
-    return rv;
-
-  return nssComponent->DispatchEvent(mType, mTokenName);
-}
-#endif // MOZ_DISABLE_CRYPTOLEGACY
-
 bool nsPSMInitPanic::isPanic = false;
 
 // This function can be called from chrome or content processes
 // to ensure that NSS is initialized.
 bool EnsureNSSInitializedChromeOrContent()
 {
   nsresult rv;
   if (XRE_GetProcessType() == GeckoProcessType_Default) {
@@ -331,131 +273,16 @@ nsNSSComponent::~nsNSSComponent()
 
   // We are being freed, drop the haveLoaded flag to re-enable
   // potential nss initialization later.
   EnsureNSSInitialized(nssShutdown);
 
   PR_LOG(gPIPNSSLog, PR_LOG_DEBUG, ("nsNSSComponent::dtor finished\n"));
 }
 
-#ifndef MOZ_DISABLE_CRYPTOLEGACY
-NS_IMETHODIMP
-nsNSSComponent::PostEvent(const nsAString& eventType,
-                          const nsAString& tokenName)
-{
-  nsCOMPtr<nsIRunnable> runnable =
-                               new nsTokenEventRunnable(eventType, tokenName);
-
-  return NS_DispatchToMainThread(runnable);
-}
-
-
-NS_IMETHODIMP
-nsNSSComponent::DispatchEvent(const nsAString& eventType,
-                              const nsAString& tokenName)
-{
-  // 'Dispatch' the event to all the windows. 'DispatchEventToWindow()' will
-  // first check to see if a given window has requested crypto events.
-  nsresult rv;
-  nsCOMPtr<nsIWindowWatcher> windowWatcher =
-                            do_GetService(NS_WINDOWWATCHER_CONTRACTID, &rv);
-
-  if (NS_FAILED(rv)) {
-    return rv;
-  }
-
-  nsCOMPtr<nsISimpleEnumerator> enumerator;
-  rv = windowWatcher->GetWindowEnumerator(getter_AddRefs(enumerator));
-  if (NS_FAILED(rv)) {
-    return rv;
-  }
-
-  bool hasMoreWindows;
-
-  while (NS_SUCCEEDED(enumerator->HasMoreElements(&hasMoreWindows))
-         && hasMoreWindows) {
-    nsCOMPtr<nsISupports> supports;
-    enumerator->GetNext(getter_AddRefs(supports));
-    nsCOMPtr<nsIDOMWindow> domWin(do_QueryInterface(supports));
-    if (domWin) {
-      nsresult rv2 = DispatchEventToWindow(domWin, eventType, tokenName);
-      if (NS_FAILED(rv2)) {
-        // return the last failure, don't let a single failure prevent
-        // continued delivery of events.
-        rv = rv2;
-      }
-    }
-  }
-  return rv;
-}
-
-nsresult
-nsNSSComponent::DispatchEventToWindow(nsIDOMWindow* domWin,
-                                      const nsAString& eventType,
-                                      const nsAString& tokenName)
-{
-  if (!domWin) {
-    return NS_OK;
-  }
-
-  // first walk the children and dispatch their events
-  nsresult rv;
-  nsCOMPtr<nsIDOMWindowCollection> frames;
-  rv = domWin->GetFrames(getter_AddRefs(frames));
-  if (NS_FAILED(rv)) {
-    return rv;
-  }
-
-  uint32_t length;
-  frames->GetLength(&length);
-  uint32_t i;
-  for (i = 0; i < length; i++) {
-    nsCOMPtr<nsIDOMWindow> childWin;
-    frames->Item(i, getter_AddRefs(childWin));
-    DispatchEventToWindow(childWin, eventType, tokenName);
-  }
-
-  // check if we've enabled smart card events on this window
-  // NOTE: it's not an error to say that we aren't going to dispatch
-  // the event.
-  nsCOMPtr<nsIDOMCrypto> crypto;
-  domWin->GetCrypto(getter_AddRefs(crypto));
-  if (!crypto) {
-    return NS_OK; // nope, it doesn't have a crypto property
-  }
-
-  bool boolrv;
-  crypto->GetEnableSmartCardEvents(&boolrv);
-  if (!boolrv) {
-    return NS_OK; // nope, it's not enabled.
-  }
-
-  // dispatch the event ...
-
-  // find the document
-  nsCOMPtr<nsIDOMDocument> doc;
-  rv = domWin->GetDocument(getter_AddRefs(doc));
-  if (!doc) {
-    return NS_FAILED(rv) ? rv : NS_ERROR_FAILURE;
-  }
-
-  nsCOMPtr<EventTarget> d = do_QueryInterface(doc);
-
-  SmartCardEventInit init;
-  init.mBubbles = false;
-  init.mCancelable = true;
-  init.mTokenName = tokenName;
-
-  nsRefPtr<SmartCardEvent> event = SmartCardEvent::Constructor(d, eventType, init);
-  event->SetTrusted(true);
-
-  return d->DispatchEvent(event, &boolrv);
-}
-#endif // MOZ_DISABLE_CRYPTOLEGACY
-
 NS_IMETHODIMP
 nsNSSComponent::PIPBundleFormatStringFromName(const char* name,
                                               const char16_t** params,
                                               uint32_t numParams,
                                               nsAString& outString)
 {
   nsresult rv = NS_ERROR_FAILURE;
 
--- a/security/manager/ssl/src/nsNSSComponent.h
+++ b/security/manager/ssl/src/nsNSSComponent.h
@@ -39,20 +39,20 @@ MOZ_WARN_UNUSED_RESULT
 #define NS_NSSCOMPONENT_CID \
 {0x4cb64dfd, 0xca98, 0x4e24, {0xbe, 0xfd, 0x0d, 0x92, 0x85, 0xa3, 0x3b, 0xcb}}
 
 #define PSM_COMPONENT_CONTRACTID "@mozilla.org/psm;1"
 
 //Define an interface that we can use to look up from the
 //callbacks passed to NSS.
 
-#define NS_INSSCOMPONENT_IID_STR "538c5093-7cfe-4f13-bc8e-e767766a2d4d"
+#define NS_INSSCOMPONENT_IID_STR "e60602a8-97a3-4fe7-b5b7-56bc6ce87ab4"
 #define NS_INSSCOMPONENT_IID \
-  { 0x538c5093, 0x7cfe, 0x4f13, \
-    { 0xbc, 0x8e, 0xe7, 0x67, 0x76, 0x6a, 0x2d, 0x4d } }
+  { 0xe60602a8, 0x97a3, 0x4fe7, \
+    { 0xb5, 0xb7, 0x56, 0xbc, 0x6c, 0xe8, 0x7a, 0xb4 } }
 
 enum EnsureNSSOperator
 {
   nssLoadingComponent = 0,
   nssInitSucceeded = 1,
   nssInitFailed = 2,
   nssShutdown = 3,
   nssEnsure = 100,
@@ -86,22 +86,16 @@ class NS_NO_VTABLE nsINSSComponent : pub
                                            nsAString& outString) = 0;
 
   NS_IMETHOD LogoutAuthenticatedPK11() = 0;
 
 #ifndef MOZ_DISABLE_CRYPTOLEGACY
   NS_IMETHOD LaunchSmartCardThread(SECMODModule* module) = 0;
 
   NS_IMETHOD ShutdownSmartCardThread(SECMODModule* module) = 0;
-
-  NS_IMETHOD PostEvent(const nsAString& eventType,
-                       const nsAString& token) = 0;
-
-  NS_IMETHOD DispatchEvent(const nsAString& eventType,
-                           const nsAString& token) = 0;
 #endif
 
   NS_IMETHOD IsNSSInitialized(bool* initialized) = 0;
 
   virtual ::mozilla::TemporaryRef<mozilla::psm::SharedCertVerifier>
     GetDefaultCertVerifier() = 0;
 };
 
@@ -144,18 +138,16 @@ public:
                                            const char16_t** params,
                                            uint32_t numParams,
                                            nsAString& outString);
   NS_IMETHOD LogoutAuthenticatedPK11();
 
 #ifndef MOZ_DISABLE_CRYPTOLEGACY
   NS_IMETHOD LaunchSmartCardThread(SECMODModule* module);
   NS_IMETHOD ShutdownSmartCardThread(SECMODModule* module);
-  NS_IMETHOD PostEvent(const nsAString& eventType, const nsAString& token);
-  NS_IMETHOD DispatchEvent(const nsAString& eventType, const nsAString& token);
   void LaunchSmartCardThreads();
   void ShutdownSmartCardThreads();
   nsresult DispatchEventToWindow(nsIDOMWindow* domWin,
                                  const nsAString& eventType,
                                  const nsAString& token);
 #endif
 
   NS_IMETHOD IsNSSInitialized(bool* initialized);
@@ -202,17 +194,16 @@ private:
 
   void deleteBackgroundThreads();
   void createBackgroundThreads();
   nsCertVerificationThread* mCertVerificationThread;
 
   nsNSSHttpInterface mHttpForNSS;
   mozilla::RefPtr<mozilla::psm::SharedCertVerifier> mDefaultCertVerifier;
 
-
   static PRStatus IdentityInfoInit(void);
 };
 
 class nsNSSErrors
 {
 public:
   static const char* getDefaultErrorStringName(PRErrorCode err);
   static const char* getOverrideErrorStringName(PRErrorCode aErrorCode);
--- a/security/manager/ssl/src/nsNSSIOLayer.cpp
+++ b/security/manager/ssl/src/nsNSSIOLayer.cpp
@@ -135,17 +135,18 @@ nsNSSSocketInfo::nsNSSSocketInfo(SharedS
     mNotedTimeUntilReady(false),
     mKEAUsed(nsISSLSocketControl::KEY_EXCHANGE_UNKNOWN),
     mKEAExpected(nsISSLSocketControl::KEY_EXCHANGE_UNKNOWN),
     mKEAKeyBits(0),
     mSSLVersionUsed(nsISSLSocketControl::SSL_VERSION_UNKNOWN),
     mMACAlgorithmUsed(nsISSLSocketControl::SSL_MAC_UNKNOWN),
     mProviderFlags(providerFlags),
     mSocketCreationTimestamp(TimeStamp::Now()),
-    mPlaintextBytesRead(0)
+    mPlaintextBytesRead(0),
+    mClientCert(nullptr)
 {
   mTLSVersionRange.min = 0;
   mTLSVersionRange.max = 0;
 }
 
 nsNSSSocketInfo::~nsNSSSocketInfo()
 {
 }
@@ -199,16 +200,32 @@ nsNSSSocketInfo::GetSSLVersionUsed(int16
 NS_IMETHODIMP
 nsNSSSocketInfo::GetMACAlgorithmUsed(int16_t* aMac)
 {
   *aMac = mMACAlgorithmUsed;
   return NS_OK;
 }
 
 NS_IMETHODIMP
+nsNSSSocketInfo::GetClientCert(nsIX509Cert** aClientCert)
+{
+  NS_ENSURE_ARG_POINTER(aClientCert);
+  *aClientCert = mClientCert;
+  NS_IF_ADDREF(*aClientCert);
+  return NS_OK;
+}
+
+NS_IMETHODIMP
+nsNSSSocketInfo::SetClientCert(nsIX509Cert* aClientCert)
+{
+  mClientCert = aClientCert;
+  return NS_OK;
+}
+
+NS_IMETHODIMP
 nsNSSSocketInfo::GetRememberClientAuthCertificate(bool* aRemember)
 {
   NS_ENSURE_ARG_POINTER(aRemember);
   *aRemember = mRememberClientAuthCertificate;
   return NS_OK;
 }
 
 NS_IMETHODIMP
@@ -1903,16 +1920,39 @@ ClientAuthDataRunnable::RunOnTargetThrea
   CERTCertListNode* node;
   ScopedCERTCertNicknames nicknames;
   int keyError = 0; // used for private key retrieval error
   SSM_UserCertChoice certChoice;
   int32_t NumberOfCerts = 0;
   void* wincx = mSocketInfo;
   nsresult rv;
 
+  nsCOMPtr<nsIX509Cert> socketClientCert;
+  mSocketInfo->GetClientCert(getter_AddRefs(socketClientCert));
+
+  // If a client cert preference was set on the socket info, use that and skip
+  // the client cert UI and/or search of the user's past cert decisions.
+  if (socketClientCert) {
+    cert = socketClientCert->GetCert();
+    if (!cert) {
+      goto loser;
+    }
+
+    // Get the private key
+    privKey = PK11_FindKeyByAnyCert(cert.get(), wincx);
+    if (!privKey) {
+      goto loser;
+    }
+
+    *mPRetCert = cert.forget();
+    *mPRetKey = privKey.forget();
+    mRV = SECSuccess;
+    return;
+  }
+
   // create caNameStrings
   arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE);
   if (!arena) {
     goto loser;
   }
 
   caNameStrings = (char**) PORT_ArenaAlloc(arena,
                                            sizeof(char*) * (mCANames->nnames));
--- a/security/manager/ssl/src/nsNSSIOLayer.h
+++ b/security/manager/ssl/src/nsNSSIOLayer.h
@@ -146,16 +146,18 @@ private:
   int16_t mKEAExpected;
   uint32_t mKEAKeyBits;
   int16_t mSSLVersionUsed;
   int16_t mMACAlgorithmUsed;
 
   uint32_t mProviderFlags;
   mozilla::TimeStamp mSocketCreationTimestamp;
   uint64_t mPlaintextBytesRead;
+
+  nsCOMPtr<nsIX509Cert> mClientCert;
 };
 
 class nsSSLIOLayerHelpers
 {
 public:
   nsSSLIOLayerHelpers();
   ~nsSSLIOLayerHelpers();
 
--- a/security/manager/ssl/src/nsSmartCardMonitor.cpp
+++ b/security/manager/ssl/src/nsSmartCardMonitor.cpp
@@ -1,58 +1,242 @@
 /* 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 "nspr.h"
 
-#include "pk11func.h"
-#include "nsNSSComponent.h"
+#include "mozilla/dom/SmartCardEvent.h"
+#include "mozilla/Services.h"
+#include "mozilla/unused.h"
+#include "nsIDOMCryptoLegacy.h"
+#include "nsIDOMDocument.h"
+#include "nsIDOMWindow.h"
+#include "nsIDOMWindowCollection.h"
+#include "nsIObserverService.h"
+#include "nsISimpleEnumerator.h"
+#include "nsIWindowWatcher.h"
+#include "nsServiceManagerUtils.h"
 #include "nsSmartCardMonitor.h"
-#include "nsServiceManagerUtils.h"
-#include "mozilla/unused.h"
+#include "pk11func.h"
 
 using namespace mozilla;
+using namespace mozilla::dom;
 
 //
 // The SmartCard monitoring thread should start up for each module we load
 // that has removable tokens. This code calls an NSS function which waits
-// until there is a change in the token state. NSS uses the 
+// until there is a change in the token state. NSS uses the
 // C_WaitForSlotEvent() call in PKCS #11 if the module implements the call,
-// otherwise NSS will poll the token in a loop with a delay of 'latency' 
+// otherwise NSS will poll the token in a loop with a delay of 'latency'
 // between polls. Note that the C_WaitForSlotEvent() may wake up on any type
 // of token event, so it's necessary to filter these events down to just the
 // insertion and removal events we are looking for.
 //
-// Once the event is found, It is passed to nsNSSComponent for dispatching
-// on the UI thread, and forwarding to any interested listeners (including
-// javascript).
+// Once the event is found, it is dispatched to the main thread to notify
+// any window where window.crypto.enableSmartCardEvents is true.
+// Additionally, all observers of the topics "smartcard-insert" and
+// "smartcard-remove" are notified by the observer service of the appropriate
+// event.
 //
 
+class nsTokenEventRunnable : public nsIRunnable {
+public:
+  nsTokenEventRunnable(const nsAString& aType, const nsAString& aTokenName)
+    : mType(aType)
+    , mTokenName(aTokenName)
+  {
+  }
+
+  NS_DECL_THREADSAFE_ISUPPORTS
+  NS_DECL_NSIRUNNABLE
+
+private:
+  virtual ~nsTokenEventRunnable() {}
+  nsresult DispatchEventToWindow(nsIDOMWindow* domWin);
+
+  nsString mType;
+  nsString mTokenName;
+};
+
+NS_IMPL_ISUPPORTS(nsTokenEventRunnable, nsIRunnable)
+
+NS_IMETHODIMP
+nsTokenEventRunnable::Run()
+{
+  MOZ_ASSERT(NS_IsMainThread());
+
+  nsCOMPtr<nsIObserverService> observerService =
+    mozilla::services::GetObserverService();
+  if (!observerService) {
+    return NS_ERROR_FAILURE;
+  }
+  // This conversion is safe because mType can only be "smartcard-insert"
+  // or "smartcard-remove".
+  NS_ConvertUTF16toUTF8 eventTypeUTF8(mType);
+  nsresult rv = observerService->NotifyObservers(nullptr, eventTypeUTF8.get(),
+                                                 mTokenName.get());
+  if (NS_FAILED(rv)) {
+    return rv;
+  }
+
+  // 'Dispatch' the event to all the windows. 'DispatchEventToWindow()' will
+  // first check to see if a given window has requested crypto events.
+  nsCOMPtr<nsIWindowWatcher> windowWatcher =
+    do_GetService(NS_WINDOWWATCHER_CONTRACTID, &rv);
+  if (NS_FAILED(rv)) {
+    return rv;
+  }
+
+  nsCOMPtr<nsISimpleEnumerator> enumerator;
+  rv = windowWatcher->GetWindowEnumerator(getter_AddRefs(enumerator));
+  if (NS_FAILED(rv)) {
+    return rv;
+  }
+
+  for (;;) {
+    bool hasMoreWindows;
+    rv = enumerator->HasMoreElements(&hasMoreWindows);
+    if (NS_FAILED(rv) || !hasMoreWindows) {
+      return rv;
+    }
+    nsCOMPtr<nsISupports> supports;
+    enumerator->GetNext(getter_AddRefs(supports));
+    nsCOMPtr<nsIDOMWindow> domWin(do_QueryInterface(supports));
+    if (domWin) {
+      rv = DispatchEventToWindow(domWin);
+      if (NS_FAILED(rv)) {
+        return rv;
+      }
+    }
+  }
+  return rv;
+}
+
+nsresult
+nsTokenEventRunnable::DispatchEventToWindow(nsIDOMWindow* domWin)
+{
+  MOZ_ASSERT(NS_IsMainThread());
+  MOZ_ASSERT(domWin);
+
+  // first walk the children and dispatch their events
+  nsCOMPtr<nsIDOMWindowCollection> frames;
+  nsresult rv = domWin->GetFrames(getter_AddRefs(frames));
+  if (NS_FAILED(rv)) {
+    return rv;
+  }
+
+  uint32_t length;
+  rv = frames->GetLength(&length);
+  if (NS_FAILED(rv)) {
+    return rv;
+  }
+  for (uint32_t i = 0; i < length; i++) {
+    nsCOMPtr<nsIDOMWindow> childWin;
+    rv = frames->Item(i, getter_AddRefs(childWin));
+    if (NS_FAILED(rv)) {
+      return rv;
+    }
+    if (domWin) {
+      rv = DispatchEventToWindow(childWin);
+      if (NS_FAILED(rv)) {
+        return rv;
+      }
+    }
+  }
+
+  // check if we've enabled smart card events on this window
+  // NOTE: it's not an error to say that we aren't going to dispatch
+  // the event.
+  nsCOMPtr<nsIDOMCrypto> crypto;
+  rv = domWin->GetCrypto(getter_AddRefs(crypto));
+  if (NS_FAILED(rv)) {
+    return rv;
+  }
+  if (!crypto) {
+    return NS_OK; // nope, it doesn't have a crypto property
+  }
+
+  bool boolrv;
+  rv = crypto->GetEnableSmartCardEvents(&boolrv);
+  if (NS_FAILED(rv)) {
+    return rv;
+  }
+  if (!boolrv) {
+    return NS_OK; // nope, it's not enabled.
+  }
+
+  // dispatch the event ...
+
+  // find the document
+  nsCOMPtr<nsIDOMDocument> doc;
+  rv = domWin->GetDocument(getter_AddRefs(doc));
+  if (NS_FAILED(rv)) {
+    return rv;
+  }
+  if (!doc) {
+    return NS_ERROR_FAILURE;
+  }
+
+  nsCOMPtr<EventTarget> d = do_QueryInterface(doc);
+
+  SmartCardEventInit init;
+  init.mBubbles = false;
+  init.mCancelable = true;
+  init.mTokenName = mTokenName;
+
+  nsRefPtr<SmartCardEvent> event(SmartCardEvent::Constructor(d, mType, init));
+  event->SetTrusted(true);
+
+  return d->DispatchEvent(event, &boolrv);
+}
 
 // self linking and removing double linked entry
 // adopts the thread it is passed.
-class SmartCardThreadEntry {
+class SmartCardThreadEntry
+{
 public:
- SmartCardThreadEntry *next;
- SmartCardThreadEntry *prev;
- SmartCardThreadEntry **head;
- SmartCardMonitoringThread *thread;
- SmartCardThreadEntry(SmartCardMonitoringThread *thread_,
-   SmartCardThreadEntry *next_, SmartCardThreadEntry *prev_,
-   SmartCardThreadEntry **head_) : 
-   next(next_), prev(prev_), head(head_), thread(thread_) { 
-    if (prev) { prev->next = this; } else { *head = this; }
-    if (next) { next->prev = this; }
+  friend class SmartCardThreadList;
+  SmartCardThreadEntry(SmartCardMonitoringThread *thread,
+                       SmartCardThreadEntry *next,
+                       SmartCardThreadEntry *prev,
+                       SmartCardThreadEntry **head)
+    : next(next)
+    , prev(prev)
+    , head(head)
+    , thread(thread)
+  {
+    if (prev) {
+      prev->next = this;
+    } else {
+      *head = this;
+    }
+    if (next) {
+      next->prev = this;
+    }
   }
-  ~SmartCardThreadEntry() {
-    if (prev) { prev->next = next; } else { *head = next; }
-    if (next) { next->prev = prev; }
+
+  ~SmartCardThreadEntry()
+  {
+    if (prev) {
+      prev->next = next;
+    } else {
+      *head = next;
+    }
+    if (next) {
+      next->prev = prev;
+    }
     // NOTE: automatically stops the thread
     delete thread;
   }
+
+private:
+  SmartCardThreadEntry *next;
+  SmartCardThreadEntry *prev;
+  SmartCardThreadEntry **head;
+  SmartCardMonitoringThread *thread;
 };
 
 //
 // SmartCardThreadList is a class to help manage the running threads.
 // That way new threads could be started and old ones terminated as we
 // load and unload modules.
 //
 SmartCardThreadList::SmartCardThreadList() : head(0)
@@ -67,50 +251,51 @@ SmartCardThreadList::~SmartCardThreadLis
   while (head) {
     delete head;
   }
 }
 
 void
 SmartCardThreadList::Remove(SECMODModule *aModule)
 {
-  for (SmartCardThreadEntry *current = head; current; current = current->next) {
+  for (SmartCardThreadEntry* current = head; current;
+       current = current->next) {
     if (current->thread->GetModule() == aModule) {
       // NOTE: automatically stops the thread and dequeues it from the list
       delete current;
       return;
     }
   }
 }
 
 // adopts the thread passed to it. Starts the thread as well
 nsresult
-SmartCardThreadList::Add(SmartCardMonitoringThread *thread)
+SmartCardThreadList::Add(SmartCardMonitoringThread* thread)
 {
-  SmartCardThreadEntry *current = new SmartCardThreadEntry(thread, head, nullptr,
-                                                           &head);
+  SmartCardThreadEntry* current = new SmartCardThreadEntry(thread, head,
+                                                           nullptr, &head);
   // OK to forget current here, it's on the list.
   unused << current;
 
   return thread->Start();
 }
 
 
 // We really should have a Unity PL Hash function...
 static PLHashNumber
-unity(const void *key) { return PLHashNumber(NS_PTR_TO_INT32(key)); }
+unity(const void* key) { return PLHashNumber(NS_PTR_TO_INT32(key)); }
 
-SmartCardMonitoringThread::SmartCardMonitoringThread(SECMODModule *module_)
+SmartCardMonitoringThread::SmartCardMonitoringThread(SECMODModule* module_)
   : mThread(nullptr)
 {
   mModule = SECMOD_ReferenceModule(module_);
   // simple hash functions, most modules have less than 3 slots, so 10 buckets
   // should be plenty
-  mHash = PL_NewHashTable(10, unity, PL_CompareValues, 
-                           PL_CompareStrings, nullptr, 0);
+  mHash = PL_NewHashTable(10, unity, PL_CompareValues, PL_CompareStrings,
+                          nullptr, 0);
 }
 
 //
 // when we shutdown the thread, be sure to stop it first. If not, it just might
 // crash when the mModule it is looking at disappears.
 //
 SmartCardMonitoringThread::~SmartCardMonitoringThread()
 {
@@ -139,146 +324,148 @@ SmartCardMonitoringThread::Start()
 // SECMOD_CancelWait for why this is so..).
 //
 void SmartCardMonitoringThread::Stop()
 {
   SECStatus rv;
 
   rv = SECMOD_CancelWait(mModule);
   if (rv != SECSuccess) {
-    // we didn't wake up the Wait, so don't try to join the thread 
+    // we didn't wake up the Wait, so don't try to join the thread
     // otherwise we will hang forever...
     return;
   }
- 
+
   // confused about the memory model here? NSPR owns the memory for
   // threads. non-joinable threads are freed when the thread dies.
   // joinable threads are freed after the call to PR_JoinThread.
   // That means if SECMOD_CancelWait fails, we'll leak the mThread
   // structure. this is considered preferable to hanging (which is
   // what will happen if we try to join a thread that blocked).
   if (mThread) {
     PR_JoinThread(mThread);
-    mThread = 0; 
+    mThread = 0;
   }
 }
 
 //
 // remember the name and series of a token in a particular slot.
 // This is important because the name is no longer available when
 // the token is removed. If listeners depended on this information,
 // They would be out of luck. It also is a handy way of making sure
 // we don't generate spurious insertion and removal events as the slot
 // cycles through various states.
 //
 void
-SmartCardMonitoringThread::SetTokenName(CK_SLOT_ID slotid, 
-                                       const char *tokenName, uint32_t series)
+SmartCardMonitoringThread::SetTokenName(CK_SLOT_ID slotid,
+                                       const char* tokenName, uint32_t series)
 {
   if (mHash) {
     if (tokenName) {
       int len = strlen(tokenName) + 1;
       /* this must match the allocator used in
        * PLHashAllocOps.freeEntry DefaultFreeEntry */
-      char *entry = (char *)PR_Malloc(len+sizeof(uint32_t));
-     
-      if (entry) {  
-        memcpy(entry,&series,sizeof(uint32_t));
-        memcpy(&entry[sizeof(uint32_t)],tokenName,len);
+      char* entry = (char*)PR_Malloc(len + sizeof(uint32_t));
 
-        PL_HashTableAdd(mHash,(void *)(uintptr_t)slotid, entry); /* adopt */
+      if (entry) {
+        memcpy(entry, &series, sizeof(uint32_t));
+        memcpy(&entry[sizeof(uint32_t)], tokenName, len);
+
+        PL_HashTableAdd(mHash, (void*)(uintptr_t)slotid, entry); /* adopt */
         return;
       }
-    } 
-    else {
+    } else {
       // if tokenName was not provided, remove the old one (implicit delete)
-      PL_HashTableRemove(mHash,(void *)(uintptr_t)slotid);
+      PL_HashTableRemove(mHash, (void*)(uintptr_t)slotid);
     }
   }
 }
 
 // retrieve the name saved above
-const char *
+const char*
 SmartCardMonitoringThread::GetTokenName(CK_SLOT_ID slotid)
 {
-  const char *tokenName = nullptr;
-  const char *entry;
+  const char* tokenName = nullptr;
+  const char* entry;
 
   if (mHash) {
-    entry = (const char *)PL_HashTableLookupConst(mHash,(void *)(uintptr_t)slotid);
+    entry = (const char*)PL_HashTableLookupConst(mHash,
+                                                 (void*)(uintptr_t)slotid);
     if (entry) {
       tokenName = &entry[sizeof(uint32_t)];
     }
   }
   return tokenName;
 }
 
 // retrieve the series saved in SetTokenName above
 uint32_t
 SmartCardMonitoringThread::GetTokenSeries(CK_SLOT_ID slotid)
 {
   uint32_t series = 0;
-  const char *entry;
+  const char* entry;
 
   if (mHash) {
-    entry = (const char *)PL_HashTableLookupConst(mHash,(void *)(uintptr_t)slotid);
+    entry = (const char*)PL_HashTableLookupConst(mHash,
+                                                 (void*)(uintptr_t)slotid);
     if (entry) {
-      memcpy(&series,entry,sizeof(uint32_t));
+      memcpy(&series, entry, sizeof(uint32_t));
     }
   }
   return series;
 }
 
 //
 // helper function to pass the event off to nsNSSComponent.
 //
-nsresult
-SmartCardMonitoringThread::SendEvent(const nsAString &eventType,
-                                     const char *tokenName)
+void
+SmartCardMonitoringThread::SendEvent(const nsAString& eventType,
+                                     const char* tokenName)
 {
-  static NS_DEFINE_CID(kNSSComponentCID, NS_NSSCOMPONENT_CID);
-
-  nsresult rv;
-  nsCOMPtr<nsINSSComponent> 
-                    nssComponent(do_GetService(kNSSComponentCID, &rv));
-  if (NS_FAILED(rv))
-    return rv;
-
-  // NSS returns actual UTF8, not ASCII
-  nssComponent->PostEvent(eventType, NS_ConvertUTF8toUTF16(tokenName));
-  return NS_OK;
+  // The token name should be UTF8, but it's not clear that this is enforced
+  // by NSS. To be safe, we explicitly check here before converting it to
+  // UTF16. If it isn't UTF8, we just use an empty string with the idea that
+  // consumers of these events should at least be notified that something
+  // happened.
+  nsAutoString tokenNameUTF16(NS_LITERAL_STRING(""));
+  if (IsUTF8(nsDependentCString(tokenName))) {
+    tokenNameUTF16.Assign(NS_ConvertUTF8toUTF16(tokenName));
+  }
+  nsCOMPtr<nsIRunnable> runnable(new nsTokenEventRunnable(eventType,
+                                                          tokenNameUTF16));
+  NS_DispatchToMainThread(runnable);
 }
 
 //
 // This is the main loop.
 //
 void SmartCardMonitoringThread::Execute()
 {
-  PK11SlotInfo *slot;
-  const char *tokenName = nullptr;
+  PK11SlotInfo* slot;
+  const char* tokenName;
 
   //
   // populate token names for already inserted tokens.
   //
-  PK11SlotList *sl =
-            PK11_FindSlotsByNames(mModule->dllName, nullptr, nullptr, true);
-  PK11SlotListElement *sle;
- 
+  PK11SlotList* sl = PK11_FindSlotsByNames(mModule->dllName, nullptr, nullptr,
+                                           true);
+
+  PK11SlotListElement* sle;
   if (sl) {
-    for (sle=PK11_GetFirstSafe(sl); sle; 
-                                      sle=PK11_GetNextSafe(sl,sle,false)) {
-      SetTokenName(PK11_GetSlotID(sle->slot), 
-                  PK11_GetTokenName(sle->slot), PK11_GetSlotSeries(sle->slot));
+    for (sle = PK11_GetFirstSafe(sl); sle;
+         sle = PK11_GetNextSafe(sl, sle, false)) {
+      SetTokenName(PK11_GetSlotID(sle->slot), PK11_GetTokenName(sle->slot),
+                   PK11_GetSlotSeries(sle->slot));
     }
     PK11_FreeSlotList(sl);
   }
 
   // loop starts..
   do {
-    slot = SECMOD_WaitForAnyTokenEvent(mModule, 0, PR_SecondsToInterval(1)  );
+    slot = SECMOD_WaitForAnyTokenEvent(mModule, 0, PR_SecondsToInterval(1));
     if (!slot) {
       break;
     }
 
     // now we have a potential insertion or removal event, see if the slot
     // is present to determine which it is...
     if (PK11_IsPresent(slot)) {
       // insertion
@@ -294,38 +481,37 @@ void SmartCardMonitoringThread::Execute(
           SendEvent(NS_LITERAL_STRING("smartcard-remove"), tokenName);
         }
         tokenName = PK11_GetTokenName(slot);
         // save the token name and series
         SetTokenName(slotID, tokenName, series);
         SendEvent(NS_LITERAL_STRING("smartcard-insert"), tokenName);
       }
     } else {
-      // retrieve token name 
+      // retrieve token name
       CK_SLOT_ID slotID = PK11_GetSlotID(slot);
       tokenName = GetTokenName(slotID);
       // if there's not a token name, then the software isn't expecting
       // a (or another) remove event.
       if (tokenName) {
         SendEvent(NS_LITERAL_STRING("smartcard-remove"), tokenName);
         // clear the token name (after we send it)
         SetTokenName(slotID, nullptr, 0);
       }
     }
     PK11_FreeSlot(slot);
 
   } while (1);
 }
 
 // accessor to help searching active Monitoring threads
-const SECMODModule * SmartCardMonitoringThread::GetModule() 
+const SECMODModule* SmartCardMonitoringThread::GetModule()
 {
   return mModule;
 }
 
 // C-like calling sequence to glue into PR_CreateThread.
-void SmartCardMonitoringThread::LaunchExecute(void *arg)
+void SmartCardMonitoringThread::LaunchExecute(void* arg)
 {
   PR_SetCurrentThreadName("SmartCard");
 
   ((SmartCardMonitoringThread*)arg)->Execute();
 }
-
--- a/security/manager/ssl/src/nsSmartCardMonitor.h
+++ b/security/manager/ssl/src/nsSmartCardMonitor.h
@@ -1,62 +1,62 @@
 /* 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 _NSSMARTCARDMONITOR_
-#define _NSSMARTCARDMONITOR_
+
+#ifndef nsSmartCardMonitor_h
+#define nsSmartCardMonitor_h
 
 #include "prthread.h"
 #include "secmod.h"
 #include "plhash.h"
 #include "pkcs11t.h"
 
 class SmartCardThreadEntry;
 class SmartCardMonitoringThread;
 
 //
 // manage a group of SmartCardMonitoringThreads
 //
 class SmartCardThreadList {
 public:
   SmartCardThreadList();
   ~SmartCardThreadList();
-  void Remove(SECMODModule *module);
-  nsresult Add(SmartCardMonitoringThread *thread);
+  void Remove(SECMODModule* module);
+  nsresult Add(SmartCardMonitoringThread* thread);
+
 private:
-  SmartCardThreadEntry *head;
+  SmartCardThreadEntry* head;
 };
 
 //
 // monitor a Module for token insertion and removal
 //
 // NOTE: this provides the application the ability to dynamically add slots
 // on the fly as necessary.
 //
 class SmartCardMonitoringThread
 {
  public:
-  SmartCardMonitoringThread(SECMODModule *module);
+  SmartCardMonitoringThread(SECMODModule* module);
   ~SmartCardMonitoringThread();
   
   nsresult Start();
   void Stop();
   
   void Execute();
   void Interrupt();
   
-  const SECMODModule *GetModule();
+  const SECMODModule* GetModule();
 
  private:
-
-  static void LaunchExecute(void *arg);
-  void SetTokenName(CK_SLOT_ID slotid, const char *tokenName, uint32_t series);
-  const char *GetTokenName(CK_SLOT_ID slotid);
+  static void LaunchExecute(void* arg);
+  void SetTokenName(CK_SLOT_ID slotid, const char* tokenName, uint32_t series);
+  const char* GetTokenName(CK_SLOT_ID slotid);
   uint32_t GetTokenSeries(CK_SLOT_ID slotid);
-  nsresult SendEvent(const nsAString &type,const char *tokenName);
-  
+  void SendEvent(const nsAString& type, const char* tokenName);
   
-  SECMODModule *mModule;
-  PLHashTable *mHash;
+  SECMODModule* mModule;
+  PLHashTable* mHash;
   PRThread* mThread;
 };
 
-#endif
+#endif // nsSmartCardMonitor_h
--- a/security/manager/ssl/tests/moz.build
+++ b/security/manager/ssl/tests/moz.build
@@ -11,8 +11,11 @@ TEST_DIRS += [
     'mochitest',
 ]
 
 TEST_DIRS += [
   'compiled',
 ]
 
 XPCSHELL_TESTS_MANIFESTS += ['unit/xpcshell.ini']
+
+if not CONFIG['MOZ_DISABLE_CRYPTOLEGACY']:
+    XPCSHELL_TESTS_MANIFESTS += ['unit/xpcshell-smartcards.ini']
--- a/security/manager/ssl/tests/unit/head_psm.js
+++ b/security/manager/ssl/tests/unit/head_psm.js
@@ -52,16 +52,17 @@ const SEC_ERROR_OCSP_UNAUTHORIZED_RESPON
 const SEC_ERROR_OCSP_OLD_RESPONSE                       = SEC_ERROR_BASE + 132;
 const SEC_ERROR_OCSP_INVALID_SIGNING_CERT               = SEC_ERROR_BASE + 144;
 const SEC_ERROR_POLICY_VALIDATION_FAILED                = SEC_ERROR_BASE + 160; // -8032
 const SEC_ERROR_OCSP_BAD_SIGNATURE                      = SEC_ERROR_BASE + 157;
 const SEC_ERROR_CERT_SIGNATURE_ALGORITHM_DISABLED       = SEC_ERROR_BASE + 176;
 const SEC_ERROR_APPLICATION_CALLBACK_ERROR              = SEC_ERROR_BASE + 178;
 
 const SSL_ERROR_BAD_CERT_DOMAIN                         = SSL_ERROR_BASE +  12;
+const SSL_ERROR_BAD_CERT_ALERT                          = SSL_ERROR_BASE +  17;
 
 const MOZILLA_PKIX_ERROR_KEY_PINNING_FAILURE            = MOZILLA_PKIX_ERROR_BASE +   0;
 
 // Supported Certificate Usages
 const certificateUsageSSLClient              = 0x0001;
 const certificateUsageSSLServer              = 0x0002;
 const certificateUsageSSLCA                  = 0x0008;
 const certificateUsageEmailSigner            = 0x0010;
@@ -197,17 +198,18 @@ function clearSessionCache() {
 
 function run_test() {
   do_get_profile();
   add_tls_server_setup("<test-server-name>");
 
   add_connection_test("<test-name-1>.example.com",
                       getXPCOMStatusFromNSS(SEC_ERROR_xxx),
                       function() { ... },
-                      function(aTransportSecurityInfo) { ... });
+                      function(aTransportSecurityInfo) { ... },
+                      function(aTransport) { ... });
   [...]
   add_connection_test("<test-name-n>.example.com", Cr.NS_OK);
 
   run_next_test();
 }
 
 */
 function add_tls_server_setup(serverBinName) {
@@ -218,18 +220,21 @@ function add_tls_server_setup(serverBinN
 
 // Add a TLS connection test case. aHost is the hostname to pass in the SNI TLS
 // extension; this should unambiguously identifiy which test is being run.
 // aExpectedResult is the expected nsresult of the connection.
 // aBeforeConnect is a callback function that takes no arguments that will be
 // called before the connection is attempted.
 // aWithSecurityInfo is a callback function that takes an
 // nsITransportSecurityInfo, which is called after the TLS handshake succeeds.
+// aAfterStreamOpen is a callback function that is called with the
+// nsISocketTransport once the output stream is ready.
 function add_connection_test(aHost, aExpectedResult,
-                             aBeforeConnect, aWithSecurityInfo) {
+                             aBeforeConnect, aWithSecurityInfo,
+                             aAfterStreamOpen) {
   const REMOTE_PORT = 8443;
 
   function Connection(aHost) {
     this.host = aHost;
     let threadManager = Cc["@mozilla.org/thread-manager;1"]
                           .getService(Ci.nsIThreadManager);
     this.thread = threadManager.currentThread;
     this.defer = Promise.defer();
@@ -263,16 +268,19 @@ function add_connection_test(aHost, aExp
       } catch (e) {
         this.result = e.result;
       }
       this.defer.resolve(this);
     },
 
     // nsIOutputStreamCallback
     onOutputStreamReady: function(aStream) {
+      if (aAfterStreamOpen) {
+        aAfterStreamOpen(this.transport);
+      }
       let sslSocketControl = this.transport.securityInfo
                                .QueryInterface(Ci.nsISSLSocketControl);
       sslSocketControl.proxyStartSSL();
       this.outputStream.write("0", 1);
       let inStream = this.transport.openInputStream(0, 0, 0)
                        .QueryInterface(Ci.nsIAsyncInputStream);
       this.inputStream = inStream;
       this.inputStream.asyncWait(this, 0, 0, this.thread);
--- a/security/manager/ssl/tests/unit/moz.build
+++ b/security/manager/ssl/tests/unit/moz.build
@@ -1,7 +1,10 @@
 # -*- Mode: python; c-basic-offset: 4; indent-tabs-mode: nil; tab-width: 40 -*-
 # vim: set filetype=python:
 # This Source Code Form is subject to the terms of the Mozilla Public
 # License, v. 2.0. If a copy of the MPL was not distributed with this
 # file, You can obtain one at http://mozilla.org/MPL/2.0/.
 
 DIRS += ['tlsserver']
+
+if not CONFIG['MOZ_DISABLE_CRYPTOLEGACY']:
+    DIRS += ['pkcs11testmodule']
new file mode 100644
--- /dev/null
+++ b/security/manager/ssl/tests/unit/pkcs11testmodule/Makefile.in
@@ -0,0 +1,7 @@
+# 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/.
+
+LIB_FILES = $(SHARED_LIBRARY)
+LIB_DEST = $(testxpcobjdir)/security/manager/ssl/tests/unit/pkcs11testmodule
+INSTALL_TARGETS += LIB
new file mode 100644
--- /dev/null
+++ b/security/manager/ssl/tests/unit/pkcs11testmodule/moz.build
@@ -0,0 +1,17 @@
+# -*- Mode: python; c-basic-offset: 4; indent-tabs-mode: nil; tab-width: 40 -*-
+# vim: set filetype=python:
+# This Source Code Form is subject to the terms of the Mozilla Public
+# License, v. 2.0. If a copy of the MPL was not distributed with this
+# file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+UNIFIED_SOURCES += [
+    'pkcs11testmodule.cpp',
+]
+
+LIBRARY_NAME = 'pkcs11testmodule'
+
+FORCE_SHARED_LIB = True
+# C_GetFunctionList needs to be exported. As it turns out, it's much easier to
+# just export all the symbols.
+NO_VISIBILITY_FLAGS = True
+NO_DIST_INSTALL = True
new file mode 100644
--- /dev/null
+++ b/security/manager/ssl/tests/unit/pkcs11testmodule/pkcs11testmodule.cpp
@@ -0,0 +1,578 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+// This is a testing PKCS #11 module that simulates a token being inserted and
+// removed from a slot every 50ms. This is achieved mainly in
+// Test_C_WaitForSlotEvent. The smartcard monitoring code essentially calls
+// this function in a tight loop. Each time, this module waits for 50ms and
+// returns, having changed its internal state to report that the token has
+// either been inserted or removed, as appropriate.
+
+#include <string.h>
+
+#if defined(WIN32)
+#  include <windows.h> // for Sleep
+#else
+#  include <unistd.h> // for usleep
+#endif
+
+#include "pkcs11.h"
+
+CK_RV Test_C_Initialize(CK_VOID_PTR)
+{
+  return CKR_OK;
+}
+
+CK_RV Test_C_Finalize(CK_VOID_PTR)
+{
+  return CKR_OK;
+}
+
+static const CK_VERSION CryptokiVersion = { 2, 2 };
+static const CK_VERSION TestLibraryVersion = { 0, 0 };
+static const char TestLibraryDescription[] = "Test PKCS11 Library";
+static const char TestManufacturerID[] = "Test PKCS11 Manufacturer ID";
+
+CK_RV Test_C_GetInfo(CK_INFO_PTR pInfo)
+{
+  if (!pInfo) {
+    return CKR_ARGUMENTS_BAD;
+  }
+
+  pInfo->cryptokiVersion = CryptokiVersion;
+  static_assert(sizeof(TestManufacturerID) <= sizeof(pInfo->manufacturerID),
+                "TestManufacturerID too long - make it shorter");
+  memcpy(pInfo->manufacturerID, TestManufacturerID, sizeof(TestManufacturerID));
+  pInfo->flags = 0; // must be 0
+  static_assert(sizeof(TestLibraryDescription) <=
+                sizeof(pInfo->libraryDescription),
+                "TestLibraryDescription too long - make it shorter");
+  memcpy(pInfo->libraryDescription, TestLibraryDescription,
+         sizeof(TestLibraryDescription));
+  pInfo->libraryVersion = TestLibraryVersion;
+  return CKR_OK;
+}
+
+CK_RV Test_C_GetFunctionList(CK_FUNCTION_LIST_PTR_PTR)
+{
+  return CKR_OK;
+}
+
+static int tokenPresent = 0;
+
+CK_RV Test_C_GetSlotList(CK_BBOOL limitToTokensPresent,
+                         CK_SLOT_ID_PTR pSlotList,
+                         CK_ULONG_PTR pulCount)
+{
+  if (!pulCount) {
+    return CKR_ARGUMENTS_BAD;
+  }
+
+  if (pSlotList) {
+    // apparently CK_SLOT_IDs are integers [1,N] because
+    // who likes counting from 0 all the time?
+    pSlotList[0] = 1;
+  }
+
+  *pulCount = (!limitToTokensPresent || tokenPresent ? 1 : 0);
+  return CKR_OK;
+}
+
+static const char TestSlotDescription[] = "Test PKCS11 Slot";
+
+CK_RV Test_C_GetSlotInfo(CK_SLOT_ID, CK_SLOT_INFO_PTR pInfo)
+{
+  if (!pInfo) {
+    return CKR_ARGUMENTS_BAD;
+  }
+
+  static_assert(sizeof(TestSlotDescription) <= sizeof(pInfo->slotDescription),
+                "TestSlotDescription too long - make it shorter");
+  memcpy(pInfo->slotDescription, TestSlotDescription,
+         sizeof(TestSlotDescription));
+  static_assert(sizeof(TestManufacturerID) <= sizeof(pInfo->manufacturerID),
+                "TestManufacturerID too long - make it shorter");
+  memcpy(pInfo->manufacturerID, TestManufacturerID, sizeof(TestManufacturerID));
+  pInfo->flags = (tokenPresent ? CKF_TOKEN_PRESENT : 0) | CKF_REMOVABLE_DEVICE;
+  pInfo->hardwareVersion = TestLibraryVersion;
+  pInfo->firmwareVersion = TestLibraryVersion;
+  return CKR_OK;
+}
+
+// Deliberately include énye to ensure we're handling encoding correctly.
+// The PKCS #11 base specification v2.20 specifies that strings be encoded
+// as UTF-8.
+static const char TestTokenLabel[] = "Test PKCS11 Tokeñ Label";
+static const char TestTokenModel[] = "Test Model";
+
+CK_RV Test_C_GetTokenInfo(CK_SLOT_ID, CK_TOKEN_INFO_PTR pInfo)
+{
+  if (!pInfo) {
+    return CKR_ARGUMENTS_BAD;
+  }
+
+  static_assert(sizeof(TestTokenLabel) <= sizeof(pInfo->label),
+                "TestTokenLabel too long - make it shorter");
+  memcpy(pInfo->label, TestTokenLabel, sizeof(TestTokenLabel));
+  static_assert(sizeof(TestManufacturerID) <= sizeof(pInfo->manufacturerID),
+                "TestManufacturerID too long - make it shorter");
+  memcpy(pInfo->manufacturerID, TestManufacturerID, sizeof(TestManufacturerID));
+  static_assert(sizeof(TestTokenModel) <= sizeof(pInfo->model),
+                "TestTokenModel too long - make it shorter");
+  memcpy(pInfo->model, TestTokenModel, sizeof(TestTokenModel));
+  memset(pInfo->serialNumber, 0, sizeof(pInfo->serialNumber));
+  pInfo->flags = CKF_TOKEN_INITIALIZED;
+  pInfo->ulMaxSessionCount = 1;
+  pInfo->ulSessionCount = 0;
+  pInfo->ulMaxRwSessionCount = 1;
+  pInfo->ulRwSessionCount = 0;
+  pInfo->ulMaxPinLen = 4;
+  pInfo->ulMinPinLen = 4;
+  pInfo->ulTotalPublicMemory = 1024;
+  pInfo->ulFreePublicMemory = 1024;
+  pInfo->ulTotalPrivateMemory = 1024;
+  pInfo->ulFreePrivateMemory = 1024;
+  pInfo->hardwareVersion = TestLibraryVersion;
+  pInfo->firmwareVersion = TestLibraryVersion;
+  memset(pInfo->utcTime, 0, sizeof(pInfo->utcTime));
+  return CKR_OK;
+}
+
+CK_RV Test_C_GetMechanismList(CK_SLOT_ID,
+                              CK_MECHANISM_TYPE_PTR,
+                              CK_ULONG_PTR pulCount)
+{
+  if (!pulCount) {
+    return CKR_ARGUMENTS_BAD;
+  }
+
+  *pulCount = 0;
+  return CKR_OK;
+}
+
+CK_RV Test_C_GetMechanismInfo(CK_SLOT_ID, CK_MECHANISM_TYPE,
+                              CK_MECHANISM_INFO_PTR)
+{
+  return CKR_OK;
+}
+
+CK_RV Test_C_InitToken(CK_SLOT_ID, CK_UTF8CHAR_PTR, CK_ULONG, CK_UTF8CHAR_PTR)
+{
+  return CKR_OK;
+}
+
+CK_RV Test_C_InitPIN(CK_SESSION_HANDLE, CK_UTF8CHAR_PTR, CK_ULONG)
+{
+  return CKR_FUNCTION_NOT_SUPPORTED;
+}
+
+CK_RV Test_C_SetPIN(CK_SESSION_HANDLE, CK_UTF8CHAR_PTR, CK_ULONG,
+                    CK_UTF8CHAR_PTR, CK_ULONG)
+{
+  return CKR_FUNCTION_NOT_SUPPORTED;
+}
+
+CK_RV Test_C_OpenSession(CK_SLOT_ID, CK_FLAGS, CK_VOID_PTR, CK_NOTIFY,
+                         CK_SESSION_HANDLE_PTR)
+{
+  return CKR_OK;
+}
+
+CK_RV Test_C_CloseSession(CK_SESSION_HANDLE)
+{
+  return CKR_OK;
+}
+
+CK_RV Test_C_CloseAllSessions(CK_SLOT_ID)
+{
+  return CKR_OK;
+}
+
+CK_RV Test_C_GetSessionInfo(CK_SESSION_HANDLE, CK_SESSION_INFO_PTR pInfo)