Merge m-c to fx-team. a=merge
authorRyan VanderMeulen <ryanvm@gmail.com>
Mon, 04 Apr 2016 23:37:40 -0400
changeset 291586 95100f7c0fd843d266af5740c7dc1b809276d897
parent 291497 99272d590c8ff6925f7b9c2471be88b0ba373174 (current diff)
parent 291585 fd37367d1b1f2952c7a970c4b41e650d7233c717 (diff)
child 291587 033ae34a1c538f7d3e2e7ae94f3265b47098169d
push id18527
push userryanvm@gmail.com
push dateTue, 05 Apr 2016 03:38:35 +0000
treeherderfx-team@95100f7c0fd8 [default view] [failures only]
perfherder[talos] [build metrics] [platform microbench] (compared to previous push)
reviewersmerge
milestone48.0a1
Merge m-c to fx-team. a=merge
build/unix/headers/bits/c++config.h
ipc/app/plugin-container/firefox-plugin-container.exe.manifest
testing/web-platform/meta/webstorage/event_setattribute.html.ini
toolkit/crashreporter/tools/upload_symbols.sh
--- a/Makefile.in
+++ b/Makefile.in
@@ -188,19 +188,28 @@ ifneq (,$(filter FasterMake+RecursiveMak
 	@# same directory, because that would blow up
 	$(if $(wildcard _build_manifests/install/$(subst /,_,$*)),$(if $(wildcard faster/install_$(subst /,_,$*)*),$(error FasterMake and RecursiveMake ends of the hybrid build system want to handle $*)))
 endif
 	$(addprefix $(call py_action,process_install_manifest,$(if $(NO_REMOVE),--no-remove )$*) ,$(wildcard _build_manifests/install/$(subst /,_,$*)))
 
 # Dummy wrapper rule to allow the faster backend to piggy back
 $(addprefix install-,$(subst /,_,$(filter dist/%,$(install_manifests)))): install-dist_%: install-dist/% ;
 
-# For compatibility
 .PHONY: install-tests
-install-tests: install-_tests
+install-tests: install-test-files
+
+# We no longer run "make install-tests" directly before running tests, but we still
+# want to depend on things like config.status, hence this target.
+.PHONY: run-tests-deps
+run-tests-deps: $(install_manifest_depends)
+
+# Force --no-remove, because $objdir/_tests is handled by multiple manifests.
+.PHONY: install-test-files
+install-test-files:
+	$(call py_action,process_install_manifest,--no-remove _tests _build_manifests/install/_test_files)
 
 include $(topsrcdir)/build/moz-automation.mk
 
 # dist and _tests should be purged during cleaning. However, we don't want them
 # purged during PGO builds because they contain some auto-generated files.
 ifneq ($(filter-out maybe_clobber_profiledbuild,$(MAKECMDGOALS)),)
 GARBAGE_DIRS += dist _tests
 endif
@@ -274,22 +283,18 @@ DUMP_SYMS_BIN ?= $(DIST)/host/bin/dump_s
 MAKE_SYM_STORE_PATH := $(DIST)/bin
 endif
 MAKE_SYM_STORE_ARGS += --install-manifest=$(DEPTH)/_build_manifests/install/dist_include,$(DIST)/include
 
 SYM_STORE_SOURCE_DIRS := $(topsrcdir)
 
 include $(topsrcdir)/toolkit/mozapps/installer/package-name.mk
 
-ifdef MOZ_SYMBOLS_EXTRA_BUILDID
-EXTRA_BUILDID := -$(MOZ_SYMBOLS_EXTRA_BUILDID)
-endif
-
 SYMBOL_INDEX_NAME = \
-  $(MOZ_APP_NAME)-$(MOZ_APP_VERSION)-$(OS_TARGET)-$(BUILDID)-$(CPU_ARCH)$(EXTRA_BUILDID)-symbols.txt
+  $(MOZ_APP_NAME)-$(MOZ_APP_VERSION)-$(OS_TARGET)-$(BUILDID)-$(CPU_ARCH)-symbols.txt
 
 buildsymbols:
 ifdef MOZ_CRASHREPORTER
 	echo building symbol store
 	$(RM) -r $(DIST)/crashreporter-symbols
 	$(RM) '$(DIST)/$(SYMBOL_ARCHIVE_BASENAME).zip'
 	$(RM) '$(DIST)/$(SYMBOL_FULL_ARCHIVE_BASENAME).zip'
 	$(NSINSTALL) -D $(DIST)/crashreporter-symbols
@@ -311,18 +316,16 @@ ifdef MOZ_CRASHREPORTER
 	cd $(DIST)/crashreporter-symbols && \
           zip -r9D '../$(PKG_PATH)$(SYMBOL_ARCHIVE_BASENAME).zip' . -i '*.sym' -i '*.txt'  -x '*test*' -x '*Test*'
 endif # MOZ_CRASHREPORTER
 
 uploadsymbols:
 ifdef MOZ_CRASHREPORTER
 ifdef SOCORRO_SYMBOL_UPLOAD_TOKEN_FILE
 	$(PYTHON) -u $(topsrcdir)/toolkit/crashreporter/tools/upload_symbols.py '$(DIST)/$(PKG_PATH)$(SYMBOL_FULL_ARCHIVE_BASENAME).zip'
-else
-	$(SHELL) $(topsrcdir)/toolkit/crashreporter/tools/upload_symbols.sh $(SYMBOL_INDEX_NAME) '$(DIST)/$(PKG_PATH)$(SYMBOL_FULL_ARCHIVE_BASENAME).zip'
 endif
 endif
 
 .PHONY: update-packaging
 update-packaging:
 	$(MAKE) -C tools/update-packaging
 
 .PHONY: pretty-package
--- a/accessible/base/AccessibleOrProxy.h
+++ b/accessible/base/AccessibleOrProxy.h
@@ -21,17 +21,17 @@ namespace a11y {
  * with size sizeof(void*).
  */
 class AccessibleOrProxy
 {
 public:
   MOZ_IMPLICIT AccessibleOrProxy(Accessible* aAcc) :
     mBits(reinterpret_cast<uintptr_t>(aAcc)) {}
   MOZ_IMPLICIT AccessibleOrProxy(ProxyAccessible* aProxy) :
-    mBits(reinterpret_cast<uintptr_t>(aProxy) | IS_PROXY) {}
+    mBits(aProxy ? (reinterpret_cast<uintptr_t>(aProxy) | IS_PROXY) : 0) {}
   MOZ_IMPLICIT AccessibleOrProxy(decltype(nullptr)) : mBits(0) {}
 
   bool IsProxy() const { return mBits & IS_PROXY; }
   ProxyAccessible* AsProxy() const
   {
     if (IsProxy()) {
       return reinterpret_cast<ProxyAccessible*>(mBits & ~IS_PROXY);
     }
--- a/accessible/ipc/ProxyAccessible.h
+++ b/accessible/ipc/ProxyAccessible.h
@@ -53,17 +53,17 @@ public:
   ProxyAccessible* PrevSibling() const
   {
     size_t idx = IndexInParent();
     return idx > 0 ? Parent()->mChildren[idx - 1] : nullptr;
   }
   ProxyAccessible* NextSibling() const
   {
     size_t idx = IndexInParent();
-    return idx < Parent()->mChildren.Length() ? Parent()->mChildren[idx + 1]
+    return idx + 1 < Parent()->mChildren.Length() ? Parent()->mChildren[idx + 1]
     : nullptr;
   }
 
   // XXX evaluate if this is fast enough.
   size_t IndexInParent() const { return Parent()->mChildren.IndexOf(this); }
   uint32_t EmbeddedChildCount() const;
   int32_t IndexOfEmbeddedChild(const ProxyAccessible*);
   ProxyAccessible* EmbeddedChildAt(size_t aChildIdx);
--- a/accessible/tests/mochitest/a11y.ini
+++ b/accessible/tests/mochitest/a11y.ini
@@ -1,34 +1,17 @@
 [DEFAULT]
 support-files =
   ../../../dom/media/test/bug461281.ogg
   dumbfile.xpi
   formimage.png
   letters.gif
   moz.png
   longdesc_src.html
-  actions.js
-  attributes.js
-  autocomplete.js
-  browser.js
-  common.js
-  events.js
-  grid.js
-  layout.js
-  name.js
-  pivot.js
-  relations.js
-  role.js
-  selectable.js
-  states.js
-  table.js
-  value.js
-  text.js
+  *.js
   treeview.css
-  treeview.js
 
 [test_aria_token_attrs.html]
 [test_bug420863.html]
 [test_descr.html]
 [test_nsIAccessibleDocument.html]
 [test_nsIAccessibleImage.html]
 [test_OuterDocAccessible.html]
--- a/accessible/tests/mochitest/actions/a11y.ini
+++ b/accessible/tests/mochitest/actions/a11y.ini
@@ -1,9 +1,12 @@
 [DEFAULT]
+support-files =
+  !/accessible/tests/mochitest/*.js
+  !/dom/media/test/bug461281.ogg
 
 [test_anchors.html]
 [test_aria.html]
 [test_controls.html]
 [test_general.html]
 [test_general.xul]
 [test_keys.html]
 [test_keys_menu.xul]
--- a/accessible/tests/mochitest/attributes/a11y.ini
+++ b/accessible/tests/mochitest/attributes/a11y.ini
@@ -1,9 +1,11 @@
 [DEFAULT]
+support-files =
+  !/accessible/tests/mochitest/*.js
 
 [test_obj.html]
 [test_obj_css.html]
 [test_obj_css.xul]
 [test_obj_group.html]
 [test_obj_group.xul]
 [test_obj_group_tree.xul]
 [test_tag.html]
--- a/accessible/tests/mochitest/bounds/a11y.ini
+++ b/accessible/tests/mochitest/bounds/a11y.ini
@@ -1,6 +1,8 @@
 [DEFAULT]
+support-files =
+  !/accessible/tests/mochitest/*.js
 
 [test_list.html]
 [test_select.html]
 [test_zoom.html]
 [test_zoom_text.html]
--- a/accessible/tests/mochitest/editabletext/a11y.ini
+++ b/accessible/tests/mochitest/editabletext/a11y.ini
@@ -1,5 +1,7 @@
 [DEFAULT]
-support-files = editabletext.js
+support-files =
+  editabletext.js
+  !/accessible/tests/mochitest/*.js
 
 [test_1.html]
 [test_2.html]
--- a/accessible/tests/mochitest/elm/a11y.ini
+++ b/accessible/tests/mochitest/elm/a11y.ini
@@ -1,9 +1,13 @@
 [DEFAULT]
+support-files =
+  !/accessible/tests/mochitest/*.js
+  !/accessible/tests/mochitest/moz.png
+  !/dom/media/test/bug461281.ogg
 
 [test_HTMLSpec.html]
 skip-if = buildapp == 'mulet'
 [test_figure.html]
 [test_listbox.xul]
 [test_MathMLSpec.html]
 [test_nsApplicationAcc.html]
 [test_plugin.html]
--- a/accessible/tests/mochitest/events/a11y.ini
+++ b/accessible/tests/mochitest/events/a11y.ini
@@ -1,13 +1,15 @@
 [DEFAULT]
 support-files =
   docload_wnd.html
   focus.html
   scroll.html
+  !/accessible/tests/mochitest/*.js
+  !/accessible/tests/mochitest/letters.gif
 
 [test_aria_alert.html]
 [test_aria_menu.html]
 [test_aria_objattr.html]
 [test_aria_statechange.html]
 [test_attrs.html]
 [test_caretmove.html]
 [test_caretmove.xul]
--- a/accessible/tests/mochitest/focus/a11y.ini
+++ b/accessible/tests/mochitest/focus/a11y.ini
@@ -1,7 +1,9 @@
 [DEFAULT]
+support-files =
+  !/accessible/tests/mochitest/*.js
 
 [test_focusedChild.html]
 skip-if = (os == 'win' && (os_version == '6.2' || os_version == '6.3')) # bug 845134
 [test_takeFocus.html]
 skip-if = buildapp == 'mulet'
 [test_takeFocus.xul]
--- a/accessible/tests/mochitest/hittest/a11y.ini
+++ b/accessible/tests/mochitest/hittest/a11y.ini
@@ -1,10 +1,12 @@
 [DEFAULT]
 support-files = zoom_tree.xul
+  !/accessible/tests/mochitest/*.js
+  !/accessible/tests/mochitest/letters.gif
 
 [test_browser.html]
 [test_canvas_hitregion.html]
 skip-if = (os == "android" || appname == "b2g")
 [test_general.html]
 [test_menu.xul]
 [test_shadowroot.html]
 [test_zoom.html]
--- a/accessible/tests/mochitest/hyperlink/a11y.ini
+++ b/accessible/tests/mochitest/hyperlink/a11y.ini
@@ -1,5 +1,7 @@
 [DEFAULT]
 support-files = hyperlink.js
+  !/accessible/tests/mochitest/*.js
+  !/accessible/tests/mochitest/letters.gif
 
 [test_general.html]
 [test_general.xul]
--- a/accessible/tests/mochitest/hypertext/a11y.ini
+++ b/accessible/tests/mochitest/hypertext/a11y.ini
@@ -1,4 +1,7 @@
 [DEFAULT]
+support-files =
+  !/accessible/tests/mochitest/*.js
+  !/accessible/tests/mochitest/letters.gif
 
 [test_general.html]
 [test_update.html]
--- a/accessible/tests/mochitest/jsat/a11y.ini
+++ b/accessible/tests/mochitest/jsat/a11y.ini
@@ -2,16 +2,18 @@
 support-files =
   dom_helper.js
   gestures.json
   jsatcommon.js
   output.js
   doc_traversal.html
   doc_content_integration.html
   doc_content_text.html
+  !/accessible/tests/mochitest/*.js
+  !/accessible/tests/mochitest/moz.png
 
 [test_alive.html]
 [test_content_integration.html]
 skip-if = buildapp == 'mulet'
 [test_content_text.html]
 skip-if = buildapp == 'mulet'
 [test_explicit_names.html]
 [test_gesture_tracker.html]
--- a/accessible/tests/mochitest/jsat/test_alive.html
+++ b/accessible/tests/mochitest/jsat/test_alive.html
@@ -13,17 +13,17 @@
           src="./jsatcommon.js"></script>
   <script type="application/javascript">
 
     function prefStart() {
       AccessFuTest.once_log("AccessFu:Enabled", () =>
         ok(AccessFu._enabled, "AccessFu was enabled again."));
       AccessFuTest.once_log("EventManager.start", AccessFuTest.nextTest);
       // Start AccessFu via pref.
-      SpecialPowers.setIntPref("accessibility.accessfu.activate", 1);
+      SpecialPowers.pushPrefEnv({"set": [['accessibility.accessfu.activate', 1]]});
     }
 
     // Listen for 'EventManager.stop' and enable AccessFu again.
     function settingsStart() {
       isnot(AccessFu._enabled, true, "AccessFu was disabled.");
       // XXX: Bug 978076 - test start with SettingsManager.
       //navigator.mozSettings.createLock().set(
       //  {'accessibility.screenreader': false});
@@ -49,17 +49,17 @@
 
     // Listen for initial 'EventManager.start' and disable AccessFu.
     function prefStop() {
       ok(AccessFu._enabled, "AccessFu was started via preference.");
       AccessFuTest.once_log("AccessFu:Disabled", () =>
         isnot(AccessFu._enabled, true, "AccessFu was disabled."));
       AccessFuTest.once_log("EventManager.stop", AccessFuTest.nextTest);
 
-      SpecialPowers.setIntPref("accessibility.accessfu.activate", 0);
+      SpecialPowers.pushPrefEnv({"set": [['accessibility.accessfu.activate', 0]]});
     }
 
     function doTest() {
       AccessFuTest.addFunc(prefStart);
       AccessFuTest.addFunc(prefStop);
       AccessFuTest.addFunc(settingsStart);
       AccessFuTest.addFunc(settingsStop);
       AccessFuTest.waitForExplicitFinish();
--- a/accessible/tests/mochitest/jsat/test_content_text.html
+++ b/accessible/tests/mochitest/jsat/test_content_text.html
@@ -181,18 +181,17 @@
             multiline: false,
             atStart: true,
             atEnd: true
            }),
            new ExpectedCursorChange([{string: 'entry'}]),
            new ExpectedTextSelectionChanged(0, 0)
           ],
           [function() {
-             SpecialPowers.setIntPref(KEYBOARD_ECHO_SETTING, 3);
-             typeKey('a')();
+             SpecialPowers.pushPrefEnv({"set": [[KEYBOARD_ECHO_SETTING, 3]]}, typeKey('a')());
            },
            new ExpectedTextChanged('a'),
            new ExpectedTextSelectionChanged(1, 1),
           ],
           [typeKey('b'),
            new ExpectedTextChanged('b'),
            new ExpectedTextSelectionChanged(2, 2),
           ],
@@ -208,48 +207,45 @@
            new ExpectedTextChanged(' abcd'),
            new ExpectedTextSelectionChanged(5, 5),
           ],
           [typeKey('e'),
            new ExpectedTextChanged('e'),
            new ExpectedTextSelectionChanged(6, 6),
           ],
           [function() {
-             SpecialPowers.setIntPref(KEYBOARD_ECHO_SETTING, 2);
-             typeKey('a')();
+             SpecialPowers.pushPrefEnv({"set": [[KEYBOARD_ECHO_SETTING, 2]]}, typeKey('a')());
            },
            new ExpectedTextChanged(''),
            new ExpectedTextSelectionChanged(7, 7),
           ],
           [typeKey('d'),
            new ExpectedTextChanged(''),
            new ExpectedTextSelectionChanged(8, 8),
           ],
           [typeKey(' '),
            new ExpectedTextChanged(' ead'),
            new ExpectedTextSelectionChanged(9, 9),
           ],
           [function() {
-             SpecialPowers.setIntPref(KEYBOARD_ECHO_SETTING, 1);
-             typeKey('f')();
+             SpecialPowers.pushPrefEnv({"set": [[KEYBOARD_ECHO_SETTING, 1]]}, typeKey('f')());
            },
            new ExpectedTextChanged('f'),
            new ExpectedTextSelectionChanged(10, 10),
           ],
           [typeKey('g'),
            new ExpectedTextChanged('g'),
            new ExpectedTextSelectionChanged(11, 11),
           ],
           [typeKey(' '),
            new ExpectedTextChanged(' '),
            new ExpectedTextSelectionChanged(12, 12),
           ],
           [function() {
-             SpecialPowers.setIntPref(KEYBOARD_ECHO_SETTING, 0);
-             typeKey('f')();
+             SpecialPowers.pushPrefEnv({"set": [[KEYBOARD_ECHO_SETTING, 0]]}, typeKey('f')());
            },
            new ExpectedTextChanged(''),
            new ExpectedTextSelectionChanged(13, 13),
           ],
           [typeKey('g'),
            new ExpectedTextChanged(''),
            new ExpectedTextSelectionChanged(14, 14),
           ],
--- a/accessible/tests/mochitest/jsat/test_explicit_names.html
+++ b/accessible/tests/mochitest/jsat/test_explicit_names.html
@@ -106,25 +106,23 @@
         oldAccOrElmOrID: "apples",
         expected: ["List of Fruits", {"string": "list"},
           {"string": "listItemsCount", "count": 4}, {"string": "listStart"},
           {"string": "link"}, "Apples", {"string": "link"}, "Bananas",
           {"string": "link"}, "Peaches", {"string": "listEnd"},
           {"string": "link"}, "Plums"]
       }];
 
-      SpecialPowers.setIntPref(PREF_UTTERANCE_ORDER, 0);
-
-      // Test various explicit names vs the utterance generated from subtrees.
-      tests.forEach(function run(test) {
-        testOutput(test.expected, test.accOrElmOrID, test.oldAccOrElmOrID, 1);
+      SpecialPowers.pushPrefEnv({"set": [[PREF_UTTERANCE_ORDER, 0]]}, function() {
+        // Test various explicit names vs the utterance generated from subtrees.
+        tests.forEach(function run(test) {
+          testOutput(test.expected, test.accOrElmOrID, test.oldAccOrElmOrID, 1);
+        });
+        SimpleTest.finish();
       });
-
-      SpecialPowers.clearUserPref(PREF_UTTERANCE_ORDER);
-      SimpleTest.finish();
     }
 
     SimpleTest.waitForExplicitFinish();
     addA11yLoadEvent(doTest);
   </script>
 </head>
 <body>
   <div id="root">
--- a/accessible/tests/mochitest/jsat/test_landmarks.html
+++ b/accessible/tests/mochitest/jsat/test_landmarks.html
@@ -5,16 +5,18 @@
   <link rel="stylesheet" type="text/css"
         href="chrome://mochikit/content/tests/SimpleTest/test.css" />
   <script type="application/javascript"
           src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"></script>
   <script type="application/javascript"
           src="../common.js"></script>
   <script type="application/javascript"
           src="output.js"></script>
+  <script type="application/javascript"
+          src="jsatcommon.js"></script>
   <script type="application/javascript">
 
     function doTest() {
       // Test the following accOrElmOrID.
       var tests = [{
         accOrElmOrID: "nav",
         expectedUtterance: [[{"string": "navigation"}, "a nav"],
                             ["a nav", {"string": "navigation"}]],
@@ -112,30 +114,36 @@
           "a child complementary"], ["a child complementary",
           {"string": "complementary"}, {"string": "main"}]],
         expectedBraille: [[{"string": "complementary"},
           "a child complementary"], ["a child complementary",
           {"string": "complementary"}]]
       }];
 
       // Test outputs (utterance and braille) for landmarks.
-      tests.forEach(function run(test) {
-        var outputOrderValues = [0, 1];
-        outputOrderValues.forEach(function testOutputOrder(outputOrder) {
-          SpecialPowers.setIntPref(PREF_UTTERANCE_ORDER, outputOrder);
-          testOutput(test.expectedUtterance[outputOrder], test.accOrElmOrID,
-            test.oldAccOrElmOrID, 1);
-          testOutput(test.expectedBraille[outputOrder], test.accOrElmOrID,
-            test.oldAccOrElmOrID, 0);
-        });
-      });
+      function testOutputOrder(aOutputOrder) {
+        return function() {
+          SpecialPowers.pushPrefEnv({
+            "set": [[PREF_UTTERANCE_ORDER, aOutputOrder]]
+          }, function() {
+            tests.forEach(function run(test) {
+              testOutput(test.expectedUtterance[aOutputOrder], test.accOrElmOrID,
+                test.oldAccOrElmOrID, 1);
+              testOutput(test.expectedBraille[aOutputOrder], test.accOrElmOrID,
+                test.oldAccOrElmOrID, 0);
+            });
+            AccessFuTest.nextTest();
+          });
+        };
+      }
 
-      // If there was an original utterance order preference, revert to it.
-      SpecialPowers.clearUserPref(PREF_UTTERANCE_ORDER);
-      SimpleTest.finish();
+      AccessFuTest.addFunc(testOutputOrder(0));
+      AccessFuTest.addFunc(testOutputOrder(1));
+      AccessFuTest.waitForExplicitFinish();
+      AccessFuTest.runTests();
     }
 
     SimpleTest.waitForExplicitFinish();
     addA11yLoadEvent(doTest);
   </script>
 </head>
 <body>
   <div id="root">
--- a/accessible/tests/mochitest/jsat/test_live_regions.html
+++ b/accessible/tests/mochitest/jsat/test_live_regions.html
@@ -9,22 +9,22 @@
           src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"></script>
   <script type="application/javascript"
           src="../common.js"></script>
   <script type="application/javascript"
           src="./jsatcommon.js"></script>
   <script type="application/javascript">
 
     function startAccessFu() {
-      SpecialPowers.setIntPref("accessibility.accessfu.activate", 1);
+      SpecialPowers.pushPrefEnv({"set": [['accessibility.accessfu.activate', 1]]});
       AccessFuTest.once_log("EventManager.start", AccessFuTest.nextTest);
     }
 
     function stopAccessFu() {
-      SpecialPowers.setIntPref("accessibility.accessfu.activate", 0);
+      SpecialPowers.pushPrefEnv({"set": [['accessibility.accessfu.activate', 0]]});
       AccessFuTest.once_log("EventManager.stop", () => AccessFuTest.finish());
     }
 
     function hide(id) {
       var element = document.getElementById(id);
       element.style.display = "none";
     }
 
--- a/accessible/tests/mochitest/jsat/test_output.html
+++ b/accessible/tests/mochitest/jsat/test_output.html
@@ -9,16 +9,18 @@ https://bugzilla.mozilla.org/show_bug.cg
     <link rel="stylesheet" type="text/css"
           href="chrome://mochikit/content/tests/SimpleTest/test.css" />
     <script type="application/javascript"
             src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"></script>
     <script type="application/javascript"
             src="../common.js"></script>
     <script type="application/javascript"
             src="./output.js"></script>
+    <script type="application/javascript"
+            src="./jsatcommon.js"></script>
     <script type="application/javascript">
 
       function doTest() {
         // Test the following accOrElmOrID (with optional old accOrElmOrID).
         // Note: each accOrElmOrID entry maps to a unique object utterance
         // generator function within the UtteranceGenerator.
         var tests = [{
           accOrElmOrID: "anchor",
@@ -501,32 +503,36 @@ https://bugzilla.mozilla.org/show_bug.cg
             {"string": "switch"}, "Another switch"], ["Another switch",
             {"string": "stateOff"}, {"string": "switch"}]],
           expectedBraille: [
             [{"string": "stateUncheckedAbbr"}, "Another switch"],
             ["Another switch", {"string": "stateUncheckedAbbr"}]]
         }];
 
         // Test all possible utterance order preference values.
-        tests.forEach(function run(test) {
-          var utteranceOrderValues = [0, 1];
-          utteranceOrderValues.forEach(
-            function testUtteranceOrder(utteranceOrder) {
-              SpecialPowers.setIntPref(PREF_UTTERANCE_ORDER, utteranceOrder);
-              testOutput(test.expectedUtterance[utteranceOrder],
-                         test.accOrElmOrID, test.oldAccOrElmOrID, 1);
-              testOutput(test.expectedBraille[utteranceOrder],
-                         test.accOrElmOrID, test.oldAccOrElmOrID, 0);
-            }
-          );
-        });
+        function testOutputOrder(aOutputOrder) {
+          return function() {
+            SpecialPowers.pushPrefEnv({
+              "set": [[PREF_UTTERANCE_ORDER, aOutputOrder]]
+            }, function() {
+              tests.forEach(function run(test) {
+                testOutput(test.expectedUtterance[aOutputOrder], test.accOrElmOrID,
+                  test.oldAccOrElmOrID, 1);
+                testOutput(test.expectedBraille[aOutputOrder], test.accOrElmOrID,
+                  test.oldAccOrElmOrID, 0);
+              });
+              AccessFuTest.nextTest();
+            });
+          };
+        }
 
-        // If there was an original utterance order preference, revert to it.
-        SpecialPowers.clearUserPref(PREF_UTTERANCE_ORDER);
-        SimpleTest.finish();
+        AccessFuTest.addFunc(testOutputOrder(0));
+        AccessFuTest.addFunc(testOutputOrder(1));
+        AccessFuTest.waitForExplicitFinish();
+        AccessFuTest.runTests();
       }
 
       SimpleTest.waitForExplicitFinish();
       addA11yLoadEvent(doTest);
 
     </script>
   </head>
   <body>
--- a/accessible/tests/mochitest/jsat/test_output_mathml.html
+++ b/accessible/tests/mochitest/jsat/test_output_mathml.html
@@ -5,16 +5,18 @@
   <link rel="stylesheet" type="text/css"
         href="chrome://mochikit/content/tests/SimpleTest/test.css" />
   <script type="application/javascript"
           src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"></script>
   <script type="application/javascript"
           src="../common.js"></script>
   <script type="application/javascript"
           src="output.js"></script>
+  <script type="application/javascript"
+          src="jsatcommon.js"></script>
   <script type="application/javascript">
 
     function doTest() {
       // Test the following accOrElmOrID.
       var tests = [{
           accOrElmOrID: "math-1",
           expectedUtterance: [
             [{"string":"open-fence"},"(","x",",","y",{"string":"close-fence"},")"],
@@ -162,30 +164,36 @@
           ],
           expectedBraille: [
             [{"string":"mathmlenclosedAbbr"},{"string":"notation-leftAbbr"},{"string":"notation-topAbbr"},{"string":"notation-bottomAbbr"},"a"],
             ["a",{"string":"notation-leftAbbr"},{"string":"notation-topAbbr"},{"string":"notation-bottomAbbr"},{"string":"mathmlenclosedAbbr"}]
           ]
         }];
 
       // Test all possible utterance order preference values.
-      tests.forEach(function run(test) {
-        var outputOrderValues = [0, 1];
-        outputOrderValues.forEach(function testOutputOrder(outputOrder) {
-          SpecialPowers.setIntPref(PREF_UTTERANCE_ORDER, outputOrder);
-          testOutput(test.expectedUtterance[outputOrder], test.accOrElmOrID,
-            test.oldAccOrElmOrID, 1);
-          testOutput(test.expectedBraille[outputOrder], test.accOrElmOrID,
-            test.oldAccOrElmOrID, 0);
-        });
-      });
+      function testOutputOrder(aOutputOrder) {
+        return function() {
+          SpecialPowers.pushPrefEnv({
+            "set": [[PREF_UTTERANCE_ORDER, aOutputOrder]]
+          }, function() {
+            tests.forEach(function run(test) {
+              testOutput(test.expectedUtterance[aOutputOrder], test.accOrElmOrID,
+                test.oldAccOrElmOrID, 1);
+              testOutput(test.expectedBraille[aOutputOrder], test.accOrElmOrID,
+                test.oldAccOrElmOrID, 0);
+            });
+            AccessFuTest.nextTest();
+          });
+        };
+      }
 
-      // If there was an original utterance order preference, revert to it.
-      SpecialPowers.clearUserPref(PREF_UTTERANCE_ORDER);
-      SimpleTest.finish();
+      AccessFuTest.addFunc(testOutputOrder(0));
+      AccessFuTest.addFunc(testOutputOrder(1));
+      AccessFuTest.waitForExplicitFinish();
+      AccessFuTest.runTests();
     }
 
     SimpleTest.waitForExplicitFinish();
     addA11yLoadEvent(doTest);
   </script>
 </head>
 <body>
   <div id="root">
--- a/accessible/tests/mochitest/jsat/test_quicknav_modes.html
+++ b/accessible/tests/mochitest/jsat/test_quicknav_modes.html
@@ -10,17 +10,17 @@
   <script type="application/javascript"
           src="../common.js"></script>
   <script type="application/javascript"
           src="./jsatcommon.js"></script>
   <script type="application/javascript">
 
     function prefStart() {
       // Start AccessFu via pref.
-      SpecialPowers.setIntPref("accessibility.accessfu.activate", 1);
+      SpecialPowers.pushPrefEnv({"set": [['accessibility.accessfu.activate', 1]]});
       AccessFuTest.once_log("EventManager.start", AccessFuTest.nextTest);
     }
 
     function nextMode(aCurrentMode, aNextMode) {
       return function() {
         is(AccessFu.Input.quickNavMode.current, aCurrentMode,
           'initial current mode is correct');
         AccessFu.Input.quickNavMode.next();
@@ -34,28 +34,32 @@
           'initial current mode is correct');
         AccessFu.Input.quickNavMode.previous();
         _expectMode(aNextMode, AccessFuTest.nextTest);
       }
     }
 
     function setMode(aModeIndex, aExpectedMode) {
       return function() {
-        SpecialPowers.setIntPref(
-          'accessibility.accessfu.quicknav_index', aModeIndex);
-        _expectMode(aExpectedMode, AccessFuTest.nextTest);
+        SpecialPowers.pushPrefEnv(
+          {"set": [['accessibility.accessfu.quicknav_index', aModeIndex]]},
+          function() {
+            _expectMode(aExpectedMode, AccessFuTest.nextTest);
+        });
       }
     }
 
     function reconfigureModes() {
-      SpecialPowers.setCharPref('accessibility.accessfu.quicknav_modes',
-        'Landmark,Button,Entry,Graphic');
-      // When the modes are reconfigured, the current mode should
-      // be set to the first in the new list.
-      _expectMode('Landmark', AccessFuTest.nextTest);
+      SpecialPowers.pushPrefEnv(
+        {"set": [['accessibility.accessfu.quicknav_modes', 'Landmark,Button,Entry,Graphic']]},
+        function() {
+          // When the modes are reconfigured, the current mode should
+          // be set to the first in the new list.
+          _expectMode('Landmark', AccessFuTest.nextTest);
+      });
     }
 
     function _expectMode(aExpectedMode, aCallback) {
       if (AccessFu.Input.quickNavMode.current === aExpectedMode) {
         ok(true, 'correct mode');
         aCallback();
       } else {
         AccessFuTest.once_log('Quicknav mode: ' + aExpectedMode, function() {
@@ -64,17 +68,17 @@
         });
       }
     }
 
     // Listen for initial 'EventManager.start' and disable AccessFu.
     function prefStop() {
       ok(AccessFu._enabled, "AccessFu was started via preference.");
       AccessFuTest.once_log("EventManager.stop", () => AccessFuTest.finish());
-      SpecialPowers.setIntPref("accessibility.accessfu.activate", 0);
+      SpecialPowers.pushPrefEnv({"set": [['accessibility.accessfu.activate', 0]]});
     }
 
     function doTest() {
       AccessFuTest.addFunc(prefStart);
       AccessFuTest.addFunc(nextMode('Link', 'Heading'));
       AccessFuTest.addFunc(nextMode('Heading', 'FormElement'));
       AccessFuTest.addFunc(nextMode('FormElement', 'Link'));
       AccessFuTest.addFunc(nextMode('Link', 'Heading'));
--- a/accessible/tests/mochitest/jsat/test_tables.html
+++ b/accessible/tests/mochitest/jsat/test_tables.html
@@ -5,16 +5,18 @@
   <link rel="stylesheet" type="text/css"
         href="chrome://mochikit/content/tests/SimpleTest/test.css" />
   <script type="application/javascript"
           src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"></script>
   <script type="application/javascript"
           src="../common.js"></script>
   <script type="application/javascript"
           src="output.js"></script>
+  <script type="application/javascript"
+          src="jsatcommon.js"></script>
   <script type="application/javascript">
 
     function doTest() {
       // Test the following accOrElmOrID.
       var tests = [{
         accOrElmOrID: "table1",
         expectedUtterance: [[
           {"string": "table"},
@@ -467,34 +469,38 @@
           ["cell3",
           {"string": "columnInfo", "args": [2]},
           {"string": "rowInfo", "args": [3]}, "col2", "row2"]],
         expectedBraille: [
           [{"string": "cellInfoAbbr", "args": [2, 3]}, "col2", "row2", "cell3"],
           ["cell3", {"string": "cellInfoAbbr", "args": [2, 3]}, "col2", "row2"]]
       }];
 
-      SpecialPowers.setIntPref(PREF_UTTERANCE_ORDER, 0);
-
       // Test outputs (utterance and braille) for tables including their
       // headers and cells.
-      tests.forEach(function run(test) {
-        var outputOrderValues = [0, 1];
-        outputOrderValues.forEach(function testOutputOrder(outputOrder) {
-          SpecialPowers.setIntPref(PREF_UTTERANCE_ORDER, outputOrder);
-          testOutput(test.expectedUtterance[outputOrder], test.accOrElmOrID,
-            test.oldAccOrElmOrID, 1);
-          testOutput(test.expectedBraille[outputOrder], test.accOrElmOrID,
-            test.oldAccOrElmOrID, 0);
-        });
-      });
+      function testOutputOrder(aOutputOrder) {
+        return function() {
+          SpecialPowers.pushPrefEnv({
+            "set": [[PREF_UTTERANCE_ORDER, aOutputOrder]]
+          }, function() {
+            tests.forEach(function run(test) {
+              testOutput(test.expectedUtterance[aOutputOrder], test.accOrElmOrID,
+                test.oldAccOrElmOrID, 1);
+              testOutput(test.expectedBraille[aOutputOrder], test.accOrElmOrID,
+                test.oldAccOrElmOrID, 0);
+            });
+            AccessFuTest.nextTest();
+          });
+        };
+      }
 
-      // If there was an original utterance order preference, revert to it.
-      SpecialPowers.clearUserPref(PREF_UTTERANCE_ORDER);
-      SimpleTest.finish();
+      AccessFuTest.addFunc(testOutputOrder(0));
+      AccessFuTest.addFunc(testOutputOrder(1));
+      AccessFuTest.waitForExplicitFinish();
+      AccessFuTest.runTests();
     }
 
     SimpleTest.waitForExplicitFinish();
     addA11yLoadEvent(doTest);
   </script>
 </head>
 <body>
   <div id="root">
--- a/accessible/tests/mochitest/name/a11y.ini
+++ b/accessible/tests/mochitest/name/a11y.ini
@@ -1,14 +1,16 @@
 [DEFAULT]
 support-files =
   general.css
   general.xbl
   markup.js
   markuprules.xml
+  !/accessible/tests/mochitest/*.js
+  !/accessible/tests/mochitest/moz.png
 
 [test_browserui.xul]
 [test_counterstyle.html]
 [test_general.html]
 [test_general.xul]
 [test_link.html]
 [test_list.html]
 [test_markup.html]
--- a/accessible/tests/mochitest/pivot/a11y.ini
+++ b/accessible/tests/mochitest/pivot/a11y.ini
@@ -1,7 +1,8 @@
 [DEFAULT]
 support-files =
   doc_virtualcursor.html
   doc_virtualcursor_text.html
+  !/accessible/tests/mochitest/*.js
 
 [test_virtualcursor.html]
 [test_virtualcursor_text.html]
--- a/accessible/tests/mochitest/relations/a11y.ini
+++ b/accessible/tests/mochitest/relations/a11y.ini
@@ -1,9 +1,11 @@
 [DEFAULT]
+support-files =
+  !/accessible/tests/mochitest/*.js
 
 [test_bindings.xhtml]
 [test_embeds.xul]
 [test_general.html]
 [test_general.xul]
 [test_tabbrowser.xul]
 [test_tree.xul]
 [test_ui_modalprompt.html]
--- a/accessible/tests/mochitest/role/a11y.ini
+++ b/accessible/tests/mochitest/role/a11y.ini
@@ -1,7 +1,10 @@
 [DEFAULT]
+support-files =
+  !/accessible/tests/mochitest/*.js
+  !/accessible/tests/mochitest/moz.png
 
 [test_aria.html]
 [test_aria.xul]
 [test_general.html]
 [test_general.xul]
 [test_svg.html]
--- a/accessible/tests/mochitest/scroll/a11y.ini
+++ b/accessible/tests/mochitest/scroll/a11y.ini
@@ -1,4 +1,6 @@
 [DEFAULT]
+support-files =
+  !/accessible/tests/mochitest/*.js
 
 [test_zoom.html]
 [test_zoom_text.html]
--- a/accessible/tests/mochitest/selectable/a11y.ini
+++ b/accessible/tests/mochitest/selectable/a11y.ini
@@ -1,8 +1,12 @@
 [DEFAULT]
+support-files =
+  !/accessible/tests/mochitest/*.js
+  !/accessible/tests/mochitest/treeview.css
+  !/accessible/tests/mochitest/treeview.js
 
 [test_aria.html]
 [test_listbox.xul]
 [test_menu.xul]
 [test_menulist.xul]
 [test_select.html]
 [test_tree.xul]
--- a/accessible/tests/mochitest/states/a11y.ini
+++ b/accessible/tests/mochitest/states/a11y.ini
@@ -1,15 +1,19 @@
 [DEFAULT]
 support-files =
   z_frames.html
   z_frames_article.html
   z_frames_checkbox.html
   z_frames_textbox.html
   z_frames_update.html
+  !/accessible/tests/mochitest/*.js
+  !/accessible/tests/mochitest/dumbfile.xpi
+  !/accessible/tests/mochitest/formimage.png
+  !/accessible/tests/mochitest/treeview.css
 
 [test_aria.html]
 [test_aria.xul]
 [test_aria_imgmap.html]
 [test_aria_widgetitems.html]
 [test_buttons.html]
 [test_controls.html]
 [test_controls.xul]
--- a/accessible/tests/mochitest/table/a11y.ini
+++ b/accessible/tests/mochitest/table/a11y.ini
@@ -1,9 +1,11 @@
 [DEFAULT]
+support-files =
+  !/accessible/tests/mochitest/*.js
 
 [test_css_tables.html]
 [test_headers_ariagrid.html]
 [test_headers_ariatable.html]
 [test_headers_listbox.xul]
 [test_headers_table.html]
 [test_headers_tree.xul]
 [test_indexes_ariagrid.html]
--- a/accessible/tests/mochitest/text/a11y.ini
+++ b/accessible/tests/mochitest/text/a11y.ini
@@ -1,10 +1,11 @@
 [DEFAULT]
 support-files = doc.html
+  !/accessible/tests/mochitest/*.js
 
 [test_atcaretoffset.html]
 [test_charboundary.html]
 [test_doc.html]
 [test_general.xul]
 [test_gettext.html]
 [test_hypertext.html]
 [test_lineboundary.html]
--- a/accessible/tests/mochitest/textattrs/a11y.ini
+++ b/accessible/tests/mochitest/textattrs/a11y.ini
@@ -1,4 +1,7 @@
 [DEFAULT]
+support-files =
+  !/accessible/tests/mochitest/*.js
+  !/accessible/tests/mochitest/moz.png
 
 [test_general.html]
 [test_invalid.html]
--- a/accessible/tests/mochitest/textcaret/a11y.ini
+++ b/accessible/tests/mochitest/textcaret/a11y.ini
@@ -1,4 +1,6 @@
 [DEFAULT]
+support-files =
+  !/accessible/tests/mochitest/*.js
 
 [test_browserui.xul]
 [test_general.html]
--- a/accessible/tests/mochitest/textrange/a11y.ini
+++ b/accessible/tests/mochitest/textrange/a11y.ini
@@ -1,4 +1,7 @@
 [DEFAULT]
+support-files =
+  !/accessible/tests/mochitest/*.js
+  !/accessible/tests/mochitest/moz.png
 
 [test_general.html]
 [test_selection.html]
--- a/accessible/tests/mochitest/textselection/a11y.ini
+++ b/accessible/tests/mochitest/textselection/a11y.ini
@@ -1,4 +1,6 @@
 [DEFAULT]
+support-files =
+  !/accessible/tests/mochitest/*.js
 
 [test_general.html]
 [test_userinput.html]
--- a/accessible/tests/mochitest/tree/a11y.ini
+++ b/accessible/tests/mochitest/tree/a11y.ini
@@ -1,12 +1,18 @@
 [DEFAULT]
 support-files =
   dockids.html
   wnd.xul
+  !/accessible/tests/mochitest/*.js
+  !/accessible/tests/mochitest/formimage.png
+  !/accessible/tests/mochitest/letters.gif
+  !/accessible/tests/mochitest/moz.png
+  !/accessible/tests/mochitest/tree/wnd.xul
+  !/dom/media/test/bug461281.ogg
 
 [test_applicationacc.xul]
 skip-if = true # Bug 561508
 [test_aria_globals.html]
 [test_aria_grid.html]
 [test_aria_imgmap.html]
 [test_aria_list.html]
 [test_aria_menu.html]
--- a/accessible/tests/mochitest/treeupdate/a11y.ini
+++ b/accessible/tests/mochitest/treeupdate/a11y.ini
@@ -1,9 +1,13 @@
 [DEFAULT]
+support-files =
+  !/accessible/tests/mochitest/*.js
+  !/accessible/tests/mochitest/letters.gif
+  !/accessible/tests/mochitest/moz.png
 
 [test_ariadialog.html]
 [test_ariaowns.html]
 [test_bug852150.xhtml]
 [test_bug883708.xhtml]
 [test_bug884251.xhtml]
 [test_bug895082.html]
 [test_bug1040735.html]
--- a/accessible/tests/mochitest/value/a11y.ini
+++ b/accessible/tests/mochitest/value/a11y.ini
@@ -1,7 +1,9 @@
 [DEFAULT]
+support-files =
+  !/accessible/tests/mochitest/*.js
 
 [test_general.html]
 [test_number.html]
 [test_progress.html]
 [test_progress.xul]
 [test_range.html]
--- a/accessible/xpcom/xpcAccessible.cpp
+++ b/accessible/xpcom/xpcAccessible.cpp
@@ -32,30 +32,34 @@ xpcAccessible::GetParent(nsIAccessible**
   return NS_OK;
 }
 
 NS_IMETHODIMP
 xpcAccessible::GetNextSibling(nsIAccessible** aNextSibling)
 {
   NS_ENSURE_ARG_POINTER(aNextSibling);
   *aNextSibling = nullptr;
+  if (IntlGeneric().IsNull())
+    return NS_ERROR_FAILURE;
 
   if (!Intl())
     return NS_ERROR_FAILURE;
 
   nsresult rv = NS_OK;
   NS_IF_ADDREF(*aNextSibling = ToXPC(Intl()->GetSiblingAtOffset(1, &rv)));
   return rv;
 }
 
 NS_IMETHODIMP
 xpcAccessible::GetPreviousSibling(nsIAccessible** aPreviousSibling)
 {
   NS_ENSURE_ARG_POINTER(aPreviousSibling);
   *aPreviousSibling = nullptr;
+  if (IntlGeneric().IsNull())
+    return NS_ERROR_FAILURE;
 
   if (!Intl())
     return NS_ERROR_FAILURE;
 
   nsresult rv = NS_OK;
   NS_IF_ADDREF(*aPreviousSibling = ToXPC(Intl()->GetSiblingAtOffset(-1, &rv)));
   return rv;
 }
@@ -144,16 +148,18 @@ xpcAccessible::GetChildren(nsIArray** aC
   return NS_OK;
 }
 
 NS_IMETHODIMP
 xpcAccessible::GetIndexInParent(int32_t* aIndexInParent)
 {
   NS_ENSURE_ARG_POINTER(aIndexInParent);
   *aIndexInParent = -1;
+  if (IntlGeneric().IsNull())
+    return NS_ERROR_FAILURE;
 
   if (!Intl())
     return NS_ERROR_FAILURE;
 
   *aIndexInParent = Intl()->IndexInParent();
   return *aIndexInParent != -1 ? NS_OK : NS_ERROR_FAILURE;
 }
 
--- a/b2g/app/b2g.js
+++ b/b2g/app/b2g.js
@@ -293,17 +293,16 @@ 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);
 
 // Layers Acceleration.  We can only have nice things on gonk, because
 // they're not maintained anywhere else.
-pref("layers.offmainthreadcomposition.enabled", true);
 #ifndef MOZ_WIDGET_GONK
 pref("dom.ipc.tabs.disabled", true);
 #else
 pref("dom.ipc.tabs.disabled", false);
 pref("layers.acceleration.disabled", false);
 pref("layers.async-pan-zoom.enabled", true);
 pref("gfx.content.azure.backends", "cairo");
 #endif
--- a/b2g/components/OopCommandLine.js
+++ b/b2g/components/OopCommandLine.js
@@ -21,17 +21,16 @@ oopCommandlineHandler.prototype = {
             let prefs = Services.prefs
             let branch = prefs.getDefaultBranch("");
 
             try {
                 // Turn on all OOP services, making desktop run similar to phone
                 // environment
                 branch.setBoolPref("dom.ipc.tabs.disabled", false);
                 branch.setBoolPref("layers.acceleration.disabled", false);
-                branch.setBoolPref("layers.offmainthreadcomposition.enabled", true);
                 branch.setBoolPref("layers.offmainthreadcomposition.async-animations", true);
                 branch.setBoolPref("layers.async-video.enabled", true);
                 branch.setBoolPref("layers.async-pan-zoom.enabled", true);
                 branch.setCharPref("gfx.content.azure.backends", "cairo");
             } catch (e) { }
 
         }
         if (cmdLine.state == Ci.nsICommandLine.STATE_REMOTE_AUTO) {
--- a/browser/base/content/browser-fullZoom.js
+++ b/browser/base/content/browser-fullZoom.js
@@ -110,18 +110,18 @@ var FullZoom = {
   },
 
   // nsIContentPrefObserver
 
   onContentPrefSet: function FullZoom_onContentPrefSet(aGroup, aName, aValue, aIsPrivate) {
     this._onContentPrefChanged(aGroup, aValue, aIsPrivate);
   },
 
-  onContentPrefRemoved: function FullZoom_onContentPrefRemoved(aGroup, aName) {
-    this._onContentPrefChanged(aGroup, undefined);
+  onContentPrefRemoved: function FullZoom_onContentPrefRemoved(aGroup, aName, aIsPrivate) {
+    this._onContentPrefChanged(aGroup, undefined, aIsPrivate);
   },
 
   /**
    * Appropriately updates the zoom level after a content preference has
    * changed.
    *
    * @param aGroup  The group of the changed preference.
    * @param aValue  The new value of the changed preference.  Pass undefined to
--- a/browser/base/content/browser.js
+++ b/browser/base/content/browser.js
@@ -3862,20 +3862,20 @@ function OpenBrowserWindow(options)
     }
   } else {
     extraFeatures = ",non-private";
   }
 
   if (options && options.remote) {
     // If we're using remote tabs by default, then OMTC will be force-enabled,
     // despite the preference returning as false.
-    let omtcEnabled = gPrefService.getBoolPref("layers.offmainthreadcomposition.enabled")
+    let omtcEnabled = !gPrefService.getBoolPref("layers.offmainthreadcomposition.force-disabled")
                       || Services.appinfo.browserTabsRemoteAutostart;
     if (!omtcEnabled) {
-      alert("To use out-of-process tabs, you must set the layers.offmainthreadcomposition.enabled preference and restart. Opening a normal window instead.");
+      alert("To use out-of-process tabs, you must unset the layers.offmainthreadcomposition.force-disabled preference and restart. Opening a normal window instead.");
     } else {
       extraFeatures += ",remote";
     }
   } else if (options && options.remote === false) {
     extraFeatures += ",non-remote";
   }
 
   // if and only if the current window is a browser window and it has a document with a character
--- a/browser/base/content/browser.xul
+++ b/browser/base/content/browser.xul
@@ -456,22 +456,35 @@
         <image id="bookmarked-notification-dropmarker-icon"/>
       </vbox>
     </hbox>
 
     <tooltip id="dynamic-shortcut-tooltip"
              onpopupshowing="UpdateDynamicShortcutTooltipText(this);"/>
 
     <menupopup id="SyncedTabsSidebarContext">
-      <menuitem label="&syncedTabs.context.openTab.label;"
-                accesskey="&syncedTabs.context.openTab.accesskey;"
-                id="syncedTabsOpenSelected"/>
+      <menuitem label="&syncedTabs.context.open.label;"
+                accesskey="&syncedTabs.context.open.accesskey;"
+                id="syncedTabsOpenSelected" where="current"/>
+      <menuitem label="&syncedTabs.context.openInNewTab.label;"
+                accesskey="&syncedTabs.context.openInNewTab.accesskey;"
+                id="syncedTabsOpenSelectedInTab" where="tab"/>
+      <menuitem label="&syncedTabs.context.openInNewWindow.label;"
+                accesskey="&syncedTabs.context.openInNewWindow.accesskey;"
+                id="syncedTabsOpenSelectedInWindow" where="window"/>
+      <menuitem label="&syncedTabs.context.openInNewPrivateWindow.label;"
+                accesskey="&syncedTabs.context.openInNewPrivateWindow.accesskey;"
+                id="syncedTabsOpenSelectedInPrivateWindow" where="window" private="true"/>
+      <menuseparator/>
       <menuitem label="&syncedTabs.context.bookmarkSingleTab.label;"
                 accesskey="&syncedTabs.context.bookmarkSingleTab.accesskey;"
                 id="syncedTabsBookmarkSelected"/>
+      <menuitem label="&syncedTabs.context.copy.label;"
+                accesskey="&syncedTabs.context.copy.accesskey;"
+                id="syncedTabsCopySelected"/>
       <menuseparator/>
       <menuitem label="&syncSyncNowItem.label;"
                 accesskey="&syncSyncNowItem.accesskey;"
                 id="syncedTabsRefresh"/>
     </menupopup>
     <menupopup id="SyncedTabsSidebarTabsFilterContext"
                class="textbox-contextmenu">
       <menuitem label="&undoCmd.label;"
--- a/browser/base/content/test/general/browser.ini
+++ b/browser/base/content/test/general/browser.ini
@@ -117,16 +117,30 @@ support-files =
   test_mcb_double_redirect_image.html
   test_mcb_redirect.js
   test_mcb_redirect.sjs
   xul_tooltiptext.xhtml
   file_bug1045809_1.html
   file_bug1045809_2.html
   file_csp_block_all_mixedcontent.html
   file_csp_block_all_mixedcontent.js
+  !/toolkit/components/passwordmgr/test/browser/form_basic.html
+  !/toolkit/components/passwordmgr/test/browser/insecure_test.html
+  !/toolkit/components/passwordmgr/test/browser/insecure_test_subframe.html
+  !/toolkit/content/tests/browser/common/mockTransfer.js
+  !/toolkit/crashreporter/test/browser/crashreport.sjs
+  !/toolkit/modules/tests/browser/metadata_*.html
+  !/toolkit/mozapps/extensions/test/xpinstall/amosigned.xpi
+  !/toolkit/mozapps/extensions/test/xpinstall/corrupt.xpi
+  !/toolkit/mozapps/extensions/test/xpinstall/incompatible.xpi
+  !/toolkit/mozapps/extensions/test/xpinstall/installtrigger.html
+  !/toolkit/mozapps/extensions/test/xpinstall/redirect.sjs
+  !/toolkit/mozapps/extensions/test/xpinstall/restartless-unsigned.xpi
+  !/toolkit/mozapps/extensions/test/xpinstall/restartless.xpi
+  !/toolkit/mozapps/extensions/test/xpinstall/theme.xpi
 
 [browser_URLBarSetURI.js]
 skip-if = (os == "linux" || os == "mac") && debug # bug 970052, bug 970053
 [browser_aboutAccounts.js]
 skip-if = os == "linux" # Bug 958026
 support-files =
   content_aboutAccounts.js
 [browser_aboutCertError.js]
--- a/browser/base/content/test/general/mochitest.ini
+++ b/browser/base/content/test/general/mochitest.ini
@@ -15,13 +15,14 @@ support-files =
   offlineChild2.cacheManifest
   offlineChild2.cacheManifest^headers^
   offlineChild2.html
   offlineEvent.cacheManifest
   offlineEvent.cacheManifest^headers^
   offlineEvent.html
   subtst_contextmenu.html
   video.ogg
+  !/image/test/mochitest/blue.png
 
 [test_bug364677.html]
 [test_bug395533.html]
 [test_offlineNotification.html]
 skip-if = buildapp == 'mulet' || e10s # Bug 1066070 - I don't think either popup notifications nor addon install stuff works?
--- a/browser/base/content/test/social/browser.ini
+++ b/browser/base/content/test/social/browser.ini
@@ -19,16 +19,17 @@ support-files =
   social_crash_content_helper.js
   social_flyout.html
   social_mark.html
   social_panel.html
   social_postActivation.html
   social_sidebar.html
   social_sidebar_empty.html
   unchecked.jpg
+  !/browser/base/content/test/plugins/blockNoPlugins.xml
 
 [browser_aboutHome_activation.js]
 [browser_addons.js]
 [browser_blocklist.js]
 [browser_share.js]
 skip-if = true # bug 1115131
 [browser_social_activation.js]
 [browser_social_chatwindow.js]
--- a/browser/components/customizableui/content/panelUI.inc.xul
+++ b/browser/components/customizableui/content/panelUI.inc.xul
@@ -135,17 +135,17 @@
                   <toolbarbutton class="PanelUI-remotetabs-prefs-button"
                                  label="&appMenuRemoteTabs.openprefs.label;"
                                  oncommand="gSyncUI.openSetup();"/>
                 </hbox>
               </vbox>
             </hbox>
             <!-- Sync is ready to Sync but we are still fetching the tabs to show -->
             <vbox id="PanelUI-remotetabs-fetching">
-              <label>&appMenuRemoteTabs.fetching.label;</label>
+              <!-- Show intentionally blank panel, see bug 1239845 -->
             </vbox>
             <!-- Sync has only 1 (ie, this) device connected -->
             <hbox id="PanelUI-remotetabs-nodevicespane" pack="center" flex="1">
               <vbox class="PanelUI-remotetabs-instruction-box">
                 <hbox pack="center">
                   <image class="fxaSyncIllustration" alt=""/>
                 </hbox>
                 <label class="PanelUI-remotetabs-instruction-label">&appMenuRemoteTabs.noclients.label;</label>
--- a/browser/components/feeds/test/chrome/chrome.ini
+++ b/browser/components/feeds/test/chrome/chrome.ini
@@ -1,9 +1,12 @@
 [DEFAULT]
 skip-if = buildapp == 'b2g'
 support-files = sample_feed.atom
+  !/browser/components/feeds/test/bug408328-data.xml
+  !/browser/components/feeds/test/valid-feed.xml
+  !/browser/components/feeds/test/valid-unsniffable-feed.xml
 
 [test_423060.xul]
 [test_bug368464.html]
 [test_bug408328.html]
 skip-if= buildapp == 'mulet'
 [test_maxSniffing.html]
--- a/browser/components/preferences/in-content/subdialogs.js
+++ b/browser/components/preferences/in-content/subdialogs.js
@@ -36,16 +36,31 @@ var gSubDialog = {
       'xml-stylesheet',
       'href="' + aStylesheetURL + '" type="text/css"'
     );
     this._frame.contentDocument.insertBefore(contentStylesheet,
                                              this._frame.contentDocument.documentElement);
   },
 
   open: function(aURL, aFeatures = null, aParams = null, aClosingCallback = null) {
+    // If we're already open/opening on this URL, do nothing.
+    if (this._openedURL == aURL && !this._isClosing) {
+      return;
+    }
+    // If we're open on some (other) URL or we're closing, open when closing has finished.
+    if (this._openedURL || this._isClosing) {
+      if (!this._isClosing) {
+        this.close();
+      }
+      let args = Array.from(arguments);
+      this._closingPromise.then(() => {
+        this.open.apply(this, args);
+      });
+      return;
+    }
     this._addDialogEventListeners();
 
     let features = (!!aFeatures ? aFeatures + "," : "") + "resizable,dialog=no,centerscreen";
     let dialog = window.openDialog(aURL, "dialogFrame", features, aParams);
     if (aClosingCallback) {
       this._closingCallback = aClosingCallback.bind(dialog);
     }
 
@@ -53,24 +68,26 @@ var gSubDialog = {
     this._isClosing = false;
     this._openedURL = aURL;
 
     features = features.replace(/,/g, "&");
     let featureParams = new URLSearchParams(features.toLowerCase());
     this._box.setAttribute("resizable", featureParams.has("resizable") &&
                                         featureParams.get("resizable") != "no" &&
                                         featureParams.get("resizable") != "0");
-    return dialog;
   },
 
   close: function(aEvent = null) {
     if (this._isClosing) {
       return;
     }
     this._isClosing = true;
+    this._closingPromise = new Promise(resolve => {
+      this._resolveClosePromise = resolve;
+    });
 
     if (this._closingCallback) {
       try {
         this._closingCallback.call(null, aEvent);
       } catch (ex) {
         Cu.reportError(ex);
       }
       this._closingCallback = null;
@@ -85,16 +102,26 @@ var gSubDialog = {
     this._box.removeAttribute("width");
     this._box.removeAttribute("height");
     this._box.style.removeProperty("min-height");
     this._box.style.removeProperty("min-width");
 
     setTimeout(() => {
       // Unload the dialog after the event listeners run so that the load of about:blank isn't
       // cancelled by the ESC <key>.
+      let onBlankLoad = e => {
+        if (this._frame.contentWindow.location.href == "about:blank") {
+          this._frame.removeEventListener("load", onBlankLoad);
+          // We're now officially done closing, so update the state to reflect that.
+          delete this._openedURL;
+          this._isClosing = false;
+          this._resolveClosePromise();
+        }
+      };
+      this._frame.addEventListener("load", onBlankLoad);
       this._frame.loadURI("about:blank");
     }, 0);
   },
 
   handleEvent: function(aEvent) {
     switch (aEvent.type) {
       case "command":
         this._frame.contentWindow.close();
@@ -127,18 +154,19 @@ var gSubDialog = {
 
   _onUnload: function(aEvent) {
     if (aEvent.target.location.href == this._openedURL) {
       this._frame.contentWindow.close();
     }
   },
 
   _onContentLoaded: function(aEvent) {
-    if (aEvent.target != this._frame || aEvent.target.contentWindow.location == "about:blank")
+    if (aEvent.target != this._frame || aEvent.target.contentWindow.location == "about:blank") {
       return;
+    }
 
     for (let styleSheetURL of this._injectedStyleSheets) {
       this.injectXMLStylesheet(styleSheetURL);
     }
 
     // Provide the ability for the dialog to know that it is being loaded "in-content".
     this._frame.contentDocument.documentElement.setAttribute("subdialog", "true");
 
@@ -164,18 +192,19 @@ var gSubDialog = {
     // XXX: Hack to make focus during the dialog's load functions work. Make the element visible
     // sooner in DOMContentLoaded but mostly invisible instead of changing visibility just before
     // the dialog's load event.
     this._overlay.style.visibility = "visible";
     this._overlay.style.opacity = "0.01";
   },
 
   _onLoad: function(aEvent) {
-    if (aEvent.target.contentWindow.location == "about:blank")
+    if (aEvent.target.contentWindow.location == "about:blank") {
       return;
+    }
 
     // Do this on load to wait for the CSS to load and apply before calculating the size.
     let docEl = this._frame.contentDocument.documentElement;
 
     let groupBoxTitle = document.getAnonymousElementByAttribute(this._box, "class", "groupbox-title");
     let groupBoxTitleHeight = groupBoxTitle.clientHeight +
                               parseFloat(getComputedStyle(groupBoxTitle).borderBottomWidth);
 
@@ -255,18 +284,19 @@ var gSubDialog = {
     // layout of the frame, but afterward they need to be removed
     // or their presence will restrict the contents of the <browser>
     // from resizing to a smaller size.
     frame.style.removeProperty("width");
     frame.style.removeProperty("height");
 
     let docEl = frame.contentDocument.documentElement;
     let persistedAttributes = docEl.getAttribute("persist");
-    if (!persistedAttributes.contains("width") &&
-        !persistedAttributes.contains("height")) {
+    if (!persistedAttributes ||
+        (!persistedAttributes.contains("width") &&
+         !persistedAttributes.contains("height"))) {
       return;
     }
 
     for (let mutation of mutations) {
       if (mutation.attributeName == "width") {
         docEl.setAttribute("width", docEl.scrollWidth);
       } else if (mutation.attributeName == "height") {
         docEl.setAttribute("height", docEl.scrollHeight);
--- a/browser/components/preferences/in-content/tests/browser.ini
+++ b/browser/components/preferences/in-content/tests/browser.ini
@@ -27,12 +27,14 @@ skip-if = true || !healthreport # Bug 11
 [browser_privacypane_1.js]
 [browser_privacypane_3.js]
 [browser_privacypane_4.js]
 [browser_privacypane_5.js]
 [browser_privacypane_8.js]
 [browser_sanitizeOnShutdown_prefLocked.js]
 [browser_searchsuggestions.js]
 [browser_subdialogs.js]
-support-files = subdialog.xul
+support-files =
+  subdialog.xul
+  subdialog2.xul
 [browser_telemetry.js]
 # Skip this test on Android and B2G as FHR and Telemetry are separate systems there.
 skip-if = !healthreport || !telemetry || (os == 'linux' && debug) || (os == 'android') || (os == 'b2g')
--- a/browser/components/preferences/in-content/tests/browser_subdialogs.js
+++ b/browser/components/preferences/in-content/tests/browser_subdialogs.js
@@ -3,27 +3,28 @@
 
 "use strict";
 
 /**
  * Tests for the sub-dialog infrastructure, not for actual sub-dialog functionality.
  */
 
 const gDialogURL = getRootDirectory(gTestPath) + "subdialog.xul";
+const gDialogURL2 = getRootDirectory(gTestPath) + "subdialog2.xul";
 
-function* open_subdialog_and_test_generic_start_state(browser, domcontentloadedFn) {
+function* open_subdialog_and_test_generic_start_state(browser, domcontentloadedFn, url = gDialogURL) {
   let domcontentloadedFnStr = domcontentloadedFn ?
     "(" + domcontentloadedFn.toString() + ")()" :
     "";
-  return ContentTask.spawn(browser, {gDialogURL, domcontentloadedFnStr}, function*(args) {
-    let {gDialogURL, domcontentloadedFnStr} = args;
+  return ContentTask.spawn(browser, {url, domcontentloadedFnStr}, function*(args) {
+    let {url, domcontentloadedFnStr} = args;
     let rv = { acceptCount: 0 };
     let win = content.window;
     let subdialog = win.gSubDialog;
-    subdialog.open(gDialogURL, null, rv);
+    subdialog.open(url, null, rv);
 
     info("waiting for subdialog DOMFrameContentLoaded");
     yield ContentTaskUtils.waitForEvent(win, "DOMFrameContentLoaded", true);
     let result;
     if (domcontentloadedFnStr) {
       result = eval(domcontentloadedFnStr);
     }
 
@@ -123,16 +124,38 @@ add_task(function* check_canceling_dialo
   yield open_subdialog_and_test_generic_start_state(tab.linkedBrowser);
 
   info("canceling the dialog");
   yield close_subdialog_and_test_generic_end_state(tab.linkedBrowser,
     function() { content.window.gSubDialog._frame.contentDocument.documentElement.cancelDialog(); },
     "cancel", 0);
 });
 
+add_task(function* check_reopening_dialog() {
+  yield open_subdialog_and_test_generic_start_state(tab.linkedBrowser);
+  info("opening another dialog which will close the first");
+  yield open_subdialog_and_test_generic_start_state(tab.linkedBrowser, "", gDialogURL2);
+  info("closing as normal");
+  yield close_subdialog_and_test_generic_end_state(tab.linkedBrowser,
+    function() { content.window.gSubDialog._frame.contentDocument.documentElement.acceptDialog(); },
+    "accept", 1);
+});
+
+add_task(function* check_opening_while_closing() {
+  yield open_subdialog_and_test_generic_start_state(tab.linkedBrowser);
+  info("closing");
+  content.window.gSubDialog.close();
+  info("reopening immediately after calling .close()");
+  yield open_subdialog_and_test_generic_start_state(tab.linkedBrowser);
+  yield close_subdialog_and_test_generic_end_state(tab.linkedBrowser,
+    function() { content.window.gSubDialog._frame.contentDocument.documentElement.acceptDialog(); },
+    "accept", 1);
+
+});
+
 add_task(function* window_close_on_dialog() {
   yield open_subdialog_and_test_generic_start_state(tab.linkedBrowser);
 
   info("canceling the dialog");
   yield close_subdialog_and_test_generic_end_state(tab.linkedBrowser,
     function() { content.window.gSubDialog._frame.contentWindow.window.close(); },
     null, 0);
 });
copy from browser/components/preferences/in-content/tests/subdialog.xul
copy to browser/components/preferences/in-content/tests/subdialog2.xul
--- a/browser/components/preferences/in-content/tests/subdialog.xul
+++ b/browser/components/preferences/in-content/tests/subdialog2.xul
@@ -2,17 +2,17 @@
 
 <!-- Any copyright is dedicated to the Public Domain.
    - http://creativecommons.org/publicdomain/zero/1.0/ -->
 
 <?xml-stylesheet href="chrome://global/skin/" type="text/css"?>
 
 <dialog id="subDialog"
         xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"
-        title="Sample sub-dialog" style="width: 32em; height: 5em;"
+        title="Sample sub-dialog #2" style="width: 32em; height: 5em;"
         onload="document.getElementById('textbox').focus();"
         ondialogaccept="acceptSubdialog();">
   <script>
     function acceptSubdialog() {
       window.arguments[0].acceptCount++;
     }
   </script>
 
--- a/browser/components/syncedtabs/SyncedTabsDeckComponent.js
+++ b/browser/components/syncedtabs/SyncedTabsDeckComponent.js
@@ -44,17 +44,19 @@ function SyncedTabsDeckComponent({
   this._getChromeWindow = getChromeWindowMock || getChromeWindow;
 
   this._deckStore = deckStore || new SyncedTabsDeckStore();
   this._syncedTabsListStore = listStore || new SyncedTabsListStore(SyncedTabs);
   this.tabListComponent = listComponent || new TabListComponent({
     window: this._window,
     store: this._syncedTabsListStore,
     View: TabListView,
-    SyncedTabs: SyncedTabs
+    SyncedTabs: SyncedTabs,
+    clipboardHelper: Cc["@mozilla.org/widget/clipboardhelper;1"]
+                       .getService(Ci.nsIClipboardHelper),
   });
 }
 
 SyncedTabsDeckComponent.prototype = {
   PANELS: {
     TABS_CONTAINER: "tabs-container",
     TABS_FETCHING: "tabs-fetching",
     NOT_AUTHED_INFO: "notAuthedInfo",
--- a/browser/components/syncedtabs/TabListComponent.js
+++ b/browser/components/syncedtabs/TabListComponent.js
@@ -17,20 +17,21 @@ this.EXPORTED_SYMBOLS = [
  * TabListComponent
  *
  * The purpose of this component is to compose the view, state, and actions.
  * It defines high level actions that act on the state and passes them to the
  * view for it to trigger during user interaction. It also subscribes the view
  * to state changes so it can rerender.
  */
 
-function TabListComponent({window, store, View, SyncedTabs}) {
+function TabListComponent({window, store, View, SyncedTabs, clipboardHelper}) {
   this._window = window;
   this._store = store;
   this._View = View;
+  this._clipboardHelper = clipboardHelper;
   // used to trigger Sync from context menu
   this._SyncedTabs = SyncedTabs;
 }
 
 TabListComponent.prototype = {
   get container() {
     return this._view.container;
   },
@@ -40,16 +41,17 @@ TabListComponent.prototype = {
 
     this._view = new this._View(this._window, {
       onSelectRow: (...args) => this.onSelectRow(...args),
       onOpenTab: (...args) => this.onOpenTab(...args),
       onMoveSelectionDown: (...args) => this.onMoveSelectionDown(...args),
       onMoveSelectionUp: (...args) => this.onMoveSelectionUp(...args),
       onToggleBranch: (...args) => this.onToggleBranch(...args),
       onBookmarkTab: (...args) => this.onBookmarkTab(...args),
+      onCopyTabLocation: (...args) => this.onCopyTabLocation(...args),
       onSyncRefresh: (...args) => this.onSyncRefresh(...args),
       onFilter: (...args) => this.onFilter(...args),
       onClearFilter: (...args) => this.onClearFilter(...args),
       onFilterFocus: (...args) => this.onFilterFocus(...args),
       onFilterBlur: (...args) => this.onFilterBlur(...args)
     });
 
     this._store.on("change", state => this._view.render(state));
@@ -99,16 +101,20 @@ TabListComponent.prototype = {
   },
 
   onBookmarkTab(uri, title) {
     this._window.top.PlacesCommandHook
       .bookmarkLink(this._window.top.PlacesUtils.bookmarksMenuFolderId, uri, title)
       .catch(Cu.reportError);
   },
 
-  onOpenTab(url, event) {
-    this._window.openUILink(url, event);
+  onOpenTab(url, where, params) {
+    this._window.openLinkIn(url, where, params);
+  },
+
+  onCopyTabLocation(url) {
+    this._clipboardHelper.copyString(url);
   },
 
   onSyncRefresh() {
     this._SyncedTabs.syncTabs(true);
   }
 };
--- a/browser/components/syncedtabs/TabListView.js
+++ b/browser/components/syncedtabs/TabListView.js
@@ -288,31 +288,38 @@ TabListView.prototype = {
         this.props.onOpenTab(selectedNode.dataset.url, event);
       } else if (selectedNode) {
         this.props.onToggleBranch(selectedNode.dataset.id);
       }
     }
   },
 
   onBookmarkTab() {
-    let item = this.container.querySelector('.item.selected');
-    if (!item || !item.dataset.url) {
-      return;
+    let item = this._getSelectedTabNode();
+    if (item) {
+      let title = item.querySelector(".item-title").textContent;
+      this.props.onBookmarkTab(item.dataset.url, title);
     }
+  },
 
-    let uri = item.dataset.url;
-    let title = item.querySelector(".item-title").textContent;
-
-    this.props.onBookmarkTab(uri, title);
+  onCopyTabLocation() {
+    let item = this._getSelectedTabNode();
+    if (item) {
+      this.props.onCopyTabLocation(item.dataset.url);
+    }
   },
 
   onOpenSelected(event) {
-    let item = this.container.querySelector('.item.selected');
-    if (this._isTab(item) && item.dataset.url) {
-      this.props.onOpenTab(item.dataset.url, event);
+    let item = this._getSelectedTabNode();
+    if (item) {
+      let where = event.target.getAttribute("where");
+      let params = {
+        private: event.target.hasAttribute("private"),
+      };
+      this.props.onOpenTab(item.dataset.url, where, params);
     }
   },
 
   onFilter(event) {
     let query = event.target.value;
     if (query) {
       this.props.onFilter(query);
     } else {
@@ -326,16 +333,24 @@ TabListView.prototype = {
 
   onFilterFocus() {
     this.props.onFilterFocus();
   },
   onFilterBlur() {
     this.props.onFilterBlur();
   },
 
+  _getSelectedTabNode() {
+    let item = this.container.querySelector('.item.selected');
+    if (this._isTab(item) && item.dataset.url) {
+      return item;
+    }
+    return null;
+  },
+
   // Set up the custom context menu
   _setupContextMenu() {
     Services.els.addSystemEventListener(this._window, "contextmenu", this, false);
     for (let getMenu of [getContextMenu, getTabsFilterContextMenu]) {
       let menu = getMenu(this._window);
       menu.addEventListener("popupshowing", this, true);
       menu.addEventListener("command", this, true);
     }
@@ -399,21 +414,27 @@ TabListView.prototype = {
       }
     }
   },
 
   handleContentContextMenuCommand(event) {
     let id = event.target.getAttribute("id");
     switch (id) {
       case "syncedTabsOpenSelected":
+      case "syncedTabsOpenSelectedInTab":
+      case "syncedTabsOpenSelectedInWindow":
+      case "syncedTabsOpenSelectedInPrivateWindow":
         this.onOpenSelected(event);
         break;
       case "syncedTabsBookmarkSelected":
         this.onBookmarkTab();
         break;
+      case "syncedTabsCopySelected":
+        this.onCopyTabLocation();
+        break;
       case "syncedTabsRefresh":
       case "syncedTabsRefreshFilter":
         this.props.onSyncRefresh();
         break;
     }
   },
 
   handleTabsFilterContextMenuCommand(event) {
--- a/browser/components/syncedtabs/sidebar.xhtml
+++ b/browser/components/syncedtabs/sidebar.xhtml
@@ -65,17 +65,17 @@
       <div class="tabs-container">
         <div class="list" role="listbox" tabindex="1"></div>
       </div>
     </template>
 
     <template id="deck-template">
       <div class="deck">
         <div class="tabs-fetching sync-state">
-          <p>&syncedTabs.sidebar.fetching.label;</p>
+          <!-- Show intentionally blank panel, see bug 1239845 -->
         </div>
         <div class="notAuthedInfo sync-state">
           <p>&syncedTabs.sidebar.notsignedin.label;</p>
           <p><a href="#" class="sync-prefs text-link">&fxaSignIn.label;</a></p>
         </div>
         <div class="singleDeviceInfo sync-state">
           <p>&syncedTabs.sidebar.noclients.label;</p>
           <p class="device-promo"></p>
--- a/browser/components/syncedtabs/test/browser/browser_sidebar_syncedtabslist.js
+++ b/browser/components/syncedtabs/test/browser/browser_sidebar_syncedtabslist.js
@@ -298,29 +298,39 @@ add_task(function* testSyncedTabsSidebar
   yield* testContextMenu(syncedTabsDeckComponent,
                          "#SyncedTabsSidebarTabsFilterContext",
                          ".tabsFilter",
                          filterMenuItems);
 
   info("Right-clicking a tab should show additional actions");
   let tabMenuItems = [
     ["menuitem#syncedTabsOpenSelected", { hidden: false }],
+    ["menuitem#syncedTabsOpenSelectedInTab", { hidden: false }],
+    ["menuitem#syncedTabsOpenSelectedInWindow", { hidden: false }],
+    ["menuitem#syncedTabsOpenSelectedInPrivateWindow", { hidden: false }],
+    ["menuseparator", { hidden: false }],
     ["menuitem#syncedTabsBookmarkSelected", { hidden: false }],
+    ["menuitem#syncedTabsCopySelected", { hidden: false }],
     ["menuseparator", { hidden: false }],
     ["menuitem#syncedTabsRefresh", { hidden: false }],
   ];
   yield* testContextMenu(syncedTabsDeckComponent,
                          "#SyncedTabsSidebarContext",
                          "#tab-7cqCr77ptzX3-0",
                          tabMenuItems);
 
   info("Right-clicking a client shouldn't show any actions");
   let sidebarMenuItems = [
     ["menuitem#syncedTabsOpenSelected", { hidden: true }],
+    ["menuitem#syncedTabsOpenSelectedInTab", { hidden: true }],
+    ["menuitem#syncedTabsOpenSelectedInWindow", { hidden: true }],
+    ["menuitem#syncedTabsOpenSelectedInPrivateWindow", { hidden: true }],
+    ["menuseparator", { hidden: true }],
     ["menuitem#syncedTabsBookmarkSelected", { hidden: true }],
+    ["menuitem#syncedTabsCopySelected", { hidden: true }],
     ["menuseparator", { hidden: true }],
     ["menuitem#syncedTabsRefresh", { hidden: false }],
   ];
   yield* testContextMenu(syncedTabsDeckComponent,
                          "#SyncedTabsSidebarContext",
                          "#item-OL3EJCsdb2JD",
                          sidebarMenuItems);
 });
--- a/browser/components/syncedtabs/test/xpcshell/test_TabListComponent.js
+++ b/browser/components/syncedtabs/test/xpcshell/test_TabListComponent.js
@@ -62,27 +62,31 @@ add_task(function* testInitUninit() {
     "view.render is called on state change");
 
   component.uninit();
   Assert.ok(view.destroy.calledOnce, "view is destroyed on uninit");
 });
 
 add_task(function* testActions() {
   let store = new SyncedTabsListStore();
+  let clipboardHelperMock = {
+    copyString() {},
+  };
   let windowMock = {
     top: {
       PlacesCommandHook: {
         bookmarkLink() { return Promise.resolve(); }
       },
       PlacesUtils: { bookmarksMenuFolderId: "id" }
     },
-    openUILink() {}
+    openLinkIn() {}
   };
   let component = new TabListComponent({
-    window: windowMock, store, View: null, SyncedTabs});
+    window: windowMock, store, View: null, SyncedTabs,
+    clipboardHelper: clipboardHelperMock});
 
   sinon.stub(store, "getData");
   component.onFilter("query");
   Assert.ok(store.getData.calledWith("query"));
 
   sinon.stub(store, "clearFilter");
   component.onClearFilter();
   Assert.ok(store.clearFilter.called);
@@ -112,18 +116,22 @@ add_task(function* testActions() {
   component.onToggleBranch("foo-id");
   Assert.ok(store.toggleBranch.secondCall.calledWith("foo-id"));
 
   sinon.spy(windowMock.top.PlacesCommandHook, "bookmarkLink");
   component.onBookmarkTab("uri", "title");
   Assert.equal(windowMock.top.PlacesCommandHook.bookmarkLink.args[0][1], "uri");
   Assert.equal(windowMock.top.PlacesCommandHook.bookmarkLink.args[0][2], "title");
 
-  sinon.spy(windowMock, "openUILink");
-  component.onOpenTab("uri", "event");
-  Assert.ok(windowMock.openUILink.calledWith("uri", "event"));
+  sinon.spy(windowMock, "openLinkIn");
+  component.onOpenTab("uri", "where", "params");
+  Assert.ok(windowMock.openLinkIn.calledWith("uri", "where", "params"));
+
+  sinon.spy(clipboardHelperMock, "copyString");
+  component.onCopyTabLocation("uri");
+  Assert.ok(clipboardHelperMock.copyString.calledWith("uri"));
 
   sinon.stub(SyncedTabs, "syncTabs");
   component.onSyncRefresh();
   Assert.ok(SyncedTabs.syncTabs.calledWith(true));
   SyncedTabs.syncTabs.restore();
 });
 
--- a/browser/config/tooltool-manifests/win32/releng.manifest
+++ b/browser/config/tooltool-manifests/win32/releng.manifest
@@ -1,20 +1,20 @@
 [
 {
 "size": 266240,
 "digest": "bb345b0e700ffab4d09436981f14b5de84da55a3f18a7f09ebc4364a4488acdeab8d46f447b12ac70f2da1444a68b8ce8b8675f0dae2ccf845e966d1df0f0869",
 "algorithm": "sha512",
 "filename": "mozmake.exe"
 },
 {
-"size": 78886322,
-"digest": "9c2c40637de27a0852aa1166f2a08159908b23f7a55855c933087c541461bbb2a1ec9e0522df0d2b9da2b2c343b673dbb5a2fa8d30216fe8acee1eb1383336ea",
+"size": 51746920,
+"digest": "9d886f27b50ad0479062674e815f3a99bd75dbcf2e3932090352f2866fc90cc8d8aea0e790a42baba3bee302f43d236cce7377d469bb665e5d5a3f5edf05d0c5",
 "algorithm": "sha512",
-"filename": "rustc-beta-i686-pc-windows-msvc.tar.bz2",
+"filename": "rustc.tar.bz2",
 "unpack": true
 },
 {
 "size": 167175,
 "digest": "0b71a936edf5bd70cf274aaa5d7abc8f77fe8e7b5593a208f805cc9436fac646b9c4f0b43c2b10de63ff3da671497d35536077ecbc72dba7f8159a38b580f831",
 "algorithm": "sha512",
 "filename": "sccache.tar.bz2",
 "unpack": true
--- a/browser/experiments/test/xpcshell/xpcshell.ini
+++ b/browser/experiments/test/xpcshell/xpcshell.ini
@@ -5,16 +5,17 @@ tags = addons
 firefox-appdir = browser
 skip-if = toolkit == 'android' || toolkit == 'gonk'
 support-files =
   experiments_1.manifest
   experiment-1.xpi
   experiment-1a.xpi
   experiment-2.xpi
   experiment-racybranch.xpi
+  !/toolkit/mozapps/extensions/test/xpcshell/head_addons.js
 generated-files =
   experiment-1.xpi
   experiment-1a.xpi
   experiment-2.xpi
   experiment-racybranch.xpi
 
 [test_activate.js]
 [test_api.js]
--- a/browser/installer/windows/nsis/installer.nsi
+++ b/browser/installer/windows/nsis/installer.nsi
@@ -473,17 +473,17 @@ Section "-Application" APP_IDX
   StrCpy $0 "Software\Microsoft\Windows\CurrentVersion\App Paths\${FileMainEXE}"
   ${WriteRegStr2} $TmpVal "$0" "" "$INSTDIR\${FileMainEXE}" 0
   ${WriteRegStr2} $TmpVal "$0" "Path" "$INSTDIR" 0
 
   StrCpy $0 "Software\Microsoft\MediaPlayer\ShimInclusionList\$R9"
   ${CreateRegKey} "$TmpVal" "$0" 0
   StrCpy $0 "Software\Microsoft\MediaPlayer\ShimInclusionList\firefox-webcontent.exe"
   ${CreateRegKey} "$TmpVal" "$0" 0
-  StrCpy $0 "Software\Microsoft\MediaPlayer\ShimInclusionList\firefox-plugin-container.exe"
+  StrCpy $0 "Software\Microsoft\MediaPlayer\ShimInclusionList\plugin-container.exe"
   ${CreateRegKey} "$TmpVal" "$0" 0
 
   ${If} $TmpVal == "HKLM"
     ; Set the permitted LSP Categories for WinVista and above
     ${SetAppLSPCategories} ${LSP_CATEGORIES}
   ${EndIf}
 
   ; Create shortcuts
--- a/browser/installer/windows/nsis/uninstaller.nsi
+++ b/browser/installer/windows/nsis/uninstaller.nsi
@@ -353,17 +353,17 @@ Section "Uninstall"
     DeleteRegKey HKLM "$0"
     DeleteRegKey HKCU "$0"
     StrCpy $0 "Software\Microsoft\MediaPlayer\ShimInclusionList\${FileMainEXE}"
     DeleteRegKey HKLM "$0"
     DeleteRegKey HKCU "$0"
     StrCpy $0 "Software\Microsoft\MediaPlayer\ShimInclusionList\firefox-webcontent.exe"
     DeleteRegKey HKLM "$0"
     DeleteRegKey HKCU "$0"
-    StrCpy $0 "Software\Microsoft\MediaPlayer\ShimInclusionList\firefox-plugin-container.exe"
+    StrCpy $0 "Software\Microsoft\MediaPlayer\ShimInclusionList\plugin-container.exe"
     DeleteRegKey HKLM "$0"
     DeleteRegKey HKCU "$0"
     StrCpy $0 "Software\Classes\MIME\Database\Content Type\application/x-xpinstall;app=firefox"
     DeleteRegKey HKLM "$0"
     DeleteRegKey HKCU "$0"
   ${Else}
     ReadRegStr $R1 HKLM "$0" ""
     ${un.RemoveQuotesFromPath} "$R1" $R1
--- a/browser/locales/en-US/chrome/browser/browser.dtd
+++ b/browser/locales/en-US/chrome/browser/browser.dtd
@@ -334,17 +334,16 @@ These should match what Safari and other
 <!ENTITY appMenuHistory.label "History">
 <!ENTITY appMenuHistory.showAll.label "Show All History">
 <!ENTITY appMenuHistory.clearRecent.label "Clear Recent History…">
 <!ENTITY appMenuHistory.restoreSession.label "Restore Previous Session">
 <!ENTITY appMenuHistory.viewSidebar.label "View History Sidebar">
 <!ENTITY appMenuHelp.tooltip "Open Help Menu">
 
 <!ENTITY appMenuRemoteTabs.label "Synced Tabs">
-<!ENTITY appMenuRemoteTabs.fetching.label "Fetching Synced Tabs…">
 <!-- LOCALIZATION NOTE (appMenuRemoteTabs.notabs.label): This is shown beneath
      the name of a device when that device has no open tabs -->
 <!ENTITY appMenuRemoteTabs.notabs.label "No open tabs">
 <!-- LOCALIZATION NOTE (appMenuRemoteTabs.tabsnotsyncing.label): This is shown
      when Sync is configured but syncing tabs is disabled. -->
 <!ENTITY appMenuRemoteTabs.tabsnotsyncing.label "Turn on tab syncing to view a list of tabs from your other devices.">
 <!-- LOCALIZATION NOTE (appMenuRemoteTabs.noclients.label): This is shown
      when Sync is configured but this appears to be the only device attached to
@@ -719,29 +718,36 @@ you can use these alternative items. Oth
 <!-- Name for the tabs toolbar as spoken by screen readers.
      The word "toolbar" is appended automatically and should not be contained below! -->
 <!ENTITY tabsToolbar.label "Browser tabs">
 
 <!-- LOCALIZATION NOTE (syncTabsMenu3.label): This appears in the history menu -->
 <!ENTITY syncTabsMenu3.label     "Synced Tabs">
 
 <!ENTITY syncedTabs.sidebar.label              "Synced Tabs">
-<!ENTITY syncedTabs.sidebar.fetching.label     "Fetching Synced Tabs…">
 <!ENTITY syncedTabs.sidebar.noclients.label    "Sign in to Firefox from your other devices to view their tabs here.">
 <!ENTITY syncedTabs.sidebar.notsignedin.label  "Sign in to view a list of tabs from your other devices.">
 <!ENTITY syncedTabs.sidebar.notabs.label       "No open tabs">
 <!ENTITY syncedTabs.sidebar.openprefs.label    "Open &syncBrand.shortName.label; Preferences">
 <!-- LOCALIZATION NOTE (syncedTabs.sidebar.tabsnotsyncing.label): This is shown
      when Sync is configured but syncing tabs is disabled. -->
 <!ENTITY syncedTabs.sidebar.tabsnotsyncing.label       "Turn on tab syncing to view a list of tabs from your other devices.">
 
-<!ENTITY syncedTabs.context.openTab.label                   "Open This Tab">
-<!ENTITY syncedTabs.context.openTab.accesskey               "O">
-<!ENTITY syncedTabs.context.bookmarkSingleTab.label         "Bookmark This Tab…">
-<!ENTITY syncedTabs.context.bookmarkSingleTab.accesskey     "B">
+<!ENTITY syncedTabs.context.open.label                       "Open">
+<!ENTITY syncedTabs.context.open.accesskey                   "O">
+<!ENTITY syncedTabs.context.openInNewTab.label               "Open in a New Tab">
+<!ENTITY syncedTabs.context.openInNewTab.accesskey           "w">
+<!ENTITY syncedTabs.context.openInNewWindow.label            "Open in a New Window">
+<!ENTITY syncedTabs.context.openInNewWindow.accesskey        "N">
+<!ENTITY syncedTabs.context.openInNewPrivateWindow.label     "Open in a New Private Window">
+<!ENTITY syncedTabs.context.openInNewPrivateWindow.accesskey "P">
+<!ENTITY syncedTabs.context.bookmarkSingleTab.label          "Bookmark This Tab…">
+<!ENTITY syncedTabs.context.bookmarkSingleTab.accesskey      "B">
+<!ENTITY syncedTabs.context.copy.label                       "Copy">
+<!ENTITY syncedTabs.context.copy.accesskey                   "C">
 
 
 <!ENTITY syncBrand.shortName.label    "Sync">
 
 <!ENTITY syncSignIn.label             "Sign In To &syncBrand.shortName.label;…">
 <!ENTITY syncSignIn.accesskey         "Y">
 <!ENTITY syncSyncNowItem.label        "Sync Now">
 <!ENTITY syncSyncNowItem.accesskey    "S">
--- a/build/autoconf/compiler-opts.m4
+++ b/build/autoconf/compiler-opts.m4
@@ -11,18 +11,16 @@ dnl set DEVELOPER_OPTIONS early; MOZ_DEF
     DEVELOPER_OPTIONS=1
   fi
   MOZ_ARG_ENABLE_BOOL(release,
   [  --enable-release        Build with more conservative, release engineering-oriented options.
                           This may slow down builds.],
       DEVELOPER_OPTIONS=,
       DEVELOPER_OPTIONS=1)
 
-  AC_SUBST(DEVELOPER_OPTIONS)
-
 dnl Default to MSVC for win32 and gcc-4.2 for darwin
 dnl ==============================================================
 if test -z "$CROSS_COMPILE"; then
 case "$target" in
 *-mingw*)
     if test -z "$CC"; then CC=cl; fi
     if test -z "$CXX"; then CXX=cl; fi
     if test -z "$CPP"; then CPP="$CC -E -nologo"; fi
--- a/build/autoconf/rust.m4
+++ b/build/autoconf/rust.m4
@@ -101,17 +101,17 @@ AC_DEFUN([MOZ_RUST_SUPPORT], [
       arm*linux-android*)
           rust_target=arm-linux-androideabi
           ;;
 
       # Windows
       i*86-pc-mingw32)
           # XXX better detection of CXX needed here, to figure out whether
           # we need i686-pc-windows-gnu instead, since mingw32 builds work.
-          rust_target=i686-pc-windows-msvc
+          rust_target=i586-pc-windows-msvc
           ;;
       x86_64-pc-mingw32)
           # XXX and here as well
           rust_target=x86_64-pc-windows-msvc
           ;;
       *)
           # Fall back to implicit (native) target when not cross-compiling
           if test -n "$CROSS_COMPILE"; then
--- a/build/autoconf/toolchain.m4
+++ b/build/autoconf/toolchain.m4
@@ -186,56 +186,35 @@ AC_CHECK_PROGS(STRIP, "${TOOLCHAIN_PREFI
 AC_CHECK_PROGS(WINDRES, "${TOOLCHAIN_PREFIX}windres", :)
 AC_CHECK_PROGS(OTOOL, "${TOOLCHAIN_PREFIX}otool", :)
 AC_CHECK_PROGS(OBJCOPY, "${TOOLCHAIN_PREFIX}objcopy", :)
 PATH=$_SAVE_PATH
 ])
 
 AC_DEFUN([MOZ_CXX11],
 [
-dnl Check whether gcc's c++0x mode works
 dnl Updates to the test below should be duplicated further below for the
 dnl cross-compiling case.
 AC_LANG_CPLUSPLUS
 if test "$GNU_CXX"; then
-    CXXFLAGS="$CXXFLAGS -std=gnu++0x"
-    _ADDED_CXXFLAGS="-std=gnu++0x"
-
-    AC_CACHE_CHECK(for gcc c++0x headers bug without rtti,
-        ac_cv_cxx0x_headers_bug,
-        [AC_TRY_COMPILE([#include <memory>], [],
-                        ac_cv_cxx0x_headers_bug="no",
-                        ac_cv_cxx0x_headers_bug="yes")])
-
-    if test "$CLANG_CXX" -a "$ac_cv_cxx0x_headers_bug" = "yes"; then
-        CXXFLAGS="$CXXFLAGS -I$_topsrcdir/build/unix/headers"
-        _ADDED_CXXFLAGS="$_ADDED_CXXFLAGS -I$_topsrcdir/build/unix/headers"
-        AC_CACHE_CHECK(whether workaround for gcc c++0x headers conflict with clang works,
-            ac_cv_cxx0x_clang_workaround,
-            [AC_TRY_COMPILE([#include <memory>], [],
-                            ac_cv_cxx0x_clang_workaround="yes",
-                            ac_cv_cxx0x_clang_workaround="no")])
-
-        if test "ac_cv_cxx0x_clang_workaround" = "no"; then
-            AC_MSG_ERROR([Your toolchain does not support C++0x/C++11 mode properly. Please upgrade your toolchain])
-        fi
-    elif test "$ac_cv_cxx0x_headers_bug" = "yes"; then
-        AC_MSG_ERROR([Your toolchain does not support C++0x/C++11 mode properly. Please upgrade your toolchain])
-    fi
+    CXXFLAGS="$CXXFLAGS -std=gnu++11"
+    _ADDED_CXXFLAGS="-std=gnu++11"
 
     if test -n "$CLANG_CC"; then
         dnl We'd normally just check for the version from CC_VERSION (fed
         dnl from __clang_major__ and __clang_minor__), but the clang that
         dnl comes with Xcode has a completely different version scheme
         dnl despite exposing the version with the same defines.
-        dnl So instead of a version check, check for one of the C++11
-        dnl features that was added in clang 3.3.
-        AC_TRY_COMPILE([], [#if !__has_feature(cxx_inheriting_constructors)
-                            #error inheriting constructors are not supported
-                            #endif],,AC_MSG_ERROR([Only clang/llvm 3.3 or newer supported]))
+        dnl So instead of a version check, do a feature check. Normally,
+        dnl we'd use __has_feature, but there are unfortunately no C++11
+        dnl differences in clang 3.4. However, it supports the 2013-08-28
+        dnl draft of the ISO WG21 SG10 feature test macro recommendations.
+        AC_TRY_COMPILE([], [#if !__cpp_static_assert
+                            #error ISO WG21 SG10 feature test macros unsupported
+                            #endif],,AC_MSG_ERROR([Only clang/llvm 3.4 or newer supported]))
     fi
 
     AC_CACHE_CHECK([whether 64-bits std::atomic requires -latomic],
         ac_cv_needs_atomic,
         AC_TRY_LINK(
             [#include <cstdint>
              #include <atomic>],
             [ std::atomic<uint64_t> foo; foo = 1; ],
@@ -295,49 +274,28 @@ EOF
             changequote([,])
 
             if test "$HOST_GCC_MAJOR_VERSION" -eq 4 -a "$HOST_GCC_MINOR_VERSION" -lt 8 ||
                test "$HOST_GCC_MAJOR_VERSION" -lt 4; then
                 AC_MSG_ERROR([Only GCC 4.8 or newer supported for host compiler])
             fi
         fi
 
-        HOST_CXXFLAGS="$HOST_CXXFLAGS -std=gnu++0x"
+        HOST_CXXFLAGS="$HOST_CXXFLAGS -std=gnu++11"
 
         _SAVE_CXXFLAGS="$CXXFLAGS"
         _SAVE_CPPFLAGS="$CPPFLAGS"
         _SAVE_CXX="$CXX"
         CXXFLAGS="$HOST_CXXFLAGS"
         CPPFLAGS="$HOST_CPPFLAGS"
         CXX="$HOST_CXX"
-        AC_CACHE_CHECK(for host gcc c++0x headers bug without rtti,
-            ac_cv_host_cxx0x_headers_bug,
-            [AC_TRY_COMPILE([#include <memory>], [],
-                            ac_cv_host_cxx0x_headers_bug="no",
-                            ac_cv_host_cxx0x_headers_bug="yes")])
-
-        if test "$host_compiler" = CLANG -a "$ac_cv_host_cxx0x_headers_bug" = "yes"; then
-            CXXFLAGS="$CXXFLAGS -I$_topsrcdir/build/unix/headers"
-            AC_CACHE_CHECK(whether workaround for host gcc c++0x headers conflict with host clang works,
-                ac_cv_host_cxx0x_clang_workaround,
-                [AC_TRY_COMPILE([#include <memory>], [],
-                                ac_cv_host_cxx0x_clang_workaround="yes",
-                                ac_cv_host_cxx0x_clang_workaround="no")])
-
-            if test "ac_cv_host_cxx0x_clang_workaround" = "no"; then
-                AC_MSG_ERROR([Your host toolchain does not support C++0x/C++11 mode properly. Please upgrade your toolchain])
-            fi
-            HOST_CXXFLAGS="$CXXFLAGS"
-        elif test "$ac_cv_host_cxx0x_headers_bug" = "yes"; then
-            AC_MSG_ERROR([Your host toolchain does not support C++0x/C++11 mode properly. Please upgrade your toolchain])
-        fi
         if test "$host_compiler" = CLANG; then
-            AC_TRY_COMPILE([], [#if !__has_feature(cxx_inheriting_constructors)
-                                #error inheriting constructors are not supported
-                                #endif],,AC_MSG_ERROR([Only clang/llvm 3.3 or newer supported]))
+            AC_TRY_COMPILE([], [#if !__cpp_static_assert
+                                #error ISO WG21 SG10 feature test macros unsupported
+                                #endif],,AC_MSG_ERROR([Only clang/llvm 3.4 or newer supported]))
         fi
 
         CXXFLAGS="$_SAVE_CXXFLAGS"
         CPPFLAGS="$_SAVE_CPPFLAGS"
         CXX="$_SAVE_CXX"
     fi
 elif test "$GNU_CXX"; then
     HOST_CXXFLAGS="$HOST_CXXFLAGS $_ADDED_CXXFLAGS"
--- a/build/docs/test_manifests.rst
+++ b/build/docs/test_manifests.rst
@@ -94,16 +94,28 @@ support-files
    ``data/**`` will match ``data/foo`` and ``data/subdir/bar``.
 
    Support files starting with ``/`` are placed in a root directory, rather
    than a location determined by the manifest location. For mochitests,
    this allows for the placement of files at the server root. The source
    file is selected from the base name (e.g., ``foo`` for ``/path/foo``).
    Files starting with ``/`` cannot be selected using globbing.
 
+   Some support files are used by tests across multiple directories. In
+   this case, a test depending on a support file from another directory
+   must note that dependency with the path to the required support file
+   in its own **support-files** entry. These use a syntax where paths
+   starting with ``!/`` will indicate the beginning of the path to a
+   shared support file starting from the root of the srcdir. For example,
+   if a manifest at ``dom/base/test/mochitest.ini`` has a support file,
+   ``dom/base/test/server-script.sjs``, and a mochitest in
+   ``dom/workers/test`` depends on that support file, the test manifest
+   at ``dom/workers/test/mochitest.ini`` must include
+   ``!/dom/base/test/server-script.sjs`` in its **support-files** entry.
+
 generated-files
    List of files that are generated as part of the build and don't exist in
    the source tree.
 
    The build system assumes that each manifest file, test file, and file
    listed in **head**, **tail**, and **support-files** is static and
    provided by the source tree (and not automatically generated as part
    of the build). This variable tells the build system not to make this
--- a/build/moz.configure/old.configure
+++ b/build/moz.configure/old.configure
@@ -243,17 +243,16 @@ def old_configure_options(*options):
     '--enable-parental-controls',
     '--enable-perf',
     '--enable-permissions',
     '--enable-pie',
     '--enable-png-arm-neon-support',
     '--enable-posix-nspr-emulation',
     '--enable-pref-extensions',
     '--enable-printing',
-    '--enable-profilelocking',
     '--enable-pulseaudio',
     '--enable-raw',
     '--enable-readline',
     '--enable-reflow-perf',
     '--enable-release',
     '--enable-replace-malloc',
     '--enable-require-all-d3dc-versions',
     '--enable-rust',
@@ -307,17 +306,16 @@ def old_configure_options(*options):
     '--with-android-min-sdk',
     '--with-android-ndk',
     '--with-android-sdk',
     '--with-android-toolchain',
     '--with-android-version',
     '--with-app-basename',
     '--with-app-name',
     '--with-arch',
-    '--with-arm-kuser',
     '--with-bing-api-keyfile',
     '--with-branding',
     '--with-crashreporter-enable-percent',
     '--with-cross-lib',
     '--with-debug-label',
     '--with-default-mozilla-five-home',
     '--with-distribution-id',
     '--with-doc-include-dirs',
@@ -357,17 +355,16 @@ def old_configure_options(*options):
     '--with-system-nss',
     '--with-system-png',
     '--with-system-zlib',
     '--with-thumb',
     '--with-thumb-interwork',
     '--with-unify-dist',
     '--with-user-appdir',
     '--with-windows-version',
-    '--with-xulrunner-stub-name',
     '--x-includes',
     '--x-libraries',
 
     # Below are the configure flags used by comm-central.
     '--enable-ldap',
     '--enable-mapi',
     '--enable-calendar',
     '--enable-incomplete-external-linkage',
@@ -406,23 +403,24 @@ def old_configure(prepare_configure, ext
     # Our logging goes to config.log, the same file old.configure uses.
     # We can't share the handle on the file, so close it. We assume nothing
     # beyond this point is going to be interesting to log to config.log from
     # our end, so we don't make the effort to recreate a logging.FileHandler.
     logger = logging.getLogger('moz.configure')
     for handler in logger.handlers:
         if isinstance(handler, logging.FileHandler):
             handler.close()
+            logger.removeHandler(handler)
 
     log_size = os.path.getsize('config.log')
 
     ret = subprocess.call(cmd)
     if ret:
         with log.queue_debug():
-            with open('config.log') as fh:
+            with encoded_open('config.log', 'r') as fh:
                 fh.seek(log_size)
                 for line in fh:
                     log.debug(line.rstrip())
             log.error('old-configure failed')
         sys.exit(ret)
 
     raw_config = {}
     with encoded_open('config.data', 'r') as fh:
deleted file mode 100644
--- a/build/unix/headers/bits/c++config.h
+++ /dev/null
@@ -1,2 +0,0 @@
-#include_next <bits/c++config.h>
-#undef _GLIBCXX_USE_FLOAT128
--- a/build/win32/Makefile.in
+++ b/build/win32/Makefile.in
@@ -26,11 +26,11 @@ libs:: $(libs-preqs)
 endif
 
 # run the binscope tool to make sure the binary and all libraries
 # are using all available Windows OS-level security mechanisms
 # Don't do this in clang-cl since it doesn't support debug information yet.
 ifndef CLANG_CL
 check::
 	$(PYTHON) $(srcdir)/autobinscope.py $(DIST)/bin/$(MOZ_APP_NAME)$(BIN_SUFFIX) $(DIST)/crashreporter-symbols/
-	$(PYTHON) $(srcdir)/autobinscope.py $(DIST)/bin/firefox-webcontent.exe $(DIST)/crashreporter-symbols/
-	$(PYTHON) $(srcdir)/autobinscope.py $(DIST)/bin/firefox-plugin-container.exe $(DIST)/crashreporter-symbols/
+	$(PYTHON) $(srcdir)/autobinscope.py $(DIST)/bin/$(MOZ_CHILD_PROCESS_NAME) $(DIST)/crashreporter-symbols/
+	$(PYTHON) $(srcdir)/autobinscope.py $(DIST)/bin/$(MOZ_PLUGIN_PROCESS_NAME) $(DIST)/crashreporter-symbols/
 endif
--- a/caps/tests/mochitest/chrome.ini
+++ b/caps/tests/mochitest/chrome.ini
@@ -1,11 +1,12 @@
 [DEFAULT]
 skip-if = buildapp == 'b2g' || os == 'android'
 support-files =
   file_disableScript.html
+  !/caps/tests/mochitest/file_disableScript.html
 
 [test_bug995943.xul]
 [test_addonMayLoad.html]
 [test_disableScript.xul]
 [test_principal_jarprefix_origin_appid_appstatus.html]
 # jarPrefix test doesn't work on Windows, see bug 776296.
 skip-if = os == "win"
--- a/caps/tests/mochitest/mochitest.ini
+++ b/caps/tests/mochitest/mochitest.ini
@@ -1,12 +1,13 @@
 [DEFAULT]
 support-files =
   file_data.txt
   file_disableScript.html
+  !/js/xpconnect/tests/mochitest/file_empty.html
 
 [test_app_principal_equality.html]
 [test_bug246699.html]
 [test_bug292789.html]
 skip-if = (buildapp == 'b2g' && toolkit != 'gonk') #Bug 931116, b2g desktop specific, initial triage
 [test_bug423375.html]
 [test_bug470804.html]
 [test_disallowInheritPrincipal.html]
--- a/chrome/test/unit_ipc/xpcshell.ini
+++ b/chrome/test/unit_ipc/xpcshell.ini
@@ -1,6 +1,10 @@
 [DEFAULT]
 head = 
 tail = 
 skip-if = toolkit == 'android' || toolkit == 'gonk'
+support-files =
+  !/chrome/test/unit/data/**
+  !/chrome/test/unit/test_resolve_uris.js
+  !/chrome/test/unit/head_crtestutils.js
 
 [test_resolve_uris_ipc.js]
--- a/devtools/client/animationinspector/test/browser.ini
+++ b/devtools/client/animationinspector/test/browser.ini
@@ -9,16 +9,21 @@ support-files =
   doc_keyframes.html
   doc_modify_playbackRate.html
   doc_negative_animation.html
   doc_pseudo_elements.html
   doc_script_animation.html
   doc_simple_animation.html
   doc_multiple_animation_types.html
   head.js
+  !/devtools/client/commandline/test/helpers.js
+  !/devtools/client/framework/test/shared-head.js
+  !/devtools/client/inspector/test/head.js
+  !/devtools/client/shared/test/test-actor-registry.js
+  !/devtools/client/shared/test/test-actor.js
 
 [browser_animation_animated_properties_displayed.js]
 [browser_animation_click_selects_animation.js]
 [browser_animation_controller_exposes_document_currentTime.js]
 skip-if = os == "linux" && !debug # Bug 1234567
 [browser_animation_empty_on_invalid_nodes.js]
 [browser_animation_keyframe_click_to_set_time.js]
 [browser_animation_keyframe_markers.js]
--- a/devtools/client/debugger/test/mochitest/browser.ini
+++ b/devtools/client/debugger/test/mochitest/browser.ini
@@ -118,16 +118,18 @@ support-files =
   doc_with-frame.html
   doc_worker-source-map.html
   doc_WorkerActor.attach-tab1.html
   doc_WorkerActor.attach-tab2.html
   doc_WorkerActor.attachThread-tab.html
   head.js
   sjs_random-javascript.sjs
   testactors.js
+  !/devtools/client/commandline/test/helpers.js
+  !/devtools/client/framework/test/shared-head.js
 
 [browser_dbg_aaa_run_first_leaktest.js]
 skip-if = e10s && debug
 [browser_dbg_addonactor.js]
 tags = addons
 [browser_dbg_addon-sources.js]
 tags = addons
 [browser_dbg_addon-workers-dbg-enabled.js]
--- a/devtools/client/eyedropper/test/browser.ini
+++ b/devtools/client/eyedropper/test/browser.ini
@@ -1,10 +1,12 @@
 [DEFAULT]
 tags = devtools
 subsuite = devtools
 support-files =
   color-block.html
   head.js
+  !/devtools/client/commandline/test/helpers.js
+  !/devtools/client/framework/test/shared-head.js
 
 [browser_eyedropper_basic.js]
 skip-if = os == "win" && debug # bug 963492
 [browser_eyedropper_cmd.js]
--- a/devtools/client/inspector/computed/test/browser.ini
+++ b/devtools/client/inspector/computed/test/browser.ini
@@ -5,16 +5,21 @@ support-files =
   doc_matched_selectors.html
   doc_media_queries.html
   doc_pseudoelement.html
   doc_sourcemaps.css
   doc_sourcemaps.css.map
   doc_sourcemaps.html
   doc_sourcemaps.scss
   head.js
+  !/devtools/client/commandline/test/helpers.js
+  !/devtools/client/inspector/test/head.js
+  !/devtools/client/framework/test/shared-head.js
+  !/devtools/client/shared/test/test-actor.js
+  !/devtools/client/shared/test/test-actor-registry.js
 
 [browser_computed_browser-styles.js]
 [browser_computed_cycle_color.js]
 [browser_computed_getNodeInfo.js]
 [browser_computed_keybindings_01.js]
 [browser_computed_keybindings_02.js]
 [browser_computed_matched-selectors-toggle.js]
 [browser_computed_matched-selectors_01.js]
--- a/devtools/client/inspector/fonts/test/browser.ini
+++ b/devtools/client/inspector/fonts/test/browser.ini
@@ -2,13 +2,18 @@
 tags = devtools
 subsuite = devtools
 support-files =
   browser_fontinspector.html
   test_iframe.html
   ostrich-black.ttf
   ostrich-regular.ttf
   head.js
+  !/devtools/client/commandline/test/helpers.js
+  !/devtools/client/inspector/test/head.js
+  !/devtools/client/framework/test/shared-head.js
+  !/devtools/client/shared/test/test-actor.js
+  !/devtools/client/shared/test/test-actor-registry.js
 
 [browser_fontinspector.js]
 [browser_fontinspector_edit-previews.js]
 [browser_fontinspector_edit-previews-show-all.js]
 [browser_fontinspector_theme-change.js]
--- a/devtools/client/inspector/layout/test/browser.ini
+++ b/devtools/client/inspector/layout/test/browser.ini
@@ -1,15 +1,20 @@
 [DEFAULT]
 tags = devtools
 subsuite = devtools
 support-files =
   doc_layout_iframe1.html
   doc_layout_iframe2.html
   head.js
+  !/devtools/client/commandline/test/helpers.js
+  !/devtools/client/inspector/test/head.js
+  !/devtools/client/framework/test/shared-head.js
+  !/devtools/client/shared/test/test-actor.js
+  !/devtools/client/shared/test/test-actor-registry.js
 
 [browser_layout.js]
 [browser_layout_editablemodel.js]
 # [browser_layout_editablemodel_allproperties.js]
 # Disabled for too many intermittent failures (bug 1009322)
 [browser_layout_editablemodel_border.js]
 [browser_layout_editablemodel_stylerules.js]
 [browser_layout_guides.js]
--- a/devtools/client/inspector/markup/test/browser.ini
+++ b/devtools/client/inspector/markup/test/browser.ini
@@ -35,16 +35,21 @@ support-files =
   lib_jquery_1.1.js
   lib_jquery_1.2_min.js
   lib_jquery_1.3_min.js
   lib_jquery_1.4_min.js
   lib_jquery_1.6_min.js
   lib_jquery_1.7_min.js
   lib_jquery_1.11.1_min.js
   lib_jquery_2.1.1_min.js
+  !/devtools/client/commandline/test/helpers.js
+  !/devtools/client/inspector/test/head.js
+  !/devtools/client/framework/test/shared-head.js
+  !/devtools/client/shared/test/test-actor.js
+  !/devtools/client/shared/test/test-actor-registry.js
 
 [browser_markup_anonymous_01.js]
 [browser_markup_anonymous_02.js]
 skip-if = e10s # scratchpad.xul is not loading in e10s window
 [browser_markup_anonymous_03.js]
 [browser_markup_anonymous_04.js]
 [browser_markup_copy_image_data.js]
 [browser_markup_css_completion_style_attribute_01.js]
--- a/devtools/client/inspector/rules/test/browser.ini
+++ b/devtools/client/inspector/rules/test/browser.ini
@@ -27,16 +27,21 @@ support-files =
   doc_sourcemaps.css.map
   doc_sourcemaps.html
   doc_sourcemaps.scss
   doc_style_editor_link.css
   doc_test_image.png
   doc_urls_clickable.css
   doc_urls_clickable.html
   head.js
+  !/devtools/client/commandline/test/helpers.js
+  !/devtools/client/inspector/test/head.js
+  !/devtools/client/framework/test/shared-head.js
+  !/devtools/client/shared/test/test-actor.js
+  !/devtools/client/shared/test/test-actor-registry.js
 
 [browser_rules_add-property-and-reselect.js]
 [browser_rules_add-property-cancel_01.js]
 [browser_rules_add-property-cancel_02.js]
 [browser_rules_add-property-cancel_03.js]
 [browser_rules_add-property-commented.js]
 [browser_rules_add-property_01.js]
 [browser_rules_add-property_02.js]
--- a/devtools/client/inspector/test/browser.ini
+++ b/devtools/client/inspector/test/browser.ini
@@ -25,16 +25,21 @@ support-files =
   doc_inspector_remove-iframe-during-load.html
   doc_inspector_search.html
   doc_inspector_search-reserved.html
   doc_inspector_search-suggestions.html
   doc_inspector_search-svg.html
   doc_inspector_select-last-selected-01.html
   doc_inspector_select-last-selected-02.html
   head.js
+  !/devtools/client/commandline/test/helpers.js
+  !/devtools/client/inspector/test/head.js
+  !/devtools/client/framework/test/shared-head.js
+  !/devtools/client/shared/test/test-actor.js
+  !/devtools/client/shared/test/test-actor-registry.js
 
 [browser_inspector_breadcrumbs.js]
 [browser_inspector_breadcrumbs_highlight_hover.js]
 [browser_inspector_breadcrumbs_keybinding.js]
 [browser_inspector_breadcrumbs_menu.js]
 [browser_inspector_breadcrumbs_mutations.js]
 [browser_inspector_delete-selected-node-01.js]
 [browser_inspector_delete-selected-node-02.js]
--- a/devtools/client/jsonview/test/browser.ini
+++ b/devtools/client/jsonview/test/browser.ini
@@ -7,15 +7,18 @@ support-files =
   doc_frame_script.js
   head.js
   invalid_json.json
   invalid_json.json^headers^
   simple_json.json
   simple_json.json^headers^
   valid_json.json
   valid_json.json^headers^
+  !/devtools/client/commandline/test/head.js
+  !/devtools/client/framework/test/head.js
+  !/devtools/client/framework/test/shared-head.js
 
 [browser_jsonview_copy_headers.js]
 [browser_jsonview_copy_json.js]
 [browser_jsonview_copy_rawdata.js]
 [browser_jsonview_filter.js]
 [browser_jsonview_invalid_json.js]
 [browser_jsonview_valid_json.js]
--- a/devtools/client/memory/test/browser/browser.ini
+++ b/devtools/client/memory/test/browser/browser.ini
@@ -1,15 +1,17 @@
 [DEFAULT]
 tags = devtools devtools-memory
 subsuite = devtools
 support-files =
   head.js
   doc_big_tree.html
   doc_steady_allocation.html
+  !/devtools/client/framework/test/shared-head.js
+  !/devtools/client/framework/test/shared-redux-head.js
 
 [browser_memory_allocationStackDisplay_01.js]
     skip-if = debug # bug 1219554
 [browser_memory_displays_01.js]
 [browser_memory_clear_snapshots.js]
 [browser_memory_diff_01.js]
 [browser_memory_dominator_trees_01.js]
 [browser_memory_dominator_trees_02.js]
--- a/devtools/client/netmonitor/har/test/browser.ini
+++ b/devtools/client/netmonitor/har/test/browser.ini
@@ -1,9 +1,11 @@
 [DEFAULT]
 tags = devtools
 subsuite = devtools
 support-files =
   head.js
   html_har_post-data-test-page.html
+  !/devtools/client/netmonitor/test/head.js
+  !/devtools/client/netmonitor/test/html_simple-test-page.html
 
 [browser_net_har_copy_all_as_har.js]
 [browser_net_har_post_data.js]
--- a/devtools/client/responsive.html/test/browser/browser.ini
+++ b/devtools/client/responsive.html/test/browser/browser.ini
@@ -1,9 +1,11 @@
 [DEFAULT]
 tags = devtools
 subsuite = devtools
 support-files =
   devices.json
   head.js
+  !/devtools/client/framework/test/shared-head.js
+  !/devtools/client/framework/test/shared-redux-head.js
 
 [browser_exit_button.js]
 [browser_viewport_basics.js]
--- a/devtools/client/responsivedesign/test/browser.ini
+++ b/devtools/client/responsivedesign/test/browser.ini
@@ -1,14 +1,16 @@
 [DEFAULT]
 tags = devtools
 subsuite = devtools
 support-files =
   head.js
   touch.html
+  !/devtools/client/commandline/test/helpers.js
+  !/devtools/client/framework/test/shared-head.js
 
 [browser_responsive_cmd.js]
 [browser_responsivecomputedview.js]
 skip-if = e10s && debug # Bug 1252201 - Docshell leak on debug e10s
 [browser_responsiveruleview.js]
 skip-if = e10s && debug # Bug 1252201 - Docshell leak on debug e10s
 [browser_responsiveui.js]
 [browser_responsiveui_touch.js]
--- a/devtools/client/shared/test/browser.ini
+++ b/devtools/client/shared/test/browser.ini
@@ -13,16 +13,17 @@ support-files =
   html-mdn-css-basic-testing.html
   html-mdn-css-no-summary.html
   html-mdn-css-no-summary-or-syntax.html
   html-mdn-css-no-syntax.html
   html-mdn-css-syntax-old-style.html
   leakhunt.js
   test-actor.js
   test-actor-registry.js
+  !/devtools/client/framework/test/shared-head.js
 
 [browser_css_angle.js]
 [browser_css_color.js]
 [browser_cubic-bezier-01.js]
 [browser_cubic-bezier-02.js]
 [browser_cubic-bezier-03.js]
 [browser_cubic-bezier-04.js]
 [browser_cubic-bezier-05.js]
--- a/devtools/client/styleeditor/test/browser.ini
+++ b/devtools/client/styleeditor/test/browser.ini
@@ -44,16 +44,18 @@ support-files =
   sourcemaps-watching.html
   test_private.css
   test_private.html
   doc_long.css
   doc_uncached.css
   doc_uncached.html
   doc_xulpage.xul
   sync.html
+  !/devtools/client/commandline/test/helpers.js
+  !/devtools/client/inspector/shared/test/head.js
 
 [browser_styleeditor_autocomplete.js]
 [browser_styleeditor_autocomplete-disabled.js]
 [browser_styleeditor_bug_740541_iframes.js]
 [browser_styleeditor_bug_851132_middle_click.js]
 [browser_styleeditor_bug_870339.js]
 [browser_styleeditor_cmd_edit.js]
 [browser_styleeditor_enabled.js]
--- a/devtools/client/webconsole/test/browser.ini
+++ b/devtools/client/webconsole/test/browser.ini
@@ -135,16 +135,19 @@ support-files =
   test-exception-stackframe.html
   test_bug_1010953_cspro.html^headers^
   test_bug_1010953_cspro.html
   test_bug1045902_console_csp_ignore_reflected_xss_message.html^headers^
   test_bug1045902_console_csp_ignore_reflected_xss_message.html
   test_bug1092055_shouldwarn.js^headers^
   test_bug1092055_shouldwarn.js
   test_bug1092055_shouldwarn.html
+  !/devtools/client/framework/test/shared-head.js
+  !/devtools/client/netmonitor/test/sjs_cors-test-server.sjs
+  !/image/test/mochitest/blue.png
 
 [browser_bug1045902_console_csp_ignore_reflected_xss_message.js]
 skip-if = (e10s && debug) || (e10s && os == 'win') # Bug 1221499 enabled these on windows
 [browser_bug664688_sandbox_update_after_navigation.js]
 [browser_bug_638949_copy_link_location.js]
 [browser_bug_862916_console_dir_and_filter_off.js]
 skip-if = (e10s && (os == 'win' || os == 'mac')) # Bug 1243976
 [browser_bug_865288_repeat_different_objects.js]
--- a/devtools/server/tests/browser/browser.ini
+++ b/devtools/server/tests/browser/browser.ini
@@ -16,16 +16,17 @@ support-files =
   storage-unsecured-iframe.html
   storage-updates.html
   storage-secured-iframe.html
   stylesheets-nested-iframes.html
   timeline-iframe-child.html
   timeline-iframe-parent.html
   director-script-target.html
   storage-helpers.js
+  !/devtools/server/tests/mochitest/hello-actor.js
 
 [browser_animation_emitMutations.js]
 [browser_animation_getFrames.js]
 [browser_animation_getProperties.js]
 [browser_animation_getMultipleStates.js]
 [browser_animation_getPlayers.js]
 [browser_animation_getStateAfterFinished.js]
 [browser_animation_getSubTreeAnimations.js]
--- a/devtools/shared/webconsole/test/chrome.ini
+++ b/devtools/shared/webconsole/test/chrome.ini
@@ -4,16 +4,18 @@ skip-if = buildapp == 'b2g'
 support-files =
   common.js
   data.json
   data.json^headers^
   helper_serviceworker.js
   network_requests_iframe.html
   sandboxed_iframe.html
   console-test-worker.js
+  !/browser/base/content/test/general/browser_star_hsts.sjs
+  !/browser/base/content/test/general/pinning_headers.sjs
 
 [test_basics.html]
 [test_bug819670_getter_throws.html]
 [test_cached_messages.html]
 [test_commands_other.html]
 [test_commands_registration.html]
 [test_consoleapi.html]
 [test_consoleapi_innerID.html]
--- a/dom/animation/test/chrome.ini
+++ b/dom/animation/test/chrome.ini
@@ -1,13 +1,15 @@
 [DEFAULT]
 support-files =
   testcommon.js
   ../../imptests/testharness.js
   ../../imptests/testharnessreport.js
+  !/dom/animation/test/chrome/file_animate_xrays.html
+
 [chrome/test_animate_xrays.html]
 # file_animate_xrays.html needs to go in mochitest.ini since it is served
 # over HTTP
 [chrome/test_animation_observers.html]
 [chrome/test_animation_performance_warning.html]
 [chrome/test_animation_properties.html]
 [chrome/test_generated_content_getAnimations.html]
 [chrome/test_restyles.html]
--- a/dom/animation/test/mochitest.ini
+++ b/dom/animation/test/mochitest.ini
@@ -1,88 +1,88 @@
 [DEFAULT]
 # Support files for chrome tests that we want to load over HTTP need
 # to go in here, not chrome.ini.
 support-files =
+  chrome/file_animate_xrays.html
+  css-animations/file_animation-cancel.html
+  css-animations/file_animation-computed-timing.html
+  css-animations/file_animation-currenttime.html
+  css-animations/file_animation-finish.html
+  css-animations/file_animation-finished.html
+  css-animations/file_animation-id.html
+  css-animations/file_animation-oncancel.html
+  css-animations/file_animation-onfinish.html
+  css-animations/file_animation-pausing.html
+  css-animations/file_animation-play.html
+  css-animations/file_animation-playstate.html
+  css-animations/file_animation-ready.html
+  css-animations/file_animation-reverse.html
+  css-animations/file_animation-starttime.html
+  css-animations/file_animations-dynamic-changes.html
+  css-animations/file_cssanimation-animationname.html
+  css-animations/file_document-get-animations.html
+  css-animations/file_effect-target.html
+  css-animations/file_element-get-animations.html
+  css-animations/file_keyframeeffect-getframes.html
+  css-animations/file_pseudoElement-get-animations.html
+  css-transitions/file_animation-cancel.html
+  css-transitions/file_animation-computed-timing.html
+  css-transitions/file_animation-currenttime.html
+  css-transitions/file_animation-finished.html
+  css-transitions/file_animation-pausing.html
+  css-transitions/file_animation-ready.html
+  css-transitions/file_animation-starttime.html
+  css-transitions/file_csstransition-transitionproperty.html
+  css-transitions/file_document-get-animations.html
+  css-transitions/file_effect-target.html
+  css-transitions/file_element-get-animations.html
+  css-transitions/file_keyframeeffect-getframes.html
+  css-transitions/file_pseudoElement-get-animations.html
+  document-timeline/file_document-timeline.html
+  mozilla/file_deferred_start.html
+  mozilla/file_hide_and_show.html
+  mozilla/file_partial_keyframes.html
   testcommon.js
-  chrome/file_animate_xrays.html
 
 [css-animations/test_animations-dynamic-changes.html]
-support-files = css-animations/file_animations-dynamic-changes.html
 [css-animations/test_animation-cancel.html]
-support-files = css-animations/file_animation-cancel.html
 [css-animations/test_animation-computed-timing.html]
-support-files = css-animations/file_animation-computed-timing.html
 [css-animations/test_animation-currenttime.html]
-support-files = css-animations/file_animation-currenttime.html
 [css-animations/test_animation-finish.html]
-support-files = css-animations/file_animation-finish.html
 [css-animations/test_animation-finished.html]
-support-files = css-animations/file_animation-finished.html
 [css-animations/test_animation-id.html]
-support-files = css-animations/file_animation-id.html
 [css-animations/test_animation-oncancel.html]
-support-files = css-animations/file_animation-oncancel.html
 [css-animations/test_animation-onfinish.html]
-support-files = css-animations/file_animation-onfinish.html
 [css-animations/test_animation-pausing.html]
-support-files = css-animations/file_animation-pausing.html
 [css-animations/test_animation-play.html]
-support-files = css-animations/file_animation-play.html
 [css-animations/test_animation-playstate.html]
-support-files = css-animations/file_animation-playstate.html
 [css-animations/test_animation-ready.html]
-support-files = css-animations/file_animation-ready.html
 [css-animations/test_animation-reverse.html]
-support-files = css-animations/file_animation-reverse.html
 [css-animations/test_animation-starttime.html]
-support-files = css-animations/file_animation-starttime.html
 [css-animations/test_cssanimation-animationname.html]
-support-files = css-animations/file_cssanimation-animationname.html
 [css-animations/test_document-get-animations.html]
-support-files = css-animations/file_document-get-animations.html
 [css-animations/test_effect-target.html]
-support-files = css-animations/file_effect-target.html
 [css-animations/test_element-get-animations.html]
 skip-if = buildapp == 'mulet'
-support-files = css-animations/file_element-get-animations.html
 [css-animations/test_keyframeeffect-getframes.html]
-support-files = css-animations/file_keyframeeffect-getframes.html
 [css-animations/test_pseudoElement-get-animations.html]
-support-files = css-animations/file_pseudoElement-get-animations.html
 [css-transitions/test_animation-cancel.html]
-support-files = css-transitions/file_animation-cancel.html
 [css-transitions/test_animation-computed-timing.html]
-support-files = css-transitions/file_animation-computed-timing.html
 [css-transitions/test_animation-currenttime.html]
-support-files = css-transitions/file_animation-currenttime.html
 [css-transitions/test_animation-finished.html]
-support-files = css-transitions/file_animation-finished.html
 [css-transitions/test_animation-pausing.html]
-support-files = css-transitions/file_animation-pausing.html
 [css-transitions/test_animation-ready.html]
-support-files = css-transitions/file_animation-ready.html
 [css-transitions/test_animation-starttime.html]
-support-files = css-transitions/file_animation-starttime.html
 [css-transitions/test_csstransition-transitionproperty.html]
-support-files = css-transitions/file_csstransition-transitionproperty.html
 [css-transitions/test_document-get-animations.html]
-support-files = css-transitions/file_document-get-animations.html
 [css-transitions/test_effect-target.html]
-support-files = css-transitions/file_effect-target.html
 [css-transitions/test_element-get-animations.html]
 skip-if = buildapp == 'mulet'
-support-files = css-transitions/file_element-get-animations.html
 [css-transitions/test_keyframeeffect-getframes.html]
-support-files = css-transitions/file_keyframeeffect-getframes.html
 [css-transitions/test_pseudoElement-get-animations.html]
-support-files = css-transitions/file_pseudoElement-get-animations.html
 [document-timeline/test_document-timeline.html]
-support-files = document-timeline/file_document-timeline.html
 [document-timeline/test_request_animation_frame.html]
 skip-if = buildapp == 'mulet'
 [mozilla/test_deferred_start.html]
-support-files = mozilla/file_deferred_start.html
 skip-if = (toolkit == 'gonk' && debug)
 [mozilla/test_hide_and_show.html]
-support-files = mozilla/file_hide_and_show.html
 [mozilla/test_partial_keyframes.html]
-support-files = mozilla/file_partial_keyframes.html
--- a/dom/base/ResponsiveImageSelector.cpp
+++ b/dom/base/ResponsiveImageSelector.cpp
@@ -127,24 +127,16 @@ ResponsiveImageSelector::SetCandidatesFr
   nsCOMPtr<nsIURI> docBaseURI = mOwnerNode ? mOwnerNode->GetBaseURI() : nullptr;
 
   if (!docBaseURI) {
     MOZ_ASSERT(false,
                "Should not be parsing SourceSet without a document");
     return false;
   }
 
-  // Preserve the default source if we have one, it has a separate setter.
-  uint32_t prevNumCandidates = mCandidates.Length();
-  nsString defaultURLString;
-  if (prevNumCandidates && (mCandidates[prevNumCandidates - 1].Type() ==
-                            ResponsiveImageCandidate::eCandidateType_Default)) {
-    defaultURLString = mCandidates[prevNumCandidates - 1].URLString();
-  }
-
   mCandidates.Clear();
 
   nsAString::const_iterator iter, end;
   aSrcSet.BeginReading(iter);
   aSrcSet.EndReading(end);
 
   // Read URL / descriptor pairs
   while (iter != end) {
@@ -182,19 +174,17 @@ ResponsiveImageSelector::SetCandidatesFr
       candidate.SetURLSpec(urlStr);
       AppendCandidateIfUnique(candidate);
     }
   }
 
   bool parsedCandidates = mCandidates.Length() > 0;
 
   // Re-add default to end of list
-  if (!defaultURLString.IsEmpty()) {
-    AppendDefaultCandidate(defaultURLString);
-  }
+  MaybeAppendDefaultCandidate();
 
   return parsedCandidates;
 }
 
 uint32_t
 ResponsiveImageSelector::NumCandidates(bool aIncludeDefault)
 {
   uint32_t candidates = mCandidates.Length();
@@ -228,20 +218,20 @@ ResponsiveImageSelector::SetDefaultSourc
 
   // Check if the last element of our candidates is a default
   int32_t candidates = mCandidates.Length();
   if (candidates && (mCandidates[candidates - 1].Type() ==
                      ResponsiveImageCandidate::eCandidateType_Default)) {
     mCandidates.RemoveElementAt(candidates - 1);
   }
 
-  // Add new default if set
-  if (!aURLString.IsEmpty()) {
-    AppendDefaultCandidate(aURLString);
-  }
+  mDefaultSourceURL = aURLString;
+
+  // Add new default to end of list
+  MaybeAppendDefaultCandidate();
 }
 
 void
 ResponsiveImageSelector::ClearSelectedCandidate()
 {
   mSelectedCandidateIndex = -1;
   mSelectedCandidateURL = nullptr;
 }
@@ -264,40 +254,55 @@ ResponsiveImageSelector::SetSizesFromDes
 }
 
 void
 ResponsiveImageSelector::AppendCandidateIfUnique(const ResponsiveImageCandidate & aCandidate)
 {
   int numCandidates = mCandidates.Length();
 
   // With the exception of Default, which should not be added until we are done
-  // building the list, the spec forbids mixing width and explicit density
-  // selectors in the same set.
-  if (numCandidates && mCandidates[0].Type() != aCandidate.Type()) {
+  // building the list.
+  if (aCandidate.Type() == ResponsiveImageCandidate::eCandidateType_Default) {
     return;
   }
 
   // Discard candidates with identical parameters, they will never match
   for (int i = 0; i < numCandidates; i++) {
     if (mCandidates[i].HasSameParameter(aCandidate)) {
       return;
     }
   }
 
   mCandidates.AppendElement(aCandidate);
 }
 
 void
-ResponsiveImageSelector::AppendDefaultCandidate(const nsAString& aURLString)
+ResponsiveImageSelector::MaybeAppendDefaultCandidate()
 {
-  NS_ENSURE_TRUE(!aURLString.IsEmpty(), /* void */);
+  NS_ENSURE_TRUE(!mDefaultSourceURL.IsEmpty(), /* void */);
+
+  int numCandidates = mCandidates.Length();
+
+  // https://html.spec.whatwg.org/multipage/embedded-content.html#update-the-source-set
+  // step 4.1.3:
+  // If child has a src attribute whose value is not the empty string and source
+  // set does not contain an image source with a density descriptor value of 1,
+  // and no image source with a width descriptor, append child's src attribute
+  // value to source set.
+  for (int i = 0; i < numCandidates; i++) {
+    if (mCandidates[i].IsComputedFromWidth()) {
+      return;
+    } else if (mCandidates[i].Density(this) == 1.0) {
+      return;
+    }
+  }
 
   ResponsiveImageCandidate defaultCandidate;
   defaultCandidate.SetParameterDefault();
-  defaultCandidate.SetURLSpec(aURLString);
+  defaultCandidate.SetURLSpec(mDefaultSourceURL);
   // We don't use MaybeAppend since we want to keep this even if it can never
   // match, as it may if the source set changes.
   mCandidates.AppendElement(defaultCandidate);
 }
 
 already_AddRefed<nsIURI>
 ResponsiveImageSelector::GetSelectedImageURL()
 {
@@ -358,32 +363,25 @@ ResponsiveImageSelector::SelectImage(boo
 
   double displayDensity = pctx->CSSPixelsToDevPixels(1.0f);
 
   // Per spec, "In a UA-specific manner, choose one image source"
   // - For now, select the lowest density greater than displayDensity, otherwise
   //   the greatest density available
 
   // If the list contains computed width candidates, compute the current
-  // effective image width. Note that we currently disallow both computed and
-  // static density candidates in the same selector, so checking the first
-  // candidate is sufficient.
-  int32_t computedWidth = -1;
-  if (numCandidates && mCandidates[0].IsComputedFromWidth()) {
-    DebugOnly<bool> computeResult = \
-      ComputeFinalWidthForCurrentViewport(&computedWidth);
-    MOZ_ASSERT(computeResult,
-               "Computed candidates not allowed without sizes data");
-
-    // If we have a default candidate in the list, don't consider it when using
-    // computed widths. (It has a static 1.0 density that is inapplicable to a
-    // sized-image)
-    if (numCandidates > 1 && mCandidates[numCandidates - 1].Type() ==
-        ResponsiveImageCandidate::eCandidateType_Default) {
-      numCandidates--;
+  // effective image width.
+  double computedWidth = -1;
+  for (int i = 0; i < numCandidates; i++) {
+    if (mCandidates[i].IsComputedFromWidth()) {
+      DebugOnly<bool> computeResult = \
+        ComputeFinalWidthForCurrentViewport(&computedWidth);
+      MOZ_ASSERT(computeResult,
+                 "Computed candidates not allowed without sizes data");
+      break;
     }
   }
 
   int bestIndex = -1;
   double bestDensity = -1.0;
   for (int i = 0; i < numCandidates; i++) {
     double candidateDensity = \
       (computedWidth == -1) ? mCandidates[i].Density(this)
@@ -418,17 +416,17 @@ int
 ResponsiveImageSelector::GetSelectedCandidateIndex()
 {
   SelectImage();
 
   return mSelectedCandidateIndex;
 }
 
 bool
-ResponsiveImageSelector::ComputeFinalWidthForCurrentViewport(int32_t *aWidth)
+ResponsiveImageSelector::ComputeFinalWidthForCurrentViewport(double *aWidth)
 {
   unsigned int numSizes = mSizeQueries.Length();
   nsIDocument* doc = Document();
   nsIPresShell *presShell = doc ? doc->GetShell() : nullptr;
   nsPresContext *pctx = presShell ? presShell->GetPresContext() : nullptr;
 
   if (!pctx) {
     MOZ_ASSERT(false, "Unable to find presContext for this content");
@@ -452,17 +450,17 @@ ResponsiveImageSelector::ComputeFinalWid
     effectiveWidth = nsRuleNode::CalcLengthWithInitialFont(pctx,
                                                            defaultWidth);
   } else {
     effectiveWidth = nsRuleNode::CalcLengthWithInitialFont(pctx,
                                                            mSizeValues[i]);
   }
 
   MOZ_ASSERT(effectiveWidth >= 0);
-  *aWidth = nsPresContext::AppUnitsToIntCSSPixels(std::max(effectiveWidth, 0));
+  *aWidth = nsPresContext::AppUnitsToDoubleCSSPixels(std::max(effectiveWidth, 0));
   return true;
 }
 
 ResponsiveImageCandidate::ResponsiveImageCandidate()
 {
   mType = eCandidateType_Invalid;
   mValue.mDensity = 1.0;
 }
@@ -728,31 +726,31 @@ ResponsiveImageCandidate::URLString() co
 {
   return mURLString;
 }
 
 double
 ResponsiveImageCandidate::Density(ResponsiveImageSelector *aSelector) const
 {
   if (mType == eCandidateType_ComputedFromWidth) {
-    int32_t width;
+    double width;
     if (!aSelector->ComputeFinalWidthForCurrentViewport(&width)) {
       return 1.0;
     }
     return Density(width);
   }
 
   // Other types don't need matching width
   MOZ_ASSERT(mType == eCandidateType_Default || mType == eCandidateType_Density,
              "unhandled candidate type");
   return Density(-1);
 }
 
 double
-ResponsiveImageCandidate::Density(int32_t aMatchingWidth) const
+ResponsiveImageCandidate::Density(double aMatchingWidth) const
 {
   if (mType == eCandidateType_Invalid) {
     MOZ_ASSERT(false, "Getting density for uninitialized candidate");
     return 1.0;
   }
 
   if (mType == eCandidateType_Default) {
     return 1.0;
@@ -760,17 +758,17 @@ ResponsiveImageCandidate::Density(int32_
 
   if (mType == eCandidateType_Density) {
     return mValue.mDensity;
   } else if (mType == eCandidateType_ComputedFromWidth) {
     if (aMatchingWidth < 0) {
       MOZ_ASSERT(false, "Don't expect to have a negative matching width at this point");
       return 1.0;
     }
-    double density = double(mValue.mWidth) / double(aMatchingWidth);
+    double density = double(mValue.mWidth) / aMatchingWidth;
     MOZ_ASSERT(density > 0.0);
     return density;
   }
 
   MOZ_ASSERT(false, "Unknown candidate type");
   return 1.0;
 }
 
--- a/dom/base/ResponsiveImageSelector.h
+++ b/dom/base/ResponsiveImageSelector.h
@@ -81,35 +81,37 @@ public:
 protected:
   virtual ~ResponsiveImageSelector();
 
 private:
   // Append a candidate unless its selector is duplicated by a higher priority
   // candidate
   void AppendCandidateIfUnique(const ResponsiveImageCandidate &aCandidate);
 
-  // Append a default candidate with this URL. Does not check if the array
-  // already contains one, use SetDefaultSource instead.
-  void AppendDefaultCandidate(const nsAString& aURLString);
+  // Append a default candidate with this URL if necessary. Does not check if
+  // the array already contains one, use SetDefaultSource instead.
+  void MaybeAppendDefaultCandidate();
 
   // Get index of selected candidate, triggering selection if necessary.
   int GetSelectedCandidateIndex();
 
   // Forget currently selected candidate. (See "NOTE ABOUT CURRENT SELECTION"
   // above.)
   void ClearSelectedCandidate();
 
   // Compute a density from a Candidate width. Returns false if sizes were not
   // specified for this selector.
   //
   // aContext is the presContext to use for current viewport sizing, null will
   // use the associated content's context.
-  bool ComputeFinalWidthForCurrentViewport(int32_t *aWidth);
+  bool ComputeFinalWidthForCurrentViewport(double* aWidth);
 
   nsCOMPtr<nsINode> mOwnerNode;
+  // The cached URL for default candidate.
+  nsString mDefaultSourceURL;
   // If this array contains an eCandidateType_Default, it should be the last
   // element, such that the Setters can preserve/replace it respectively.
   nsTArray<ResponsiveImageCandidate> mCandidates;
   int mSelectedCandidateIndex;
   // The cached resolved URL for mSelectedCandidateIndex, such that we only
   // resolve the absolute URL at selection time
   nsCOMPtr<nsIURI> mSelectedCandidateURL;
 
@@ -145,17 +147,17 @@ public:
   bool HasSameParameter(const ResponsiveImageCandidate & aOther) const;
 
   const nsAString& URLString() const;
 
   // Compute and return the density relative to a selector.
   double Density(ResponsiveImageSelector *aSelector) const;
   // If the width is already known. Useful when iterating over candidates to
   // avoid having each call re-compute the width.
-  double Density(int32_t aMatchingWidth) const;
+  double Density(double aMatchingWidth) const;
 
   // If this selector is computed from the selector's matching width.
   bool IsComputedFromWidth() const;
 
   enum eCandidateType {
     eCandidateType_Invalid,
     eCandidateType_Density,
     // Treated as 1.0 density, but a separate type so we can update the
--- a/dom/base/test/mochitest.ini
+++ b/dom/base/test/mochitest.ini
@@ -258,16 +258,19 @@ support-files =
   file_explicit_user_agent.sjs
   referrer_change_server.sjs
   file_change_policy_redirect.html
   file_bug1198095.js
   file_bug1250148.sjs
   mozbrowser_api_utils.js
   websocket_helpers.js
   websocket_tests.js
+  !/dom/html/test/form_submit_server.sjs
+  !/dom/security/test/cors/file_CrossSiteXHR_server.sjs
+  !/image/test/mochitest/blue.png
 
 [test_anonymousContent_api.html]
 [test_anonymousContent_append_after_reflow.html]
 [test_anonymousContent_canvas.html]
 skip-if = buildapp == 'b2g' # Requires webgl support
 [test_anonymousContent_insert.html]
 [test_anonymousContent_manipulate_content.html]
 [test_anonymousContent_style_csp.html]
--- a/dom/base/test/unit_ipc/xpcshell.ini
+++ b/dom/base/test/unit_ipc/xpcshell.ini
@@ -1,7 +1,10 @@
 [DEFAULT]
 head =
 tail =
 skip-if = toolkit == 'android' || toolkit == 'gonk'
+support-files =
+  !/dom/base/test/unit/test_bug553888.js
+  !/dom/base/test/unit/test_xhr_document.js
 
 [test_bug553888_wrap.js]
 [test_xhr_document_ipc.js]
--- a/dom/bindings/Codegen.py
+++ b/dom/bindings/Codegen.py
@@ -12316,18 +12316,25 @@ class CGDictionary(CGThing):
             Argument('bool', 'passedToJSImpl', default='false')
         ], body=body)
 
     def initFromJSONMethod(self):
         return ClassMethod(
             "Init", "bool",
             [Argument('const nsAString&', 'aJSON')],
             body=dedent("""
-                MOZ_ASSERT(NS_IsMainThread());
-                AutoSafeJSContext cx;
+                AutoJSAPI jsapi;
+                JSObject* cleanGlobal = SimpleGlobalObject::Create(SimpleGlobalObject::GlobalType::BindingDetail);
+                if (!cleanGlobal) {
+                  return false;
+                }
+                if (!jsapi.Init(cleanGlobal)) {
+                  return false;
+                }
+                JSContext* cx = jsapi.cx();
                 JS::Rooted<JS::Value> json(cx);
                 bool ok = ParseJSON(cx, aJSON, &json);
                 NS_ENSURE_TRUE(ok, false);
                 return Init(cx, json);
                 """))
 
     def toJSONMethod(self):
         return ClassMethod(
@@ -12480,20 +12487,22 @@ class CGDictionary(CGThing):
                 body='// Do nothing here; this is used by our "Fast" subclass\n')
         ]
         methods = []
 
         if self.needToInitIds:
             methods.append(self.initIdsMethod())
 
         methods.append(self.initMethod())
-        methods.append(self.initFromJSONMethod())
+        canBeRepresentedAsJSON = self.dictionarySafeToJSONify(self.dictionary)
+        if canBeRepresentedAsJSON:
+            methods.append(self.initFromJSONMethod())
         try:
             methods.append(self.toObjectInternalMethod())
-            if self.dictionarySafeToJSONify(self.dictionary):
+            if canBeRepresentedAsJSON:
                 methods.append(self.toJSONMethod())
         except MethodNotNewObjectError:
             # If we can't have a ToObjectInternal() because one of our members
             # can only be returned from [NewObject] methods, then just skip
             # generating ToObjectInternal() and ToJSON (since the latter depens
             # on the former).
             pass
         methods.append(self.traceDictionaryMethod())
@@ -13394,16 +13403,18 @@ class CGBindingRoot(CGThing):
             bindingHeaders["jsapi.h"] = True
 
         # For things that have [UseCounter]
         def descriptorRequiresTelemetry(desc):
             iface = desc.interface
             return any(m.getExtendedAttribute("UseCounter") for m in iface.members)
         bindingHeaders["mozilla/UseCounter.h"] = any(
             descriptorRequiresTelemetry(d) for d in descriptors)
+        bindingHeaders["mozilla/dom/SimpleGlobalObject.h"] = any(
+            CGDictionary.dictionarySafeToJSONify(d) for d in dictionaries)
 
         cgthings.extend(traverseMethods)
         cgthings.extend(unlinkMethods)
 
         # Do codegen for all the dictionaries.  We have to be a bit careful
         # here, because we have to generate these in order from least derived
         # to most derived so that class inheritance works out.  We also have to
         # generate members before the dictionary that contains them.
new file mode 100644
--- /dev/null
+++ b/dom/bindings/SimpleGlobalObject.cpp
@@ -0,0 +1,169 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#include "mozilla/dom/SimpleGlobalObject.h"
+
+#include "jsapi.h"
+#include "js/Class.h"
+
+#include "nsContentUtils.h"
+#include "nsJSPrincipals.h"
+#include "nsNullPrincipal.h"
+#include "nsThreadUtils.h"
+
+#include "xpcprivate.h"
+
+namespace mozilla {
+namespace dom {
+
+NS_IMPL_CYCLE_COLLECTION_CLASS(SimpleGlobalObject)
+
+NS_IMPL_CYCLE_COLLECTION_UNLINK_BEGIN(SimpleGlobalObject)
+  NS_IMPL_CYCLE_COLLECTION_UNLINK_PRESERVED_WRAPPER
+  tmp->UnlinkHostObjectURIs();
+NS_IMPL_CYCLE_COLLECTION_UNLINK_END
+
+NS_IMPL_CYCLE_COLLECTION_TRAVERSE_BEGIN(SimpleGlobalObject)
+
+  NS_IMPL_CYCLE_COLLECTION_TRAVERSE_SCRIPT_OBJECTS
+  tmp->TraverseHostObjectURIs(cb);
+NS_IMPL_CYCLE_COLLECTION_TRAVERSE_END
+
+NS_IMPL_CYCLE_COLLECTION_TRACE_WRAPPERCACHE(SimpleGlobalObject)
+
+NS_IMPL_CYCLE_COLLECTING_ADDREF(SimpleGlobalObject)
+NS_IMPL_CYCLE_COLLECTING_RELEASE(SimpleGlobalObject)
+NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION(SimpleGlobalObject)
+  NS_WRAPPERCACHE_INTERFACE_MAP_ENTRY
+  NS_INTERFACE_MAP_ENTRY(nsIGlobalObject)
+NS_INTERFACE_MAP_END
+
+static bool
+SimpleGlobal_enumerate(JSContext *cx, JS::Handle<JSObject *> obj)
+{
+  return JS_EnumerateStandardClasses(cx, obj);
+}
+
+static bool
+SimpleGlobal_resolve(JSContext *cx, JS::Handle<JSObject *> obj,
+                    JS::Handle<jsid> id, bool *resolvedp)
+{
+  return JS_ResolveStandardClass(cx, obj, id, resolvedp);
+}
+
+static void
+SimpleGlobal_finalize(js::FreeOp *fop, JSObject *obj)
+{
+  SimpleGlobalObject* globalObject =
+    static_cast<SimpleGlobalObject*>(JS_GetPrivate(obj));
+  NS_RELEASE(globalObject);
+}
+
+static void
+SimpleGlobal_moved(JSObject *obj, const JSObject *old)
+{
+  SimpleGlobalObject* globalObject =
+    static_cast<SimpleGlobalObject*>(JS_GetPrivate(obj));
+  globalObject->UpdateWrapper(obj, old);
+}
+
+const js::Class SimpleGlobalClass = {
+    "",
+    JSCLASS_GLOBAL_FLAGS | JSCLASS_HAS_PRIVATE | JSCLASS_PRIVATE_IS_NSISUPPORTS,
+    nullptr,
+    nullptr,
+    nullptr,
+    nullptr,
+    SimpleGlobal_enumerate,
+    SimpleGlobal_resolve,
+    nullptr,
+    SimpleGlobal_finalize,
+    nullptr,
+    nullptr,
+    nullptr,
+    JS_GlobalObjectTraceHook,
+    JS_NULL_CLASS_SPEC, {
+      false,
+      nullptr,
+      SimpleGlobal_moved
+    }, JS_NULL_OBJECT_OPS
+};
+
+// static
+JSObject*
+SimpleGlobalObject::Create(GlobalType globalType, JS::Handle<JS::Value> proto)
+{
+  JSContext* cx = nsContentUtils::GetDefaultJSContextForThread();
+  JSAutoRequest ar(cx);
+
+  JS::CompartmentOptions options;
+  options.creationOptions().setInvisibleToDebugger(true);
+
+  nsCOMPtr<nsIPrincipal> principal;
+  if (NS_IsMainThread()) {
+    principal = nsNullPrincipal::Create();
+    if (!principal) {
+      return nullptr;
+    }
+  }
+
+  JS::Rooted<JSObject*> global(cx,
+    JS_NewGlobalObject(cx, js::Jsvalify(&SimpleGlobalClass),
+                       nsJSPrincipals::get(principal),
+                       JS::DontFireOnNewGlobalHook, options));
+
+  if (!global) {
+    JS_ClearPendingException(cx);
+    return nullptr;
+  }
+
+  JSAutoCompartment ac(cx, global);
+
+  // It's important to create the nsIGlobalObject for our new global before we
+  // start trying to wrap things like the prototype into its compartment,
+  // because the wrap operation relies on the global having its nsIGlobalObject
+  // already.
+  RefPtr<SimpleGlobalObject> globalObject =
+    new SimpleGlobalObject(global, globalType);
+
+  // Pass on ownership of globalObject to |global|.
+  JS_SetPrivate(global, globalObject.forget().take());
+
+  if (proto.isObjectOrNull()) {
+    JS::Rooted<JSObject*> protoObj(cx, proto.toObjectOrNull());
+    if (!JS_WrapObject(cx, &protoObj)) {
+      JS_ClearPendingException(cx);
+      return nullptr;
+    }
+
+    if (!JS_SetPrototype(cx, global, protoObj)) {
+      JS_ClearPendingException(cx);
+      return nullptr;
+    }
+  } else if (!proto.isUndefined()) {
+    // Bogus proto.
+    return nullptr;
+  }
+
+  JS_FireOnNewGlobalObject(cx, global);
+  return global;
+}
+
+// static
+SimpleGlobalObject::GlobalType
+SimpleGlobalObject::SimpleGlobalType(JSObject* obj)
+{
+  if (js::GetObjectClass(obj) != &SimpleGlobalClass) {
+    return SimpleGlobalObject::GlobalType::NotSimpleGlobal;
+  }
+
+  SimpleGlobalObject* globalObject =
+    static_cast<SimpleGlobalObject*>(JS_GetPrivate(obj));
+  return globalObject->Type();
+}
+
+} // namespace mozilla
+} // namespace dom
new file mode 100644
--- /dev/null
+++ b/dom/bindings/SimpleGlobalObject.h
@@ -0,0 +1,99 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+/**
+ * A simplere nsIGlobalObject implementation that can be used to set up a new
+ * global without anything interesting in it other than the JS builtins.  This
+ * is safe to use on both mainthread and worker threads.
+ */
+
+#ifndef mozilla_dom_SimpleGlobalObject_h__
+#define mozilla_dom_SimpleGlobalObject_h__
+
+#include "nsIGlobalObject.h"
+#include "nsWrapperCache.h"
+#include "js/TypeDecls.h"
+#include "nsISupportsImpl.h"
+#include "nsCycleCollectionParticipant.h"
+
+namespace mozilla {
+namespace dom {
+
+class SimpleGlobalObject : public nsIGlobalObject,
+                           public nsWrapperCache
+{
+public:
+  enum class GlobalType {
+    BindingDetail, // Should only be used by DOM bindings code.
+    WorkerDebuggerSandbox,
+    NotSimpleGlobal // Sentinel to be used by BasicGlobalType.
+  };
+
+  // Create a new JS global object that can be used to do some work.  This
+  // global will NOT have any DOM APIs exposed in it, will not be visible to the
+  // debugger, and will not have a useful concept of principals, so don't try to
+  // use it with any DOM objects.  Apart from that, running code with
+  // side-effects is safe in this global.  Importantly, when you are first
+  // handed this global it's guaranteed to have pristine built-ins.  The
+  // corresponding nsIGlobalObject* for this global object will be a
+  // SimpleGlobalObject of the type provided; JS_GetPrivate on the returned
+  // JSObject* will return the SimpleGlobalObject*.
+  //
+  // If the provided prototype value is undefined, it is ignored.  If it's an
+  // object or null, it's set as the prototype of the created global.  If it's
+  // anything else, this function returns null.
+  //
+  // Note that creating new globals is not cheap and should not be done
+  // gratuitously.  Please think carefully before you use this function.
+  static JSObject* Create(GlobalType globalType,
+                          JS::Handle<JS::Value> proto =
+                            JS::UndefinedHandleValue);
+
+  NS_DECL_CYCLE_COLLECTING_ISUPPORTS
+  NS_DECL_CYCLE_COLLECTION_SCRIPT_HOLDER_CLASS_AMBIGUOUS(SimpleGlobalObject,
+                                                         nsIGlobalObject)
+
+  // Gets the GlobalType of this SimpleGlobalObject.
+  GlobalType Type() const
+  {
+    return mType;
+  }
+
+  // Gets the GlobalType of the SimpleGlobalObject for the given JSObject*, if
+  // the given JSObject* is the global corresponding to a SimpleGlobalObject.
+  // Oherwise, returns GlobalType::NotSimpleGlobal.
+  static GlobalType SimpleGlobalType(JSObject* obj);
+
+  virtual JSObject *GetGlobalJSObject() override
+  {
+    return GetWrapper();
+  }
+
+  virtual JSObject* WrapObject(JSContext* cx,
+                               JS::Handle<JSObject*> aGivenProto) override
+  {
+    MOZ_CRASH("SimpleGlobalObject doesn't use DOM bindings!");
+  }
+
+private:
+  SimpleGlobalObject(JSObject *global, GlobalType type)
+    : mType(type)
+  {
+    SetWrapper(global);
+  }
+
+  virtual ~SimpleGlobalObject()
+  {
+    ClearWrapper();
+  }
+
+  const GlobalType mType;
+};
+
+} // namespace dom
+} // namespace mozilla
+
+#endif /* mozilla_dom_SimpleGlobalObject_h__ */
--- a/dom/bindings/moz.build
+++ b/dom/bindings/moz.build
@@ -29,16 +29,17 @@ EXPORTS.mozilla.dom += [
     'Exceptions.h',
     'IterableIterator.h',
     'JSSlots.h',
     'MozMap.h',
     'NonRefcountedDOMObject.h',
     'Nullable.h',
     'PrimitiveConversions.h',
     'RootedDictionary.h',
+    'SimpleGlobalObject.h',
     'StructuredClone.h',
     'ToJSValue.h',
     'TypedArray.h',
     'UnionMember.h',
 ]
 
 # Generated bindings reference *Binding.h, not mozilla/dom/*Binding.h. And,
 # since we generate exported bindings directly to $(DIST)/include, we need
@@ -81,16 +82,17 @@ LOCAL_INCLUDES += [
 UNIFIED_SOURCES += [
     'BindingUtils.cpp',
     'CallbackInterface.cpp',
     'CallbackObject.cpp',
     'Date.cpp',
     'DOMJSProxyHandler.cpp',
     'Exceptions.cpp',
     'IterableIterator.cpp',
+    'SimpleGlobalObject.cpp',
     'ToJSValue.cpp',
 ]
 
 SOURCES += [
     'StructuredClone.cpp',
 ]
 
 # Tests for maplike and setlike require bindings to be built, which means they
--- a/dom/bindings/test/chrome.ini
+++ b/dom/bindings/test/chrome.ini
@@ -1,10 +1,16 @@
 [DEFAULT]
 skip-if = buildapp == 'b2g'
+support-files =
+  !/dom/bindings/test/file_bug707564.html
+  !/dom/bindings/test/file_bug775543.html
+  !/dom/bindings/test/file_document_location_set_via_xray.html
+  !/dom/bindings/test/file_dom_xrays.html
+  !/dom/bindings/test/file_proxies_via_xray.html
 
 [test_bug707564-chrome.html]
 [test_bug775543.html]
 [test_document_location_set_via_xray.html]
 [test_dom_xrays.html]
 [test_proxies_via_xray.html]
 [test_document_location_via_xray_cached.html]
 [test_blacklisted_prerendering_function.xul]
--- a/dom/bindings/test/mochitest.ini
+++ b/dom/bindings/test/mochitest.ini
@@ -3,16 +3,17 @@ support-files =
   file_InstanceOf.html
   file_bug707564.html
   file_bug707564-2.html
   file_bug775543.html
   file_document_location_set_via_xray.html
   file_dom_xrays.html
   file_proxies_via_xray.html
   forOf_iframe.html
+  !/js/xpconnect/tests/mochitest/file_empty.html
 
 [test_async_stacks.html]
 [test_ByteString.html]
 [test_InstanceOf.html]
 [test_bug560072.html]
 [test_bug707564.html]
 [test_bug742191.html]
 [test_bug759621.html]
--- a/dom/browser-element/mochitest/priority/mochitest.ini
+++ b/dom/browser-element/mochitest/priority/mochitest.ini
@@ -1,30 +1,34 @@
 [DEFAULT]
 # Good luck running these tests on anything but desktop Linux.
 run-if = os == 'linux' && buildapp == 'browser' && !e10s
+support-files =
+  file_Audio.html
+  file_HighPriority.html
+  file_MultipleFrames.html
+  file_NestedFramesOuter.html
+  file_WebGLContextLost.html
+  silence.ogg
+  !/dom/browser-element/mochitest/browserElementTestHelpers.js
+  !/dom/browser-element/mochitest/file_empty.html
 
 # Note: ../browserElementTestHelpers.js makes all tests in this directory OOP,
 # because testing the process-priority manager without OOP frames does not make
 # much sense.
 
 [test_Simple.html]
 [test_Visibility.html]
 [test_HighPriority.html]
-support-files = file_HighPriority.html
 [test_Background.html]
 [test_BackgroundLRU.html]
 [test_Activity.html]
 [test_Audio.html]
-support-files = file_Audio.html silence.ogg
 [test_Keyboard.html]
 [test_MultipleActivities.html]
 [test_MultipleFrames.html]
-support-files = file_MultipleFrames.html
 [test_Preallocated.html]
 disabled = bug 968604, bug 987164
 [test_ExpectingSystemMessage.html]
 [test_ExpectingSystemMessage2.html]
 [test_NestedFrames.html]
-support-files = file_NestedFramesOuter.html
 [test_WebGLContextLost.html]
 disabled = bug 865844
-support-files = file_WebGLContextLost.html
--- a/dom/events/DeviceMotionEvent.cpp
+++ b/dom/events/DeviceMotionEvent.cpp
@@ -30,31 +30,50 @@ DeviceMotionEvent::InitDeviceMotionEvent
                      const nsAString& aType,
                      bool aCanBubble,
                      bool aCancelable,
                      const DeviceAccelerationInit& aAcceleration,
                      const DeviceAccelerationInit& aAccelIncludingGravity,
                      const DeviceRotationRateInit& aRotationRate,
                      Nullable<double> aInterval)
 {
+  InitDeviceMotionEvent(aType, aCanBubble, aCancelable, aAcceleration,
+                        aAccelIncludingGravity, aRotationRate, aInterval,
+                        Nullable<uint64_t>());
+}
+
+void
+DeviceMotionEvent::InitDeviceMotionEvent(
+                     const nsAString& aType,
+                     bool aCanBubble,
+                     bool aCancelable,
+                     const DeviceAccelerationInit& aAcceleration,
+                     const DeviceAccelerationInit& aAccelIncludingGravity,
+                     const DeviceRotationRateInit& aRotationRate,
+                     Nullable<double> aInterval,
+                     Nullable<uint64_t> aTimeStamp)
+{
   Event::InitEvent(aType, aCanBubble, aCancelable);
 
   mAcceleration = new DeviceAcceleration(this, aAcceleration.mX,
                                          aAcceleration.mY,
                                          aAcceleration.mZ);
 
   mAccelerationIncludingGravity =
     new DeviceAcceleration(this, aAccelIncludingGravity.mX,
                            aAccelIncludingGravity.mY,
                            aAccelIncludingGravity.mZ);
 
   mRotationRate = new DeviceRotationRate(this, aRotationRate.mAlpha,
                                          aRotationRate.mBeta,
                                          aRotationRate.mGamma);
   mInterval = aInterval;
+  if (!aTimeStamp.IsNull()) {
+    mEvent->mTime = aTimeStamp.Value();
+  }
 }
 
 already_AddRefed<DeviceMotionEvent>
 DeviceMotionEvent::Constructor(const GlobalObject& aGlobal,
                                const nsAString& aType,
                                const DeviceMotionEventInit& aEventInitDict,
                                ErrorResult& aRv)
 {
@@ -136,14 +155,14 @@ DeviceRotationRate::~DeviceRotationRate(
 } // namespace mozilla
 
 using namespace mozilla;
 using namespace mozilla::dom;
 
 already_AddRefed<DeviceMotionEvent>
 NS_NewDOMDeviceMotionEvent(EventTarget* aOwner,
                            nsPresContext* aPresContext,
-                           WidgetEvent* aEvent) 
+                           WidgetEvent* aEvent)
 {
   RefPtr<DeviceMotionEvent> it =
     new DeviceMotionEvent(aOwner, aPresContext, aEvent);
   return it.forget();
 }
--- a/dom/events/DeviceMotionEvent.h
+++ b/dom/events/DeviceMotionEvent.h
@@ -125,16 +125,26 @@ public:
          const nsAString& aType,
          bool aCanBubble,
          bool aCancelable,
          const DeviceAccelerationInit& aAcceleration,
          const DeviceAccelerationInit& aAccelerationIncludingGravity,
          const DeviceRotationRateInit& aRotationRate,
          Nullable<double> aInterval);
 
+  void InitDeviceMotionEvent(
+         const nsAString& aType,
+         bool aCanBubble,
+         bool aCancelable,
+         const DeviceAccelerationInit& aAcceleration,
+         const DeviceAccelerationInit& aAccelerationIncludingGravity,
+         const DeviceRotationRateInit& aRotationRate,
+         Nullable<double> aInterval,
+         Nullable<uint64_t> aTimeStamp);
+
   static already_AddRefed<DeviceMotionEvent>
   Constructor(const GlobalObject& aGlobal,
               const nsAString& aType,
               const DeviceMotionEventInit& aEventInitDict,
               ErrorResult& aRv);
 
 protected:
   ~DeviceMotionEvent() {}
--- a/dom/events/test/mochitest.ini
+++ b/dom/events/test/mochitest.ini
@@ -7,16 +7,17 @@ support-files =
   bug426082.html
   bug656379-1.html
   bug418986-3.js
   error_event_worker.js
   empty.js
   window_bug493251.html
   window_bug659071.html
   window_wheel_default_action.html
+  !/gfx/layers/apz/test/mochitest/apz_test_utils.js
 
 [test_accel_virtual_modifier.html]
 [test_addEventListenerExtraArg.html]
 [test_all_synthetic_events.html]
 [test_bug226361.xhtml]
 skip-if = buildapp == 'b2g' || buildapp == 'mulet'
 [test_bug238987.html]
 skip-if = buildapp == 'b2g'
--- a/dom/html/test/forms/mochitest.ini
+++ b/dom/html/test/forms/mochitest.ini
@@ -1,12 +1,13 @@
 [DEFAULT]
 support-files =
   save_restore_radio_groups.sjs
   test_input_number_data.js
+  !/dom/html/test/reflect.js
 
 [test_bug1039548.html]
 [test_button_attributes_reflection.html]
 [test_input_radio_radiogroup.html]
 [test_input_radio_required.html]
 [test_change_event.html]
 skip-if = (buildapp == 'b2g' && toolkit != 'gonk') #Bug 931116, b2g desktop specific, initial triage
 [test_datalist_element.html]
--- a/dom/interfaces/base/nsIContentPrefService.idl
+++ b/dom/interfaces/base/nsIContentPrefService.idl
@@ -29,18 +29,22 @@ interface nsIContentPrefObserver : nsISu
                         [optional] in boolean aIsPrivate);
 
   /**
    * Called when a content pref is removed.
    *
    * @param    aGroup      the group to which the pref belongs, or null
    *                       if it's a global pref (applies to all sites)
    * @param    aName       the name of the pref that was removed
+   * @param    aIsPrivate  an optional flag determining whether the
+   *                       original context is private or not
    */
-  void onContentPrefRemoved(in AString aGroup, in AString aName);
+  void onContentPrefRemoved(in AString aGroup,
+                            in AString aName,
+                            [optional] in boolean aIsPrivate);
 };
 
 [scriptable, function, uuid(c1b3d6df-5373-4606-8494-8bcf14a7fc62)]
 interface nsIContentPrefCallback : nsISupports
 {
   void onResult(in nsIVariant aResult);
 };
 
--- a/dom/media/test/mochitest.ini
+++ b/dom/media/test/mochitest.ini
@@ -568,16 +568,18 @@ support-files =
   wavedata_s24.wav
   wavedata_s24.wav^headers^
   wavedata_s16.wav
   wavedata_s16.wav^headers^
   wavedata_u8.wav
   wavedata_u8.wav^headers^
   wavedata_ulaw.wav
   wavedata_ulaw.wav^headers^
+  !/dom/canvas/test/captureStream_common.js
+  !/dom/html/test/reflect.js
 
 [test_access_control.html]
 skip-if = buildapp == 'b2g' && toolkit != 'gonk' # bug 1082984
 [test_aspectratio_mp4.html]
 [test_audio1.html]
 [test_audio2.html]
 [test_audioDocumentTitle.html]
 skip-if = true # bug 475110 - disabled since we don't play Wave files standalone
--- a/dom/media/tests/mochitest/identity/mochitest.ini
+++ b/dom/media/tests/mochitest/identity/mochitest.ini
@@ -3,16 +3,24 @@
 # broken HTTPS on b2g emulator - bug 1135339
 # Android 4.3 - bug 981881
 # Exit code -11 for linux/opt/non-e10s - bug 1256284
 subsuite = media
 skip-if = android_version == '18' || (buildapp == 'b2g' && toolkit != 'gonk') || (buildapp == 'b2g' && toolkit == 'gonk') || buildapp == 'mulet' || (os == 'linux' && !debug && !e10s)
 support-files =
   /.well-known/idp-proxy/idp.js
   identityPcTest.js
+  !/dom/media/tests/mochitest/blacksilence.js
+  !/dom/media/tests/mochitest/dataChannel.js
+  !/dom/media/tests/mochitest/head.js
+  !/dom/media/tests/mochitest/network.js
+  !/dom/media/tests/mochitest/pc.js
+  !/dom/media/tests/mochitest/sdpUtils.js
+  !/dom/media/tests/mochitest/templates.js
+  !/dom/media/tests/mochitest/turnConfig.js
 tags = msg
 
 [test_idpproxy.html]
 support-files =
   /.well-known/idp-proxy/idp-redirect-http.js
   /.well-known/idp-proxy/idp-redirect-http.js^headers^
   /.well-known/idp-proxy/idp-redirect-http-trick.js
   /.well-known/idp-proxy/idp-redirect-http-trick.js^headers^
--- a/dom/media/tests/mochitest/mochitest.ini
+++ b/dom/media/tests/mochitest/mochitest.ini
@@ -9,16 +9,24 @@ support-files =
   network.js
   nonTrickleIce.js
   pc.js
   templates.js
   NetworkPreparationChromeScript.js
   blacksilence.js
   turnConfig.js
   sdpUtils.js
+  !/dom/canvas/test/captureStream_common.js
+  !/dom/canvas/test/webgl-mochitest/webgl-util.js
+  !/dom/media/test/manifest.js
+  !/dom/media/test/320x240.ogv
+  !/dom/media/test/r11025_s16_c1.wav
+  !/dom/media/test/bug461281.ogg
+  !/dom/media/test/seek.webm
+  !/dom/media/test/gizmo.mp4
 
 [test_dataChannel_basicAudio.html]
 skip-if = toolkit == 'gonk' || buildapp == 'mulet' # Bug 962984 for debug, bug 963244 for opt
 [test_dataChannel_basicAudioVideo.html]
 skip-if = toolkit == 'gonk' || buildapp == 'mulet' || android_version == '18' # b2g(Bug 960442, video support for WebRTC is disabled on b2g), android(Bug 1189784, timeouts on 4.3 emulator)
 [test_dataChannel_basicAudioVideoNoBundle.html]
 skip-if = toolkit == 'gonk' || buildapp == 'mulet' || android_version == '18' # b2g(Bug 960442, video support for WebRTC is disabled on b2g) FAILS WHEN RUN MANUALLY ON AWS, android(Bug 1189784, timeouts on 4.3 emulator)
 [test_dataChannel_basicAudioVideoCombined.html]
--- a/dom/plugins/test/mochitest/chrome.ini
+++ b/dom/plugins/test/mochitest/chrome.ini
@@ -1,14 +1,15 @@
 [DEFAULT]
 skip-if = (buildapp == 'b2g' || buildapp == 'mulet')
 support-files =
   hang_test.js
   privatemode_perwindowpb.xul
   plugin-utils.js
+  !/toolkit/crashreporter/test/browser/crashreport.sjs
 
 [test_bug479979.xul]
 [test_bug751809.html]
 [test_busy_hang.xul]
 skip-if = (!crashreporter) || (os != "win")
 [test_clear_site_data.html]
 [test_convertpoint.xul]
 skip-if = toolkit != "cocoa"
--- a/dom/plugins/test/mochitest/mochitest.ini
+++ b/dom/plugins/test/mochitest/mochitest.ini
@@ -18,16 +18,17 @@ support-files =
   mixed_case_mime.sjs
   neverending.sjs
   npruntime_identifiers_subpage.html
   plugin-stream-referer.sjs
   plugin_window.html
   pluginstream.js
   post.sjs
   plugin-utils.js
+  !/toolkit/components/passwordmgr/test/authenticate.sjs
 
 [test_GCrace.html]
 [test_NPNVdocumentOrigin.html]
 [test_NPPVpluginWantsAllNetworkStreams.html]
 [test_bug406541.html]
 [test_bug532208.html]
 [test_bug539565-1.html]
 [test_bug539565-2.html]
--- a/dom/plugins/test/unit/xpcshell.ini
+++ b/dom/plugins/test/unit/xpcshell.ini
@@ -1,14 +1,16 @@
 [DEFAULT]
 skip-if = toolkit == 'android' || toolkit == 'gonk'
 head = head_plugins.js
 tail =
 tags = addons
 firefox-appdir = browser
+support-files =
+  !/toolkit/mozapps/extensions/test/xpcshell/head_addons.js
 
 [test_allowed_types.js]
 skip-if = appname == "thunderbird"
 reason = plugins are disabled by default in Thunderbird
 [test_bug455213.js]
 # Bug 676953: test fails consistently on Android
 fail-if = os == "android"
 [test_bug471245.js]
--- a/dom/security/test/csp/browser.ini
+++ b/dom/security/test/csp/browser.ini
@@ -1,3 +1,5 @@
 [DEFAULT]
+support-files =
+  !/dom/security/test/csp/file_testserver.sjs
 [browser_test_web_manifest.js]
 [browser_test_web_manifest_mixed_content.js]
--- a/dom/security/test/csp/chrome.ini
+++ b/dom/security/test/csp/chrome.ini
@@ -1,5 +1,7 @@
 [DEFAULT]
 skip-if = buildapp == 'b2g' || os == 'android'
+support-files =
+  !/dom/security/test/csp/file_bug768029.html
 
 [test_bug768029.html]
 [test_bug773891.html]
--- a/dom/security/test/csp/mochitest.ini
+++ b/dom/security/test/csp/mochitest.ini
@@ -155,16 +155,17 @@ support-files =
   file_docwrite_meta.js
   file_multipart_testserver.sjs
   file_fontloader.sjs
   file_fontloader.woff
   file_block_all_mcb.sjs
   file_block_all_mixed_content_frame_navigation1.html
   file_block_all_mixed_content_frame_navigation2.html
   file_form_action_server.sjs
+  !/image/test/mochitest/blue.png
 
 [test_base-uri.html]
 [test_blob_data_schemes.html]
 [test_connect-src.html]
 [test_CSP.html]
 [test_allow_https_schemes.html]
 skip-if = buildapp == 'b2g' #no ssl support
 [test_bug663567.html]
--- a/dom/security/test/mixedcontentblocker/mochitest.ini
+++ b/dom/security/test/mixedcontentblocker/mochitest.ini
@@ -7,15 +7,17 @@ support-files =
   file_frameNavigation_grandchild.html
   file_frameNavigation_innermost.html
   file_frameNavigation_secure.html
   file_frameNavigation_secure_grandchild.html
   file_main.html
   file_main_bug803225.html
   file_main_bug803225_websocket_wsh.py
   file_server.sjs
+  !/dom/media/test/320x240.ogv
+  !/image/test/mochitest/blue.png
 
 [test_main.html]
 skip-if = buildapp == 'mulet' || buildapp == 'b2g' || toolkit == 'android' #TIMED_OUT, SSL_REQUIRED # Bug 1141029 Mulet parity with B2G Desktop for TC
 [test_bug803225.html]
 skip-if = buildapp == 'mulet' || buildapp == 'b2g' || toolkit == 'android' #TIMED_OUT, SSL_REQUIRED # Bug 1141029 Mulet parity with B2G Desktop for TC
 [test_frameNavigation.html]
 skip-if = buildapp == 'b2g' || toolkit == 'android' || (os == 'mac' || os == 'win') #TIMED_OUT, SSL_REQUIRED, OSX/Win: Bug 1241634
--- a/dom/system/nsDeviceSensors.cpp
+++ b/dom/system/nsDeviceSensors.cpp
@@ -327,16 +327,17 @@ nsDeviceSensors::Notify(const mozilla::h
   uint32_t type = aSensorData.sensor();
 
   const InfallibleTArray<float>& values = aSensorData.values();
   size_t len = values.Length();
   double x = len > 0 ? values[0] : 0.0;
   double y = len > 1 ? values[1] : 0.0;
   double z = len > 2 ? values[2] : 0.0;
   double w = len > 3 ? values[3] : 0.0;
+  PRTime timestamp = aSensorData.timestamp();
 
   nsCOMArray<nsIDOMWindow> windowListeners;
   for (uint32_t i = 0; i < mWindowListeners[type]->Length(); i++) {
     windowListeners.AppendObject(mWindowListeners[type]->SafeElementAt(i));
   }
 
   for (uint32_t i = windowListeners.Count(); i > 0 ; ) {
     --i;
@@ -346,17 +347,17 @@ nsDeviceSensors::Notify(const mozilla::h
         continue;
     }
 
     if (nsCOMPtr<nsIDOMDocument> domDoc = do_QueryInterface(pwindow->GetDoc())) {
       nsCOMPtr<mozilla::dom::EventTarget> target = do_QueryInterface(windowListeners[i]);
       if (type == nsIDeviceSensorData::TYPE_ACCELERATION ||
         type == nsIDeviceSensorData::TYPE_LINEAR_ACCELERATION ||
         type == nsIDeviceSensorData::TYPE_GYROSCOPE) {
-        FireDOMMotionEvent(domDoc, target, type, x, y, z);
+        FireDOMMotionEvent(domDoc, target, type, timestamp, x, y, z);
       } else if (type == nsIDeviceSensorData::TYPE_ORIENTATION) {
         FireDOMOrientationEvent(target, x, y, z, Orientation::kAbsolute);
       } else if (type == nsIDeviceSensorData::TYPE_ROTATION_VECTOR) {
         const Orientation orient = RotationVectorToOrientation(x, y, z, w);
         FireDOMOrientationEvent(target, orient.alpha, orient.beta, orient.gamma,
                                 Orientation::kAbsolute);
       } else if (type == nsIDeviceSensorData::TYPE_GAME_ROTATION_VECTOR) {
         const Orientation orient = RotationVectorToOrientation(x, y, z, w);
@@ -483,16 +484,17 @@ nsDeviceSensors::FireDOMOrientationEvent
     Dispatch(aTarget, NS_LITERAL_STRING("deviceorientation"));
   }
 }
 
 void
 nsDeviceSensors::FireDOMMotionEvent(nsIDOMDocument *domdoc,
                                     EventTarget* target,
                                     uint32_t type,
+                                    PRTime timestamp,
                                     double x,
                                     double y,
                                     double z)
 {
   // Attempt to coalesce events
   TimeDuration sensorPollDuration =
     TimeDuration::FromMilliseconds(DEFAULT_SENSOR_POLL);
   bool fireEvent =
@@ -548,17 +550,18 @@ nsDeviceSensors::FireDOMMotionEvent(nsID
   DeviceMotionEvent* me = static_cast<DeviceMotionEvent*>(event.get());
 
   me->InitDeviceMotionEvent(NS_LITERAL_STRING("devicemotion"),
                             true,
                             false,
                             *mLastAcceleration,
                             *mLastAccelerationIncludingGravity,
                             *mLastRotationRate,
-                            Nullable<double>(DEFAULT_SENSOR_POLL));
+                            Nullable<double>(DEFAULT_SENSOR_POLL),
+                            Nullable<uint64_t>(timestamp));
 
   event->SetTrusted(true);
 
   bool defaultActionEnabled = true;
   target->DispatchEvent(event, &defaultActionEnabled);
 
   mLastRotationRate.reset();
   mLastAccelerationIncludingGravity.reset();
--- a/dom/system/nsDeviceSensors.h
+++ b/dom/system/nsDeviceSensors.h
@@ -58,16 +58,17 @@ private:
                                double aAlpha,
                                double aBeta,
                                double aGamma,
                                bool aIsAbsolute);
 
   void FireDOMMotionEvent(class nsIDOMDocument *domDoc,
                           mozilla::dom::EventTarget* target,
                           uint32_t type,
+                          PRTime timestamp,
                           double x,
                           double y,
                           double z);
 
   bool mEnabled;
 
   inline bool IsSensorEnabled(uint32_t aType) {
     return mWindowListeners[aType]->Length() > 0;
--- a/dom/tests/browser/browser.ini
+++ b/dom/tests/browser/browser.ini
@@ -2,16 +2,17 @@
 support-files =
   browser_frame_elements.html
   page_privatestorageevent.html
   position.html
   test-console-api.html
   test_bug1004814.html
   worker_bug1004814.js
   geo_leak_test.html
+  !/dom/tests/mochitest/geolocation/network_geolocation.sjs
 
 [browser_test_toolbars_visibility.js]
 support-files =
   test_new_window_from_content_child.html
 [browser_bug1008941_dismissGeolocationHanger.js]
 skip-if = buildapp == 'mulet'
 [browser_test__content.js]
 skip-if = e10s
--- a/dom/tests/mochitest/chrome/chrome.ini
+++ b/dom/tests/mochitest/chrome/chrome.ini
@@ -23,16 +23,20 @@ support-files =
   queryCaretRectWin.html
   selectAtPoint.html
   sizemode_attribute.xul
   window_activation.xul
   window_callback_wrapping.xul
   window_docshell_swap.xul
   window_focus.xul
   window_focus_docnav.xul
+  !/dom/tests/mochitest/general/file_clonewrapper.html
+  !/dom/tests/mochitest/general/file_moving_nodeList.html
+  !/dom/tests/mochitest/general/file_moving_xhr.html
+  !/dom/tests/mochitest/geolocation/network_geolocation.sjs
 
 [test_DOMWindowCreated.xul]
 [test_DOM_element_instanceof.xul]
 [test_activation.xul]
 tags = fullscreen
 [test_bug799299.xul]
 [test_bug800817.xul]
 [test_bug830396.xul]
--- a/dom/tests/mochitest/fetch/mochitest.ini
+++ b/dom/tests/mochitest/fetch/mochitest.ini
@@ -13,16 +13,26 @@ support-files =
   worker_wrapper.js
   message_receiver.html
   reroute.html
   reroute.js
   reroute.js^headers^
   sw_reroute.js
   empty.js
   empty.js^headers^
+  !/dom/base/test/file_XHR_binary1.bin
+  !/dom/base/test/file_XHR_binary1.bin^headers^
+  !/dom/base/test/file_XHR_binary2.bin
+  !/dom/base/test/file_XHR_pass1.xml
+  !/dom/base/test/file_XHR_pass2.txt
+  !/dom/base/test/file_XHR_pass3.txt
+  !/dom/base/test/file_XHR_pass3.txt^headers^
+  !/dom/base/test/responseIdentical.sjs
+  !/dom/html/test/form_submit_server.sjs
+  !/dom/security/test/cors/file_CrossSiteXHR_server.sjs
 
 [test_headers.html]
 [test_headers_sw_reroute.html]
 skip-if = buildapp == 'b2g' # Bug 1137683
 [test_headers_mainthread.html]
 skip-if = (e10s && debug && os == 'win')
 [test_fetch_app_protocol.html]
 skip-if = (buildapp != 'b2g' && buildapp != 'mulet')
--- a/dom/tests/mochitest/general/mochitest.ini
+++ b/dom/tests/mochitest/general/mochitest.ini
@@ -40,16 +40,22 @@ support-files =
   frameStorageAllowed.html
   frameStoragePrevented.html
   frameStorageChrome.html
   frameStorageNullprincipal.sjs
   workerStorageAllowed.js
   workerStoragePrevented.js
   storagePermissionsUtils.js
   frameSelectEvents.html
+  !/image/test/mochitest/big.png
+  !/image/test/mochitest/blue.png
+  !/image/test/mochitest/clear.png
+  !/image/test/mochitest/damon.jpg
+  !/image/test/mochitest/over.png
+  !/image/test/mochitest/red.png
 
 [test_497898.html]
 skip-if = ((buildapp == 'mulet' || buildapp == 'b2g') && toolkit != 'gonk') || toolkit == 'android' #Bug 931116, b2g desktop specific, initial triage
 [test_bug504220.html]
 [test_bug628069_1.html]
 skip-if = (buildapp == 'b2g' && toolkit != 'gonk') #Bug 931116, b2g desktop specific, initial triage
 [test_bug628069_2.html]
 [test_bug631440.html]
--- a/dom/workers/ServiceWorkerManager.cpp
+++ b/dom/workers/ServiceWorkerManager.cpp
@@ -3770,25 +3770,30 @@ ServiceWorkerManager::IsAvailable(nsIPri
   return registration && registration->mActiveWorker;
 }
 
 bool
 ServiceWorkerManager::IsControlled(nsIDocument* aDoc, ErrorResult& aRv)
 {
   MOZ_ASSERT(aDoc);
 
+  if (nsContentUtils::IsInPrivateBrowsing(aDoc)) {
+    // Handle the case where a service worker was previously registered in
+    // a non-private window (bug 1255621).
+    return false;
+  }
+
   RefPtr<ServiceWorkerRegistrationInfo> registration;
   nsresult rv = GetDocumentRegistration(aDoc, getter_AddRefs(registration));
   if (NS_WARN_IF(NS_FAILED(rv) && rv != NS_ERROR_NOT_AVAILABLE)) {
     // It's OK to ignore the case where we don't have a registration.
     aRv.Throw(rv);
     return false;
   }
 
-  MOZ_ASSERT_IF(!!registration, !nsContentUtils::IsInPrivateBrowsing(aDoc));
   return !!registration;
 }
 
 nsresult
 ServiceWorkerManager::GetDocumentRegistration(nsIDocument* aDoc,
                                               ServiceWorkerRegistrationInfo** aRegistrationInfo)
 {
   RefPtr<ServiceWorkerRegistrationInfo> registration;
--- a/dom/workers/WorkerScope.cpp
+++ b/dom/workers/WorkerScope.cpp
@@ -14,16 +14,17 @@
 #include "mozilla/dom/Fetch.h"
 #include "mozilla/dom/FunctionBinding.h"
 #include "mozilla/dom/IDBFactory.h"
 #include "mozilla/dom/ImageBitmap.h"
 #include "mozilla/dom/Promise.h"
 #include "mozilla/dom/PromiseWorkerProxy.h"
 #include "mozilla/dom/ServiceWorkerGlobalScopeBinding.h"
 #include "mozilla/dom/SharedWorkerGlobalScopeBinding.h"
+#include "mozilla/dom/SimpleGlobalObject.h"
 #include "mozilla/dom/WorkerDebuggerGlobalScopeBinding.h"
 #include "mozilla/dom/WorkerGlobalScopeBinding.h"
 #include "mozilla/dom/WorkerLocation.h"
 #include "mozilla/dom/WorkerNavigator.h"
 #include "mozilla/dom/cache/CacheStorage.h"
 #include "mozilla/Services.h"
 #include "nsServiceManagerUtils.h"
 
@@ -705,164 +706,38 @@ WorkerDebuggerGlobalScope::GetGlobal(JSC
   WorkerGlobalScope* scope = mWorkerPrivate->GetOrCreateGlobalScope(aCx);
   if (!scope) {
     aRv.Throw(NS_ERROR_FAILURE);
   }
 
   aGlobal.set(scope->GetWrapper());
 }
 
-class WorkerDebuggerSandboxPrivate : public nsIGlobalObject,
-                                     public nsWrapperCache
-{
-public:
-  explicit WorkerDebuggerSandboxPrivate(JSObject *global)
-  {
-    SetWrapper(global);
-  }
-
-  NS_DECL_CYCLE_COLLECTING_ISUPPORTS
-  NS_DECL_CYCLE_COLLECTION_SCRIPT_HOLDER_CLASS_AMBIGUOUS(WorkerDebuggerSandboxPrivate,
-                                                         nsIGlobalObject)
-
-  virtual JSObject *GetGlobalJSObject() override
-  {
-    return GetWrapper();
-  }
-
-  virtual JSObject* WrapObject(JSContext* cx,
-                               JS::Handle<JSObject*> aGivenProto) override
-  {
-    MOZ_CRASH("WorkerDebuggerSandboxPrivate doesn't use DOM bindings!");
-  }
-
-private:
-  virtual ~WorkerDebuggerSandboxPrivate()
-  {
-    ClearWrapper();
-  }
-};
-
-NS_IMPL_CYCLE_COLLECTION_CLASS(WorkerDebuggerSandboxPrivate)
-
-NS_IMPL_CYCLE_COLLECTION_UNLINK_BEGIN(WorkerDebuggerSandboxPrivate)
-  NS_IMPL_CYCLE_COLLECTION_UNLINK_PRESERVED_WRAPPER
-  tmp->UnlinkHostObjectURIs();
-NS_IMPL_CYCLE_COLLECTION_UNLINK_END
-
-NS_IMPL_CYCLE_COLLECTION_TRAVERSE_BEGIN(WorkerDebuggerSandboxPrivate)
-
-  NS_IMPL_CYCLE_COLLECTION_TRAVERSE_SCRIPT_OBJECTS
-  tmp->TraverseHostObjectURIs(cb);
-NS_IMPL_CYCLE_COLLECTION_TRAVERSE_END
-
-NS_IMPL_CYCLE_COLLECTION_TRACE_WRAPPERCACHE(WorkerDebuggerSandboxPrivate)
-
-NS_IMPL_CYCLE_COLLECTING_ADDREF(WorkerDebuggerSandboxPrivate)
-NS_IMPL_CYCLE_COLLECTING_RELEASE(WorkerDebuggerSandboxPrivate)
-NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION(WorkerDebuggerSandboxPrivate)
-  NS_WRAPPERCACHE_INTERFACE_MAP_ENTRY
-  NS_INTERFACE_MAP_ENTRY(nsIGlobalObject)
-NS_INTERFACE_MAP_END
-
-static bool
-workerdebuggersandbox_enumerate(JSContext *cx, JS::Handle<JSObject *> obj)
-{
-  return JS_EnumerateStandardClasses(cx, obj);
-}
-
-static bool
-workerdebuggersandbox_resolve(JSContext *cx, JS::Handle<JSObject *> obj,
-                              JS::Handle<jsid> id, bool *resolvedp)
-{
-  return JS_ResolveStandardClass(cx, obj, id, resolvedp);
-}
-
-static void
-workerdebuggersandbox_finalize(js::FreeOp *fop, JSObject *obj)
-{
-  WorkerDebuggerSandboxPrivate *sandboxPrivate =
-    static_cast<WorkerDebuggerSandboxPrivate *>(JS_GetPrivate(obj));
-  NS_RELEASE(sandboxPrivate);
-}
-
-static void
-workerdebuggersandbox_moved(JSObject *obj, const JSObject *old)
-{
-  WorkerDebuggerSandboxPrivate *sandboxPrivate =
-    static_cast<WorkerDebuggerSandboxPrivate *>(JS_GetPrivate(obj));
-  sandboxPrivate->UpdateWrapper(obj, old);
-}
-
-const js::Class workerdebuggersandbox_class = {
-    "workerdebuggersandbox",
-    JSCLASS_GLOBAL_FLAGS | JSCLASS_HAS_PRIVATE | JSCLASS_PRIVATE_IS_NSISUPPORTS,
-    nullptr,
-    nullptr,
-    nullptr,
-    nullptr,
-    workerdebuggersandbox_enumerate,
-    workerdebuggersandbox_resolve,
-    nullptr, /* mayResolve */
-    workerdebuggersandbox_finalize,
-    nullptr,
-    nullptr,
-    nullptr,
-    JS_GlobalObjectTraceHook,
-    JS_NULL_CLASS_SPEC, {
-      false,
-      nullptr,
-      workerdebuggersandbox_moved
-    }, JS_NULL_OBJECT_OPS
-};
 
 void
 WorkerDebuggerGlobalScope::CreateSandbox(JSContext* aCx, const nsAString& aName,
                                          JS::Handle<JSObject*> aPrototype,
                                          JS::MutableHandle<JSObject*> aResult,
                                          ErrorResult& aRv)
 {
   mWorkerPrivate->AssertIsOnWorkerThread();
 
   aResult.set(nullptr);
 
-  JS::CompartmentOptions options;
-  options.creationOptions().setInvisibleToDebugger(true);
-
+  JS::Rooted<JS::Value> protoVal(aCx);
+  protoVal.setObjectOrNull(aPrototype);
   JS::Rooted<JSObject*> sandbox(aCx,
-    JS_NewGlobalObject(aCx, js::Jsvalify(&workerdebuggersandbox_class), nullptr,
-                       JS::DontFireOnNewGlobalHook, options));
+    SimpleGlobalObject::Create(SimpleGlobalObject::GlobalType::WorkerDebuggerSandbox,
+                               protoVal));
+
   if (!sandbox) {
-    aRv.NoteJSContextException(aCx);
+    aRv.Throw(NS_ERROR_OUT_OF_MEMORY);
     return;
   }
 
-  {
-    JSAutoCompartment ac(aCx, sandbox);
-
-    JS::Rooted<JSObject*> prototype(aCx, aPrototype);
-    if (!JS_WrapObject(aCx, &prototype)) {
-      aRv.NoteJSContextException(aCx);
-      return;
-    }
-
-    if (!JS_SetPrototype(aCx, sandbox, prototype)) {
-      aRv.NoteJSContextException(aCx);
-      return;
-    }
-
-    RefPtr<WorkerDebuggerSandboxPrivate> sandboxPrivate =
-      new WorkerDebuggerSandboxPrivate(sandbox);
-
-    // Pass on ownership of sandboxPrivate to |sandbox|.
-    JS_SetPrivate(sandbox, sandboxPrivate.forget().take());
-  }
-
-  JS_FireOnNewGlobalObject(aCx, sandbox);
-
   if (!JS_WrapObject(aCx, &sandbox)) {
     aRv.NoteJSContextException(aCx);
     return;
   }
 
   aResult.set(sandbox);
 }
 
@@ -995,17 +870,17 @@ GetGlobalObjectForGlobal(JSObject* globa
   nsIGlobalObject* globalObject = nullptr;
   UNWRAP_WORKER_OBJECT(WorkerGlobalScope, global, globalObject);
 
   if (!globalObject) {
     UNWRAP_OBJECT(WorkerDebuggerGlobalScope, global, globalObject);
 
     if (!globalObject) {
       MOZ_ASSERT(IsDebuggerSandbox(global));
-      globalObject = static_cast<WorkerDebuggerSandboxPrivate*>(JS_GetPrivate(global));
+      globalObject = static_cast<SimpleGlobalObject*>(JS_GetPrivate(global));
 
       MOZ_ASSERT(globalObject);
     }
   }
 
   return globalObject;
 }
 
@@ -1023,17 +898,18 @@ IsDebuggerGlobal(JSObject* object)
   nsIGlobalObject* globalObject = nullptr;
   return NS_SUCCEEDED(UNWRAP_OBJECT(WorkerDebuggerGlobalScope, object,
                                     globalObject)) && !!globalObject;
 }
 
 bool
 IsDebuggerSandbox(JSObject* object)
 {
-  return js::GetObjectClass(object) == &workerdebuggersandbox_class;
+  return SimpleGlobalObject::SimpleGlobalType(object) ==
+    SimpleGlobalObject::GlobalType::WorkerDebuggerSandbox;
 }
 
 bool
 GetterOnlyJSNative(JSContext* aCx, unsigned aArgc, JS::Value* aVp)
 {
   JS_ReportErrorNumber(aCx, js::GetErrorMessage, nullptr, JSMSG_GETTER_ONLY);
   return false;
 }
--- a/dom/workers/test/browser.ini
+++ b/dom/workers/test/browser.ini
@@ -1,10 +1,12 @@
 [DEFAULT]
 support-files =
   bug1047663_tab.html
   bug1047663_worker.sjs
   frame_script.js
   head.js
+  !/dom/base/test/file_empty.html
+  !/dom/base/test/file_bug945152.jar
 
 [browser_bug1047663.js]
 [browser_bug1104623.js]
 run-if = buildapp == 'browser'
--- a/dom/workers/test/chrome.ini
+++ b/dom/workers/test/chrome.ini
@@ -5,64 +5,62 @@ support-files =
   WorkerDebugger.console_debugger.js
   WorkerDebugger.console_worker.js
   WorkerDebugger.initialize_childWorker.js
   WorkerDebugger.initialize_debugger.js
   WorkerDebugger.initialize_worker.js
   WorkerDebugger.postMessage_childWorker.js
   WorkerDebugger.postMessage_debugger.js
   WorkerDebugger.postMessage_worker.js
-  WorkerDebugger_frozen_iframe1.html
-  WorkerDebugger_frozen_iframe2.html
-  WorkerDebugger_frozen_worker1.js
-  WorkerDebugger_frozen_worker2.js
   WorkerDebuggerGlobalScope.createSandbox_debugger.js
   WorkerDebuggerGlobalScope.createSandbox_sandbox.js
   WorkerDebuggerGlobalScope.createSandbox_worker.js
   WorkerDebuggerGlobalScope.enterEventLoop_childWorker.js
   WorkerDebuggerGlobalScope.enterEventLoop_debugger.js
   WorkerDebuggerGlobalScope.enterEventLoop_worker.js
   WorkerDebuggerGlobalScope.reportError_childWorker.js
   WorkerDebuggerGlobalScope.reportError_debugger.js
   WorkerDebuggerGlobalScope.reportError_worker.js
   WorkerDebuggerGlobalScope.setImmediate_debugger.js
   WorkerDebuggerGlobalScope.setImmediate_worker.js
   WorkerDebuggerManager_childWorker.js
   WorkerDebuggerManager_worker.js
   WorkerDebugger_childWorker.js
+  WorkerDebugger_frozen_iframe1.html
+  WorkerDebugger_frozen_iframe2.html
+  WorkerDebugger_frozen_worker1.js
+  WorkerDebugger_frozen_worker2.js
   WorkerDebugger_promise_debugger.js
   WorkerDebugger_promise_worker.js
-  WorkerDebugger_worker.js
   WorkerDebugger_sharedWorker.js
   WorkerDebugger_suspended_debugger.js
   WorkerDebugger_suspended_worker.js
+  WorkerDebugger_worker.js
   WorkerTest.jsm
   WorkerTest_subworker.js
   WorkerTest_worker.js
+  bug1062920_worker.js
   chromeWorker_subworker.js
   chromeWorker_worker.js
   dom_worker_helper.js
-  file_url.jsm
-  file_worker.js
+  empty.html
   fileBlobSubWorker_worker.js
   fileBlob_worker.js
   filePosting_worker.js
   fileReadSlice_worker.js
   fileReaderSyncErrors_worker.js
   fileReaderSync_worker.js
   fileSlice_worker.js
   fileSubWorker_worker.js
+  file_url.jsm
   file_worker.js
   jsm_url_worker.js
-  workersDisabled_worker.js
-  file_url.jsm
-  bug1062920_worker.js
-  empty.html
   sharedWorker_privateBrowsing.js
   test_bug883784.jsm
+  workersDisabled_worker.js
 
 [test_WorkerDebugger.initialize.xul]
 [test_WorkerDebugger.postMessage.xul]
 [test_WorkerDebugger.xul]
 [test_WorkerDebuggerGlobalScope.createSandbox.xul]
 [test_WorkerDebuggerGlobalScope.enterEventLoop.xul]
 [test_WorkerDebuggerGlobalScope.reportError.xul]
 [test_WorkerDebuggerGlobalScope.setImmediate.xul]
--- a/dom/workers/test/mochitest.ini
+++ b/dom/workers/test/mochitest.ini
@@ -125,16 +125,38 @@ support-files =
   sharedWorker_lifetime.js
   worker_referrer.js
   websocket_https.html
   websocket_https_worker.js
   worker_fileReader.js
   fileapi_chromeScript.js
   importScripts_3rdParty_worker.js
   xhr_cors_redirect.sjs
+  !/dom/base/test/file_XHRResponseURL.js
+  !/dom/base/test/file_XHRResponseURL.sjs
+  !/dom/base/test/file_XHRResponseURL.text
+  !/dom/base/test/file_XHRResponseURL.text^headers^
+  !/dom/base/test/file_XHRResponseURL_nocors.text
+  !/dom/base/test/file_XHR_timeout.sjs
+  !/dom/base/test/file_websocket_basic_wsh.py
+  !/dom/base/test/file_websocket_hello_wsh.py
+  !/dom/base/test/file_websocket_http_resource.txt
+  !/dom/base/test/file_websocket_permessage_deflate_disabled_wsh.py
+  !/dom/base/test/file_websocket_permessage_deflate_params_wsh.py
+  !/dom/base/test/file_websocket_permessage_deflate_rejected_wsh.py
+  !/dom/base/test/file_websocket_permessage_deflate_wsh.py
+  !/dom/base/test/file_websocket_wsh.py
+  !/dom/base/test/test_XHR_system.html
+  !/dom/base/test/test_XHR_timeout.js
+  !/dom/base/test/test_performance_observer.js
+  !/dom/base/test/test_performance_user_timing.js
+  !/dom/base/test/websocket_helpers.js
+  !/dom/base/test/websocket_tests.js
+  !/dom/tests/mochitest/notification/MockServices.js
+  !/dom/tests/mochitest/notification/NotificationTest.js
 
 [test_404.html]
 [test_atob.html]
 [test_blobConstructor.html]
 [test_blobWorkers.html]
 [test_bug949946.html]
 [test_bug978260.html]
 [test_bug998474.html]
--- a/dom/workers/test/serviceworkers/mochitest.ini
+++ b/dom/workers/test/serviceworkers/mochitest.ini
@@ -194,16 +194,19 @@ support-files =
   xslt/*
   unresolved_fetch_worker.js
   header_checker.sjs
   openWindow_worker.js
   redirect.sjs
   open_window/client.html
   lorem_script.js
   file_blob_response_worker.js
+  !/dom/security/test/cors/file_CrossSiteXHR_server.sjs
+  !/dom/tests/mochitest/notification/MockServices.js
+  !/dom/tests/mochitest/notification/NotificationTest.js
 
 [test_bug1151916.html]
 [test_claim.html]
 [test_claim_fetch.html]
 [test_claim_oninstall.html]
 [test_close.html]
 [test_controller.html]
 [test_cross_origin_url_after_redirect.html]
--- a/dom/workers/test/serviceworkers/test_privateBrowsing.html
+++ b/dom/workers/test/serviceworkers/test_privateBrowsing.html
@@ -7,16 +7,18 @@
 <body>
 
 <script type="application/javascript">
 
 const Ci = Components.interfaces;
 var mainWindow;
 
 var contentPage = "http://mochi.test:8888/chrome/dom/workers/test/empty.html";
+var workerScope = "http://mochi.test:8888/chrome/dom/workers/test/serviceworkers/";
+var workerURL = workerScope + "worker.js";
 
 function testOnWindow(aIsPrivate, aCallback) {
   var win = mainWindow.OpenBrowserWindow({private: aIsPrivate});
   win.addEventListener("load", function onLoad() {
     win.removeEventListener("load", onLoad, false);
     win.addEventListener("DOMContentLoaded", function onInnerLoad() {
       if (win.content.location.href != contentPage) {
         win.gBrowser.loadURI(contentPage);
@@ -39,51 +41,73 @@ function setupWindow() {
                      .QueryInterface(Ci.nsIDocShellTreeItem)
                      .rootTreeItem
                      .QueryInterface(Ci.nsIInterfaceRequestor)
                      .getInterface(Ci.nsIDOMWindow);
   runTest();
 }
 
 var wN;
+var registration;
 var wP;
 
+function testPrivateWindow() {
+  testOnWindow(true, function(aWin) {
+    wP = aWin;
+    ok(!("serviceWorker" in wP.content.navigator), "ServiceWorkers are not available for private windows");
+    runTest();
+  });
+}
+
 function doTests() {
   testOnWindow(false, function(aWin) {
     wN = aWin;
     ok("serviceWorker" in wN.content.navigator, "ServiceWorkers are available for normal windows");
 
-    testOnWindow(true, function(aWin) {
-      wP = aWin;
-      ok(!("serviceWorker" in wP.content.navigator), "ServiceWorkers are not available for private windows");
-      runTest();
-    });
+    wN.content.navigator.serviceWorker.register(workerURL,
+                                                { scope: workerScope })
+      .then(function(aRegistration) {
+        registration = aRegistration;
+        ok(registration, "Registering a service worker in a normal window should succeed");
+
+        // Bug 1255621: We should be able to load a controlled document in a private window.
+        testPrivateWindow();
+      }, function(aError) {
+        ok(false, "Error registering worker in normal window: " + aError);
+        testPrivateWindow();
+      });
   });
 }
 
 var steps = [
   setupWindow,
   doTests
 ];
 
+function cleanup() {
+  wN.close();
+  wP.close();
+
+  SimpleTest.finish();
+}
+
 function runTest() {
   if (!steps.length) {
-    wN.close();
-    wP.close();
+    registration.unregister().then(cleanup, cleanup);
 
-    SimpleTest.finish();
     return;
   }
 
   var step = steps.shift();
   step();
 }
 
 SimpleTest.waitForExplicitFinish();
 SpecialPowers.pushPrefEnv({"set": [
   ["dom.serviceWorkers.enabled", true],
+  ["dom.serviceWorkers.testing.enabled", true],
   ["browser.startup.page", 0],
   ["browser.startup.homepage_override.mstone", "ignore"],
 ]}, runTest);
 
 </script>
 </body>
 </html>
--- a/gfx/2d/DrawTargetCairo.cpp
+++ b/gfx/2d/DrawTargetCairo.cpp
@@ -716,20 +716,29 @@ DrawTargetCairo::Snapshot()
   return snapshot.forget();
 }
 
 bool
 DrawTargetCairo::LockBits(uint8_t** aData, IntSize* aSize,
                           int32_t* aStride, SurfaceFormat* aFormat,
                           IntPoint* aOrigin)
 {
-  cairo_surface_t* surf = cairo_get_group_target(mContext);
+  cairo_surface_t* target = cairo_get_group_target(mContext);
+  cairo_surface_t* surf = target;
+#ifdef CAIRO_HAS_WIN32_SURFACE
+  if (cairo_surface_get_type(surf) == CAIRO_SURFACE_TYPE_WIN32) {
+    cairo_surface_t* imgsurf = cairo_win32_surface_get_image(surf);
+    if (imgsurf) {
+      surf = imgsurf;
+    }
+  }
+#endif
   if (cairo_surface_get_type(surf) == CAIRO_SURFACE_TYPE_IMAGE) {
     PointDouble offset;
-    cairo_surface_get_device_offset(surf, &offset.x, &offset.y);
+    cairo_surface_get_device_offset(target, &offset.x, &offset.y);
     // verify the device offset can be converted to integers suitable for a bounds rect
     IntPoint origin(int32_t(-offset.x), int32_t(-offset.y));
     if (-PointDouble(origin) != offset ||
         (!aOrigin && origin != IntPoint())) {
       return false;
     }
 
     WillChange();
@@ -751,16 +760,24 @@ DrawTargetCairo::LockBits(uint8_t** aDat
 }
 
 void
 DrawTargetCairo::ReleaseBits(uint8_t* aData)
 {
   MOZ_ASSERT(mLockedBits == aData);
   mLockedBits = nullptr;
   cairo_surface_t* surf = cairo_get_group_target(mContext);
+#ifdef CAIRO_HAS_WIN32_SURFACE
+  if (cairo_surface_get_type(surf) == CAIRO_SURFACE_TYPE_WIN32) {
+    cairo_surface_t* imgsurf = cairo_win32_surface_get_image(surf);
+    if (imgsurf) {
+      cairo_surface_mark_dirty(imgsurf);
+    }
+  }
+#endif
   cairo_surface_mark_dirty(surf);
 }
 
 void
 DrawTargetCairo::Flush()
 {
   cairo_surface_t* surf = cairo_get_group_target(mContext);
   cairo_surface_flush(surf);
--- a/gfx/gl/GLLibraryEGL.cpp
+++ b/gfx/gl/GLLibraryEGL.cpp
@@ -156,17 +156,17 @@ GetAndInitDisplay(GLLibraryEGL& egl, voi
 static EGLDisplay
 GetAndInitDisplayForAccelANGLE(GLLibraryEGL& egl)
 {
     EGLDisplay ret = 0;
 
     // D3D11 ANGLE only works with OMTC; there's a bug in the non-OMTC layer
     // manager, and it's pointless to try to fix it.  We also don't try
     // D3D11 ANGLE if the layer manager is prefering D3D9 (hrm, do we care?)
-    if (gfxPrefs::LayersOffMainThreadCompositionEnabled() &&
+    if (!gfxPrefs::LayersOffMainThreadCompositionForceDisabled() &&
         !gfxPrefs::LayersPreferD3D9())
     {
         if (gfxPrefs::WebGLANGLEForceD3D11())
             return GetAndInitDisplay(egl, LOCAL_EGL_D3D11_ONLY_DISPLAY_ANGLE);
 
         if (gfxPrefs::WebGLANGLETryD3D11() &&
             gfxPlatform::CanUseDirect3D11ANGLE())
         {
--- a/gfx/layers/ImageContainer.cpp
+++ b/gfx/layers/ImageContainer.cpp
@@ -98,29 +98,82 @@ BufferRecycleBin::GetBuffer(uint32_t aSi
  * destroyed on) the ImageBridge thread, except when we need to destroy it
  * during shutdown.
  * An ImageContainer owns one of these; we have a weak reference to our
  * ImageContainer.
  */
 class ImageContainerChild : public PImageContainerChild {
 public:
   explicit ImageContainerChild(ImageContainer* aImageContainer)
-    : mLock("ImageContainerChild"), mImageContainer(aImageContainer) {}
+    : mLock("ImageContainerChild")
+    , mImageContainer(aImageContainer)
+    , mImageContainerReleased(false)
+    , mIPCOpen(true)
+  {}
+
   void ForgetImageContainer()
   {
     MutexAutoLock lock(mLock);
     mImageContainer = nullptr;
   }
 
   // This protects mImageContainer. This is always taken before the
   // mImageContainer's monitor (when both need to be held).
   Mutex mLock;
   ImageContainer* mImageContainer;
+  // If mImageContainerReleased is false when we try to deallocate this actor,
+  // it means the ImageContainer is still holding a pointer to this.
+  // mImageContainerReleased must not be accessed off the ImageBridgeChild thread.
+  bool mImageContainerReleased;
+  // If mIPCOpen is false, it means the IPDL code tried to deallocate the actor
+  // before the ImageContainer released it. When this happens we don't actually
+  // delete the actor right away because the ImageContainer has a reference to
+  // it. In this case the actor will be deleted when the ImageContainer lets go
+  // of it.
+  // mIPCOpen must not be accessed off the ImageBridgeChild thread.
+  bool mIPCOpen;
 };
 
+// static
+void
+ImageContainer::DeallocActor(PImageContainerChild* aActor)
+{
+  MOZ_ASSERT(aActor);
+  MOZ_ASSERT(InImageBridgeChildThread());
+
+  auto actor = static_cast<ImageContainerChild*>(aActor);
+  if (actor->mImageContainerReleased) {
+    delete actor;
+  } else {
+    actor->mIPCOpen = false;
+  }
+}
+
+// static
+void
+ImageContainer::AsyncDestroyActor(PImageContainerChild* aActor)
+{
+  MOZ_ASSERT(aActor);
+  MOZ_ASSERT(InImageBridgeChildThread());
+
+  auto actor = static_cast<ImageContainerChild*>(aActor);
+
+  // Setting mImageContainerReleased to true means next time DeallocActor is
+  // called, the actor will be deleted.
+  actor->mImageContainerReleased = true;
+
+  if (actor->mIPCOpen && ImageBridgeChild::IsCreated() && !ImageBridgeChild::IsShutDown()) {
+    actor->SendAsyncDelete();
+  } else {
+    // The actor is already dead as far as IPDL is concerned, probably because
+    // of a channel error. We can deallocate it now.
+    DeallocActor(actor);
+  }
+}
+
 ImageContainer::ImageContainer(Mode flag)
 : mReentrantMonitor("ImageContainer.mReentrantMonitor"),
   mGenerationCounter(++sGenerationCounter),
   mPaintCount(0),
   mDroppedImageCount(0),
   mImageFactory(new ImageFactory()),
   mRecycleBin(new BufferRecycleBin()),
   mImageClient(nullptr),
--- a/gfx/layers/ImageContainer.h
+++ b/gfx/layers/ImageContainer.h
@@ -549,16 +549,22 @@ public:
   PImageContainerChild* GetPImageContainerChild();
   static void NotifyComposite(const ImageCompositeNotification& aNotification);
 
   /**
    * Main thread only.
    */
   static ProducerID AllocateProducerID();
 
+  /// ImageBridgeChild thread only.
+  static void AsyncDestroyActor(PImageContainerChild* aActor);
+
+  /// ImageBridgeChild thread only.
+  static void DeallocActor(PImageContainerChild* aActor);
+
 private:
   typedef mozilla::ReentrantMonitor ReentrantMonitor;
 
   // Private destructor, to discourage deletion outside of Release():
   B2G_ACL_EXPORT ~ImageContainer();
 
   void SetCurrentImageInternal(const nsTArray<NonOwningImage>& aImages);
 
--- a/gfx/layers/ipc/ImageBridgeChild.cpp
+++ b/gfx/layers/ipc/ImageBridgeChild.cpp
@@ -444,18 +444,19 @@ ConnectImageBridgeInChildProcess(Transpo
 
 static void ReleaseImageClientNow(ImageClient* aClient,
                                   PImageContainerChild* aChild)
 {
   MOZ_ASSERT(InImageBridgeChildThread());
   if (aClient) {
     aClient->Release();
   }
-  if (aChild && ImageBridgeChild::IsCreated() && !ImageBridgeChild::IsShutDown()) {
-    aChild->SendAsyncDelete();
+
+  if (aChild) {
+    ImageContainer::AsyncDestroyActor(aChild);
   }
 }
 
 // static
 void ImageBridgeChild::DispatchReleaseImageClient(ImageClient* aClient,
                                                   PImageContainerChild* aChild)
 {
   if (!aClient && !aChild) {
@@ -1091,17 +1092,17 @@ ImageBridgeChild::AllocPImageContainerCh
   // we always use the "power-user" ctor
   NS_RUNTIMEABORT("not reached");
   return nullptr;
 }
 
 bool
 ImageBridgeChild::DeallocPImageContainerChild(PImageContainerChild* actor)
 {
-  delete actor;
+  ImageContainer::DeallocActor(actor);
   return true;
 }
 
 bool
 ImageBridgeChild::RecvParentAsyncMessages(InfallibleTArray<AsyncParentMessageData>&& aMessages)
 {
   for (AsyncParentMessageArray::index_type i = 0; i < aMessages.Length(); ++i) {
     const AsyncParentMessageData& message = aMessages[i];
--- a/gfx/thebes/gfxPlatform.cpp
+++ b/gfx/thebes/gfxPlatform.cpp
@@ -594,23 +594,22 @@ gfxPlatform::Init()
     {
       nsAutoCString forcedPrefs;
       // D2D prefs
       forcedPrefs.AppendPrintf("FP(D%d%d%d",
                                gfxPrefs::Direct2DDisabled(),
                                gfxPrefs::Direct2DForceEnabled(),
                                gfxPrefs::DirectWriteFontRenderingForceEnabled());
       // Layers prefs
-      forcedPrefs.AppendPrintf("-L%d%d%d%d%d%d",
+      forcedPrefs.AppendPrintf("-L%d%d%d%d%d",
                                gfxPrefs::LayersAMDSwitchableGfxEnabled(),
                                gfxPrefs::LayersAccelerationDisabled(),
                                gfxPrefs::LayersAccelerationForceEnabled(),
                                gfxPrefs::LayersD3D11DisableWARP(),
-                               gfxPrefs::LayersD3D11ForceWARP(),
-                               gfxPrefs::LayersOffMainThreadCompositionForceEnabled());
+                               gfxPrefs::LayersD3D11ForceWARP());
       // WebGL prefs
       forcedPrefs.AppendPrintf("-W%d%d%d%d%d%d%d%d",
                                gfxPrefs::WebGLANGLEForceD3D11(),
                                gfxPrefs::WebGLANGLEForceWARP(),
                                gfxPrefs::WebGLDisabled(),
                                gfxPrefs::WebGLDisableANGLE(),
                                gfxPrefs::WebGLDXGLEnabled(),
                                gfxPrefs::WebGLForceEnabled(),
@@ -2215,18 +2214,17 @@ gfxPlatform::UsesOffMainThreadCompositin
 {
   InitLayersAccelerationPrefs();
   static bool firstTime = true;
   static bool result = false;
 
   if (firstTime) {
     result =
       sPrefBrowserTabsRemoteAutostart ||
-      gfxPrefs::LayersOffMainThreadCompositionEnabled() ||
-      gfxPrefs::LayersOffMainThreadCompositionForceEnabled();
+      !gfxPrefs::LayersOffMainThreadCompositionForceDisabled();
 #if defined(MOZ_WIDGET_GTK)
     // Linux users who chose OpenGL are being grandfathered in to OMTC
     result |= gfxPrefs::LayersAccelerationForceEnabled();
 
 #endif
     firstTime = false;
   }
 
--- a/gfx/thebes/gfxPrefs.h
+++ b/gfx/thebes/gfxPrefs.h
@@ -364,18 +364,17 @@ private:
   DECL_GFX_PREF(Live, "layers.flash-borders",                  FlashLayerBorders, bool, false);
   DECL_GFX_PREF(Once, "layers.force-shmem-tiles",              ForceShmemTiles, bool, false);
   DECL_GFX_PREF(Live, "layers.frame-counter",                  DrawFrameCounter, bool, false);
   DECL_GFX_PREF(Once, "layers.gralloc.disable",                DisableGralloc, bool, false);
   DECL_GFX_PREF(Live, "layers.low-precision-buffer",           UseLowPrecisionBuffer, bool, false);
   DECL_GFX_PREF(Live, "layers.low-precision-opacity",          LowPrecisionOpacity, float, 1.0f);
   DECL_GFX_PREF(Live, "layers.low-precision-resolution",       LowPrecisionResolution, float, 0.25f);
   DECL_GFX_PREF(Live, "layers.max-active",                     MaxActiveLayers, int32_t, -1);
-  DECL_GFX_PREF(Once, "layers.offmainthreadcomposition.enabled", LayersOffMainThreadCompositionEnabled, bool, false);
-  DECL_GFX_PREF(Once, "layers.offmainthreadcomposition.force-enabled", LayersOffMainThreadCompositionForceEnabled, bool, false);
+  DECL_GFX_PREF(Once, "layers.offmainthreadcomposition.force-disabled", LayersOffMainThreadCompositionForceDisabled, bool, false);
   DECL_GFX_PREF(Live, "layers.offmainthreadcomposition.frame-rate", LayersCompositionFrameRate, int32_t,-1);
   DECL_GFX_PREF(Live, "layers.orientation.sync.timeout",       OrientationSyncMillis, uint32_t, (uint32_t)0);
   DECL_GFX_PREF(Once, "layers.overzealous-gralloc-unlocking",  OverzealousGrallocUnlocking, bool, false);
   DECL_GFX_PREF(Once, "layers.prefer-d3d9",                    LayersPreferD3D9, bool, false);
   DECL_GFX_PREF(Once, "layers.prefer-opengl",                  LayersPreferOpenGL, bool, false);
   DECL_GFX_PREF(Live, "layers.progressive-paint",              ProgressivePaintDoNotUseDirectly, bool, false);
   DECL_GFX_PREF(Once, "layers.stereo-video.enabled",           StereoVideoEnabled, bool, false);
 
--- a/image/test/mochitest/chrome.ini
+++ b/image/test/mochitest/chrome.ini
@@ -1,60 +1,18 @@
 [DEFAULT]
 skip-if = buildapp == 'b2g' || os == 'android'
 support-files =
-  animated-gif-finalframe.gif
-  animated-gif.gif
-  animated-gif2.gif
-  animated1.gif
-  animated2.gif
-  animation.svg
   animationPolling.js
-  bad.jpg
-  damon.jpg
-  filter-final.svg
-  filter.svg
-  first-frame-padding.gif
-  ico-bmp-opaque.ico
-  ico-bmp-transparent.ico
   iframe.html
   imgutils.js
-  invalid.jpg
-  lime-anim-100x100-2.svg
-  lime-anim-100x100.svg
-  lime100x100.svg
-  opaque.bmp
-  purple.gif
-  red.gif
-  red.png
   ref-iframe.html
-  rillybad.jpg
-  transparent.gif
-  transparent.png
-  bug1132427.html
-  bug1132427.gif
 
-[test_animSVGImage.html]
-[test_animSVGImage2.html]
 [test_animation.html]
 disabled = bug 1100497
 [test_animation2.html]
 disabled = bug 1101415
-[test_background_image_anim.html]
-[test_bullet_animation.html]
 [test_bug415761.html]
 skip-if = os != "win" || os_version == "6.2"
 support-files =
   bug415761.ico
-[test_changeOfSource.html]
-[test_changeOfSource2.html]
-[test_has_transparency.html]
-[test_net_failedtoprocess.html]
-[test_removal_ondecode.html]
-[test_removal_onload.html]
-[test_staticClone.html]
-[test_svg_animatedGIF.html]
-[test_svg_filter_animation.html]
-[test_synchronized_animation.html]
 [test_undisplayed_iframe.html]
 disabled = bug 1060869
-[test_xultree_animation.xhtml]
-[test_bug1132427.html]
--- a/image/test/mochitest/mochitest.ini
+++ b/image/test/mochitest/mochitest.ini
@@ -1,13 +1,18 @@
 [DEFAULT]
 support-files =
   INT32_MIN.bmp
+  animated1.gif
+  animated2.gif
+  animated-gif.gif
   animated-gif2.gif
   animated-gif_trailing-garbage.gif
+  animated-gif-finalframe.gif
+  animation.svg
   animationPolling.js
   bad.jpg
   big.png
   blue.png
   bug399925.gif
   bug468160.sjs
   bug478398_ONLY.png
   bug490949-iframe.html
@@ -25,41 +30,55 @@ support-files =
   bug671906.sjs
   bug733553-informant.sjs
   bug733553.sjs
   bug767779.sjs
   bug89419-iframe.html
   bug89419.sjs
   bug900200.png
   bug900200-ref.png
+  bug1132427.html
+  bug1132427.gif
   bug1180105.sjs
   bug1180105-waiter.sjs
   bug1217571-iframe.html
   clear.gif
   clear.png
   clear2.gif
   clear2-results.gif
   damon.jpg
   error-early.png
+  filter-final.svg
+  filter.svg
+  first-frame-padding.gif
   green.png
   green-background.html
   grey.png
+  ico-bmp-opaque.ico
+  ico-bmp-transparent.ico
   imgutils.js
   invalid.jpg
   keep.gif
   keep.png
   lime100x100.svg
+  lime-anim-100x100.svg
+  lime-anim-100x100-2.svg
+  opaque.bmp
+  purple.gif
+  red.gif
   red.png
   restore-previous.gif
   restore-previous.png
   rillybad.jpg
   schrep.png
   shaver.png
   short_header.gif
   source.png
+  transparent.gif
+  transparent.png
   over.png
   6M-pixels.png
   12M-pixels-1.png
   12M-pixels-2.png
 
 [test_ImageContentLoaded.html]
 [test_bug399925.html]
 skip-if = buildapp == 'b2g' && debug # Bug 1182951
@@ -90,8 +109,40 @@ skip-if = buildapp == 'b2g' && debug # B
 [test_drawDiscardedImage.html]
 skip-if = toolkit == "gonk" #Bug 997034 - canvas.toDataURL() often causes lost connection to device.
 [test_error_events.html]
 [test_short_gif_header.html]
 [test_image_buffer_limit.html]
 #skip-if = toolkit != "gonk" #Image buffer limit is only set for Firefox OS currently.
 disabled = bug 1060869
 [test_image_crossorigin_data_url.html]
+[test_animSVGImage.html]
+skip-if = buildapp == 'b2g' || os == 'android'
+[test_animSVGImage2.html]
+skip-if = buildapp == 'b2g' || os == 'android'
+[test_background_image_anim.html]
+skip-if = buildapp == 'b2g' || os == 'android'
+[test_bullet_animation.html]
+skip-if = buildapp == 'b2g' || os == 'android'
+[test_changeOfSource.html]
+skip-if = buildapp == 'b2g' || os == 'android'
+[test_changeOfSource2.html]
+skip-if = buildapp == 'b2g' || os == 'android'
+[test_has_transparency.html]
+skip-if = buildapp == 'b2g' || os == 'android'
+[test_net_failedtoprocess.html]
+skip-if = buildapp == 'b2g' || os == 'android'
+[test_removal_ondecode.html]
+skip-if = buildapp == 'b2g' || os == 'android'
+[test_removal_onload.html]
+skip-if = buildapp == 'b2g' || os == 'android'
+[test_staticClone.html]
+skip-if = buildapp == 'b2g' || os == 'android'
+[test_svg_animatedGIF.html]
+skip-if = buildapp == 'b2g' || os == 'android'
+[test_svg_filter_animation.html]
+skip-if = buildapp == 'b2g' || os == 'android'
+[test_synchronized_animation.html]
+skip-if = buildapp == 'b2g' || os == 'android'
+[test_xultree_animation.xhtml]
+skip-if = buildapp == 'b2g' || os == 'android'
+[test_bug1132427.html]
+skip-if = buildapp == 'b2g' || os == 'android'
--- a/image/test/mochitest/test_animSVGImage.html
+++ b/image/test/mochitest/test_animSVGImage.html
@@ -1,38 +1,37 @@
 <!DOCTYPE HTML>
 <html>
 <!--
 https://bugzilla.mozilla.org/show_bug.cgi?id=610419
 -->
 <head>
   <title>Test for Bug 610419</title>
-  <script type="application/javascript" src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"></script>
-  <script type="application/javascript" src="chrome://mochikit/content/tests/SimpleTest/WindowSnapshot.js"></script>
+  <script type="application/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
+  <script type="application/javascript" src="/tests/SimpleTest/WindowSnapshot.js"></script>
   <script type="application/javascript" src="imgutils.js"></script>
-  <link rel="stylesheet" type="text/css" href="chrome://mochikit/content/tests/SimpleTest/test.css" />
+  <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
 </head>
 <body>
 <a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=610419">Mozilla Bug 610419</a>
 <p id="display"></p>
 <div id="content">
   <div id="referenceDiv" style="height: 100px; width: 100px;
                                 display: none; background: lime"></div>
   <img>
 </div>
 <pre id="test">
 <script type="application/javascript;version=1.8">
 /** Test for Bug 610419**/
 
+SimpleTest.requestFlakyTimeout("Pre-existing timeouts when converting from mochitest-chrome");
 SimpleTest.waitForExplicitFinish();
 
 const FAILURE_TIMEOUT = 120000; // Fail early after 120 seconds (2 minutes)
 
-const Cc = Components.classes;
-const Ci = Components.interfaces;
 const gImg = document.getElementsByTagName("img")[0];
 
 var gMyDecoderObserver; // value will be set in main()
 var gReferenceSnapshot; // value will be set in takeReferenceSnapshot()
 var gPollCounter = 0;
 var gIsTestFinished = false;
 
 
--- a/image/test/mochitest/test_animSVGImage2.html
+++ b/image/test/mochitest/test_animSVGImage2.html
@@ -1,38 +1,39 @@
 <!DOCTYPE HTML>
 <html>
 <!--
 https://bugzilla.mozilla.org/show_bug.cgi?id=907503
 -->
 <head>
   <title>Test for Bug 907503</title>
-  <script type="application/javascript" src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"></script>
-  <script type="application/javascript" src="chrome://mochikit/content/tests/SimpleTest/WindowSnapshot.js"></script>
+  <script type="application/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
+  <script type="application/javascript" src="/tests/SimpleTest/WindowSnapshot.js"></script>
   <script type="application/javascript" src="imgutils.js"></script>
-  <link rel="stylesheet" type="text/css" href="chrome://mochikit/content/tests/SimpleTest/test.css" />
+  <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
 </head>
 <body>
 <a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=907503">Mozilla Bug 907503</a>
 <p id="display"></p>
 <div id="content">
   <div id="referenceDiv" style="height: 100px; width: 100px;
                                 display: none; background: lime"></div>
   <img>
 </div>
 <pre id="test">
 <script type="application/javascript;version=1.8">
 /** Test for Bug 907503**/
 
+SimpleTest.requestFlakyTimeout("Early failure timeout");
 SimpleTest.waitForExplicitFinish();
 
 const FAILURE_TIMEOUT = 120000; // Fail early after 120 seconds (2 minutes)
 
-const Cc = Components.classes;
-const Ci = Components.interfaces;
+const Cc = SpecialPowers.Cc;
+const Ci = SpecialPowers.Ci;
 const gImg = document.getElementsByTagName("img")[0];
 
 var gMyDecoderObserver; // value will be set in main()
 var gReferenceSnapshot; // value will be set in takeReferenceSnapshot()
 var gOnFrameUpdateCounter = 0;
 var gIsTestFinished = false;
 
 
@@ -80,32 +81,32 @@ function failTest() {
 }
 
 function cleanUpAndFinish() {
   // On the off chance that failTest and myOnFrameUpdate are triggered
   // back-to-back, use a flag to prevent multiple calls to SimpleTest.finish.
   if (gIsTestFinished) {
     return;
   }
-  let imgLoadingContent = gImg.QueryInterface(Ci.nsIImageLoadingContent);
+  let imgLoadingContent = SpecialPowers.wrap(gImg).QueryInterface(Ci.nsIImageLoadingContent);
   imgLoadingContent.removeObserver(gMyDecoderObserver);
   SimpleTest.finish();
   gIsTestFinished = true;
 }
 
 function main() {
   takeReferenceSnapshot();
 
   // Create, customize & attach decoder observer
   observer = new ImageDecoderObserverStub();
   observer.frameUpdate = myOnFrameUpdate;
   gMyDecoderObserver =
     Cc["@mozilla.org/image/tools;1"].getService(Ci.imgITools)
-      .createScriptedObserver(observer);
-  let imgLoadingContent = gImg.QueryInterface(Ci.nsIImageLoadingContent);
+      .createScriptedObserver(SpecialPowers.wrapCallbackObject(observer));
+  let imgLoadingContent = SpecialPowers.wrap(gImg).QueryInterface(Ci.nsIImageLoadingContent);
   imgLoadingContent.addObserver(gMyDecoderObserver);
 
   // We want to test the cold loading behavior, so clear cache in case an
   // earlier test got our image in there already.
   clearAllImageCaches();
 
   // kick off image-loading! myOnFrameUpdate handles the rest.
   gImg.setAttribute("src", "lime-anim-100x100-2.svg");
--- a/image/test/mochitest/test_background_image_anim.html
+++ b/image/test/mochitest/test_background_image_anim.html
@@ -1,20 +1,20 @@
 <!DOCTYPE HTML>
 <html>
 <!--
 https://bugzilla.mozilla.org/show_bug.cgi?id=666446
 -->
 <head>
   <title>Test for Bug 666446 - Animated Background Images</title>
-  <script type="application/javascript" src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"></script>
-  <script type="application/javascript" src="chrome://mochikit/content/tests/SimpleTest/WindowSnapshot.js"></script>
+  <script type="application/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
+  <script type="application/javascript" src="/tests/SimpleTest/WindowSnapshot.js"></script>
   <script type="application/javascript" src="imgutils.js"></script>
   <script type="application/javascript" src="animationPolling.js"></script>
-  <link rel="stylesheet" type="text/css" href="chrome://mochikit/content/tests/SimpleTest/test.css" />
+  <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
 </head>
 <body>
 <a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=666446">
 Mozilla Bug 666446: lots of animated gifs swamp us with paint events
 </a>
 <p id="display"></p>
 <div id="content">
   <div id="referenceDiv" style="height: 140px; width: 140px;
--- a/image/test/mochitest/test_bug1132427.html
+++ b/image/test/mochitest/test_bug1132427.html
@@ -1,15 +1,15 @@
 <!DOCTYPE HTML>
 <html>
 <head>
   <title>Test for scrolling selection into view</title>
-  <script type="text/javascript" src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"></script>
-  <script type="text/javascript" src="chrome://mochikit/content/tests/SimpleTest/WindowSnapshot.js"></script>
-  <link rel="stylesheet" type="text/css" href="chrome://mochikit/content/tests/SimpleTest/test.css" />
+  <script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
+  <script type="text/javascript" src="/tests/SimpleTest/WindowSnapshot.js"></script>
+  <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
 </head>
 <body>
 
 <pre id="test">
 <script class="testbody" type="text/javascript">
 
 // We open a window which contains two copies of the same gif. One at a scaled size, one at the
 // natural image size. We rely on the bug only showing up in the scaled image. The gif has three
@@ -19,25 +19,25 @@
 // from the last frame to the first frame. We compare a middle pixel of the two images to make
 // sure that they are the same at 100ms for a second. If the bug appears then the middle pixel
 // on the scaled image will always be blue and so should not match the middle pixel on the
 // unscaled image which should be white two thirds of the time. If the timers fire at bad times
 // and only fire when both frames are displaying blue we won't be able to detect this bug and the
 // test will pass without testing anything important, but that's not a big deal. That should be
 // rare enough, and the next time the test is run will should do proper testing.
 
+SimpleTest.requestFlakyTimeout("Pre-existing timeouts when converting from mochitest-chrome");
 SimpleTest.waitForExplicitFinish();
 addLoadEvent(openWindow);
 
 var win = null;
 
 function openWindow() {
   win = window.open("bug1132427.html",
                 "", "scrollbars=yes,toolbar,menubar,width=600,height=800");
-  win.addEventListener("load", doTest, false);
   win.focus();
 }
 
 function doTest() {
   setTimeout(continueTest, 1000);
 }
 
 function checkPixel(canvas, context, x1, y1, x2, y2) {
@@ -48,29 +48,29 @@ function checkPixel(canvas, context, x1,
 }
 
 var iterationsLeft = 10;
 
 function continueTest() {
   // we need to drawWindow the chrome window so we can get a dump of the retained widget layers
   // if we have to repaint to fulfill this drawWindow request then it will be impossible to
   // observe the bug
-  var chromewin = win.QueryInterface(Components.interfaces.nsIInterfaceRequestor)
-                     .getInterface(Components.interfaces.nsIWebNavigation)
-                     .QueryInterface(Components.interfaces.nsIDocShellTreeItem)
+  var chromewin = SpecialPowers.wrap(win).QueryInterface(SpecialPowers.Ci.nsIInterfaceRequestor)
+                     .getInterface(SpecialPowers.Ci.nsIWebNavigation)
+                     .QueryInterface(SpecialPowers.Ci.nsIDocShellTreeItem)
                      .rootTreeItem
-                     .QueryInterface(Components.interfaces.nsIInterfaceRequestor)
-                     .getInterface(Components.interfaces.nsIDOMWindow);
+                     .QueryInterface(SpecialPowers.Ci.nsIInterfaceRequestor)
+                     .getInterface(SpecialPowers.Ci.nsIDOMWindow);
 
   var el = window.document.createElementNS("http://www.w3.org/1999/xhtml", "canvas");
   el.width = chromewin.innerWidth;
   el.height = chromewin.innerHeight;
   var ctx = el.getContext("2d");
   // pass the correct flags so we don't have to flush the retained layers
-  ctx.drawWindow(chromewin, 0, 0, chromewin.innerWidth, chromewin.innerHeight, "rgba(0,0,0,0)",
+  SpecialPowers.wrap(ctx).drawWindow(chromewin, 0, 0, chromewin.innerWidth, chromewin.innerHeight, "rgba(0,0,0,0)",
     ctx.DRAWWINDOW_USE_WIDGET_LAYERS | ctx.DRAWWINDOW_DRAW_VIEW | ctx.DRAWWINDOW_DRAW_CARET);
 
   var leftbox = win.document.getElementById("left").getBoundingClientRect();
   var rightbox = win.document.getElementById("right").getBoundingClientRect();
   // this is actually chrome on left and right, but in practice we have none so it doesn't matter
   var chromeleft = win.outerWidth - win.innerWidth;
   // this is actually chrome on top and bottom, but bottom chrome is usually small to none and we have
   // 100px to spare in hitting the middle of the image elements (they are 200x200)
--- a/image/test/mochitest/test_bullet_animation.html
+++ b/image/test/mochitest/test_bullet_animation.html
@@ -1,21 +1,20 @@
 <!DOCTYPE HTML>
 <html>
 <!--
 https://bugzilla.mozilla.org/show_bug.cgi?id=666446
 -->
 <head>
   <title>Test for Bug 666446 - Animated Bullets</title>
-  <script type="application/javascript" src="chrome://mochikit/content/MochiKit/packed.js"></script>
-  <script type="application/javascript" src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"></script>
-  <script type="application/javascript" src="chrome://mochikit/content/tests/SimpleTest/WindowSnapshot.js"></script>
+  <script type="application/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
+  <script type="application/javascript" src="/tests/SimpleTest/WindowSnapshot.js"></script>
   <script type="application/javascript" src="imgutils.js"></script>
   <script type="application/javascript" src="animationPolling.js"></script>
-  <link rel="stylesheet" type="text/css" href="chrome://mochikit/content/tests/SimpleTest/test.css" />
+  <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
 </head>
 <body>
 <a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=666446">
 Mozilla Bug 666446: lots of animated gifs swamp us with paint events
 </a>
 <p id="display"></p>
 
 <div id="content">
--- a/image/test/mochitest/test_changeOfSource.html
+++ b/image/test/mochitest/test_changeOfSource.html
@@ -1,21 +1,20 @@
 <!DOCTYPE HTML>
 <html>
 <!--
 https://bugzilla.mozilla.org/show_bug.cgi?id=666446
 -->
 <head>
   <title>Test for Bug 666446 - Change of Source (1st Version)</title>
-  <script type="application/javascript" src="chrome://mochikit/content/MochiKit/packed.js"></script>
-  <script type="application/javascript" src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"></script>
-  <script type="application/javascript" src="chrome://mochikit/content/tests/SimpleTest/WindowSnapshot.js"></script>
+  <script type="application/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
+  <script type="application/javascript" src="/tests/SimpleTest/WindowSnapshot.js"></script>
   <script type="application/javascript" src="imgutils.js"></script>
   <script type="application/javascript" src="animationPolling.js"></script>
-  <link rel="stylesheet" type="text/css" href="chrome://mochikit/content/tests/SimpleTest/test.css" />
+  <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
 </head>
 <body>
 <a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=666446">
 Mozilla Bug 666446: lots of animated gifs swamp us with paint events
 </a>
 <p id="display"></p>
 
 <div id="content">
--- a/image/test/mochitest/test_changeOfSource2.html
+++ b/image/test/mochitest/test_changeOfSource2.html
@@ -1,21 +1,20 @@
 <!DOCTYPE HTML>
 <html>
 <!--
 https://bugzilla.mozilla.org/show_bug.cgi?id=666446
 -->
 <head>
   <title>Test for Bug 691792 - Change of Source (2nd Version)</title>
-  <script type="application/javascript" src="chrome://mochikit/content/MochiKit/packed.js"></script>
-  <script type="application/javascript" src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"></script>
-  <script type="application/javascript" src="chrome://mochikit/content/tests/SimpleTest/WindowSnapshot.js"></script>
+  <script type="application/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
+  <script type="application/javascript" src="/tests/SimpleTest/WindowSnapshot.js"></script>
   <script type="application/javascript" src="imgutils.js"></script>
   <script type="application/javascript" src="animationPolling.js"></script>
-  <link rel="stylesheet" type="text/css" href="chrome://mochikit/content/tests/SimpleTest/test.css" />
+  <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
 </head>
 <body>
 <a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=691792">
 Mozilla Bug 691792: Change of src attribute for animated gifs no longer works as expected
 </a>
 <p id="display"></p>
 
 <div id="content">
--- a/image/test/mochitest/test_has_transparency.html
+++ b/image/test/mochitest/test_has_transparency.html
@@ -1,35 +1,36 @@
 <!DOCTYPE HTML>
 <html>
 <!--
 https://bugzilla.mozilla.org/show_bug.cgi?id=1089880
 -->
 <head>
   <title>Test for Bug 1089880</title>
-  <script type="application/javascript" src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"></script>
-  <script type="application/javascript" src="chrome://mochikit/content/tests/SimpleTest/WindowSnapshot.js"></script>
+  <script type="application/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
+  <script type="application/javascript" src="/tests/SimpleTest/WindowSnapshot.js"></script>
   <script type="application/javascript" src="imgutils.js"></script>
-  <link rel="stylesheet" type="text/css" href="chrome://mochikit/content/tests/SimpleTest/test.css" />
+  <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
 </head>
 <body>
 <a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=1089880">Mozilla Bug 1089880</a>
 <p id="display"></p>
 <div id="content">
 </div>
 <pre id="test">
 <script type="application/javascript;version=1.8">
 /** Test for Bug 1089880 **/
 
+SimpleTest.requestFlakyTimeout("Early failure timeout");
 SimpleTest.waitForExplicitFinish();
 
 const FAILURE_TIMEOUT = 120000; // Fail early after 120 seconds (2 minutes)
 
-const Cc = Components.classes;
-const Ci = Components.interfaces;
+const Cc = SpecialPowers.Cc;
+const Ci = SpecialPowers.Ci;
 const gContent = document.getElementById("content");
 
 var gCanvas;
 var gCanvasCtx;
 var gImg;
 var gMyDecoderObserver;
 var gIsTestFinished = false;
 var gFiles;
@@ -119,17 +120,17 @@ function failTest() {
   cleanUpAndFinish();
 }
 
 function cleanUpAndFinish() {
   if (gIsTestFinished) {
     return;
   }
   gIsTestFinished = true;
-  let imgLoadingContent = gImg.QueryInterface(Ci.nsIImageLoadingContent);
+  let imgLoadingContent = SpecialPowers.wrap(gImg).QueryInterface(Ci.nsIImageLoadingContent);
   imgLoadingContent.removeObserver(gMyDecoderObserver);
   SimpleTest.finish();
 }
 
 function main() {
   gFiles = testFiles();
   gCanvas = document.createElement('canvas');
   gCanvasCtx = gCanvas.getContext('2d');
@@ -138,18 +139,18 @@ function main() {
   gImg.onerror = onError;
 
   // Create, customize & attach decoder observer.
   observer = new ImageDecoderObserverStub();
   observer.hasTransparency = onHasTransparency;
   observer.decodeComplete = onDecodeComplete;
   gMyDecoderObserver =
     Cc["@mozilla.org/image/tools;1"].getService(Ci.imgITools)
-      .createScriptedObserver(observer);
-  let imgLoadingContent = gImg.QueryInterface(Ci.nsIImageLoadingContent);
+      .createScriptedObserver(SpecialPowers.wrapCallbackObject(observer));
+  let imgLoadingContent = SpecialPowers.wrap(gImg).QueryInterface(Ci.nsIImageLoadingContent);
   imgLoadingContent.addObserver(gMyDecoderObserver);
 
   // We want to test the cold loading behavior, so clear cache in case an
   // earlier test got our image in there already.
   clearAllImageCaches();
 
   // Load the first image.
   loadNext();
--- a/image/test/mochitest/test_net_failedtoprocess.html
+++ b/image/test/mochitest/test_net_failedtoprocess.html
@@ -1,52 +1,51 @@
 <!DOCTYPE HTML>
 <html>
 <!--
 Test that a image decoding error producs a net:failed-to-process-uri-content
 observer event with the nsIURI of the failed image as the subject
 -->
 <head>
   <title>Test for image net:failed-to-process-uri-content</title>
-  <script type="application/javascript" src="chrome://mochikit/content/MochiKit/packed.js"></script>
-  <script type="application/javascript" src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"></script>
-  <link rel="stylesheet" type="text/css" href="chrome://mochikit/content/tests/SimpleTest/test.css" />
+  <script type="application/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
+  <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
 </head>
 <body>
 <p id="display"></p>
 <pre id="test">
 </pre>
 <script type="application/javascript">
 
 SimpleTest.waitForExplicitFinish();
 
-const Ci = Components.interfaces;
-const Cc = Components.classes;
+const Ci = SpecialPowers.Ci;
+const Cc = SpecialPowers.Cc;
 var obs = Cc["@mozilla.org/observer-service;1"].getService();
 obs = obs.QueryInterface(Ci.nsIObserverService);
 
 var observer = {
   QueryInterface: function (aIID) {
     if (aIID.equals(Ci.nsISupports) ||
         aIID.equals(Ci.nsIObserver))
       return this;
     throw Cr.NS_ERROR_NO_INTERFACE;
   },
 
   observe: function(subject, topic, data) {
     ok(topic == "net:failed-to-process-uri-content", "wrong topic");
     subject = subject.QueryInterface(Ci.nsIURI);
-    ok(subject.asciiSpec == "chrome://mochitests/content/chrome/image/test/mochitest/invalid.jpg", "wrong subject");
+    is(subject.asciiSpec, "http://mochi.test:8888/tests/image/test/mochitest/invalid.jpg", "wrong subject");
 
     obs.removeObserver(this, "net:failed-to-process-uri-content");
 
     SimpleTest.finish();
   }
 };
 
-obs.addObserver(observer, "net:failed-to-process-uri-content", false);
+obs.addObserver(SpecialPowers.wrapCallbackObject(observer), "net:failed-to-process-uri-content", false);
 
 document.write('<img src="damon.jpg">');
 document.write('<img src="invalid.jpg">');
 
 </script>
 </body>
 </html>
--- a/image/test/mochitest/test_removal_ondecode.html
+++ b/image/test/mochitest/test_removal_ondecode.html
@@ -1,35 +1,36 @@
 <!DOCTYPE HTML>
 <html>
 <!--
 https://bugzilla.mozilla.org/show_bug.cgi?id=841579
 -->
 <head>
   <title>Test for Bug 841579</title>
-  <script type="application/javascript" src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"></script>
-  <script type="application/javascript" src="chrome://mochikit/content/tests/SimpleTest/WindowSnapshot.js"></script>
+  <script type="application/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
+  <script type="application/javascript" src="/tests/SimpleTest/WindowSnapshot.js"></script>
   <script type="application/javascript" src="imgutils.js"></script>
-  <link rel="stylesheet" type="text/css" href="chrome://mochikit/content/tests/SimpleTest/test.css" />
+  <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
 </head>
 <body>
 <a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=841579">Mozilla Bug 841579</a>
 <p id="display"></p>
 <div id="content">
 </div>
 <pre id="test">
 <script type="application/javascript;version=1.8">
 /** Test for Bug 841579**/
 
+SimpleTest.requestFlakyTimeout("Early failure timeout");
 SimpleTest.waitForExplicitFinish();
 
 const FAILURE_TIMEOUT = 120000; // Fail early after 120 seconds (2 minutes)
 
-const Cc = Components.classes;
-const Ci = Components.interfaces;
+const Cc = SpecialPowers.Cc;
+const Ci = SpecialPowers.Ci;
 const gContent = document.getElementById("content");
 
 var gImg;
 var gMyDecoderObserver;
 var gIsTestFinished = false;
 var gFiles;
 var gNotifications = 0;
 var gLoads = 0;
@@ -77,17 +78,17 @@ function onNotification()
 }
 
 function cleanUpAndFinish() {
   // On the off chance that failTest and myOnStopFrame are triggered
   // back-to-back, use a flag to prevent multiple calls to SimpleTest.finish.
   if (gIsTestFinished) {
     return;
   }
-  let imgLoadingContent = gImg.QueryInterface(Ci.nsIImageLoadingContent);
+  let imgLoadingContent = SpecialPowers.wrap(gImg).QueryInterface(Ci.nsIImageLoadingContent);
   imgLoadingContent.removeObserver(gMyDecoderObserver);
   // TODO - this isn't the case until post-bug 716140's refactorings
   // ok(gNotifications == gLoads, "Should be notified the same number of times as loads");
   SimpleTest.finish();
   gIsTestFinished = true;
 }
 
 function main() {
@@ -98,18 +99,18 @@ function main() {
 
   // Create, customize & attach decoder observer
   observer = new ImageDecoderObserverStub();
   observer.sizeAvailable = onSizeAvailable;
   observer.loadComplete = onLoadComplete;
   observer.decodeComplete = onDecodeComplete;
   gMyDecoderObserver =
     Cc["@mozilla.org/image/tools;1"].getService(Ci.imgITools)
-      .createScriptedObserver(observer);
-  let imgLoadingContent = gImg.QueryInterface(Ci.nsIImageLoadingContent);
+      .createScriptedObserver(SpecialPowers.wrapCallbackObject(observer));
+  let imgLoadingContent = SpecialPowers.wrap(gImg).QueryInterface(Ci.nsIImageLoadingContent);
   imgLoadingContent.addObserver(gMyDecoderObserver);
 
   // We want to test the cold loading behavior, so clear cache in case an
   // earlier test got our image in there already.
   clearAllImageCaches();
 
   // kick off image-loading! myOnStopFrame handles the rest.
   gImg.setAttribute("src", gFiles.next());
--- a/image/test/mochitest/test_removal_onload.html
+++ b/image/test/mochitest/test_removal_onload.html
@@ -1,35 +1,36 @@
 <!DOCTYPE HTML>
 <html>
 <!--
 https://bugzilla.mozilla.org/show_bug.cgi?id=841579
 -->
 <head>
   <title>Test for Bug 841579</title>
-  <script type="application/javascript" src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"></script>
-  <script type="application/javascript" src="chrome://mochikit/content/tests/SimpleTest/WindowSnapshot.js"></script>
+  <script type="application/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
+  <script type="application/javascript" src="/tests/SimpleTest/WindowSnapshot.js"></script>
   <script type="application/javascript" src="imgutils.js"></script>
-  <link rel="stylesheet" type="text/css" href="chrome://mochikit/content/tests/SimpleTest/test.css" />
+  <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
 </head>
 <body>
 <a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=841579">Mozilla Bug 841579</a>
 <p id="display"></p>
 <div id="content">
 </div>
 <pre id="test">
 <script type="application/javascript;version=1.8">
 /** Test for Bug 841579**/
 
+SimpleTest.requestFlakyTimeout("Early failure timeout");
 SimpleTest.waitForExplicitFinish();
 
 const FAILURE_TIMEOUT = 120000; // Fail early after 120 seconds (2 minutes)
 
-const Cc = Components.classes;
-const Ci = Components.interfaces;
+const Cc = SpecialPowers.Cc;
+const Ci = SpecialPowers.Ci;
 const gContent = document.getElementById("content");
 
 var gImg;
 var gMyDecoderObserver;
 var gIsTestFinished = false;
 var gFiles;
 var gNotifications = 0;
 var gLoads = 0;
@@ -77,17 +78,17 @@ function onNotification()
 }
 
 function cleanUpAndFinish() {
   // On the off chance that failTest and myOnStopFrame are triggered
   // back-to-back, use a flag to prevent multiple calls to SimpleTest.finish.
   if (gIsTestFinished) {
     return;
   }
-  let imgLoadingContent = gImg.QueryInterface(Ci.nsIImageLoadingContent);
+  let imgLoadingContent = SpecialPowers.wrap(gImg).QueryInterface(Ci.nsIImageLoadingContent);
   imgLoadingContent.removeObserver(gMyDecoderObserver);
   // TODO: this isn't the case until post-bug 716140's refactorings
   // ok(gNotifications == gLoads, "Should be notified the same number of times as loads");
   SimpleTest.finish();
   gIsTestFinished = true;
 }
 
 function main() {
@@ -98,18 +99,18 @@ function main() {
 
   // Create, customize & attach decoder observer
   observer = new ImageDecoderObserverStub();
   observer.sizeAvailable = onSizeAvailable;
   observer.loadComplete = onLoadComplete;
   observer.decodeComplete = onDecodeComplete;
   gMyDecoderObserver =
     Cc["@mozilla.org/image/tools;1"].getService(Ci.imgITools)
-      .createScriptedObserver(observer);
-  let imgLoadingContent = gImg.QueryInterface(Ci.nsIImageLoadingContent);
+      .createScriptedObserver(SpecialPowers.wrapCallbackObject(observer));
+  let imgLoadingContent = SpecialPowers.wrap(gImg).QueryInterface(Ci.nsIImageLoadingContent);
   imgLoadingContent.addObserver(gMyDecoderObserver);
 
   // We want to test the cold loading behavior, so clear cache in case an
   // earlier test got our image in there already.
   clearAllImageCaches();
 
   // kick off image-loading! myOnStopFrame handles the rest.
   gImg.setAttribute("src", gFiles.next());
--- a/image/test/mochitest/test_staticClone.html
+++ b/image/test/mochitest/test_staticClone.html
@@ -1,36 +1,36 @@
 <!DOCTYPE HTML>
 <html>
 <!--
 https://bugzilla.mozilla.org/show_bug.cgi?id=878037
 -->
 <head>
   <title>Test for Bug 878037</title>
-  <script type="application/javascript" src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"></script>
-  <link rel="stylesheet" type="text/css" href="chrome://mochikit/content/tests/SimpleTest/test.css"/>
+  <script type="application/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
+  <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css"/>
 </head>
 <body>
 <a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=878037">Mozilla Bug 878037</a>
 <p id="display"></p>
 <div>
   <!-- transparent-animation.gif from the gif reftests. -->
   <img id="animated" src="data:image/gif;base64,R0lGODlhZABkAIABAP8AAP///yH5BAkBAAEALAAAAABLAGQAAAK8jI+py+0Po5y02ouz3rz7D4biSJbmiabqyrbuC8fyTNf2jef6zvf+DwwKh8Si8YhMKpchgPMJjUqnVOipis1ir9qul+sNV8HistVkTj/JajG7/UXDy+95tm4fy/NdPF/q93dWIqgVWAhwWKgoyPjnyAeZJ2lHOWcJh9mmqcaZ5mkGSreHOCXqRloadRrGGkeoapoa6+TaN0tra4gbq3vHq+q7BVwqrMeEnKy8zNzs/AwdLT1NXW19jZ1tUgAAIfkECQEAAQAsAAAAADQAZAAAArCMj6nL7Q+jnLTai7PevPsPhuJIluaJpurKtu4Lx/JM1/aN5/rO9/7vAAiHxKLxiCRCkswmc+mMSqHSapJqzSof2u4Q67WCw1MuOTs+N9Pqq7kdZcON8vk2aF+/88g6358HaCc4Rwhn2IaopnjGSOYYBukl2UWpZYm2x0enuXnX4NnXGQqAKTYaalqlWoZH+snwWsQah+pJ64Sr5ypbCvQLHCw8TFxsfIycrLzM3PxQAAAh+QQJAQABACwAAAAAGwBkAAACUIyPqcvtD6OctNqLs968+w+G4kiW5omm6sq27gTE8kzX9o3n+s73/g8MCofEovGITCqXzKbzCY1Kp9Sq9YrNarfcrvdrfYnH5LL5jE6r16sCADs=">
 </div>
 <pre id="test">
 <script type="application/javascript">
 /** Test for Bug 878037**/
 
 SimpleTest.waitForExplicitFinish();
 
 window.onload = function() {
   var img = document.getElementById("animated");
-  var content =  img.QueryInterface(Components.interfaces.nsIImageLoadingContent);
+  var content =  SpecialPowers.wrap(img).QueryInterface(SpecialPowers.Ci.nsIImageLoadingContent);
 
-  var request = content.getRequest(Components.interfaces.nsIImageLoadingContent.CURRENT_REQUEST);
+  var request = content.getRequest(SpecialPowers.Ci.nsIImageLoadingContent.CURRENT_REQUEST);
 
   var staticReq = request.getStaticRequest();
   var clone = staticReq.clone(null);
 
   ok(true, "hooray, we didn't crash!");
 
   SimpleTest.finish();
 }
--- a/image/test/mochitest/test_svg_animatedGIF.html
+++ b/image/test/mochitest/test_svg_animatedGIF.html
@@ -1,20 +1,20 @@
 <!DOCTYPE HTML>
 <html>
 <!--
 https://bugzilla.mozilla.org/show_bug.cgi?id=666446
 -->
 <head>
   <title>Test for Bug 666446 - Animated Raster Images inside of SVG Frames</title>
-  <script type="application/javascript" src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"></script>
-  <script type="application/javascript" src="chrome://mochikit/content/tests/SimpleTest/WindowSnapshot.js"></script>
+  <script type="application/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
+  <script type="application/javascript" src="/tests/SimpleTest/WindowSnapshot.js"></script>
   <script type="application/javascript" src="imgutils.js"></script>
   <script type="application/javascript" src="animationPolling.js"></script>
-  <link rel="stylesheet" type="text/css" href="chrome://mochikit/content/tests/SimpleTest/test.css" />
+  <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
 </head>
 
 <!--  Make sure embed element is snapped to an exact pixel. -->
 <div class="bug-header" style="height: 100px;">
   <a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=666446">
   Mozilla Bug 666446: lots of animated gifs swamp us with paint events
   </a>
 </div>
--- a/image/test/mochitest/test_svg_filter_animation.html
+++ b/image/test/mochitest/test_svg_filter_animation.html
@@ -1,20 +1,20 @@
 <!DOCTYPE HTML>
 <html>
 <!--
 https://bugzilla.mozilla.org/show_bug.cgi?id=666446
 -->
 <head>
   <title>Test for Bug 666446 - Animated Images within SVG Filters</title>
-  <script type="application/javascript" src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"></script>
-  <script type="application/javascript" src="chrome://mochikit/content/tests/SimpleTest/WindowSnapshot.js"></script>
+  <script type="application/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
+  <script type="application/javascript" src="/tests/SimpleTest/WindowSnapshot.js"></script>
   <script type="application/javascript" src="imgutils.js"></script>
   <script type="application/javascript" src="animationPolling.js"></script>
-  <link rel="stylesheet" type="text/css" href="chrome://mochikit/content/tests/SimpleTest/test.css" />
+  <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
 </head>
 <body>
 <a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=666446">
 Mozilla Bug 666446: lots of animated gifs swamp us with paint events
 </a>
 <p id="display"></p>
 <div id="content">
   <embed id="referenceImage" src="filter-final.svg" type="image/svg+xml" style="display: none;"/>
--- a/image/test/mochitest/test_synchronized_animation.html
+++ b/image/test/mochitest/test_synchronized_animation.html
@@ -1,56 +1,56 @@
 <!DOCTYPE HTML>
 <html>
 <!--
 https://bugzilla.mozilla.org/show_bug.cgi?id=867758
 -->
 <head>
   <title>Test for Bug 867758</title>
-  <script type="application/javascript" src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"></script>
-  <script type="application/javascript" src="chrome://mochikit/content/tests/SimpleTest/WindowSnapshot.js"></script>
+  <script type="application/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
+  <script type="application/javascript" src="/tests/SimpleTest/WindowSnapshot.js"></script>
   <script type="application/javascript" src="imgutils.js"></script>
-  <link rel="stylesheet" type="text/css" href="chrome://mochikit/content/tests/SimpleTest/test.css" />
+  <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
 </head>
 <body>
 <a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=867758">Mozilla Bug 867758</a>
 <p id="display"></p>
 <div id="content">
 </div>
 <pre id="test">
 <script type="application/javascript;version=1.8">
 /** Test for Bug 867758**/
 
+SimpleTest.requestFlakyTimeout("Early failure timeout");
 SimpleTest.waitForExplicitFinish();
 
 const FAILURE_TIMEOUT = 120000; // Fail early after 120 seconds (2 minutes)
 
-const Cc = Components.classes;
-const Ci = Components.interfaces;
-const Cu = Components.utils;
+const Cc = SpecialPowers.Cc;
+const Ci = SpecialPowers.Ci;
 const gContent = document.getElementById("content");
 
 var gDispatched = false;
 var gRanEvent = false;
 var gObserver;
 var gImg1;
 var gImg2;
 var gFirstImageLoaded = false;
 var gOuter;
 var gFinished = false;
 var gFirstRequest = null;
 
 function cleanUpAndFinish() {
   if (gFinished) {
     return;
   }
-  var imgLoadingContent = gImg1.QueryInterface(Ci.nsIImageLoadingContent);
+  var imgLoadingContent = SpecialPowers.wrap(gImg1).QueryInterface(Ci.nsIImageLoadingContent);
   imgLoadingContent.removeObserver(gOuter);
 
-  imgLoadingContent = gImg2.QueryInterface(Ci.nsIImageLoadingContent);
+  imgLoadingContent = SpecialPowers.wrap(gImg2).QueryInterface(Ci.nsIImageLoadingContent);
   imgLoadingContent.removeObserver(gOuter);
 
   SimpleTest.finish();
 
   gFinished = true;
 }
 
 function frameUpdate(aRequest) {
@@ -74,17 +74,17 @@ function failTest() {
 function waitForLoadAndTest(image) {
   return () => {
     // Draw the image into a canvas to ensure it's decoded.
     var canvas = document.createElement('canvas');
     var context = canvas.getContext('2d');
     context.drawImage(image, 0, 0);
 
     // Attach the observer.
-    var imgLoadingContent = image.QueryInterface(Ci.nsIImageLoadingContent);
+    var imgLoadingContent = SpecialPowers.wrap(image).QueryInterface(Ci.nsIImageLoadingContent);
     imgLoadingContent.addObserver(gOuter);
 
     // If the other image already loaded, add both images to the document, which
     // begins the real test.
     if (gFirstImageLoaded) {
       gContent.appendChild(gImg1);
       gContent.appendChild(gImg2);
     } else {
@@ -96,17 +96,17 @@ function waitForLoadAndTest(image) {
 function main() {
   gImg1 = new Image();
   gImg2 = new Image();
 
   // Create and customize decoder observer
   var obs = new ImageDecoderObserverStub();
   obs.frameUpdate = frameUpdate;
 
-  gOuter = Cc["@mozilla.org/image/tools;1"].getService(Ci.imgITools).createScriptedObserver(obs);
+  gOuter = Cc["@mozilla.org/image/tools;1"].getService(Ci.imgITools).createScriptedObserver(SpecialPowers.wrapCallbackObject(obs));
 
   // We want to test the cold loading behavior, so clear cache in case an
   // earlier test got our image in there already.
   clearAllImageCaches();
 
   // These are two copies of the same image; hence, they have the same frame rate.
   gImg1.src = "animated1.gif";
   gImg2.src = "animated2.gif";
--- a/image/test/mochitest/test_xultree_animation.xhtml
+++ b/image/test/mochitest/test_xultree_animation.xhtml
@@ -3,21 +3,21 @@
 xmlns="http://www.w3.org/1999/xhtml"
       xmlns:xul="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"
       xml:lang="en" lang="en">
 <!--
 https://bugzilla.mozilla.org/show_bug.cgi?id=666446
 -->
 <head>
   <title>Test for Bug 666446 - Animated Images within SVG Filters</title>
-  <script type="application/javascript" src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"></script>
-  <script type="application/javascript" src="chrome://mochikit/content/tests/SimpleTest/WindowSnapshot.js"></script>
+  <script type="application/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
+  <script type="application/javascript" src="/tests/SimpleTest/WindowSnapshot.js"></script>
   <script type="application/javascript" src="imgutils.js"></script>
   <script type="application/javascript" src="animationPolling.js"></script>
-  <link rel="stylesheet" type="text/css" href="chrome://mochikit/content/tests/SimpleTest/test.css" />
+  <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
 </head>
 <body>
 <a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=666446">
 Mozilla Bug 666446: lots of animated gifs swamp us with paint events
 </a>
 <p id="display"></p>
 <div id="content">
   <xul:caption label="Bug 666446 - XULTree Test" />
--- a/ipc/app/plugin-container/Makefile.in
+++ b/ipc/app/plugin-container/Makefile.in
@@ -1,24 +1,32 @@
 # 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 MOZ_WINCONSOLE
+ifdef MOZ_DEBUG
+MOZ_WINCONSOLE = 1
+else
+MOZ_WINCONSOLE = 0
+endif
+endif
+
 # This switches $(INSTALL) to copy mode, like $(SYSINSTALL), so things that
 # # shouldn't get 755 perms need $(IFLAGS1) for either way of calling nsinstall.
 NSDISTMODE = copy
 
 include $(topsrcdir)/config/config.mk
 
 include $(topsrcdir)/config/rules.mk
 
 ifeq ($(OS_ARCH),WINNT) #{
 # Note the manifest file exists in the tree, so we use the explicit filename
 # here.
-EXTRA_DEPS += firefox-plugin-container.exe.manifest
+EXTRA_DEPS += plugin-container.exe.manifest
 endif #}
 
 ifeq (cocoa,$(MOZ_WIDGET_TOOLKIT)) #{
 
 libs::
 	$(NSINSTALL) -D $(DIST)/bin/$(PROGRAM).app
 	rsync -a -C --exclude '*.in' $(srcdir)/macbuild/Contents $(DIST)/bin/$(MOZ_PLUGIN_PROCESS_NAME).app 
 	sed -e 's/%PROGRAM%/$(MOZ_PLUGIN_PROCESS_NAME)/' $(srcdir)/macbuild/Contents/Info.plist.in > $(DIST)/bin/$(MOZ_PLUGIN_PROCESS_NAME).app/Contents/Info.plist
deleted file mode 100644
--- a/ipc/app/plugin-container/firefox-plugin-container.exe.manifest
+++ /dev/null
@@ -1,43 +0,0 @@
-<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
-<assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0">
-<assemblyIdentity
-        version="1.0.0.0"
-        processorArchitecture="*"
-        name="firefox-plugin-container"
-        type="win32"
-/>
-<description>Firefox Runtime</description>
-<dependency>
-        <dependentAssembly>
-                <assemblyIdentity
-                        type="win32"
-                        name="Microsoft.Windows.Common-Controls"
-                        version="6.0.0.0"
-                        processorArchitecture="*"
-                        publicKeyToken="6595b64144ccf1df"
-                        language="*"
-                />
-        </dependentAssembly>
-</dependency>
-  <ms_asmv3:trustInfo xmlns:ms_asmv3="urn:schemas-microsoft-com:asm.v3">
-    <ms_asmv3:security>
-      <ms_asmv3:requestedPrivileges>
-        <ms_asmv3:requestedExecutionLevel level="asInvoker" uiAccess="false" />
-      </ms_asmv3:requestedPrivileges>
-    </ms_asmv3:security>
-  </ms_asmv3:trustInfo>
-  <ms_asmv3:application xmlns:ms_asmv3="urn:schemas-microsoft-com:asm.v3">
-    <ms_asmv3:windowsSettings xmlns="http://schemas.microsoft.com/SMI/2005/WindowsSettings">
-      <dpiAware>True/PM</dpiAware>
-    </ms_asmv3:windowsSettings>
-  </ms_asmv3:application>
-  <compatibility xmlns="urn:schemas-microsoft-com:compatibility.v1">
-    <application>
-      <supportedOS Id="{8e0f7a12-bfb3-4fe8-b9a5-48fd50a15a9a}"/>
-      <supportedOS Id="{1f676c76-80e1-4239-95bb-83d0f6d0da78}"/>
-      <supportedOS Id="{4a2f28e3-53b9-4441-ba9c-d69d4a4a6e38}"/>
-      <supportedOS Id="{35138b9a-5d96-4fbd-8e2d-a2440225f93a}"/>
-      <supportedOS Id="{e2011457-1546-43c5-a5fe-008deee3d3f0}"/>
-    </application>
-  </compatibility>
-</assembly>
new file mode 100644
--- /dev/null
+++ b/ipc/app/plugin-container/plugin-container.exe.manifest
@@ -0,0 +1,43 @@
+<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
+<assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0">
+<assemblyIdentity
+        version="1.0.0.0"
+        processorArchitecture="*"
+        name="plugin-container"
+        type="win32"
+/>
+<description>Firefox Runtime</description>
+<dependency>
+        <dependentAssembly>
+                <assemblyIdentity
+                        type="win32"
+                        name="Microsoft.Windows.Common-Controls"
+                        version="6.0.0.0"
+                        processorArchitecture="*"
+                        publicKeyToken="6595b64144ccf1df"
+                        language="*"
+                />
+        </dependentAssembly>
+</dependency>
+  <ms_asmv3:trustInfo xmlns:ms_asmv3="urn:schemas-microsoft-com:asm.v3">
+    <ms_asmv3:security>
+      <ms_asmv3:requestedPrivileges>
+        <ms_asmv3:requestedExecutionLevel level="asInvoker" uiAccess="false" />
+      </ms_asmv3:requestedPrivileges>
+    </ms_asmv3:security>
+  </ms_asmv3:trustInfo>
+  <ms_asmv3:application xmlns:ms_asmv3="urn:schemas-microsoft-com:asm.v3">
+    <ms_asmv3:windowsSettings xmlns="http://schemas.microsoft.com/SMI/2005/WindowsSettings">
+      <dpiAware>True/PM</dpiAware>
+    </ms_asmv3:windowsSettings>
+  </ms_asmv3:application>
+  <compatibility xmlns="urn:schemas-microsoft-com:compatibility.v1">
+    <application>
+      <supportedOS Id="{8e0f7a12-bfb3-4fe8-b9a5-48fd50a15a9a}"/>
+      <supportedOS Id="{1f676c76-80e1-4239-95bb-83d0f6d0da78}"/>
+      <supportedOS Id="{4a2f28e3-53b9-4441-ba9c-d69d4a4a6e38}"/>
+      <supportedOS Id="{35138b9a-5d96-4fbd-8e2d-a2440225f93a}"/>
+      <supportedOS Id="{e2011457-1546-43c5-a5fe-008deee3d3f0}"/>
+    </application>
+  </compatibility>
+</assembly>
--- a/ipc/glue/GeckoChildProcessHost.cpp
+++ b/ipc/glue/GeckoChildProcessHost.cpp
@@ -138,17 +138,17 @@ GeckoChildProcessHost::~GeckoChildProces
 #if defined(MOZ_WIDGET_COCOA)
   if (mChildTask != MACH_PORT_NULL)
     mach_port_deallocate(mach_task_self(), mChildTask);
 #endif
 }
 
 //static
 void
-GeckoChildProcessHost::GetPathToBinary(FilePath& exePath)
+GeckoChildProcessHost::GetPathToBinary(FilePath& exePath, GeckoProcessType processType)
 {
   if (ShouldHaveDirectoryService()) {
     MOZ_ASSERT(gGREBinPath);
 #ifdef OS_WIN
     exePath = FilePath(char16ptr_t(gGREBinPath));
 #elif MOZ_WIDGET_COCOA
     nsCOMPtr<nsIFile> childProcPath;
     NS_NewLocalFile(nsDependentString(gGREBinPath), false,
@@ -182,18 +182,18 @@ GeckoChildProcessHost::GetPathToBinary(F
 
   // We must use the PIE binary on 5.0 and higher
   const char* processName = mozilla::AndroidBridge::Bridge()->GetAPIVersion() >= 21 ?
     MOZ_CHILD_PROCESS_NAME_PIE : MOZ_CHILD_PROCESS_NAME;
 
   exePath = exePath.AppendASCII(processName);
 #else
 #ifdef OS_WIN
-  if (XRE_GetProcessType() == GeckoProcessType_Plugin ||
-      XRE_GetProcessType() == GeckoProcessType_GMPlugin) {
+  if (processType == GeckoProcessType_Plugin ||
+      processType == GeckoProcessType_GMPlugin) {
     exePath = exePath.AppendASCII(MOZ_PLUGIN_PROCESS_NAME);
   } else
 #endif
     exePath = exePath.AppendASCII(MOZ_CHILD_PROCESS_NAME);
 #endif
 }
 
 #ifdef MOZ_WIDGET_COCOA
@@ -264,17 +264,17 @@ uint32_t GeckoChildProcessHost::GetSuppo
 {
 #ifdef MOZ_WIDGET_COCOA
   if (type == GeckoProcessType_Plugin) {
 
     // Cache this, it shouldn't ever change.
     static uint32_t pluginContainerArchs = 0;
     if (pluginContainerArchs == 0) {
       FilePath exePath;
-      GetPathToBinary(exePath);
+      GetPathToBinary(exePath, type);
       nsresult rv = GetArchitecturesForBinary(exePath.value().c_str(), &pluginContainerArchs);
       NS_ASSERTION(NS_SUCCEEDED(rv) && pluginContainerArchs != 0, "Getting architecture of plugin container failed!");
       if (NS_FAILED(rv) || pluginContainerArchs == 0) {
         pluginContainerArchs = base::GetCurrentProcessArchitecture();
       }
     }
     return pluginContainerArchs;
   }
@@ -757,17 +757,17 @@ GeckoChildProcessHost::PerformAsyncLaunc
     interpose.Append(path.get());
     interpose.AppendLiteral("/libplugin_child_interpose.dylib");
     newEnvVars["DYLD_INSERT_LIBRARIES"] = interpose.get();
 # endif  // OS_LINUX
   }
 #endif  // OS_LINUX || OS_MACOSX
 
   FilePath exePath;
-  GetPathToBinary(exePath);
+  GetPathToBinary(exePath, mProcessType);
 
 #ifdef MOZ_WIDGET_ANDROID
   // The java wrapper unpacks this for us but can't make it executable
   chmod(exePath.value().c_str(), 0700);
 #endif  // MOZ_WIDGET_ANDROID
 
 #ifdef ANDROID
   // Remap the Android property workspace to a well-known int,
@@ -936,17 +936,17 @@ GeckoChildProcessHost::PerformAsyncLaunc
                                      parent_send_port_memory, parent_send_port_memory_ack, false);
 
 #endif
 
 //--------------------------------------------------
 #elif defined(OS_WIN)
 
   FilePath exePath;
-  GetPathToBinary(exePath);
+  GetPathToBinary(exePath, mProcessType);
 
   CommandLine cmdLine(exePath.ToWStringHack());
   cmdLine.AppendSwitchWithValue(switches::kProcessChannelID, channel_id());
 
   for (std::vector<std::string>::iterator it = aExtraOpts.begin();
        it != aExtraOpts.end();
        ++it) {
       cmdLine.AppendLooseValue(UTF8ToWide(*it));
--- a/ipc/glue/GeckoChildProcessHost.h
+++ b/ipc/glue/GeckoChildProcessHost.h
@@ -184,17 +184,17 @@ private:
 
   // Does the actual work for AsyncLaunch, on the IO thread.
   bool PerformAsyncLaunchInternal(std::vector<std::string>& aExtraOpts,
                                   base::ProcessArchitecture arch);
 
   bool RunPerformAsyncLaunch(StringVector aExtraOpts=StringVector(),
 			     base::ProcessArchitecture aArch=base::GetCurrentProcessArchitecture());
 
-  static void GetPathToBinary(FilePath& exePath);
+  static void GetPathToBinary(FilePath& exePath, GeckoProcessType processType);
 
   void SetChildLogName(const char* varName, const char* origLogName);
 
   // In between launching the subprocess and handing off its IPC
   // channel, there's a small window of time in which *we* might still
   // be the channel listener, and receive messages.  That's bad
   // because we have no idea what to do with those messages.  So queue
   // them here until we hand off the eventual listener.
--- a/ipc/glue/MessageChannel.cpp
+++ b/ipc/glue/MessageChannel.cpp
@@ -1733,25 +1733,25 @@ MessageChannel::MaybeUndeferIncall()
 
     size_t stackDepth = InterruptStackDepth();
 
     // the other side can only *under*-estimate our actual stack depth
     IPC_ASSERT(mDeferred.top().interrupt_remote_stack_depth_guess() <= stackDepth,
                "fatal logic error");
 
     // maybe time to process this message
-    Message call = mDeferred.top();
+    Message call(Move(mDeferred.top()));
     mDeferred.pop();
 
     // fix up fudge factor we added to account for race
     IPC_ASSERT(0 < mRemoteStackDepthGuess, "fatal logic error");
     --mRemoteStackDepthGuess;
 
     MOZ_RELEASE_ASSERT(call.priority() == IPC::Message::PRIORITY_NORMAL);
-    mPending.push_back(call);
+    mPending.push_back(Move(call));
 }
 
 void
 MessageChannel::FlushPendingInterruptQueue()
 {
     AssertWorkerThread();
     mMonitor->AssertNotCurrentThreadOwns();
 
--- a/js/src/asmjs/WasmIonCompile.cpp
+++ b/js/src/asmjs/WasmIonCompile.cpp
@@ -44,28 +44,36 @@ class FunctionCompiler
           : ins(ins),
             index(index)
         {}
     };
 
     typedef Vector<ControlFlowPatch, 0, SystemAllocPolicy> ControlFlowPatchVector;
     typedef Vector<ControlFlowPatchVector, 0, SystemAllocPolicy> ControlFlowPatchsVector;
 
+  public:
+    class Call;
+
+  private:
+    typedef Vector<Call*, 0, SystemAllocPolicy> CallVector;
+
     ModuleGeneratorThreadView& mg_;
     Decoder&                   decoder_;
     const FuncBytes&           func_;
     const ValTypeVector&       locals_;
     size_t                     lastReadCallSite_;
 
     TempAllocator&             alloc_;
     MIRGraph&                  graph_;
     const CompileInfo&         info_;
     MIRGenerator&              mirGen_;
 
     MBasicBlock*               curBlock_;
+    CallVector                 callStack_;
+    uint32_t                   maxStackArgBytes_;
 
     uint32_t                   loopDepth_;
     uint32_t                   blockDepth_;
     ControlFlowPatchsVector    blockPatches_;
 
     FuncCompileResults&        compileResults_;
 
   public:
@@ -80,16 +88,17 @@ class FunctionCompiler
         func_(func),
         locals_(locals),
         lastReadCallSite_(0),
         alloc_(mirGen.alloc()),
         graph_(mirGen.graph()),
         info_(mirGen.info()),
         mirGen_(mirGen),
         curBlock_(nullptr),
+        maxStackArgBytes_(0),
         loopDepth_(0),
         blockDepth_(0),
         compileResults_(compileResults)
     {}
 
     ModuleGeneratorThreadView& mg() const    { return mg_; }
     TempAllocator&             alloc() const { return alloc_; }
     MacroAssembler&            masm() const  { return compileResults_.masm(); }
@@ -149,18 +158,21 @@ class FunctionCompiler
                 return false;
         }
 
         addInterruptCheck();
 
         return true;
     }
 
-    void checkPostconditions()
+    void finish()
     {
+        mirGen().initWasmMaxStackArgBytes(maxStackArgBytes_);
+
+        MOZ_ASSERT(callStack_.empty());
         MOZ_ASSERT(loopDepth_ == 0);
         MOZ_ASSERT(blockDepth_ == 0);
 #ifdef DEBUG
         for (ControlFlowPatchVector& patches : blockPatches_) {
             MOZ_ASSERT(patches.empty());
         }
 #endif
         MOZ_ASSERT(inDeadCode());
@@ -658,18 +670,18 @@ class FunctionCompiler
 
         if (inDeadCode())
             return;
 
         // WasmHandleExecutionInterrupt takes 0 arguments and the stack is
         // always ABIStackAlignment-aligned, but don't forget to account for
         // ShadowStackSpace and any other ABI warts.
         ABIArgGenerator abi;
-        if (abi.stackBytesConsumedSoFar() > mirGen_.maxAsmJSStackArgBytes())
-            mirGen_.setAsmJSMaxStackArgBytes(abi.stackBytesConsumedSoFar());
+
+        propagateMaxStackArgBytes(abi.stackBytesConsumedSoFar());
 
         CallSiteDesc callDesc(0, CallSiteDesc::Relative);
         curBlock_->add(MAsmJSInterruptCheck::New(alloc()));
     }
 
     MDefinition* extractSimdElement(SimdLane lane, MDefinition* base, MIRType type, SimdSign sign)
     {
         if (inDeadCode())
@@ -713,84 +725,91 @@ class FunctionCompiler
     // When this occurs childClobbers_ = true and the parent expression's
     // arguments are stored above the maximum depth clobbered by a child
     // expression.
 
     class Call
     {
         uint32_t lineOrBytecode_;
         ABIArgGenerator abi_;
-        uint32_t prevMaxStackBytes_;
         uint32_t maxChildStackBytes_;
         uint32_t spIncrement_;
         MAsmJSCall::Args regArgs_;
         Vector<MAsmJSPassStackArg*, 0, SystemAllocPolicy> stackArgs_;
         bool childClobbers_;
 
         friend class FunctionCompiler;
 
       public:
         Call(FunctionCompiler& f, uint32_t lineOrBytecode)
           : lineOrBytecode_(lineOrBytecode),
-            prevMaxStackBytes_(0),
             maxChildStackBytes_(0),
             spIncrement_(0),
             childClobbers_(false)
         { }
     };
 
-    void startCallArgs(Call* call)
+    bool startCallArgs(Call* call)
     {
-        if (inDeadCode())
-            return;
-        call->prevMaxStackBytes_ = mirGen().resetAsmJSMaxStackArgBytes();
+        // Always push calls to maintain the invariant that if we're inDeadCode
+        // in finishCallArgs, we have something to pop.
+        return callStack_.append(call);
     }
 
     bool passArg(MDefinition* argDef, ValType type, Call* call)
     {
         if (inDeadCode())
             return true;
 
-        uint32_t childStackBytes = mirGen().resetAsmJSMaxStackArgBytes();
-        call->maxChildStackBytes_ = Max(call->maxChildStackBytes_, childStackBytes);
-        if (childStackBytes > 0 && !call->stackArgs_.empty())
-            call->childClobbers_ = true;
-
         ABIArg arg = call->abi_.next(ToMIRType(type));
-        if (arg.kind() == ABIArg::Stack) {
-            MAsmJSPassStackArg* mir = MAsmJSPassStackArg::New(alloc(), arg.offsetFromArgBase(),
-                                                              argDef);
-            curBlock_->add(mir);
-            if (!call->stackArgs_.append(mir))
-                return false;
-        } else {
-            if (!call->regArgs_.append(MAsmJSCall::Arg(arg.reg(), argDef)))
-                return false;
+        if (arg.kind() != ABIArg::Stack)
+            return call->regArgs_.append(MAsmJSCall::Arg(arg.reg(), argDef));
+
+        auto* mir = MAsmJSPassStackArg::New(alloc(), arg.offsetFromArgBase(), argDef);
+        curBlock_->add(mir);
+        return call->stackArgs_.append(mir);
+    }
+
+    void propagateMaxStackArgBytes(uint32_t stackBytes)
+    {
+        if (callStack_.empty()) {
+            // Outermost call
+            maxStackArgBytes_ = Max(maxStackArgBytes_, stackBytes);
+            return;
         }
-        return true;
+
+        // Non-outermost call
+        Call* outer = callStack_.back();
+        outer->maxChildStackBytes_ = Max(outer->maxChildStackBytes_, stackBytes);
+        if (stackBytes && !outer->stackArgs_.empty())
+            outer->childClobbers_ = true;
     }
 
     void finishCallArgs(Call* call)
     {
-        if (inDeadCode())
+        MOZ_ALWAYS_TRUE(callStack_.popCopy() == call);
+
+        if (inDeadCode()) {
+            propagateMaxStackArgBytes(call->maxChildStackBytes_);
             return;
-        uint32_t parentStackBytes = call->abi_.stackBytesConsumedSoFar();
-        uint32_t newStackBytes;
+        }
+
+        uint32_t stackBytes = call->abi_.stackBytesConsumedSoFar();
+
         if (call->childClobbers_) {
             call->spIncrement_ = AlignBytes(call->maxChildStackBytes_, AsmJSStackAlignment);
-            for (unsigned i = 0; i < call->stackArgs_.length(); i++)
-                call->stackArgs_[i]->incrementOffset(call->spIncrement_);
-            newStackBytes = Max(call->prevMaxStackBytes_,
-                                call->spIncrement_ + parentStackBytes);
+            for (MAsmJSPassStackArg* stackArg : call->stackArgs_)
+                stackArg->incrementOffset(call->spIncrement_);
+            stackBytes += call->spIncrement_;
         } else {
             call->spIncrement_ = 0;
-            newStackBytes = Max(call->prevMaxStackBytes_,
-                                Max(call->maxChildStackBytes_, parentStackBytes));
+            stackBytes = Max(stackBytes, call->maxChildStackBytes_);
         }
-        mirGen_.setAsmJSMaxStackArgBytes(newStackBytes);
+
+        propagateMaxStackArgBytes(stackBytes);
     }
 
   private:
     bool callPrivate(MAsmJSCall::Callee callee, const Call& call, ExprType ret, MDefinition** def)
     {
         if (inDeadCode()) {
             *def = nullptr;
             return true;
@@ -890,25 +909,24 @@ class FunctionCompiler
     {
         if (inDeadCode())
             return;
         MAsmJSVoidReturn* ins = MAsmJSVoidReturn::New(alloc());
         curBlock_->end(ins);
         curBlock_ = nullptr;
     }
 
-    bool unreachableTrap()
+    void unreachableTrap()
     {
         if (inDeadCode())
-            return true;
+            return;
 
         auto* ins = MAsmThrowUnreachable::New(alloc());
         curBlock_->end(ins);
         curBlock_ = nullptr;
-        return true;
     }
 
     bool branchAndStartThen(MDefinition* cond, MBasicBlock** thenBlock, MBasicBlock** elseBlock)
     {
         if (inDeadCode())
             return true;
 
         bool hasThenBlock = *thenBlock != nullptr;
@@ -1122,16 +1140,17 @@ class FunctionCompiler
 
         uint32_t headerLabel = blockDepth_ - 1;
         uint32_t afterLabel = blockDepth_ - 2;
 
         if (!loopHeader) {
             MOZ_ASSERT(inDeadCode());
             MOZ_ASSERT(afterLabel >= blockPatches_.length() || blockPatches_[afterLabel].empty());
             MOZ_ASSERT(headerLabel >= blockPatches_.length() || blockPatches_[headerLabel].empty());
+            *loopResult = nullptr;
             blockDepth_ -= 2;
             loopDepth_--;
             return true;
         }
 
         // Expr::Loop doesn't have an implicit backedge so temporarily set
         // aside the end of the loop body to bind backedges.
         MBasicBlock* loopBody = curBlock_;
@@ -1674,17 +1693,18 @@ EmitAtomicsExchange(FunctionCompiler& f,
         return false;
     *def = f.atomicExchangeHeap(base, access, value);
     return true;
 }
 
 static bool
 EmitCallArgs(FunctionCompiler& f, const Sig& sig, FunctionCompiler::Call* call)
 {
-    f.startCallArgs(call);
+    if (!f.startCallArgs(call))
+        return false;
     for (ValType argType : sig.args()) {
         MDefinition* arg;
         if (!EmitExpr(f, &arg))
             return false;
         if (!f.passArg(arg, argType, call))
             return false;
     }
     f.finishCallArgs(call);
@@ -1745,17 +1765,18 @@ EmitCallImport(FunctionCompiler& f, uint
 static bool
 EmitF32MathBuiltinCall(FunctionCompiler& f, uint32_t callOffset, Expr f32, MDefinition** def)
 {
     MOZ_ASSERT(f32 == Expr::F32Ceil || f32 == Expr::F32Floor);
 
     uint32_t lineOrBytecode = f.readCallSiteLineOrBytecode(callOffset);
 
     FunctionCompiler::Call call(f, lineOrBytecode);
-    f.startCallArgs(&call);
+    if (!f.startCallArgs(&call))
+        return false;
 
     MDefinition* firstArg;
     if (!EmitExpr(f, &firstArg) || !f.passArg(firstArg, ValType::F32, &call))
         return false;
 
     f.finishCallArgs(&call);
 
     SymbolicAddress callee = f32 == Expr::F32Ceil ? SymbolicAddress::CeilF : SymbolicAddress::FloorF;
@@ -1763,17 +1784,18 @@ EmitF32MathBuiltinCall(FunctionCompiler&
 }
 
 static bool
 EmitF64MathBuiltinCall(FunctionCompiler& f, uint32_t callOffset, Expr f64, MDefinition** def)
 {
     uint32_t lineOrBytecode = f.readCallSiteLineOrBytecode(callOffset);
 
     FunctionCompiler::Call call(f, lineOrBytecode);
-    f.startCallArgs(&call);
+    if (!f.startCallArgs(&call))
+        return false;
 
     MDefinition* firstArg;
     if (!EmitExpr(f, &firstArg) || !f.passArg(firstArg, ValType::F64, &call))
         return false;
 
     if (f64 == Expr::F64Pow || f64 == Expr::F64Atan2) {
         MDefinition* secondArg;
         if (!EmitExpr(f, &secondArg) || !f.passArg(secondArg, ValType::F64, &call))
@@ -2669,17 +2691,18 @@ EmitReturn(FunctionCompiler& f, MDefinit
     *def = nullptr;
     return true;
 }
 
 static bool
 EmitUnreachable(FunctionCompiler& f, MDefinition** def)
 {
     *def = nullptr;
-    return f.unreachableTrap();
+    f.unreachableTrap();
+    return true;
 }
 
 static bool
 EmitBlock(FunctionCompiler& f, MDefinition** def)
 {
     if (!f.startBlock())
         return false;
     if (uint32_t numStmts = f.readVarU32()) {
@@ -3153,17 +3176,17 @@ wasm::IonCompileFunction(IonCompileTask*
                 return false;
         }
 
         if (IsVoid(f.sig().ret()))
             f.returnVoid();
         else
             f.returnExpr(last);
 
-        f.checkPostconditions();
+        f.finish();
     }
 
     // Compile MIR graph
     {
         jit::SpewBeginFunction(&mir, nullptr);
         jit::AutoSpewEndFunction spewEndFunction(&mir);
 
         if (!OptimizeMIR(&mir))
--- a/js/src/builtin/TestingFunctions.cpp
+++ b/js/src/builtin/TestingFunctions.cpp
@@ -555,16 +555,20 @@ WasmBinaryToText(JSContext* cx, unsigned
     CallArgs args = CallArgsFromVp(argc, vp);
 
     if (!args.get(0).isObject() || !args.get(0).toObject().is<TypedArrayObject>()) {
         JS_ReportErrorNumber(cx, GetErrorMessage, nullptr, JSMSG_WASM_BAD_BUF_ARG);
         return false;
     }
 
     Rooted<TypedArrayObject*> code(cx, &args[0].toObject().as<TypedArrayObject>());
+
+    if (!TypedArrayObject::ensureHasBuffer(cx, code))
+        return false;
+
     if (code->isSharedMemory()) {
         JS_ReportErrorNumber(cx, GetErrorMessage, nullptr, JSMSG_WASM_BAD_BUF_ARG);
         return false;
     }
 
     const uint8_t* bufferStart = code->bufferUnshared()->dataPointer();
     const uint8_t* bytes = bufferStart + code->byteOffset();
     uint32_t length = code->byteLength();
--- a/js/src/jit-test/tests/wasm/random-control-flow.js
+++ b/js/src/jit-test/tests/wasm/random-control-flow.js
@@ -28,8 +28,76 @@ wasmEvalText(`(module (func
       )
       (i32.const 2)
     )
     (i32.const 3)
     (i32.const 4)
   )
 ))
 `);
+
+wasmEvalText(`(module
+  (func (result i32) (param i32) (param i32) (i32.const 0))
+  (func (result i32)
+   (call 0 (i32.const 1) (call 0 (i32.const 2) (i32.const 3)))
+   (call 0 (trap) (i32.const 4))
+  )
+)`);
+
+wasmEvalText(`
+(module
+
+ (func
+  (param i32) (param i32) (param i32) (param i32)
+  (result i32)
+  (i32.const 0)
+ )
+
+ (func (result i32)
+  (call 0
+   (i32.const 42)
+   (i32.const 53)
+   (call 0 (i32.const 100) (i32.const 13) (i32.const 37) (i32.const 128))
+   (return (i32.const 42))
+  )
+ )
+
+ (export "" 1)
+)
+`)();
+
+wasmEvalText(`
+(module
+    (import "check" "one" (param i32))
+    (import "check" "two" (param i32) (param i32))
+    (func (param i32) (call_import 0 (get_local 0)))
+    (func (param i32) (param i32) (call_import 1 (get_local 0) (get_local 1)))
+    (func
+        (call 1
+            (i32.const 43)
+            (block $b
+                (if (i32.const 1)
+                    (call 0
+                        (block
+                            (call 0 (i32.const 42))
+                            (br $b (i32.const 10)))))
+                (i32.const 44))))
+    (export "foo" 2))
+`, {
+    check: {
+        one(x) {
+            assertEq(x, 42);
+        },
+        two(x, y) {
+            assertEq(x, 43);
+            assertEq(y, 10);
+        }
+    }
+}).foo();
+
+wasmEvalText(`(module (func
+ (return (i32.const 0))
+ (select
+  (loop (i32.const 1))
+  (loop (i32.const 2))
+  (i32.const 3)
+ )
+))`);
--- a/js/src/jit-test/tests/wasm/totext1.js
+++ b/js/src/jit-test/tests/wasm/totext1.js
@@ -1,13 +1,21 @@
 if (!wasmIsSupported())
      quit();
- 
+
 load(libdir + "asserts.js");
 
+var caught = false;
+try {
+    wasmBinaryToText(new Int8Array(1));
+} catch (e) {
+    caught = true;
+}
+assertEq(caught, true);
+
 function runTest(code) {
   var expected = wasmTextToBinary(code);
   var s = wasmBinaryToText(expected);
   print("TEXT: " + s);
   var roundtrip = wasmTextToBinary(s);
   assertDeepEq(expected, roundtrip);
 }
 
@@ -17,17 +25,17 @@ runTest(`
   (func (param i32) (result f64)
      (local $l f32)
      (block
         (set_local $l (f32.const 0.0))
         (loop $exit $cont
            (br_if $exit (get_local 0))
            (br 2)
         )
-        (if (i32.const 1) 
+        (if (i32.const 1)
            (f64.min (f64.neg (f64.const 1)) (f64.const 0))
            (f64.add (f64.const 0.5) (f64.load offset=0 (i32.const 0)) )
         )
      )
      (i32.store16 (i32.const 8) (i32.const 128))
 
      (return (f64.const 0))
   )
--- a/js/src/jit/IonAnalysis.cpp
+++ b/js/src/jit/IonAnalysis.cpp
@@ -2263,16 +2263,42 @@ CheckUse(const MDefinition* producer, co
     fprintf(stderr, "==Check Use\n");
     use->producer()->dump(stderr);
     fprintf(stderr, "  index: %" PRIuSIZE "\n", use->consumer()->indexOf(use));
     use->consumer()->dump(stderr);
     fprintf(stderr, "==End\n");
 #endif
     ++*usesBalance;
 }
+
+// To properly encode entry resume points, we have to ensure that all the
+// operands of the entry resume point are located before the safeInsertTop
+// location.
+static void
+AssertOperandsBeforeSafeInsertTop(MResumePoint* resume)
+{
+    MBasicBlock* block = resume->block();
+    if (block == block->graph().osrBlock())
+        return;
+    MInstruction* stop = block->safeInsertTop();
+    for (size_t i = 0, e = resume->numOperands(); i < e; ++i) {
+        MDefinition* def = resume->getOperand(i);
+        if (def->block() != block)
+            continue;
+        if (def->isPhi())
+            continue;
+
+        for (MInstructionIterator ins = block->begin(); true; ins++) {
+            if (*ins == def)
+                break;
+            MOZ_ASSERT(*ins != stop,
+                       "Resume point operand located after the safeInsertTop location");
+        }
+    }
+}
 #endif // DEBUG
 
 void
 jit::AssertBasicGraphCoherency(MIRGraph& graph)
 {
 #ifdef DEBUG
     MOZ_ASSERT(graph.entryBlock()->numPredecessors() == 0);
     MOZ_ASSERT(graph.entryBlock()->phisEmpty());
@@ -2300,23 +2326,24 @@ jit::AssertBasicGraphCoherency(MIRGraph&
                       block->entryResumePoint() != nullptr);
 
         for (size_t i = 0; i < block->numSuccessors(); i++)
             MOZ_ASSERT(CheckSuccessorImpliesPredecessor(*block, block->getSuccessor(i)));
 
         for (size_t i = 0; i < block->numPredecessors(); i++)
             MOZ_ASSERT(CheckPredecessorImpliesSuccessor(*block, block->getPredecessor(i)));
 
-        if (block->entryResumePoint()) {
-            MOZ_ASSERT(!block->entryResumePoint()->instruction());
-            MOZ_ASSERT(block->entryResumePoint()->block() == *block);
+        if (MResumePoint* resume = block->entryResumePoint()) {
+            MOZ_ASSERT(!resume->instruction());
+            MOZ_ASSERT(resume->block() == *block);
+            AssertOperandsBeforeSafeInsertTop(resume);
         }
-        if (block->outerResumePoint()) {
-            MOZ_ASSERT(!block->outerResumePoint()->instruction());
-            MOZ_ASSERT(block->outerResumePoint()->block() == *block);
+        if (MResumePoint* resume = block->outerResumePoint()) {
+            MOZ_ASSERT(!resume->instruction());
+            MOZ_ASSERT(resume->block() == *block);
         }
         for (MResumePointIterator iter(block->resumePointsBegin()); iter != block->resumePointsEnd(); iter++) {
             // We cannot yet assert that is there is no instruction then this is
             // the entry resume point because we are still storing resume points
             // in the InlinePropertyTable.
             MOZ_ASSERT_IF(iter->instruction(), iter->instruction()->block() == *block);
             for (uint32_t i = 0, e = iter->numOperands(); i < e; i++)
                 CheckOperand(*iter, iter->getUseFor(i), &usesBalance);
--- a/js/src/jit/MIRGenerator.h
+++ b/js/src/jit/MIRGenerator.h
@@ -130,29 +130,24 @@ class MIRGenerator
     AbortReason abortReason() {
         return abortReason_;
     }
 
     bool compilingAsmJS() const {
         return info_->compilingAsmJS();
     }
 
-    uint32_t maxAsmJSStackArgBytes() const {
-        MOZ_ASSERT(compilingAsmJS());
-        return maxAsmJSStackArgBytes_;
-    }
-    uint32_t resetAsmJSMaxStackArgBytes() {
+    uint32_t wasmMaxStackArgBytes() const {
         MOZ_ASSERT(compilingAsmJS());
-        uint32_t old = maxAsmJSStackArgBytes_;
-        maxAsmJSStackArgBytes_ = 0;
-        return old;
+        return wasmMaxStackArgBytes_;
     }
-    void setAsmJSMaxStackArgBytes(uint32_t n) {
+    void initWasmMaxStackArgBytes(uint32_t n) {
         MOZ_ASSERT(compilingAsmJS());
-        maxAsmJSStackArgBytes_ = n;
+        MOZ_ASSERT(wasmMaxStackArgBytes_ == 0);
+        wasmMaxStackArgBytes_ = n;
     }
     uint32_t minAsmJSHeapLength() const {
         return minAsmJSHeapLength_;
     }
     void setPerformsCall() {
         performsCall_ = true;
     }
     bool performsCall() const {
@@ -184,17 +179,17 @@ class MIRGenerator
     MIRGraph* graph_;
     AbortReason abortReason_;
     bool shouldForceAbort_; // Force AbortReason_Disable
     ObjectGroupVector abortedPreliminaryGroups_;
     bool error_;
     mozilla::Atomic<bool, mozilla::Relaxed>* pauseBuild_;
     mozilla::Atomic<bool, mozilla::Relaxed> cancelBuild_;
 
-    uint32_t maxAsmJSStackArgBytes_;
+    uint32_t wasmMaxStackArgBytes_;
     bool performsCall_;
     bool usesSimd_;
     bool usesSimdCached_;
 
     // Keep track of whether frame arguments are modified during execution.
     // RegAlloc needs to know this as spilling values back to their register
     // slots is not compatible with that.
     bool modifiesFrameArguments_;
--- a/js/src/jit/MIRGraph.cpp
+++ b/js/src/jit/MIRGraph.cpp
@@ -26,17 +26,17 @@ MIRGenerator::MIRGenerator(CompileCompar
     alloc_(alloc),
     graph_(graph),
     abortReason_(AbortReason_NoAbort),
     shouldForceAbort_(false),
     abortedPreliminaryGroups_(*alloc_),
     error_(false),
     pauseBuild_(nullptr),
     cancelBuild_(false),
-    maxAsmJSStackArgBytes_(0),
+    wasmMaxStackArgBytes_(0),
     performsCall_(false),
     usesSimd_(false),
     usesSimdCached_(false),
     modifiesFrameArguments_(false),
     instrumentedProfiling_(false),
     instrumentedProfilingIsCached_(false),
     safeForMinorGC_(true),
 #if defined(ASMJS_MAY_USE_SIGNAL_HANDLERS_FOR_OOB)
@@ -907,25 +907,29 @@ MBasicBlock::moveBefore(MInstruction* at
     ins->setBlock(at->block());
     at->block()->instructions_.insertBefore(at, ins);
     ins->setTrackedSite(at->trackedSite());
 }
 
 MInstruction*
 MBasicBlock::safeInsertTop(MDefinition* ins, IgnoreTop ignore)
 {
+    MOZ_ASSERT(graph().osrBlock() != this,
+               "We are not supposed to add any instruction in OSR blocks.");
+
     // Beta nodes and interrupt checks are required to be located at the
     // beginnings of basic blocks, so we must insert new instructions after any
     // such instructions.
     MInstructionIterator insertIter = !ins || ins->isPhi()
                                     ? begin()
                                     : begin(ins->toInstruction());
     while (insertIter->isBeta() ||
            insertIter->isInterruptCheck() ||
            insertIter->isConstant() ||
+           insertIter->isParameter() ||
            (!(ignore & IgnoreRecover) && insertIter->isRecoveredOnBailout()))
     {
         insertIter++;
     }
 
     return *insertIter;
 }
 
--- a/js/src/jit/RangeAnalysis.cpp
+++ b/js/src/jit/RangeAnalysis.cpp
@@ -2359,17 +2359,21 @@ RangeAnalysis::addRangeAssertions()
 
             if (!alloc().ensureBallast())
                 return false;
             MAssertRange* guard = MAssertRange::New(alloc(), ins, new(alloc()) Range(r));
 
             // Beta nodes and interrupt checks are required to be located at the
             // beginnings of basic blocks, so we must insert range assertions
             // after any such instructions.
-            MInstruction* insertAt = block->safeInsertTop(ins);
+            MInstruction* insertAt = nullptr;
+            if (block->graph().osrBlock() == block)
+                insertAt = ins->toInstruction();
+            else
+                insertAt = block->safeInsertTop(ins);
 
             if (insertAt == *iter)
                 block->insertAfter(insertAt,  guard);
             else
                 block->insertBefore(insertAt, guard);
         }
     }
 
--- a/js/src/jit/shared/CodeGenerator-shared.cpp
+++ b/js/src/jit/shared/CodeGenerator-shared.cpp
@@ -78,17 +78,17 @@ CodeGeneratorShared::CodeGeneratorShared
     if (gen->isProfilerInstrumentationEnabled())
         masm.enableProfilingInstrumentation();
 
     if (gen->compilingAsmJS()) {
         // Since asm.js uses the system ABI which does not necessarily use a
         // regular array where all slots are sizeof(Value), it maintains the max
         // argument stack depth separately.
         MOZ_ASSERT(graph->argumentSlotCount() == 0);
-        frameDepth_ += gen->maxAsmJSStackArgBytes();
+        frameDepth_ += gen->wasmMaxStackArgBytes();
 
         if (gen->usesSimd()) {
             // If the function uses any SIMD then we may need to insert padding
             // so that local slots are aligned for SIMD.
             frameInitialAdjustment_ = ComputeByteAlignment(sizeof(AsmJSFrame),
                                                            AsmJSStackAlignment);
             frameDepth_ += frameInitialAdjustment_;
             // Keep the stack aligned. Some SIMD sequences build values on the
--- a/js/src/js-config.in
+++ b/js/src/js-config.in
@@ -103,14 +103,14 @@ if test "$echo_includedir" = "yes"; then
     echo $includedir
 fi
 
 if test "$echo_libdir" = "yes"; then
     echo $libdir
 fi
 
 if test "$echo_cflags" = "yes"; then
-    echo "-std=gnu++0x -include $includedir/$JS_LIBRARY_NAME/js/RequiredDefines.h -I$includedir/$JS_LIBRARY_NAME $NSPR_CFLAGS"
+    echo "-std=gnu++11 -include $includedir/$JS_LIBRARY_NAME/js/RequiredDefines.h -I$includedir/$JS_LIBRARY_NAME $NSPR_CFLAGS"
 fi
 
 if test "$echo_libs" = "yes"; then
     echo "$MOZ_JS_LIBS $JS_CONFIG_LIBS"
 fi
--- a/js/src/old-configure.in
+++ b/js/src/old-configure.in
@@ -141,28 +141,19 @@ else
     MOZ_PATH_PROGS(AS, $AS as, $CC)
     AC_CHECK_PROGS(AR, ar, :)
     AC_CHECK_PROGS(LD, ld, :)
     AC_CHECK_PROGS(STRIP, strip, :)
     AC_CHECK_PROGS(WINDRES, windres, :)
     if test -z "$HOST_CC"; then
         HOST_CC='$(CC)'
     fi
-    if test -z "$HOST_CFLAGS"; then
-        HOST_CFLAGS='$(CFLAGS)'
-    fi
     if test -z "$HOST_CXX"; then
         HOST_CXX='$(CXX)'
     fi
-    if test -z "$HOST_CXXFLAGS"; then
-        HOST_CXXFLAGS='$(CXXFLAGS)'
-    fi
-    if test -z "$HOST_LDFLAGS"; then
-        HOST_LDFLAGS='$(LDFLAGS)'
-    fi
     if test -z "$HOST_RANLIB"; then
         HOST_RANLIB='$(RANLIB)'
     fi
     if test -z "$HOST_AR"; then
         HOST_AR='$(AR)'
     fi
     if test -z "$HOST_AR_FLAGS"; then
         HOST_AR_FLAGS='$(AR_FLAGS)'
@@ -400,38 +391,34 @@ fi
 AC_SUBST(QEMU_CANT_RUN_JS_SHELL)
 
 AC_SUBST(_MSC_VER)
 
 AC_SUBST(GNU_AS)
 AC_SUBST(GNU_LD)
 AC_SUBST(GNU_CC)
 AC_SUBST(GNU_CXX)
-AC_SUBST(INTEL_CC)
-AC_SUBST(INTEL_CXX)
 
 dnl ========================================================
 dnl Checks for programs.
 dnl ========================================================
 if test -z "$COMPILE_ENVIRONMENT"; then
     NSINSTALL_BIN='$(PYTHON) $(topsrcdir)/config/nsinstall.py'
 fi
 AC_SUBST(NSINSTALL_BIN)
 
 if test "$COMPILE_ENVIRONMENT"; then
 
 dnl ========================================================
 dnl = Mac OS X toolchain support
 dnl ========================================================
 
 dnl The universal machinery sets UNIVERSAL_BINARY to inform packager.mk
-dnl that a universal binary is being produced and MOZ_CAN_RUN_PROGRAMS
-dnl when we can run target binaries.
+dnl that a universal binary is being produced.
 AC_SUBST(UNIVERSAL_BINARY)
-AC_SUBST(MOZ_CAN_RUN_PROGRAMS)
 
 dnl ========================================================
 dnl Check for MacOS deployment target version
 dnl ========================================================
 
 MOZ_ARG_ENABLE_STRING(macos-target,
                       [  --enable-macos-target=VER (default=10.6)
                           Set the minimum MacOS version needed at runtime],
@@ -579,19 +566,17 @@ AC_SUBST(MOZJS_MINOR_VERSION)
 AC_SUBST(MOZJS_PATCH_VERSION)
 AC_SUBST(MOZJS_ALPHA)
 
 
 dnl ========================================================
 dnl set the defaults first
 dnl ========================================================
 AS_BIN=$AS
-AR_LIST='$(AR) t'
 AR_EXTRACT='$(AR) x'
-AR_DELETE='$(AR) d'
 AS='$(CC)'
 AS_DASH_C_FLAG='-c'
 DLL_PREFIX=lib
 LIB_PREFIX=lib
 DLL_SUFFIX=.so
 OBJ_SUFFIX=o
 LIB_SUFFIX=a
 IMPORT_LIB_SUFFIX=
@@ -728,24 +713,18 @@ MOZ_ARG_ENABLE_BOOL(warnings-as-errors,
                           Enable treating warnings as errors],
     MOZ_ENABLE_WARNINGS_AS_ERRORS=1,
     MOZ_ENABLE_WARNINGS_AS_ERRORS=)
 
 dnl ========================================================
 dnl GNU specific defaults
 dnl ========================================================
 if test "$GNU_CC"; then
-    # Per bug 719659 comment 2, some of the headers on ancient build machines
-    # may require gnu89 inline semantics.  But otherwise, we use C99.
-    # But on OS X we just use C99 plus GNU extensions, in order to fix
-    # bug 917526.
+    # We use C99.
     CFLAGS="$CFLAGS -std=gnu99"
-    if test "${OS_ARCH}" != Darwin; then
-        CFLAGS="$CFLAGS -fgnu89-inline"
-    fi
     MKSHLIB='$(CXX) $(CXXFLAGS) $(DSO_PIC_CFLAGS) $(DSO_LDOPTS) -Wl,-h,$(DSO_SONAME) -o $@'
     MKCSHLIB='$(CC) $(CFLAGS) $(DSO_PIC_CFLAGS) $(DSO_LDOPTS) -Wl,-h,$(DSO_SONAME) -o $@'
     DSO_LDOPTS='-shared'
     if test "$GCC_USE_GNU_LD"; then
         # Some tools like ASan use a runtime library that is only
         # linked against executables, so we must allow undefined
         # symbols for shared objects in some cases.
         if test -z "$MOZ_NO_WLZDEFS"; then
@@ -1151,19 +1130,17 @@ case "$target" in
         dnl but we work around it here.
         PROFILE_USE_CFLAGS="-GL -wd4624 -wd4952"
         dnl XXX: should be -LTCG:PGOPTIMIZE, but that fails on libxul.
         dnl Probably also a compiler bug, but what can you do?
         PROFILE_USE_LDFLAGS="-LTCG:PGUPDATE"
         LDFLAGS="$LDFLAGS -DYNAMICBASE"
         RCFLAGS="-nologo"
     fi
-    AC_DEFINE(HAVE_SNPRINTF)
     AC_DEFINE(HAVE__MSIZE)
-    AC_DEFINE(HW_THREADS)
     AC_DEFINE(STDC_HEADERS)
     AC_DEFINE(WIN32_LEAN_AND_MEAN)
     BIN_SUFFIX='.exe'
     MOZ_USER_DIR="Mozilla"
 
     case "$host_os" in
     cygwin*|msvc*|mks*)
         AC_MSG_ERROR([Using a Cygwin build environment is unsupported. Configure cannot check for presence of necessary headers. Please upgrade to MozillaBuild; see https://developer.mozilla.org/en/Windows_Build_Prerequisites.])
@@ -1891,35 +1868,16 @@ dnl =
 dnl = Application
 dnl =
 dnl ========================================================
 
 MOZ_ARG_HEADER(Application)
 
 ENABLE_TESTS=1
 
-USE_ARM_KUSER=
-
-case "${target}" in
-    arm*-android*|arm*-linuxandroid*)
-        USE_ARM_KUSER=1
-        ;;
-esac
-
-dnl ========================================================
-dnl Use ARM userspace kernel helpers; tell NSPR to enable
-dnl their usage and use them in spidermonkey.
-dnl ========================================================
-MOZ_ARG_WITH_BOOL(arm-kuser,
-[  --with-arm-kuser         Use kuser helpers (Linux/ARM only -- requires kernel 2.6.13 or later)],
-    USE_ARM_KUSER=1,)
-if test -n "$USE_ARM_KUSER"; then
-   AC_DEFINE(USE_ARM_KUSER)
-fi
-
 dnl ========================================================
 dnl =
 dnl = Components & Features
 dnl =
 dnl ========================================================
 MOZ_ARG_HEADER(Components and Features)
 
 dnl ========================================================
@@ -2607,19 +2565,17 @@ AC_SUBST(CROSS_LIB)
 dnl ========================================================
 dnl =
 dnl = Maintainer debug option (no --enable equivalent)
 dnl =
 dnl ========================================================
 
 AC_SUBST(AR)
 AC_SUBST(AR_FLAGS)
-AC_SUBST(AR_LIST)
 AC_SUBST(AR_EXTRACT)
-AC_SUBST(AR_DELETE)
 AC_SUBST(AS)
 AC_SUBST(ASFLAGS)
 AC_SUBST(AS_DASH_C_FLAG)
 AC_SUBST(LD)
 AC_SUBST(RC)
 AC_SUBST(RCFLAGS)
 AC_SUBST(MC)
 AC_SUBST(WINDRES)
--- a/js/xpconnect/tests/chrome/chrome.ini
+++ b/js/xpconnect/tests/chrome/chrome.ini
@@ -7,16 +7,33 @@ support-files =
   file_bug1050049.xml
   file_discardSystemSource.html
   worker_discardSystemSource.js
   file_evalInSandbox.html
   file_expandosharing.jsm
   outoflinexulscript.js
   subscript.js
   utf8_subscript.js
+  !/js/xpconnect/tests/mochitest/bug500931_helper.html
+  !/js/xpconnect/tests/mochitest/bug571849_helper.html
+  !/js/xpconnect/tests/mochitest/chrome_wrappers_helper.html
+  !/js/xpconnect/tests/mochitest/file_bug706301.html
+  !/js/xpconnect/tests/mochitest/file_bug738244.html
+  !/js/xpconnect/tests/mochitest/file_bug760131.html
+  !/js/xpconnect/tests/mochitest/file_bug795275.html
+  !/js/xpconnect/tests/mochitest/file_bug795275.xml
+  !/js/xpconnect/tests/mochitest/file_bug799348.html
+  !/js/xpconnect/tests/mochitest/file_bug860494.html
+  !/js/xpconnect/tests/mochitest/file_documentdomain.html
+  !/js/xpconnect/tests/mochitest/file_doublewrappedcompartments.html
+  !/js/xpconnect/tests/mochitest/file_empty.html
+  !/js/xpconnect/tests/mochitest/file_exnstack.html
+  !/js/xpconnect/tests/mochitest/file_expandosharing.html
+  !/js/xpconnect/tests/mochitest/file_nodelists.html
+  !/js/xpconnect/tests/mochitest/file_evalInSandbox.html
 
 [test_APIExposer.xul]
 [test_bug361111.xul]
 [test_bug448587.xul]
 [test_bug484459.xul]
 skip-if = os == 'win' || os == 'mac' # bug 1131110
 [test_bug500931.xul]
 [test_bug503926.xul]
--- a/layout/base/nsDocumentViewer.cpp
+++ b/layout/base/nsDocumentViewer.cpp
@@ -2447,68 +2447,50 @@ nsDocumentViewer::DetachFromTopLevelWidg
     }
   }
   mAttachedToParent = false;
 }
 
 nsView*
 nsDocumentViewer::FindContainerView()
 {
-  nsView* containerView = nullptr;
-
-  if (mContainer) {
-    nsCOMPtr<nsIDocShell> docShell(mContainer);
-    nsCOMPtr<nsPIDOMWindowOuter> pwin(docShell->GetWindow());
-    if (pwin) {
-      nsCOMPtr<Element> containerElement = pwin->GetFrameElementInternal();
-      if (!containerElement) {
-        return nullptr;
-      }
-
-      nsCOMPtr<nsIPresShell> parentPresShell;
-      nsCOMPtr<nsIDocument> parentDoc = containerElement->GetCurrentDoc();
-      if (parentDoc) {
-        parentPresShell = parentDoc->GetShell();
-      }
-
-      if (!parentPresShell) {
-        nsCOMPtr<nsIDocShellTreeItem> parentDocShellItem;
-        docShell->GetParent(getter_AddRefs(parentDocShellItem));
-        if (parentDocShellItem) {
-          nsCOMPtr<nsIDocShell> parentDocShell = do_QueryInterface(parentDocShellItem);
-          parentPresShell = parentDocShell->GetPresShell();
-        }
-      }
-      if (!parentPresShell) {
-        NS_WARNING("Subdocument container has no presshell");
-      } else {
-        nsIFrame* subdocFrame = parentPresShell->GetRealPrimaryFrameFor(containerElement);
-        if (subdocFrame) {
-          // subdocFrame might not be a subdocument frame; the frame
-          // constructor can treat a <frame> as an inline in some XBL
-          // cases. Treat that as display:none, the document is not
-          // displayed.
-          if (subdocFrame->GetType() == nsGkAtoms::subDocumentFrame) {
-            NS_ASSERTION(subdocFrame->GetView(), "Subdoc frames must have views");
-            nsView* innerView =
-              static_cast<nsSubDocumentFrame*>(subdocFrame)->EnsureInnerView();
-            containerView = innerView;
-          } else {
-            NS_WARN_IF_FALSE(!subdocFrame->GetType(),
-                             "Subdocument container has non-subdocument frame");
-          }
-        } else {
-          // XXX Silenced by default in bug 1175289
-          LAYOUT_WARNING("Subdocument container has no frame");
-        }
-      }
-    }
+  if (!mContainer) {
+    return nullptr;
+  }
+
+  nsCOMPtr<nsIDocShell> docShell(mContainer);
+  nsCOMPtr<nsPIDOMWindowOuter> pwin(docShell->GetWindow());
+  if (!pwin) {
+    return nullptr;
+  }
+
+  nsCOMPtr<Element> containerElement = pwin->GetFrameElementInternal();
+  if (!containerElement) {
+    return nullptr;
   }
 
-  return containerView;
+  nsIFrame* subdocFrame = nsLayoutUtils::GetRealPrimaryFrameFor(containerElement);
+  if (!subdocFrame) {
+    // XXX Silenced by default in bug 1175289
+    LAYOUT_WARNING("Subdocument container has no frame");
+    return nullptr;
+  }
+
+  // subdocFrame might not be a subdocument frame; the frame
+  // constructor can treat a <frame> as an inline in some XBL
+  // cases. Treat that as display:none, the document is not
+  // displayed.
+  if (subdocFrame->GetType() != nsGkAtoms::subDocumentFrame) {
+    NS_WARN_IF_FALSE(!subdocFrame->GetType(),
+                     "Subdocument container has non-subdocument frame");
+    return nullptr;
+  }
+
+  NS_ASSERTION(subdocFrame->GetView(), "Subdoc frames must have views");
+  return static_cast<nsSubDocumentFrame*>(subdocFrame)->EnsureInnerView();
 }
 
 nsresult
 nsDocumentViewer::CreateDeviceContext(nsView* aContainerView)
 {
   NS_PRECONDITION(!mPresShell && !mWindow,
                   "This will screw up our existing presentation");
   NS_PRECONDITION(mDocument, "Gotta have a document here");
--- a/layout/base/nsIPresShell.h
+++ b/layout/base/nsIPresShell.h
@@ -491,25 +491,16 @@ public:
 
   /**
   * Returns the canvas frame associated with the frame hierarchy.
   * Returns nullptr if is XUL document.
   */
   virtual nsCanvasFrame* GetCanvasFrame() const = 0;
 
   /**
-   * Gets the real primary frame associated with the content object.
-   *
-   * In the case of absolutely positioned elements and floated elements,
-   * the real primary frame is the frame that is out of the flow and not the
-   * placeholder frame.
-   */
-  virtual nsIFrame* GetRealPrimaryFrameFor(nsIContent* aContent) const = 0;
-
-  /**
    * Gets the placeholder frame associated with the specified frame. This is
    * a helper frame that forwards the request to the frame manager.
    */
   virtual nsIFrame* GetPlaceholderFrameFor(nsIFrame* aFrame) const = 0;
 
   /**
    * Tell the pres shell that a frame needs to be marked dirty and needs
    * Reflow.  It's OK if this is an ancestor of the frame needing reflow as
--- a/layout/base/nsLayoutUtils.cpp
+++ b/layout/base/nsLayoutUtils.cpp
@@ -1528,16 +1528,27 @@ nsLayoutUtils::GetStyleFrame(const nsICo
   nsIFrame *frame = aContent->GetPrimaryFrame();
   if (!frame) {
     return nullptr;
   }
 
   return nsLayoutUtils::GetStyleFrame(frame);
 }
 
+/* static */ nsIFrame*
+nsLayoutUtils::GetRealPrimaryFrameFor(const nsIContent* aContent)
+{
+  nsIFrame *frame = aContent->GetPrimaryFrame();
+  if (!frame) {
+    return nullptr;
+  }
+
+  return nsPlaceholderFrame::GetRealFrameFor(frame);
+}
+
 nsIFrame*
 nsLayoutUtils::GetFloatFromPlaceholder(nsIFrame* aFrame) {
   NS_ASSERTION(nsGkAtoms::placeholderFrame == aFrame->GetType(),
                "Must have a placeholder here");
   if (aFrame->GetStateBits() & PLACEHOLDER_FOR_FLOAT) {
     nsIFrame *outOfFlowFrame =
       nsPlaceholderFrame::GetRealFrameForPlaceholder(aFrame);
     NS_ASSERTION(outOfFlowFrame->IsFloating(),
--- a/layout/base/nsLayoutUtils.h
+++ b/layout/base/nsLayoutUtils.h
@@ -353,16 +353,25 @@ public:
    * Given a content node,
    * return the frame that has the non-psuedoelement style context for
    * the content.  May return null.
    * This is aContent->GetPrimaryFrame() except for tableOuter frames.
    */
   static nsIFrame* GetStyleFrame(const nsIContent* aContent);
 
   /**
+   * Gets the real primary frame associated with the content object.
+   *
+   * In the case of absolutely positioned elements and floated elements,
+   * the real primary frame is the frame that is out of the flow and not the
+   * placeholder frame.
+   */
+  static nsIFrame* GetRealPrimaryFrameFor(const nsIContent* aContent);
+
+  /**
    * IsGeneratedContentFor returns true if aFrame is the outermost
    * frame for generated content of type aPseudoElement for aContent.
    * aFrame *might not* have the aPseudoElement pseudo-style! For example
    * it might be a table outer frame and the inner table frame might
    * have the pseudo-style.
    *
    * @param aContent the content node we're looking at.  If this is
    *        null, then we just assume that aFrame has the right content
--- a/layout/base/nsPresContext.h
+++ b/layout/base/nsPresContext.h
@@ -631,16 +631,20 @@ public:
   static int32_t AppUnitsToIntCSSPixels(nscoord aAppUnits)
   { return NSAppUnitsToIntPixels(aAppUnits,
              float(AppUnitsPerCSSPixel())); }
 
   static float AppUnitsToFloatCSSPixels(nscoord aAppUnits)
   { return NSAppUnitsToFloatPixels(aAppUnits,
              float(AppUnitsPerCSSPixel())); }
 
+  static double AppUnitsToDoubleCSSPixels(nscoord aAppUnits)
+  { return NSAppUnitsToDoublePixels(aAppUnits,
+             double(AppUnitsPerCSSPixel())); }
+
   nscoord DevPixelsToAppUnits(int32_t aPixels) const
   { return NSIntPixelsToAppUnits(aPixels, AppUnitsPerDevPixel()); }
 
   int32_t AppUnitsToDevPixels(nscoord aAppUnits) const
   { return NSAppUnitsToIntPixels(aAppUnits,
              float(AppUnitsPerDevPixel())); }
 
   int32_t CSSPixelsToDevPixels(int32_t aPixels)
--- a/layout/base/nsPresShell.cpp
+++ b/layout/base/nsPresShell.cpp
@@ -4557,28 +4557,16 @@ PresShell::StyleRuleAdded(StyleSheetHand
 
 void
 PresShell::StyleRuleRemoved(StyleSheetHandle aStyleSheet)
 {
   RecordStyleSheetChange(aStyleSheet);
 }
 
 nsIFrame*
-PresShell::GetRealPrimaryFrameFor(nsIContent* aContent) const
-{
-  if (aContent->GetComposedDoc() != GetDocument()) {
-    return nullptr;
-  }
-  nsIFrame *primaryFrame = aContent->GetPrimaryFrame();
-  if (!primaryFrame)
-    return nullptr;
-  return nsPlaceholderFrame::GetRealFrameFor(primaryFrame);
-}
-
-nsIFrame*
 PresShell::GetPlaceholderFrameFor(nsIFrame* aFrame) const
 {
   return mFrameConstructor->GetPlaceholderFrameFor(aFrame);
 }
 
 nsresult
 PresShell::RenderDocument(const nsRect& aRect, uint32_t aFlags,
                           nscolor aBackgroundColor,
--- a/layout/base/nsPresShell.h
+++ b/layout/base/nsPresShell.h
@@ -115,17 +115,16 @@ public:
 
   virtual void BeginObservingDocument() override;
   virtual void EndObservingDocument() override;
   virtual nsresult Initialize(nscoord aWidth, nscoord aHeight) override;
   virtual nsresult ResizeReflow(nscoord aWidth, nscoord aHeight) override;
   virtual nsresult ResizeReflowIgnoreOverride(nscoord aWidth, nscoord aHeight) override;
   virtual nsIPageSequenceFrame* GetPageSequenceFrame() const override;
   virtual nsCanvasFrame* GetCanvasFrame() const override;
-  virtual nsIFrame* GetRealPrimaryFrameFor(nsIContent* aContent) const override;
 
   virtual nsIFrame* GetPlaceholderFrameFor(nsIFrame* aFrame) const override;
   virtual void FrameNeedsReflow(nsIFrame *aFrame, IntrinsicDirty aIntrinsicDirty,
                                 nsFrameState aBitToAdd,
                                 ReflowRootHandling aRootHandling =
                                   eInferFromBitToAdd) override;
   virtual void FrameNeedsToContinueReflow(nsIFrame *aFrame) override;
   virtual void CancelAllPendingReflows() override;
--- a/mobile/android/app/mobile.js
+++ b/mobile/android/app/mobile.js
@@ -575,17 +575,16 @@ pref("app.update.channel", "@MOZ_UPDATE_
 pref("editor.singleLine.pasteNewlines", 2);
 
 // 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);
 // APZ prefs that are different from B2G
 pref("apz.allow_immediate_handoff", false);
 pref("apz.touch_start_tolerance", "0.06");
 pref("apz.axis_lock.breakout_angle", "0.7853982");    // PI / 4 (45 degrees)
--- a/mobile/android/base/java/org/mozilla/gecko/GeckoAppShell.java
+++ b/mobile/android/base/java/org/mozilla/gecko/GeckoAppShell.java
@@ -260,16 +260,17 @@ public class GeckoAppShell
     public static native SurfaceBits getSurfaceBits(Surface surface);
 
     public static native void addPresentationSurface(Surface surface);
     public static native void removePresentationSurface(Surface surface);
 
     public static native void onFullScreenPluginHidden(View view);
 
     private static LayerView sLayerView;
+    private static Rect sScreenSize;
 
     public static void setLayerView(LayerView lv) {
         if (sLayerView == lv) {
             return;
         }
         sLayerView = lv;
     }
 
@@ -1278,17 +1279,17 @@ public class GeckoAppShell
         GeckoProcessesVisitor visitor = new GeckoProcessesVisitor() {
             @Override
             public boolean callback(int pid) {
                 if (pid != android.os.Process.myPid())
                     android.os.Process.killProcess(pid);
                 return true;
             }
         };
-            
+
         EnumerateGeckoProcesses(visitor);
     }
 
     interface GeckoProcessesVisitor{
         boolean callback(int pid);
     }
 
     private static void EnumerateGeckoProcesses(GeckoProcessesVisitor visiter) {
@@ -1300,17 +1301,17 @@ public class GeckoAppShell
             java.lang.Process ps = Runtime.getRuntime().exec("ps");
             BufferedReader in = new BufferedReader(new InputStreamReader(ps.getInputStream()),
                                                    2048);
 
             String headerOutput = in.readLine();
 
             // figure out the column offsets.  We only care about the pid and user fields
             StringTokenizer st = new StringTokenizer(headerOutput);
-            
+
             int tokenSoFar = 0;
             while (st.hasMoreTokens()) {
                 String next = st.nextToken();
                 if (next.equalsIgnoreCase("PID"))
                     pidColumn = tokenSoFar;
                 else if (next.equalsIgnoreCase("USER"))
                     userColumn = tokenSoFar;
                 tokenSoFar++;
@@ -1433,17 +1434,17 @@ public class GeckoAppShell
             return null;
         }
     }
 
     public static String getMimeTypeFromExtension(String ext) {
         final MimeTypeMap mtm = MimeTypeMap.getSingleton();
         return mtm.getMimeTypeFromExtension(ext);
     }
-    
+
     private static Drawable getDrawableForExtension(PackageManager pm, String aExt) {
         Intent intent = new Intent(Intent.ACTION_VIEW);
         final String mimeType = getMimeTypeFromExtension(aExt);
         if (mimeType != null && mimeType.length() > 0)
             intent.setType(mimeType);
         else
             return null;
 
@@ -2205,17 +2206,17 @@ public class GeckoAppShell
     @WrapForJNI(stubName = "GetProxyForURIWrapper")
     public static String getProxyForURI(String spec, String scheme, String host, int port) {
         final ProxySelector ps = new ProxySelector();
 
         Proxy proxy = ps.select(scheme, host);
         if (Proxy.NO_PROXY.equals(proxy)) {
             return "DIRECT";
         }
-        
+
         switch (proxy.type()) {
             case HTTP:
                 return "PROXY " + proxy.address().toString();
             case SOCKS:
                 return "SOCKS " + proxy.address().toString();
         }
 
         return "DIRECT";
@@ -2370,16 +2371,23 @@ public class GeckoAppShell
             return 2;
         } else if (pm.hasSystemFeature(PackageManager.FEATURE_TOUCHSCREEN)) {
             // 1 finger
             return 1;
         }
         return 0;
     }
 
+    public static synchronized void resetScreenSize() {
+        sScreenSize = null;
+    }
+
     @WrapForJNI
-    static Rect getScreenSize() {
-        final WindowManager wm = (WindowManager)
-                getApplicationContext().getSystemService(Context.WINDOW_SERVICE);
-        final Display disp = wm.getDefaultDisplay();
-        return new Rect(0, 0, disp.getWidth(), disp.getHeight());
+    public static synchronized Rect getScreenSize() {
+        if (sScreenSize == null) {
+            final WindowManager wm = (WindowManager)
+                    getApplicationContext().getSystemService(Context.WINDOW_SERVICE);
+            final Display disp = wm.getDefaultDisplay();
+            sScreenSize = new Rect(0, 0, disp.getWidth(), disp.getHeight());
+        }
+        return sScreenSize;
     }
 }
--- a/mobile/android/base/java/org/mozilla/gecko/GeckoEvent.java
+++ b/mobile/android/base/java/org/mozilla/gecko/GeckoEvent.java
@@ -446,16 +446,19 @@ public class GeckoEvent {
                 // s.values[3] was optional in API <= 18, so we need to compute it
                 // The values form a unit quaternion, so we can compute the angle of
                 // rotation purely based on the given 3 values.
                 event.mW = 1 - s.values[0]*s.values[0] - s.values[1]*s.values[1] - s.values[2]*s.values[2];
                 event.mW = (event.mW > 0.0) ? Math.sqrt(event.mW) : 0.0;
             }
             break;
         }
+
+        // SensorEvent timestamp is in nanoseconds, Gecko expects microseconds.
+        event.mTime = s.timestamp / 1000;
         return event;
     }
 
     public static GeckoEvent createLocationEvent(Location l) {
         GeckoEvent event = GeckoEvent.get(NativeGeckoEvent.LOCATION_EVENT);
         event.mLocation = l;
         return event;
     }
--- a/mobile/android/base/java/org/mozilla/gecko/GeckoScreenOrientation.java
+++ b/mobile/android/base/java/org/mozilla/gecko/GeckoScreenOrientation.java
@@ -35,17 +35,17 @@ public class GeckoScreenOrientation {
         DEFAULT(1 << 4);
 
         public final short value;
 
         private ScreenOrientation(int value) {
             this.value = (short)value;
         }
 
-        private final static ScreenOrientation[] sValues = ScreenOrientation.values(); 
+        private final static ScreenOrientation[] sValues = ScreenOrientation.values();
 
         public static ScreenOrientation get(int value) {
             for (ScreenOrientation orient: sValues) {
                 if (orient.value == value) {
                     return orient;
                 }
             }
             return NONE;
@@ -151,16 +151,17 @@ public class GeckoScreenOrientation {
                 aScreenOrientation = ScreenOrientation.PORTRAIT_PRIMARY;
             } else if (aScreenOrientation == ScreenOrientation.LANDSCAPE) {
                 aScreenOrientation = ScreenOrientation.LANDSCAPE_PRIMARY;
             }
             GeckoAppShell.sendEventToGecko(
                 GeckoEvent.createScreenOrientationEvent(aScreenOrientation.value,
                                                         getAngle()));
         }
+        GeckoAppShell.resetScreenSize();
         return true;
     }
 
     /*
      * @return The Android orientation (Configuration.orientation).
      */
     public int getAndroidOrientation() {
         return screenOrientationToAndroidOrientation(getScreenOrientation());
--- a/modules/libjar/test/mochitest/mochitest.ini
+++ b/modules/libjar/test/mochitest/mochitest.ini
@@ -1,11 +1,12 @@
 [DEFAULT]
 skip-if = buildapp == 'b2g'
 support-files =
   bug403331.zip
   bug403331.zip^headers^
   openredirect.sjs
+  !/dom/base/test/file_bug945152.jar
 
 [test_bug403331.html]
 [test_bug1034143_mapped.html]
 run-if = os == 'linux'
 [test_bug1173171.html]
\ No newline at end of file
--- a/modules/libpref/init/all.js
+++ b/modules/libpref/init/all.js
@@ -4417,18 +4417,16 @@ pref("layers.tile-height", 256);
 pref("layers.max-active", -1);
 // If this is set the tile size will only be treated as a suggestion.
 // On B2G we will round this to the stride of the underlying allocation.
 // On any platform we may later use the screen size and ignore
 // tile-width/tile-height entirely. Its recommended to turn this off
 // if you change the tile size.
 pref("layers.tiles.adjust", true);
 
-// Set the default values, and then override per-platform as needed
-pref("layers.offmainthreadcomposition.enabled", true);
 // Compositor target frame rate. NOTE: If vsync is enabled the compositor
 // frame rate will still be capped.
 // -1 -> default (match layout.frame_rate or 60 FPS)
 // 0  -> full-tilt mode: Recomposite even if not transaction occured.
 pref("layers.offmainthreadcomposition.frame-rate", -1);
 
 #ifdef XP_MACOSX
 pref("layers.enable-tiles", true);
--- a/mozglue/build/WindowsDllBlocklist.cpp
+++ b/mozglue/build/WindowsDllBlocklist.cpp
@@ -192,17 +192,17 @@ static DllBlockInfo sWindowsDllBlocklist
   // NetOp School, discontinued product, bug 763395
   { "nlsp.dll", MAKE_VERSION(6, 23, 2012, 19) },
 
   // Orbit Downloader, bug 1222819
   { "grabdll.dll", MAKE_VERSION(2, 6, 1, 0) },
   { "grabkernel.dll", MAKE_VERSION(1, 0, 0, 1) },
 
   // ESET, bug 1229252
-  { "eOppMonitor.dll", ALL_VERSIONS },
+  { "eoppmonitor.dll", ALL_VERSIONS },
 
   { nullptr, 0 }
 };
 
 #ifndef STATUS_DLL_NOT_FOUND
 #define STATUS_DLL_NOT_FOUND ((DWORD)0xC0000135L)
 #endif
 
--- a/netwerk/cookie/test/unit_ipc/xpcshell.ini
+++ b/netwerk/cookie/test/unit_ipc/xpcshell.ini
@@ -1,7 +1,10 @@
 [DEFAULT]
 head = 
 tail = 
 skip-if = toolkit == 'android' || toolkit == 'gonk'
+support-files =
+  !/netwerk/cookie/test/unit/test_parser_0001.js
+  !/netwerk/cookie/test/unit/test_parser_0019.js
 
 [test_ipc_parser_0001.js]
 [test_ipc_parser_0019.js]
--- a/netwerk/protocol/http/InterceptedChannel.cpp
+++ b/netwerk/protocol/http/InterceptedChannel.cpp
@@ -193,16 +193,19 @@ InterceptedChannelChrome::ResetIntercept
   mChannel->SetApplyConversion(mOldApplyConversion);
 
   nsCOMPtr<nsIURI> uri;
   mChannel->GetURI(getter_AddRefs(uri));
 
   nsresult rv = mChannel->StartRedirectChannelToURI(uri, nsIChannelEventSink::REDIRECT_INTERNAL);
   NS_ENSURE_SUCCESS(rv, rv);
 
+  mResponseBody->Close();
+  mResponseBody = nullptr;
+
   mReleaseHandle = nullptr;
   mChannel = nullptr;
   return NS_OK;
 }
 
 NS_IMETHODIMP
 InterceptedChannelChrome::SynthesizeStatus(uint16_t aStatus, const nsACString& aReason)
 {
@@ -225,16 +228,21 @@ InterceptedChannelChrome::SynthesizeHead
 
 NS_IMETHODIMP
 InterceptedChannelChrome::FinishSynthesizedResponse(const nsACString& aFinalURLSpec)
 {
   if (!mChannel) {
     return NS_ERROR_NOT_AVAILABLE;
   }
 
+  // Make sure the cache entry's output stream is always closed.  If the
+  // channel was intercepted with a null-body response then its possible
+  // the synthesis completed without a stream copy operation.
+  mResponseBody->Close();
+
   mReportCollector->FlushConsoleReports(mChannel);
 
   EnsureSynthesizedResponse();
 
   // If the synthesized response is a redirect, then we want to respect
   // the encoding of whatever is loaded as a result.
   if (WillRedirect(mSynthesizedResponseHead.ref())) {
     nsresult rv = mChannel->SetApplyConversion(mOldApplyConversion);
@@ -377,16 +385,17 @@ NS_IMETHODIMP
 InterceptedChannelContent::ResetInterception()
 {
   if (!mChannel) {
     return NS_ERROR_NOT_AVAILABLE;
   }
 
   mReportCollector->FlushConsoleReports(mChannel);
 
+  mResponseBody->Close();
   mResponseBody = nullptr;
   mSynthesizedInput = nullptr;
 
   mChannel->ResetInterception();
   mReleaseHandle = nullptr;
   mChannel = nullptr;
   return NS_OK;
 }
@@ -413,16 +422,21 @@ InterceptedChannelContent::SynthesizeHea
 
 NS_IMETHODIMP
 InterceptedChannelContent::FinishSynthesizedResponse(const nsACString& aFinalURLSpec)
 {
   if (NS_WARN_IF(!mChannel)) {
     return NS_ERROR_NOT_AVAILABLE;
   }
 
+  // Make sure the body output stream is always closed.  If the channel was
+  // intercepted with a null-body response then its possible the synthesis
+  // completed without a stream copy operation.
+  mResponseBody->Close();
+
   mReportCollector->FlushConsoleReports(mChannel);
 
   EnsureSynthesizedResponse();
 
   nsCOMPtr<nsIURI> originalURI;
   mChannel->GetURI(getter_AddRefs(originalURI));
 
   nsCOMPtr<nsIURI> responseURI;
--- a/netwerk/streamconv/converters/nsHTTPCompressConv.cpp
+++ b/netwerk/streamconv/converters/nsHTTPCompressConv.cpp
@@ -139,17 +139,17 @@ nsHTTPCompressConv::OnStopRequest(nsIReq
     nsCOMPtr<nsIForcePendingChannel> fpChannel = do_QueryInterface(request);
     bool isPending = false;
     if (request) {
       request->IsPending(&isPending);
     }
     if (fpChannel && !isPending) {
       fpChannel->ForcePending(true);
     }
-    if (mBrotli->mTotalOut == 0 && !BrotliStateIsStreamEnd(&mBrotli->mState)) {
+    if (mBrotli && (mBrotli->mTotalOut == 0) && !BrotliStateIsStreamEnd(&mBrotli->mState)) {
       status = NS_ERROR_INVALID_CONTENT_ENCODING;
     }
     LOG(("nsHttpCompresssConv %p onstop brotlihandler rv %x\n", this, status));
     if (fpChannel && !isPending) {
       fpChannel->ForcePending(false);
     }
   }
   return mListener->OnStopRequest(request, aContext, status);
--- a/netwerk/test/mochitests/mochitest.ini
+++ b/netwerk/test/mochitests/mochitest.ini
@@ -10,16 +10,17 @@ support-files =
   web_packaged_app.sjs
   signed_web_packaged_app.sjs
   signed_web_packaged_app_random.sjs
   file_loadinfo_redirectchain.sjs
   redirect_idn.html^headers^
   redirect_idn.html
   empty.html
   redirect.sjs
+  !/dom/apps/tests/file_app.sjs
 
 [test_arraybufferinputstream.html]
 [test_partially_cached_content.html]
 [test_rel_preconnect.html]
 [test_uri_scheme.html]
 [test_user_agent_overrides.html]
 skip-if = e10s
 [test_user_agent_updates.html]
--- a/netwerk/test/unit/test_protocolproxyservice.js
+++ b/netwerk/test/unit/test_protocolproxyservice.js
@@ -927,17 +927,17 @@ var directFilterListener = {
 };
 
 function run_isresolvable_test()
 {
   // test a non resolvable host in the pac file
 
   var pac = 'data:text/plain,' +
             'function FindProxyForURL(url, host) {' +
-            ' if (isResolvable("nonexistant.lan"))' +
+            ' if (isResolvable("nonexistant.lan.onion"))' +
             '   return "DIRECT";' +
             ' return "PROXY 127.0.0.1:1234";' +
             '}';
 
   var channel = NetUtil.newChannel({
     uri: "http://www.mozilla.org/",
     loadUsingSystemPrincipal: true
   });
--- a/netwerk/test/unit_ipc/xpcshell.ini
+++ b/netwerk/test/unit_ipc/xpcshell.ini
@@ -1,14 +1,63 @@
 [DEFAULT]
 head = head_channels_clone.js head_cc.js
 tail =
 skip-if = toolkit == 'android' || toolkit == 'gonk'
 support-files = child_app_offline.js
-	child_app_offline_notifications.js
+  child_app_offline_notifications.js
+  !/netwerk/test/unit/test_XHR_redirects.js
+  !/netwerk/test/unit/test_bug248970_cookie.js
+  !/netwerk/test/unit/test_bug528292.js
+  !/netwerk/test/unit/test_cache_jar.js
+  !/netwerk/test/unit/test_cacheflags.js
+  !/netwerk/test/unit/test_channel_close.js
+  !/netwerk/test/unit/test_cookie_header.js
+  !/netwerk/test/unit/test_cookiejars.js
+  !/netwerk/test/unit/test_dns_cancel.js
+  !/netwerk/test/unit/test_dns_per_interface.js
+  !/netwerk/test/unit/test_dns_service.js
+  !/netwerk/test/unit/test_duplicate_headers.js
+  !/netwerk/test/unit/test_event_sink.js
+  !/netwerk/test/unit/test_getHost.js
+  !/netwerk/test/unit/test_head.js
+  !/netwerk/test/unit/test_headers.js
+  !/netwerk/test/unit/test_httpsuspend.js
+  !/netwerk/test/unit/test_post.js
+  !/netwerk/test/unit/test_predictor.js
+  !/netwerk/test/unit/test_progress.js
+  !/netwerk/test/unit/test_redirect-caching_canceled.js
+  !/netwerk/test/unit/test_redirect-caching_failure.js
+  !/netwerk/test/unit/test_redirect-caching_passing.js
+  !/netwerk/test/unit/test_redirect_canceled.js
+  !/netwerk/test/unit/test_redirect_different-protocol.js
+  !/netwerk/test/unit/test_redirect_failure.js
+  !/netwerk/test/unit/test_redirect_from_script.js
+  !/netwerk/test/unit/test_redirect_history.js
+  !/netwerk/test/unit/test_redirect_passing.js
+  !/netwerk/test/unit/test_reentrancy.js
+  !/netwerk/test/unit/test_reply_without_content_type.js
+  !/netwerk/test/unit/test_resumable_channel.js
+  !/netwerk/test/unit/test_simple.js
+  !/netwerk/test/unit/test_synthesized_response.js
+  !/netwerk/test/unit/test_xmlhttprequest.js
+  !/netwerk/test/unit/head_channels.js
+  !/netwerk/test/unit/head_cache2.js
+  !/netwerk/test/unit/data/image.png
+  !/netwerk/test/unit/data/system_root.lnk
+  !/netwerk/test/unit/data/test_psl.txt
+  !/netwerk/test/unit/data/test_readline1.txt
+  !/netwerk/test/unit/data/test_readline2.txt
+  !/netwerk/test/unit/data/test_readline3.txt
+  !/netwerk/test/unit/data/test_readline4.txt
+  !/netwerk/test/unit/data/test_readline5.txt
+  !/netwerk/test/unit/data/test_readline6.txt
+  !/netwerk/test/unit/data/test_readline7.txt
+  !/netwerk/test/unit/data/test_readline8.txt
+  !/netwerk/test/unit/data/signed_win.exe
 
 [test_bug528292_wrap.js]
 [test_bug248970_cookie_wrap.js]
 [test_cacheflags_wrap.js]
 [test_cache_jar_wrap.js]
 [test_channel_close_wrap.js]
 [test_cookie_header_wrap.js]
 [test_cookiejars_wrap.js]
--- a/old-configure.in
+++ b/old-configure.in
@@ -252,28 +252,19 @@ else
     AC_CHECK_PROGS(AR, ar, :)
     AC_CHECK_PROGS(LD, ld, :)
     AC_CHECK_PROGS(STRIP, strip, :)
     AC_CHECK_PROGS(WINDRES, windres, :)
     AC_CHECK_PROGS(OTOOL, otool, :)
     if test -z "$HOST_CC"; then
         HOST_CC="$CC"
     fi
-    if test -z "$HOST_CFLAGS"; then
-        HOST_CFLAGS="$CFLAGS"
-    fi
     if test -z "$HOST_CXX"; then
         HOST_CXX="$CXX"
     fi
-    if test -z "$HOST_CXXFLAGS"; then
-        HOST_CXXFLAGS="$CXXFLAGS"
-    fi
-    if test -z "$HOST_LDFLAGS"; then
-        HOST_LDFLAGS="$LDFLAGS"
-    fi
     if test -z "$HOST_RANLIB"; then
         HOST_RANLIB="$RANLIB"
     fi
     if test -z "$HOST_AR"; then
         HOST_AR="$AR"
     fi
     if test -z "$HOST_AR_FLAGS"; then
         HOST_AR_FLAGS="$AR_FLAGS"
@@ -592,31 +583,28 @@ esac
 if test -n "$_WIN32_MSVC"; then
     SKIP_PATH_CHECKS=1
     SKIP_COMPILER_CHECKS=1
     SKIP_LIBRARY_CHECKS=1
 
     # Since we're skipping compiler and library checks, hard-code
     # some facts here.
     AC_DEFINE(HAVE_IO_H)
-    AC_DEFINE(HAVE_SETBUF)
     AC_DEFINE(HAVE_ISATTY)
 fi
 
 fi # COMPILE_ENVIRONMENT
 
 AC_SUBST(MIDL_FLAGS)
 AC_SUBST(_MSC_VER)
 
 AC_SUBST(GNU_AS)
 AC_SUBST(GNU_LD)
 AC_SUBST(GNU_CC)
 AC_SUBST(GNU_CXX)
-AC_SUBST(INTEL_CC)
-AC_SUBST(INTEL_CXX)
 
 AC_SUBST(STL_FLAGS)
 AC_SUBST(WRAP_STL_INCLUDES)
 AC_SUBST(MOZ_MSVC_STL_WRAP_RAISE)
 
 dnl ========================================================
 dnl Checks for programs.
 dnl ========================================================
@@ -627,20 +615,18 @@ AC_SUBST(NSINSTALL_BIN)
 
 if test "$COMPILE_ENVIRONMENT"; then
 
 dnl ========================================================
 dnl = Mac OS X toolchain support
 dnl ========================================================
 
 dnl The universal machinery sets UNIVERSAL_BINARY to inform packager.mk
-dnl that a universal binary is being produced and MOZ_CAN_RUN_PROGRAMS
-dnl when we can run target binaries.
+dnl that a universal binary is being produced.
 AC_SUBST(UNIVERSAL_BINARY)
-AC_SUBST(MOZ_CAN_RUN_PROGRAMS)
 
 MOZ_ARG_WITH_STRING(unify-dist,
 [  --with-unify-dist=dir   Location of the dist directory to unify with at packaging time (Mac OS X universal build only)],
     UNIFY_DIST=$withval)
 if test -n "$UNIVERSAL_BINARY"; then
     if test -z "$UNIFY_DIST"; then
         AC_MSG_ERROR([You need to provide the --with-unify-dist=dir argument when performing a universal build])
     fi
@@ -746,19 +732,17 @@ AC_PATH_XTRA
 XCFLAGS="$X_CFLAGS"
 
 fi # COMPILE_ENVIRONMENT
 
 dnl ========================================================
 dnl set the defaults first
 dnl ========================================================
 AS_BIN=$AS
-AR_LIST='$(AR) t'
 AR_EXTRACT='$(AR) x'
-AR_DELETE='$(AR) d'
 AS='$(CC)'
 AS_DASH_C_FLAG='-c'
 DLL_PREFIX=lib
 LIB_PREFIX=lib
 DLL_SUFFIX=.so
 OBJ_SUFFIX=o
 LIB_SUFFIX=a
 IMPORT_LIB_SUFFIX=
@@ -923,24 +907,18 @@ MOZ_ARG_ENABLE_BOOL(warnings-as-errors,
 
 dnl ========================================================
 dnl GNU specific defaults
 dnl ========================================================
 if test "$GNU_CC"; then
     MMX_FLAGS="-mmmx"
     SSE_FLAGS="-msse"
     SSE2_FLAGS="-msse2"
-    # Per bug 719659 comment 2, some of the headers on ancient build machines
-    # may require gnu89 inline semantics.  But otherwise, we use C99.
-    # But on OS X we just use C99 plus GNU extensions, in order to fix
-    # bug 917526.
+    # We use C99.
     CFLAGS="$CFLAGS -std=gnu99"
-    if test "${OS_ARCH}" != Darwin; then
-        CFLAGS="$CFLAGS -fgnu89-inline"
-    fi
     # FIXME: Let us build with strict aliasing. bug 414641.
     CFLAGS="$CFLAGS -fno-strict-aliasing"
     MKSHLIB='$(CXX) $(CXXFLAGS) $(DSO_PIC_CFLAGS) $(DSO_LDOPTS) -Wl,-h,$(DSO_SONAME) -o $@'
     MKCSHLIB='$(CC) $(CFLAGS) $(DSO_PIC_CFLAGS) $(DSO_LDOPTS) -Wl,-h,$(DSO_SONAME) -o $@'
     WARNINGS_AS_ERRORS='-Werror'
     DSO_CFLAGS=''
     DSO_PIC_CFLAGS='-fPIC'
     ASFLAGS="$ASFLAGS -fPIC"
@@ -1558,17 +1536,16 @@ case "$target" in
         # make 'foo == bar;' error out
         CFLAGS="$CFLAGS -we4553"
         CXXFLAGS="$CXXFLAGS -we4553"
         LIBS="$LIBS kernel32.lib user32.lib gdi32.lib winmm.lib wsock32.lib advapi32.lib secur32.lib netapi32.lib"
         MOZ_DEBUG_LDFLAGS='-DEBUG -DEBUGTYPE:CV'
         WARNINGS_AS_ERRORS='-WX'
         MOZ_OPTIMIZE_FLAGS='-O1 -Oi'
         MOZ_FIX_LINK_PATHS=
-        MOZ_COMPONENT_NSPR_LIBS='$(NSPR_LIBS)'
         LDFLAGS="$LDFLAGS -LARGEADDRESSAWARE -NXCOMPAT"
         if test -z "$DEVELOPER_OPTIONS"; then
             LDFLAGS="$LDFLAGS -RELEASE"
         fi
         dnl For profile-guided optimization
         PROFILE_GEN_CFLAGS="-GL"
         num_cores=$($PYTHON -c 'import multiprocessing; print(min(8,multiprocessing.cpu_count()))')
         cgthreads="-CGTHREADS:${num_cores}"
@@ -1594,18 +1571,16 @@ case "$target" in
         dnl Minimum reqiurement of Gecko is VS2010 or later which supports
         dnl both SSSE3 and SSE4.1.
         HAVE_TOOLCHAIN_SUPPORT_MSSSE3=1
         HAVE_TOOLCHAIN_SUPPORT_MSSE4_1=1
         dnl allow AVX2 code from VS2012
         HAVE_X86_AVX2=1
         MOZ_MEMORY=1
     fi
-    AC_DEFINE(HAVE_SNPRINTF)
-    AC_DEFINE(HW_THREADS)
     AC_DEFINE(STDC_HEADERS)
     AC_DEFINE(WIN32_LEAN_AND_MEAN)
     dnl See http://support.microsoft.com/kb/143208 to use STL
     AC_DEFINE(NOMINMAX)
     BIN_SUFFIX='.exe'
     MOZ_USER_DIR="Mozilla"
 
     case "$host_os" in
@@ -2677,17 +2652,16 @@ CFLAGS=$_SAVE_CFLAGS
 LDFLAGS=$_SAVE_LDFLAGS
 LIBS=$_SAVE_LIBS
 
 if test "${PNG_DIR}" -a -d "${PNG_DIR}" -a "$MOZ_SYSTEM_PNG" = 1; then
     MOZ_PNG_CFLAGS="-I${PNG_DIR}/include"
     MOZ_PNG_LIBS="-L${PNG_DIR}/lib ${MOZ_PNG_LIBS}"
 fi
 
-MOZ_PNG_ARM_NEON_CHECK=
 if test "$MOZ_SYSTEM_PNG" != 1 -a "$CPU_ARCH" = "arm" ; then
     MOZ_ARG_ENABLE_STRING(png-arm-neon-support,
         [  --enable-png-arm-neon-support=TYPE
              Options include:
                  no
                  check (default)
                  nocheck (faster but unsafe)],
         [MOZ_PNG_ARM_NEON_SUPPORT=$enableval ] )
@@ -2696,23 +2670,20 @@ if test "$MOZ_SYSTEM_PNG" != 1 -a "$CPU_
             # enable-png-arm-neon-support = no
             ;;
         nocheck)
             # enable-png-arm-neon-support = nocheck
             MOZ_PNG_ARM_NEON=1
             ;;
         *)
             MOZ_PNG_ARM_NEON=1
-            MOZ_PNG_ARM_NEON_CHECK=1
             ;;
     esac
 fi
 
-AC_SUBST(MOZ_PNG_ARM_NEON_CHECK)
-
 fi # SKIP_LIBRARY_CHECKS
 
 AC_SUBST(MOZ_PNG_ARM_NEON)
 
 dnl ========================================================
 dnl system HunSpell Support
 dnl ========================================================
 MOZ_ARG_ENABLE_BOOL(system-hunspell,
@@ -2785,17 +2756,16 @@ VPX_AS_CONVERSION=
 VPX_X86_ASM=
 VPX_ARM_ASM=
 LIBJPEG_TURBO_AS=
 LIBJPEG_TURBO_ASFLAGS=
 MOZ_PERMISSIONS=1
 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_APZ=
 MOZ_TOOLKIT_SEARCH=1
 MOZ_UI_LOCALE=en-US
 MOZ_UNIVERSALCHARDET=1
@@ -2808,17 +2778,16 @@ if test "$MOZ_IOS"; then
 fi
 MOZ_NO_SMART_CARDS=
 NSS_DISABLE_DBM=
 NECKO_COOKIES=1
 NECKO_PROTOCOLS_DEFAULT="about app data file ftp http res viewsource websocket wyciwyg device"
 if test -n "$MOZ_RTSP"; then
   NECKO_PROTOCOLS_DEFAULT="$NECKO_PROTOCOLS_DEFAULT rtsp"
 fi
-USE_ARM_KUSER=
 BUILD_CTYPES=1
 MOZ_USE_NATIVE_POPUP_WINDOWS=
 MOZ_ANDROID_HISTORY=
 MOZ_WEBSMS_BACKEND=
 MOZ_ANDROID_BEAM=
 MOZ_LOCALE_SWITCHER=
 MOZ_ANDROID_SEARCH_ACTIVITY=
 MOZ_ANDROID_DOWNLOADS_INTEGRATION=
@@ -2843,40 +2812,27 @@ case "$target_os" in
     mingw*)
         NS_ENABLE_TSF=1
         AC_DEFINE(NS_ENABLE_TSF)
         ;;
 esac
 
 case "${target}" in
     *-android*|*-linuxandroid*)
-        if test "$CPU_ARCH" = "arm" ; then
-          USE_ARM_KUSER=1
-        fi
-
         NSS_DISABLE_DBM=1
         MOZ_THEME_FASTSTRIPE=1
         MOZ_TREE_FREETYPE=1
         if test "$COMPILE_ENVIRONMENT"; then
             MOZ_MEMORY=1
         fi
         MOZ_RAW=1
         ;;
 
 esac
 
-MOZ_ARG_WITH_STRING(xulrunner-stub-name,
-[  --with-xulrunner-stub-name=appname   Create the xulrunner stub with the given name],
-  XULRUNNER_STUB_NAME=$withval)
-
-if test -z "$XULRUNNER_STUB_NAME"; then
-  XULRUNNER_STUB_NAME=xulrunner-stub
-fi
-AC_SUBST(XULRUNNER_STUB_NAME)
-
 # The app update channel is 'default' when not supplied. The value is used in
 # the application's confvars.sh so it must be set before confvars.sh is called.
 MOZ_ARG_ENABLE_STRING([update-channel],
 [  --enable-update-channel=CHANNEL
                           Select application update channel (default=default)],
     MOZ_UPDATE_CHANNEL=`echo $enableval | tr A-Z a-z`)
 
 if test -z "$MOZ_UPDATE_CHANNEL"; then
@@ -3160,27 +3116,16 @@ if test "$COMPILE_ENVIRONMENT"; then
     TK_CFLAGS=$MOZ_GTK2_CFLAGS
     TK_LIBS=$MOZ_GTK2_LIBS
   fi
 fi # COMPILE_ENVIRONMENT
 
 AC_SUBST(MOZ_FS_LAYOUT)
 
 dnl ========================================================
-dnl Use ARM userspace kernel helpers; tell NSPR to enable
-dnl their usage and use them in spidermonkey.
-dnl ========================================================
-MOZ_ARG_WITH_BOOL(arm-kuser,
-[  --with-arm-kuser         Use kuser helpers (Linux/ARM only -- requires kernel 2.6.13 or later)],
-    USE_ARM_KUSER=1,)
-if test -n "$USE_ARM_KUSER"; then
-   AC_DEFINE(USE_ARM_KUSER)
-fi
-
-dnl ========================================================
 dnl = startup-notification support module
 dnl ========================================================
 
 if test "$MOZ_ENABLE_GTK"
 then
     MOZ_ENABLE_STARTUP_NOTIFICATION=
 
     MOZ_ARG_ENABLE_BOOL(startup-notification,
@@ -3326,24 +3271,20 @@ then
       AC_DEFINE(MOZ_ENABLE_QTNETWORK)
     fi
 
     MOZ_ENABLE_QTMOBILITY=
     PKG_CHECK_MODULES(_QTMOBILITY, QtSensors QtFeedback QtLocation,
                       MOZ_ENABLE_QTMOBILITY=1,
                       MOZ_ENABLE_QTMOBILITY=)
     if test "$MOZ_ENABLE_QTMOBILITY"; then
-       MOZ_ENABLE_QTMOBILITY=1
        MOZ_QT_CFLAGS="$MOZ_QT_CFLAGS $_QTMOBILITY_CFLAGS"
        MOZ_QT_LIBS="$MOZ_QT_LIBS $_QTMOBILITY_LIBS"
-       AC_DEFINE(MOZ_ENABLE_QTMOBILITY)
-       AC_SUBST(MOZ_ENABLE_QTMOBILITY)
     else
        AC_CHECK_LIB(QtSensors, main, [
-          MOZ_ENABLE_QTMOBILITY=1
           MOZ_QT_CFLAGS="$MOZ_QT_CFLAGS -I$QTDIR/include/QtMobility"
           MOZ_QT_CFLAGS="$MOZ_QT_CFLAGS -I$QTDIR/include/QtSensors"
           MOZ_QT_CFLAGS="$MOZ_QT_CFLAGS -I$QTDIR/include/QtFeedback"
           MOZ_QT_CFLAGS="$MOZ_QT_CFLAGS -I$QTDIR/include/QtLocation"
           MOZ_QT_LIBS="$MOZ_QT_LIBS -lQtSensors -lQtFeedback -lQtLocation"
        ])
     fi
 
@@ -3384,24 +3325,22 @@ then
        MOZ_QT_LIBS="$MOZ_QT_LIBS $_CONTENTACTION_LIBS"
        AC_DEFINE(MOZ_ENABLE_CONTENTACTION)
        AC_SUBST(MOZ_ENABLE_CONTENTACTION)
     fi
     TK_CFLAGS=$MOZ_QT_CFLAGS
     TK_LIBS=$MOZ_QT_LIBS
 fi
 
-AC_SUBST(GTK_CONFIG)
 AC_SUBST_LIST(TK_CFLAGS)
 AC_SUBST_LIST(TK_LIBS)
 
 AC_SUBST(MOZ_ENABLE_QT)
 AC_SUBST(MOZ_ENABLE_QTNETWORK)
 AC_SUBST(MOZ_ENABLE_QMSYSTEM2)
-AC_SUBST(MOZ_ENABLE_QTMOBILITY)
 AC_SUBST_LIST(MOZ_QT_CFLAGS)
 AC_SUBST_LIST(MOZ_QT_LIBS)
 
 AC_SUBST(MOC)
 AC_SUBST(RCC)
 
 dnl ========================================================
 dnl =
@@ -3887,17 +3826,16 @@ MOZ_ARG_ENABLE_BOOL(hardware-aec-ns,
     MOZ_WEBRTC_HARDWARE_AEC_NS=1,
     MOZ_WEBRTC_HARDWARE_AEC_NS=)
 
 if test -n "$MOZ_WEBRTC_HARDWARE_AEC_NS"; then
     AC_DEFINE(MOZ_WEBRTC_HARDWARE_AEC_NS)
 fi
 
 AC_SUBST(MOZ_WEBRTC)
-AC_SUBST(MOZ_WEBRTC_LEAKING_TESTS)
 AC_SUBST(MOZ_WEBRTC_SIGNALING)
 AC_SUBST(MOZ_PEERCONNECTION)
 AC_SUBST(MOZ_WEBRTC_ASSERT_ALWAYS)
 AC_SUBST(MOZ_WEBRTC_HARDWARE_AEC_NS)
 AC_SUBST(MOZ_SCTP)
 AC_SUBST(MOZ_SRTP)
 AC_SUBST_LIST(MOZ_WEBRTC_X11_LIBS)
 
@@ -4151,17 +4089,16 @@ else
     MOZ_TREMOR=1
 fi
 
 if test -z "$MOZ_SYSTEM_LIBVPX"; then
 
     dnl Detect if we can use an assembler to compile optimized assembly for libvpx.
     dnl We currently require yasm on all x86 platforms and require yasm 1.1.0 on Win32.
     dnl We currently require gcc on all arm platforms.
-    VPX_NEED_OBJ_INT_EXTRACT=
 
     dnl See if we have assembly on this platform.
     case "$OS_ARCH:$CPU_ARCH" in
     Darwin:x86)
       VPX_USE_YASM=1
       VPX_X86_ASM=1
     ;;
     Darwin:x86_64)
@@ -4227,25 +4164,16 @@ if test -z "$MOZ_SYSTEM_LIBVPX"; then
     if test -n "$COMPILE_ENVIRONMENT" -a -n "$VPX_USE_YASM" -a -z "$YASM"; then
       AC_MSG_ERROR([yasm is a required build tool for this architecture when webm is enabled. You may either install yasm or --disable-webm (which disables the WebM video format). See https://developer.mozilla.org/en/YASM for more details.])
     fi # COMPILE_ENVIRONMENT and others
 
     if test -n "$VPX_USE_YASM" && test "$OS_ARCH:$CPU_ARCH" != "WINNT:x86_64"; then
       VPX_ASFLAGS="-DPIC"
     fi
 
-    if test -z "$GNU_CC" -a -z "$INTEL_CC" -a -z "$CLANG_CC" ; then
-      dnl We prefer to get asm offsets using inline assembler, which the above
-      dnl compilers can do. When we're not using one of those, we have to fall
-      dnl back to obj_int_extract, which reads them from a compiled object
-      dnl file. Unfortunately, that only works if we're compiling on a system
-      dnl with the header files for the appropriate object file format.
-      VPX_NEED_OBJ_INT_EXTRACT=1
-    fi
-
     if test -n "$VPX_X86_ASM"; then
       AC_DEFINE(VPX_X86_ASM)
     elif test -n "$VPX_ARM_ASM"; then
       AC_DEFINE(VPX_ARM_ASM)
     else
       AC_MSG_WARN([No assembler or assembly support for libvpx. Using unoptimized C routines.])
     fi
 
@@ -5857,19 +5785,16 @@ else
     AC_DEFINE(MOZ_MEMORY_DARWIN)
     ;;
   *-*freebsd*)
     AC_DEFINE(MOZ_MEMORY_BSD)
     ;;
   *-android*|*-linuxandroid*)
     AC_DEFINE(MOZ_MEMORY_LINUX)
     AC_DEFINE(MOZ_MEMORY_ANDROID)
-    if test -n "$gonkdir"; then
-      AC_DEFINE(MOZ_MEMORY_GONK)
-    fi
     ;;
   *-*linux*)
     AC_DEFINE(MOZ_MEMORY_LINUX)
     ;;
   *-netbsd*)
     AC_DEFINE(MOZ_MEMORY_BSD)
     ;;
   *-mingw*)
@@ -6502,35 +6427,16 @@ if test -n "$INTEL_CC"; then
   PROFILE_USE_LDFLAGS=
 fi
 
 AC_SUBST(PROFILE_GEN_CFLAGS)
 AC_SUBST(PROFILE_GEN_LDFLAGS)
 AC_SUBST(PROFILE_USE_CFLAGS)
 AC_SUBST(PROFILE_USE_LDFLAGS)
 
-dnl =============================================
-dnl Support for -fno-integrated-as (recent clang)
-dnl =============================================
-dnl Under clang 3.4+, use -fno-integrated-as to
-dnl build libvpx's vp8_asm_enc_offsets.c
-
-_SAVE_CFLAGS="$CFLAGS"
-CFLAGS="$CFLAGS -fno-integrated-as -S"
-
-AC_MSG_CHECKING([whether C compiler supports -fno-integrated-as])
-AC_TRY_COMPILE([], [return 0;],
-               [ NO_INTEGRATED_AS_CFLAGS="-fno-integrated-as"
-                 result="yes" ], result="no")
-AC_MSG_RESULT([$result])
-
-CFLAGS="$_SAVE_CFLAGS"
-
-AC_SUBST(NO_INTEGRATED_AS_CFLAGS)
-
 fi # ! SKIP_COMPILER_CHECKS
 
 AC_DEFINE(CPP_THROW_NEW, [throw()])
 AC_LANG_C
 
 if test "$COMPILE_ENVIRONMENT"; then
 MOZ_EXPAND_LIBS
 fi # COMPILE_ENVIRONMENT
@@ -6905,30 +6811,16 @@ if test "$MOZ_XUL"; then
 else
   dnl remove extensions that require XUL
   MOZ_EXTENSIONS=`echo $MOZ_EXTENSIONS | sed -e 's/inspector//' -e 's/irc//' -e 's/tasks//'`
 fi
 
 AC_SUBST(MOZ_XUL)
 
 dnl ========================================================
-dnl disable profile locking
-dnl   do no use this in applications that can have more than
-dnl   one process accessing the profile directory.
-dnl ========================================================
-MOZ_ARG_DISABLE_BOOL(profilelocking,
-[  --disable-profilelocking
-                          Disable profile locking],
-    MOZ_PROFILELOCKING=,
-    MOZ_PROFILELOCKING=1 )
-if test "$MOZ_PROFILELOCKING"; then
-  AC_DEFINE(MOZ_PROFILELOCKING)
-fi
-
-dnl ========================================================
 dnl necko configuration options
 dnl ========================================================
 
 dnl
 dnl option to disable various necko protocols
 dnl
 MOZ_ARG_ENABLE_STRING(necko-protocols,
 [  --enable-necko-protocols[={http,ftp,default,all,none}]
@@ -7083,19 +6975,17 @@ fi
 dnl ========================================================
 dnl =
 dnl = Maintainer debug option (no --enable equivalent)
 dnl =
 dnl ========================================================
 
 AC_SUBST(AR)
 AC_SUBST(AR_FLAGS)
-AC_SUBST(AR_LIST)
 AC_SUBST(AR_EXTRACT)
-AC_SUBST(AR_DELETE)
 AC_SUBST(AS)
 AC_SUBST(ASFLAGS)
 AC_SUBST(AS_DASH_C_FLAG)
 AC_SUBST(LD)
 AC_SUBST(RC)
 AC_SUBST(RCFLAGS)
 AC_SUBST(MC)
 AC_SUBST(WINDRES)
@@ -7120,18 +7010,16 @@ AC_SUBST(TOOLCHAIN_PREFIX)
 
 AC_SUBST(JAVA)
 AC_SUBST(JAVAC)
 AC_SUBST(JAVAH)
 AC_SUBST(JAR)
 AC_SUBST(JARSIGNER)
 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_APZ)
 AC_SUBST(MOZ_ANDROID_ANR_REPORTER)
 AC_SUBST(MOZ_CRASHREPORTER)
 AC_SUBST(MOZ_CRASHREPORTER_INJECTOR)
@@ -7171,17 +7059,16 @@ AC_SUBST(MOZ_EXCLUDE_HYPHENATION_DICTION
 AC_SUBST(MOZ_INSTALL_TRACKING)
 AC_SUBST(MOZ_SWITCHBOARD)
 AC_SUBST(ENABLE_STRIP)
 AC_SUBST(PKG_SKIP_STRIP)
 AC_SUBST(STRIP_FLAGS)
 AC_SUBST(USE_ELF_HACK)
 AC_SUBST(INCREMENTAL_LINKER)
 AC_SUBST(MOZ_COMPONENTS_VERSION_SCRIPT_LDFLAGS)
-AC_SUBST(MOZ_COMPONENT_NSPR_LIBS)
 
 AC_SUBST(MOZ_FIX_LINK_PATHS)
 
 AC_SUBST(MOZ_POST_PROGRAM_COMMAND)
 AC_SUBST(MOZ_LINKER_EXTRACT)
 
 AC_SUBST(MOZ_ADDON_SIGNING)
 AC_SUBST(MOZ_REQUIRE_SIGNING)
@@ -7220,37 +7107,16 @@ MOZ_MACBUNDLE_ID=`echo $MOZ_APP_DISPLAYN
 MOZ_MACBUNDLE_ID=${MOZ_DISTRIBUTION_ID}.${MOZ_MACBUNDLE_ID}
 if test "$MOZ_DEBUG"; then
   MOZ_MACBUNDLE_ID=${MOZ_MACBUNDLE_ID}debug
 fi
 
 AC_DEFINE_UNQUOTED(MOZ_MACBUNDLE_ID,$MOZ_MACBUNDLE_ID)
 AC_SUBST(MOZ_MACBUNDLE_ID)
 
-dnl ========================================================
-dnl = Child Process Name for IPC
-dnl ========================================================
-if test "$MOZ_WIDGET_TOOLKIT" != "android"; then
-  MOZ_CHILD_PROCESS_NAME="firefox-webcontent${BIN_SUFFIX}"
-  MOZ_PLUGIN_PROCESS_NAME="firefox-plugin-container${BIN_SUFFIX}"
-else
-  # We want to let Android unpack the file at install time, but it only does
-  # so if the file is named libsomething.so. The lib/ path is also required
-  # because the unpacked file will be under the lib/ subdirectory and will
-  # need to be executed from that path.
-  MOZ_CHILD_PROCESS_NAME="libfirefox-webcontent.so"
-  MOZ_CHILD_PROCESS_NAME_PIE="libplugin-container-pie.so"
-  AC_SUBST(MOZ_CHILD_PROCESS_NAME_PIE)
-fi
-MOZ_CHILD_PROCESS_BUNDLE="plugin-container.app/Contents/MacOS/"
-
-AC_SUBST(MOZ_CHILD_PROCESS_NAME)
-AC_SUBST(MOZ_CHILD_PROCESS_BUNDLE)
-AC_SUBST(MOZ_PLUGIN_PROCESS_NAME)
-
 # The following variables are available to branding and application
 # configuration ($BRANDING/configure.sh and $APPLICATION/confvars.sh):
 # - MOZ_APP_VENDOR: Used for application.ini's "Vendor" field, which also
 # impacts profile location and user-visible fields.
 # - MOZ_APP_BASENAME: Typically stays consistent for multiple branded
 # versions of a given application (e.g. Aurora and Firefox both use
 # "Firefox"), but may vary for full rebrandings (e.g. Iceweasel). Used
 # for application.ini's "Name" field, which controls profile location in
@@ -7291,16 +7157,37 @@ fi
 if test -z "$MOZ_APP_VERSION_DISPLAY"; then
    MOZ_APP_VERSION_DISPLAY=$MOZ_APP_VERSION
 fi
 
 if test -z "$ANDROID_PACKAGE_NAME" ; then
    ANDROID_PACKAGE_NAME="org.mozilla.$MOZ_APP_NAME"
 fi
 
+dnl ========================================================
+dnl = Child Process Name for IPC
+dnl ========================================================
+if test "$MOZ_WIDGET_TOOLKIT" != "android"; then
+  MOZ_CHILD_PROCESS_NAME="${MOZ_APP_NAME}-webcontent${BIN_SUFFIX}"
+  MOZ_PLUGIN_PROCESS_NAME="plugin-container${BIN_SUFFIX}"
+else
+  # We want to let Android unpack the file at install time, but it only does
+  # so if the file is named libsomething.so. The lib/ path is also required
+  # because the unpacked file will be under the lib/ subdirectory and will
+  # need to be executed from that path.
+  MOZ_CHILD_PROCESS_NAME="libfirefox-webcontent.so"
+  MOZ_CHILD_PROCESS_NAME_PIE="libplugin-container-pie.so"
+  AC_SUBST(MOZ_CHILD_PROCESS_NAME_PIE)
+fi
+MOZ_CHILD_PROCESS_BUNDLE="plugin-container.app/Contents/MacOS/"
+
+AC_SUBST(MOZ_CHILD_PROCESS_NAME)
+AC_SUBST(MOZ_CHILD_PROCESS_BUNDLE)
+AC_SUBST(MOZ_PLUGIN_PROCESS_NAME)
+
 # Mozilla released Firefox for Android {Release,Beta} and {Aurora,Nightly} to
 # the public with specific common shared IDs and we need to keep them
 # consistent forever.  The specific common values are set by per-channel
 # branding; all other channels use a generic sharedID, set below.
 if test -z "$MOZ_ANDROID_SHARED_ID" ; then
    MOZ_ANDROID_SHARED_ID="${ANDROID_PACKAGE_NAME}.sharedID"
 fi
 
@@ -7468,17 +7355,16 @@ OS_LDFLAGS="$LDFLAGS"
 OS_LIBS="$LIBS"
 AC_SUBST(OS_CFLAGS)
 AC_SUBST(OS_CXXFLAGS)
 AC_SUBST(OS_CPPFLAGS)
 AC_SUBST(OS_COMPILE_CFLAGS)
 AC_SUBST(OS_COMPILE_CXXFLAGS)
 AC_SUBST(OS_LDFLAGS)
 AC_SUBST(OS_LIBS)
-AC_SUBST(WCHAR_CFLAGS)
 
 AC_SUBST(HOST_CC)
 AC_SUBST(HOST_CXX)
 AC_SUBST(HOST_CFLAGS)
 AC_SUBST(HOST_CPPFLAGS)
 AC_SUBST(HOST_CXXFLAGS)
 AC_SUBST(HOST_LDFLAGS)
 AC_SUBST(HOST_OPTIMIZE_FLAGS)
@@ -7528,17 +7414,16 @@ AC_SUBST(MOZ_DIRECTSHOW)
 AC_SUBST(MOZ_ANDROID_OMX)
 AC_SUBST(MOZ_OMX_PLUGIN)
 AC_SUBST(MOZ_VPX_ERROR_CONCEALMENT)
 AC_SUBST(VPX_USE_YASM)
 AC_SUBST_LIST(VPX_ASFLAGS)
 AC_SUBST(VPX_AS_CONVERSION)
 AC_SUBST(VPX_X86_ASM)
 AC_SUBST(VPX_ARM_ASM)
-AC_SUBST(VPX_NEED_OBJ_INT_EXTRACT)
 AC_SUBST(MOZ_CODE_COVERAGE)
 AC_SUBST(LIBJPEG_TURBO_USE_YASM)
 AC_SUBST_LIST(LIBJPEG_TURBO_ASFLAGS)
 AC_SUBST(MOZ_LIBAV_FFT)
 AC_SUBST_LIST(LIBAV_FFT_ASFLAGS)
 AC_SUBST(MOZ_DEVTOOLS)
 
 AC_SUBST(MOZ_PACKAGE_JSSHELL)
--- a/python/mozbuild/mozbuild/backend/common.py
+++ b/python/mozbuild/mozbuild/backend/common.py
@@ -169,35 +169,42 @@ class WebIDLCollection(object):
 class TestManager(object):
     """Helps hold state related to tests."""
 
     def __init__(self, config):
         self.config = config
         self.topsrcdir = mozpath.normpath(config.topsrcdir)
 
         self.tests_by_path = defaultdict(list)
+        self.installs_by_path = defaultdict(list)
+        self.deferred_installs = set()
 
-    def add(self, t, flavor=None, topsrcdir=None):
+    def add(self, t, flavor, topsrcdir):
         t = dict(t)
         t['flavor'] = flavor
 
-        if topsrcdir is None:
-            topsrcdir = self.topsrcdir
-        else:
-            topsrcdir = mozpath.normpath(topsrcdir)
-
         path = mozpath.normpath(t['path'])
         assert mozpath.basedir(path, [topsrcdir])
 
         key = path[len(topsrcdir)+1:]
         t['file_relpath'] = key
         t['dir_relpath'] = mozpath.dirname(key)
 
         self.tests_by_path[key].append(t)
 
+    def add_installs(self, obj, topsrcdir):
+        for src, (dest, _) in obj.installs.iteritems():
+            key = src[len(topsrcdir)+1:]
+            self.installs_by_path[key].append((src, dest))
+        for src, pat, dest in obj.pattern_installs:
+            key = mozpath.join(src[len(topsrcdir)+1:], pat)
+            self.installs_by_path[key].append((src, pat, dest))
+        for path in obj.deferred_installs:
+            self.deferred_installs.add(path[2:])
+
 
 class BinariesCollection(object):
     """Tracks state of binaries produced by the build."""
 
     def __init__(self):
         self.shared_libraries = []
         self.programs = []
 
@@ -213,18 +220,18 @@ class CommonBackend(BuildBackend):
         self._configs = set()
         self._ipdl_sources = set()
 
     def consume_object(self, obj):
         self._configs.add(obj.config)
 
         if isinstance(obj, TestManifest):
             for test in obj.tests:
-                self._test_manager.add(test, flavor=obj.flavor,
-                    topsrcdir=obj.topsrcdir)
+                self._test_manager.add(test, obj.flavor, obj.topsrcdir)
+            self._test_manager.add_installs(obj, obj.topsrcdir)
 
         elif isinstance(obj, XPIDLFile):
             # TODO bug 1240134 tracks not processing XPIDL files during
             # artifact builds.
             self._idl_manager.register_idl(obj)
 
         elif isinstance(obj, ConfigFileSubstitution):
             # Do not handle ConfigFileSubstitution for Makefiles. Leave that
@@ -354,16 +361,24 @@ class CommonBackend(BuildBackend):
         for config in self._configs:
             self.backend_input_files.add(config.source)
 
         # Write out a machine-readable file describing every test.
         topobjdir = self.environment.topobjdir
         with self._write_file(mozpath.join(topobjdir, 'all-tests.json')) as fh:
             json.dump(self._test_manager.tests_by_path, fh)
 
+        path = mozpath.join(self.environment.topobjdir, 'test-installs.json')
+        with self._write_file(path) as fh:
+            json.dump({k: v for k, v in self._test_manager.installs_by_path.items()
+                       if k in self._test_manager.deferred_installs},
+                      fh,
+                      sort_keys=True,
+                      indent=4)
+
         # Write out a machine-readable file describing binaries.
         with self._write_file(mozpath.join(topobjdir, 'binaries.json')) as fh:
             d = {
                 'shared_libraries': [s.to_dict() for s in self._binaries.shared_libraries],
                 'programs': [p.to_dict() for p in self._binaries.programs],
             }
             json.dump(d, fh, sort_keys=True, indent=4)
 
--- a/python/mozbuild/mozbuild/backend/recursivemake.py
+++ b/python/mozbuild/mozbuild/backend/recursivemake.py
@@ -1037,32 +1037,32 @@ class RecursiveMakeBackend(CommonBackend
         self.backend_input_files.add(mozpath.join(obj.topsrcdir,
             obj.manifest_relpath))
 
         # Don't allow files to be defined multiple times unless it is allowed.
         # We currently allow duplicates for non-test files or test files if
         # the manifest is listed as a duplicate.
         for source, (dest, is_test) in obj.installs.items():
             try:
-                self._install_manifests['_tests'].add_symlink(source, dest)
+                self._install_manifests['_test_files'].add_symlink(source, dest)
             except ValueError:
                 if not obj.dupe_manifest and is_test:
                     raise
 
         for base, pattern, dest in obj.pattern_installs:
             try:
-                self._install_manifests['_tests'].add_pattern_symlink(base,
+                self._install_manifests['_test_files'].add_pattern_symlink(base,
                     pattern, dest)
             except ValueError:
                 if not obj.dupe_manifest:
                     raise
 
         for dest in obj.external_installs:
             try:
-                self._install_manifests['_tests'].add_optional_exists(dest)
+                self._install_manifests['_test_files'].add_optional_exists(dest)
             except ValueError:
                 if not obj.dupe_manifest:
                     raise
 
         m = self._test_manifests.setdefault(obj.flavor,
             (obj.install_prefix, set()))
         m[1].add(obj.manifest_obj_relpath)
 
--- a/python/mozbuild/mozbuild/configure/util.py
+++ b/python/mozbuild/mozbuild/configure/util.py
@@ -1,15 +1,17 @@
 # This Source Code Form is subject to the terms of the Mozilla Public
 # License, v. 2.0. If a copy of the MPL was not distributed with this
 # file, You can obtain one at http://mozilla.org/MPL/2.0/.
 
 from __future__ import absolute_import, print_function, unicode_literals
 
+import codecs
 import itertools
+import locale
 import logging
 import os
 import sys
 from collections import deque
 from contextlib import contextmanager
 from distutils.version import LooseVersion
 
 
@@ -53,17 +55,29 @@ class ConfigureOutputHandler(logging.Han
 
     Messages below that level can be kept until an ERROR message is received,
     at which point the last `maxlen` accumulated messages below INFO are
     printed out. This feature is only enabled under the `queue_debug` context
     manager.
     '''
     def __init__(self, stdout=sys.stdout, stderr=sys.stderr, maxlen=20):
         super(ConfigureOutputHandler, self).__init__()
-        self._stdout, self._stderr = stdout, stderr
+
+        # Python has this feature where it sets the encoding of pipes to
+        # ascii, which blatantly fails when trying to print out non-ascii.
+        def fix_encoding(fh):
+            try:
+                if not fh.isatty():
+                    return codecs.getwriter(locale.getpreferredencoding())(fh)
+            except AttributeError:
+                pass
+            return fh
+
+        self._stdout = fix_encoding(stdout)
+        self._stderr = fix_encoding(stderr) if stdout != stderr else self._stdout
         try:
             fd1 = self._stdout.fileno()
             fd2 = self._stderr.fileno()
             self._same_output = self._is_same_output(fd1, fd2)
         except AttributeError:
             self._same_output = self._stdout == self._stderr
         self._stdout_waiting = None
         self._debug = deque(maxlen=maxlen + 1)
@@ -102,29 +116,17 @@ class ConfigureOutputHandler(logging.Han
                     msg = '%s\n' % msg
             elif (record.levelno < logging.INFO and
                     self._keep_if_debug != self.PRINT):
                 if self._keep_if_debug == self.KEEP:
                     self._debug.append(record)
                 return
             else:
                 if record.levelno >= logging.ERROR and len(self._debug):
-                    self._keep_if_debug = self.PRINT
-                    if len(self._debug) == self._debug.maxlen:
-                        r = self._debug.popleft()
-                        self.emit(logging.LogRecord(
-                            r.name, r.levelno, r.pathname, r.lineno,
-                            '<truncated - see config.log for full output>',
-                            (), None))
-                    while True:
-                        try:
-                            self.emit(self._debug.popleft())
-                        except IndexError:
-                            break
-                    self._keep_if_debug = self.KEEP
+                    self._emit_queue()
 
                 if self._stdout_waiting == self.WAITING and self._same_output:
                     self._stdout_waiting = self.INTERRUPTED
                     self._stdout.write('\n')
                     self._stdout.flush()
                 stream = self._stderr
                 msg = '%s\n' % self.format(record)
             stream.write(msg)
@@ -132,20 +134,41 @@ class ConfigureOutputHandler(logging.Han
         except (KeyboardInterrupt, SystemExit):
             raise
         except:
             self.handleError(record)
 
     @contextmanager
     def queue_debug(self):
         self._keep_if_debug = self.KEEP
-        yield
+        try:
+            yield
+        except Exception:
+            self._emit_queue()
+            # The exception will be handled and very probably printed out by
+            # something upper in the stack.
+            raise
         self._keep_if_debug = self.THROW
         self._debug.clear()
 
+    def _emit_queue(self):
+        self._keep_if_debug = self.PRINT
+        if len(self._debug) == self._debug.maxlen:
+            r = self._debug.popleft()
+            self.emit(logging.LogRecord(
+                r.name, r.levelno, r.pathname, r.lineno,
+                '<truncated - see config.log for full output>',
+                (), None))
+        while True:
+            try:
+                self.emit(self._debug.popleft())
+            except IndexError:
+                break
+        self._keep_if_debug = self.KEEP
+
 
 class LineIO(object):
     '''File-like class that sends each line of the written data to a callback
     (without carriage returns).
     '''
     def __init__(self, callback):
         self._callback = callback
         self._buf = ''
--- a/python/mozbuild/mozbuild/controller/building.py
+++ b/python/mozbuild/mozbuild/controller/building.py
@@ -21,18 +21,22 @@ from collections import (
 
 try:
     import psutil
 except Exception:
     psutil = None
 
 from mozsystemmonitor.resourcemonitor import SystemResourceMonitor
 
+import mozpack.path as mozpath
+
 from ..base import MozbuildObject
 
+from ..testing import install_test_files
+
 from ..compilation.warnings import (
     WarningsCollector,
     WarningsDatabase,
 )
 
 from textwrap import TextWrapper
 
 INSTALL_TESTS_CLOBBER = ''.join([TextWrapper().fill(line) + '\n' for line in
@@ -648,22 +652,24 @@ class CCacheStats(object):
             return '%.1f Mbytes' % (float(v) / CCacheStats.MiB)
         else:
             return '%.1f Kbytes' % (float(v) / CCacheStats.KiB)
 
 
 class BuildDriver(MozbuildObject):
     """Provides a high-level API for build actions."""
 
-    def install_tests(self, remove=True):
-        """Install test files (through manifest)."""
+    def install_tests(self, test_objs):
+        """Install test files."""
 
         if self.is_clobber_needed():
             print(INSTALL_TESTS_CLOBBER.format(
                   clobber_file=os.path.join(self.topobjdir, 'CLOBBER')))
             sys.exit(1)
 
-        env = {}
-        if not remove:
-            env[b'NO_REMOVE'] = b'1'
-
-        self._run_make(target='install-tests', append_env=env, pass_thru=True,
-            print_directory=False)
+        if not test_objs:
+            # If we don't actually have a list of tests to install we install
+            # test and support files wholesale.
+            self._run_make(target='install-test-files', pass_thru=True,
+                           print_directory=False)
+        else:
+            install_test_files(mozpath.normpath(self.topsrcdir), self.topobjdir,
+                               '_tests', test_objs)
--- a/python/mozbuild/mozbuild/frontend/data.py
+++ b/python/mozbuild/mozbuild/frontend/data.py
@@ -556,16 +556,20 @@ class TestManifest(ContextDerived):
 
         # Where all files for this manifest flavor are installed in the unified
         # test package directory.
         'install_prefix',
 
         # Set of files provided by an external mechanism.
         'external_installs',
 
+        # Set of files required by multiple test directories, whose installation
+        # will be resolved when running tests.
+        'deferred_installs',
+
         # The full path of this manifest file.
         'path',
 
         # The directory where this manifest is defined.
         'directory',
 
         # The parsed manifestparser.TestManifest instance.
         'manifest',
@@ -597,16 +601,17 @@ class TestManifest(ContextDerived):
         self.install_prefix = install_prefix
         self.manifest_relpath = relpath
         self.manifest_obj_relpath = relpath
         self.dupe_manifest = dupe_manifest
         self.installs = {}
         self.pattern_installs = []
         self.tests = []
         self.external_installs = set()
+        self.deferred_installs = set()
 
 
 class LocalInclude(ContextDerived):
     """Describes an individual local include path."""
 
     __slots__ = (
         'path',
     )
--- a/python/mozbuild/mozbuild/frontend/emitter.py
+++ b/python/mozbuild/mozbuild/frontend/emitter.py
@@ -78,16 +78,17 @@ from mozpack.chrome.manifest import (
 )
 
 from .reader import SandboxValidationError
 
 from ..testing import (
     TEST_MANIFESTS,
     REFTEST_FLAVORS,
     WEB_PLATFORM_TESTS_FLAVORS,
+    SupportFilesConverter,
 )
 
 from .context import (
     Context,
     SourcePath,
     ObjDirPath,
     Path,
     SubContext,
@@ -134,16 +135,17 @@ class TreeMetadataEmitter(LoggingMixin):
         if os.path.exists(subconfigures):
             paths = open(subconfigures).read().splitlines()
         self._external_paths = set(mozpath.normsep(d) for d in paths)
         # Add security/nss manually, since it doesn't have a subconfigure.
         self._external_paths.add('security/nss')
 
         self._emitter_time = 0.0
         self._object_count = 0
+        self._test_files_converter = SupportFilesConverter()
 
     def summary(self):
         return ExecutionSummary(
             'Processed into {object_count:d} build config descriptors in '
             '{execution_time:.2f}s',
             execution_time=self._emitter_time,
             object_count=self._object_count)
 
@@ -1091,73 +1093,34 @@ class TreeMetadataEmitter(LoggingMixin):
             out_dir = mozpath.join(install_prefix, manifest_reldir)
             if 'install-to-subdir' in defaults:
                 # This is terrible, but what are you going to do?
                 out_dir = mozpath.join(out_dir, defaults['install-to-subdir'])
                 obj.manifest_obj_relpath = mozpath.join(manifest_reldir,
                                                         defaults['install-to-subdir'],
                                                         mozpath.basename(path))
 
+            def process_support_files(test):
+                install_info = self._test_files_converter.convert_support_files(
+                    test, install_root, manifest_dir, out_dir)
 
-            # "head" and "tail" lists.
-            # All manifests support support-files.
-            #
-            # Keep a set of already seen support file patterns, because
-            # repeatedly processing the patterns from the default section
-            # for every test is quite costly (see bug 922517).
-            extras = (('head', set()),
-                      ('tail', set()),
-                      ('support-files', set()))
-            def process_support_files(test):
-                for thing, seen in extras:
-                    value = test.get(thing, '')
-                    if value in seen:
-                        continue
-                    seen.add(value)
-                    for pattern in value.split():
-                        # We only support globbing on support-files because
-                        # the harness doesn't support * for head and tail.
-                        if '*' in pattern and thing == 'support-files':
-                            obj.pattern_installs.append(
-                                (manifest_dir, pattern, out_dir))
-                        # "absolute" paths identify files that are to be
-                        # placed in the install_root directory (no globs)
-                        elif pattern[0] == '/':
-                            full = mozpath.normpath(mozpath.join(manifest_dir,
-                                mozpath.basename(pattern)))
-                            obj.installs[full] = (mozpath.join(install_root,
-                                pattern[1:]), False)
-                        else:
-                            full = mozpath.normpath(mozpath.join(manifest_dir,
-                                pattern))
+                obj.pattern_installs.extend(install_info.pattern_installs)
+                for source, dest in install_info.installs:
+                    obj.installs[source] = (dest, False)
+                obj.external_installs |= install_info.external_installs
+                for install_path in install_info.deferred_installs:
+                    if all(['*' not in install_path,
+                            not os.path.isfile(mozpath.join(context.config.topsrcdir,
+                                                            install_path[2:])),
+                            install_path not in install_info.external_installs]):
+                        raise SandboxValidationError('Error processing test '
+                           'manifest %s: entry in support-files not present '
+                           'in the srcdir: %s' % (path, install_path), context)
 
-                            dest_path = mozpath.join(out_dir, pattern)
-
-                            # If the path resolves to a different directory
-                            # tree, we take special behavior depending on the
-                            # entry type.
-                            if not full.startswith(manifest_dir):
-                                # If it's a support file, we install the file
-                                # into the current destination directory.
-                                # This implementation makes installing things
-                                # with custom prefixes impossible. If this is
-                                # needed, we can add support for that via a
-                                # special syntax later.
-                                if thing == 'support-files':
-                                    dest_path = mozpath.join(out_dir,
-                                        os.path.basename(pattern))
-                                # If it's not a support file, we ignore it.
-                                # This preserves old behavior so things like
-                                # head files doesn't get installed multiple
-                                # times.
-                                else:
-                                    continue
-
-                            obj.installs[full] = (mozpath.normpath(dest_path),
-                                False)
+                obj.deferred_installs |= install_info.deferred_installs
 
             for test in filtered:
                 obj.tests.append(test)
 
                 # Some test files are compiled and should not be copied into the
                 # test package. They function as identifiers rather than files.
                 if package_tests:
                     manifest_relpath = mozpath.relpath(test['path'],
@@ -1180,20 +1143,18 @@ class TreeMetadataEmitter(LoggingMixin):
             # FUTURE we should be able to detect autogenerated files from
             # other build metadata. Once we do that, we can get rid of this.
             for f in defaults.get('generated-files', '').split():
                 # We re-raise otherwise the stack trace isn't informative.
                 try:
                     del obj.installs[mozpath.join(manifest_dir, f)]
                 except KeyError:
                     raise SandboxValidationError('Error processing test '
-                        'manifest %s: entry in generated-files not present '
-                        'elsewhere in manifest: %s' % (path, f), context)
-
-                obj.external_installs.add(mozpath.join(out_dir, f))
+                       'manifest %s: entry in generated-files not present '
+                       'elsewhere in manifest: %s' % (path, f), context)
 
             yield obj
         except (AssertionError, Exception):
             raise SandboxValidationError('Error processing test '
                 'manifest file %s: %s' % (path,
                     '\n'.join(traceback.format_exception(*sys.exc_info()))),
                 context)
 
new file mode 100644
new file mode 100644
--- /dev/null
+++ b/python/mozbuild/mozbuild/test/backend/data/test-manifest-shared-support/child/browser.ini
@@ -0,0 +1,6 @@
+[DEFAULT]
+support-files =
+  another-file.sjs
+  data/**
+
+[test_sub.js]
\ No newline at end of file
new file mode 100644
new file mode 100644
new file mode 100644
new file mode 100644
--- /dev/null
+++ b/python/mozbuild/mozbuild/test/backend/data/test-manifest-shared-support/mochitest.ini
@@ -0,0 +1,8 @@
+[DEFAULT]
+support-files =
+  support-file.txt
+  !/child/test_sub.js
+  !/child/another-file.sjs
+  !/child/data/**
+
+[test_foo.js]
new file mode 100644
--- /dev/null
+++ b/python/mozbuild/mozbuild/test/backend/data/test-manifest-shared-support/moz.build
@@ -0,0 +1,5 @@
+# Any copyright is dedicated to the Public Domain.
+# http://creativecommons.org/publicdomain/zero/1.0/
+
+MOCHITEST_MANIFESTS += ['mochitest.ini']
+BROWSER_CHROME_MANIFESTS += ['child/browser.ini']
new file mode 100644
new file mode 100644
--- a/python/mozbuild/mozbuild/test/backend/test_recursivemake.py
+++ b/python/mozbuild/mozbuild/test/backend/test_recursivemake.py
@@ -534,24 +534,64 @@ class TestRecursiveMakeBackend(BackendTe
             self.assertIn('dir1/test_bar.js', o)
 
             self.assertEqual(len(o['xpcshell.js']), 1)
 
     def test_test_manifest_pattern_matches_recorded(self):
         """Pattern matches in test manifests' support-files should be recorded."""
         env = self._consume('test-manifests-written', RecursiveMakeBackend)
         m = InstallManifest(path=mozpath.join(env.topobjdir,
-            '_build_manifests', 'install', '_tests'))
+            '_build_manifests', 'install', '_test_files'))
 
         # This is not the most robust test in the world, but it gets the job
         # done.
         entries = [e for e in m._dests.keys() if '**' in e]
         self.assertEqual(len(entries), 1)
         self.assertIn('support/**', entries[0])
 
+    def test_test_manifest_deffered_installs_written(self):
+        """Shared support files are written to their own data file by the backend."""
+        env = self._consume('test-manifest-shared-support', RecursiveMakeBackend)
+        all_tests_path = mozpath.join(env.topobjdir, 'all-tests.json')
+        self.assertTrue(os.path.exists(all_tests_path))
+        test_installs_path = mozpath.join(env.topobjdir, 'test-installs.json')
+
+        with open(test_installs_path, 'r') as fh:
+            test_installs = json.load(fh)
+
+        self.assertEqual(set(test_installs.keys()),
+                         set(['child/test_sub.js',
+                              'child/data/**',
+                              'child/another-file.sjs']))
+        for key in test_installs.keys():
+            self.assertIn(key, test_installs)
+
+        test_files_manifest = mozpath.join(env.topobjdir,
+                                           '_build_manifests',
+                                           'install',
+                                           '_test_files')
+
+        # First, read the generated for ini manifest contents.
+        m = InstallManifest(path=test_files_manifest)
+
+        # Then, synthesize one from the test-installs.json file. This should
+        # allow us to re-create a subset of the above.
+        synthesized_manifest = InstallManifest()
+        for item, installs in test_installs.items():
+            for install_info in installs:
+                if len(install_info) == 3:
+                    synthesized_manifest.add_pattern_symlink(*install_info)
+                if len(install_info) == 2:
+                    synthesized_manifest.add_symlink(*install_info)
+
+        self.assertEqual(len(synthesized_manifest), 3)
+        for item, info in synthesized_manifest._dests.items():
+            self.assertIn(item, m)
+            self.assertEqual(info, m._dests[item])
+
     def test_xpidl_generation(self):
         """Ensure xpidl files and directories are written out."""
         env = self._consume('xpidl', RecursiveMakeBackend)
 
         # Install manifests should contain entries.
         install_dir = mozpath.join(env.topobjdir, '_build_manifests',
             'install')
         self.assertTrue(os.path.isfile(mozpath.join(install_dir, 'dist_idl')))
@@ -764,17 +804,17 @@ class TestRecursiveMakeBackend(BackendTe
 
         self.assertIn('JAR_MANIFEST := %s/jar.mn' % env.topsrcdir, lines)
 
     def test_test_manifests_duplicate_support_files(self):
         """Ensure duplicate support-files in test manifests work."""
         env = self._consume('test-manifests-duplicate-support-files',
             RecursiveMakeBackend)
 
-        p = os.path.join(env.topobjdir, '_build_manifests', 'install', '_tests')
+        p = os.path.join(env.topobjdir, '_build_manifests', 'install', '_test_files')
         m = InstallManifest(p)
         self.assertIn('testing/mochitest/tests/support-file.txt', m)
 
     def test_android_eclipse(self):
         env = self._consume('android_eclipse', RecursiveMakeBackend)
 
         with open(mozpath.join(env.topobjdir, 'backend.mk'), 'rb') as fh:
             lines = fh.readlines()
@@ -819,17 +859,17 @@ class TestRecursiveMakeBackend(BackendTe
             o = json.load(fh)
 
             self.assertIn('mochitest.js', o)
             self.assertIn('not_packaged.java', o)
 
         man_dir = mozpath.join(env.topobjdir, '_build_manifests', 'install')
         self.assertTrue(os.path.isdir(man_dir))
 
-        full = mozpath.join(man_dir, '_tests')
+        full = mozpath.join(man_dir, '_test_files')
         self.assertTrue(os.path.exists(full))
 
         m = InstallManifest(path=full)
 
         # Only mochitest.js should be in the install manifest.
         self.assertTrue('testing/mochitest/tests/mochitest.js' in m)
 
         # The path is odd here because we do not normalize at test manifest
--- a/python/mozbuild/mozbuild/test/configure/test_util.py
+++ b/python/mozbuild/mozbuild/test/configure/test_util.py
@@ -225,16 +225,37 @@ class TestConfigureOutputHandler(unittes
             'checking bar... no\n'
             'DEBUG:<truncated - see config.log for full output>\n'
             'DEBUG:do baz\n'
             'DEBUG:do qux\n'
             'DEBUG:do hoge\n'
             'ERROR:fail\n'
         )
 
+        out.seek(0)
+        out.truncate()
+
+        try:
+            with handler.queue_debug():
+                logger.info('checking bar... ')
+                logger.debug('do foo')
+                logger.debug('do bar')
+                logger.info('no')
+                e = Exception('fail')
+                raise e
+        except Exception as caught:
+            self.assertIs(caught, e)
+
+        self.assertEqual(
+            out.getvalue(),
+            'checking bar... no\n'
+            'DEBUG:do foo\n'
+            'DEBUG:do bar\n'
+        )
+
     def test_is_same_output(self):
         fd1 = sys.stderr.fileno()
         fd2 = os.dup(fd1)
         try:
             self.assertTrue(ConfigureOutputHandler._is_same_output(fd1, fd2))
         finally:
             os.close(fd2)
 
new file mode 100644
new file mode 100644
--- /dev/null
+++ b/python/mozbuild/mozbuild/test/frontend/data/test-manifest-shared-missing/child/browser.ini
@@ -0,0 +1,6 @@
+[DEFAULT]
+support-files =
+  another-file.sjs
+  data/**
+
+[test_sub.js]
\ No newline at end of file
new file mode 100644
new file mode 100644
new file mode 100644
new file mode 100644
--- /dev/null
+++ b/python/mozbuild/mozbuild/test/frontend/data/test-manifest-shared-missing/mochitest.ini
@@ -0,0 +1,9 @@
+[DEFAULT]
+support-files =
+  support-file.txt
+  !/child/test_sub.js
+  !/child/another-file.sjs
+  !/child/data/**
+  !/does/not/exist.sjs
+
+[test_foo.js]
new file mode 100644
--- /dev/null
+++ b/python/mozbuild/mozbuild/test/frontend/data/test-manifest-shared-missing/moz.build
@@ -0,0 +1,5 @@
+# Any copyright is dedicated to the Public Domain.
+# http://creativecommons.org/publicdomain/zero/1.0/
+
+MOCHITEST_MANIFESTS += ['mochitest.ini']
+BROWSER_CHROME_MANIFESTS += ['child/browser.ini']
new file mode 100644
new file mode 100644
new file mode 100644
new file mode 100644
--- /dev/null
+++ b/python/mozbuild/mozbuild/test/frontend/data/test-manifest-shared-support/child/browser.ini
@@ -0,0 +1,6 @@
+[DEFAULT]
+support-files =
+  another-file.sjs
+  data/**
+
+[test_sub.js]
\ No newline at end of file
new file mode 100644
new file mode 100644
new file mode 100644
new file mode 100644
--- /dev/null
+++ b/python/mozbuild/mozbuild/test/frontend/data/test-manifest-shared-support/mochitest.ini
@@ -0,0 +1,8 @@
+[DEFAULT]
+support-files =
+  support-file.txt
+  !/child/test_sub.js
+  !/child/another-file.sjs
+  !/child/data/**
+
+[test_foo.js]
new file mode 100644
--- /dev/null
+++ b/python/mozbuild/mozbuild/test/frontend/data/test-manifest-shared-support/moz.build
@@ -0,0 +1,5 @@
+# Any copyright is dedicated to the Public Domain.
+# http://creativecommons.org/publicdomain/zero/1.0/
+
+MOCHITEST_MANIFESTS += ['mochitest.ini']
+BROWSER_CHROME_MANIFESTS += ['child/browser.ini']
new file mode 100644
new file mode 100644
--- a/python/mozbuild/mozbuild/test/frontend/test_emitter.py
+++ b/python/mozbuild/mozbuild/test/frontend/test_emitter.py
@@ -439,16 +439,43 @@ class TestEmitterBasic(unittest.TestCase
         expected = [
             mozpath.normpath(mozpath.join(o.install_prefix, "../.well-known/foo.txt")),
             mozpath.join(o.install_prefix, "absolute-support.ini"),
             mozpath.join(o.install_prefix, "test_file.js"),
         ]
         paths = sorted([v[0] for v in o.installs.values()])
         self.assertEqual(paths, expected)
 
+    def test_test_manifest_shared_support_files(self):
+        """Support files starting with '!' are given separate treatment, so their
+        installation can be resolved when running tests.
+        """
+        reader = self.reader('test-manifest-shared-support')
+        supported, child = self.read_topsrcdir(reader)
+
+        expected_deferred_installs = {
+            '!/child/test_sub.js',
+            '!/child/another-file.sjs',
+            '!/child/data/**',
+        }
+
+        self.assertEqual(len(supported.installs), 3)
+        self.assertEqual(set(supported.deferred_installs),
+                         expected_deferred_installs)
+        self.assertEqual(len(child.installs), 3)
+        self.assertEqual(len(child.pattern_installs), 1)
+
+    def test_test_manifest_deffered_install_missing(self):
+        """A non-existent shared support file reference produces an error."""
+        reader = self.reader('test-manifest-shared-missing')
+
+        with self.assertRaisesRegexp(SandboxValidationError,
+                                     'entry in support-files not present in the srcdir'):
+            self.read_topsrcdir(reader)
+
     def test_test_manifest_install_to_subdir(self):
         """ """
         reader = self.reader('test-manifest-install-subdir')
 
         objs = self.read_topsrcdir(reader)
         self.assertEqual(len(objs), 1)
         o = objs[0]
         self.assertEqual(len(o.installs), 3)
--- a/python/mozbuild/mozbuild/test/test_testing.py
+++ b/python/mozbuild/mozbuild/test/test_testing.py
@@ -234,16 +234,20 @@ class TestTestResolver(Base):
         topobjdir = tempfile.mkdtemp()
         self._temp_dirs.append(topobjdir)
 
         with open(os.path.join(topobjdir, 'all-tests.json'), 'wt') as fh:
             fh.write(ALL_TESTS_JSON)
 
         o = MozbuildObject(self.FAKE_TOPSRCDIR, None, None, topobjdir=topobjdir)
 
+        # Monkey patch the test resolver to avoid tests failing to find make
+        # due to our fake topscrdir.
+        TestResolver._run_make = lambda *a, **b: None
+
         return o._spawn(TestResolver)
 
     def test_cwd_children_only(self):
         """If cwd is defined, only resolve tests under the specified cwd."""
         r = self._get_resolver()
 
         # Pretend we're under '/services' and ask for 'common'. This should
         # pick up all tests from '/services/common'
--- a/python/mozbuild/mozbuild/testing.py
+++ b/python/mozbuild/mozbuild/testing.py
@@ -5,16 +5,19 @@
 from __future__ import absolute_import, unicode_literals
 
 import json
 import os
 import sys
 
 import mozpack.path as mozpath
 
+from mozpack.copier import FileCopier
+from mozpack.manifests import InstallManifest
+
 from .base import MozbuildObject
 from .util import OrderedDefaultDict
 from collections import defaultdict
 
 import manifestparser
 import reftest
 
 def rewrite_test_base(test, new_base, honor_install_to_subdir=False):
@@ -162,16 +165,22 @@ class TestMetadata(object):
 
 
 class TestResolver(MozbuildObject):
     """Helper to resolve tests from the current environment to test files."""
 
     def __init__(self, *args, **kwargs):
         MozbuildObject.__init__(self, *args, **kwargs)
 
+        # If installing tests is going to result in re-generating the build
+        # backend, we need to do this here, so that the updated contents of
+        # all-tests.json make it to the set of tests to run.
+        self._run_make(target='run-tests-deps', pass_thru=True,
+                       print_directory=False)
+
         self._tests = TestMetadata(filename=os.path.join(self.topobjdir,
             'all-tests.json'))
         self._test_rewrites = {
             'a11y': os.path.join(self.topobjdir, '_tests', 'testing',
                 'mochitest', 'a11y'),
             'browser-chrome': os.path.join(self.topobjdir, '_tests', 'testing',
                 'mochitest', 'browser'),
             'jetpack-package': os.path.join(self.topobjdir, '_tests', 'testing',
@@ -282,16 +291,195 @@ REFTEST_FLAVORS = ('crashtest', 'reftest
 WEB_PLATFORM_TESTS_FLAVORS = ('web-platform-tests',)
 
 def all_test_flavors():
     return ([v[0] for v in TEST_MANIFESTS.values()] +
             list(REFTEST_FLAVORS) +
             list(WEB_PLATFORM_TESTS_FLAVORS) +
             ['python'])
 
+class TestInstallInfo(object):
+    def __init__(self):
+        self.pattern_installs = []
+        self.installs = []
+        self.external_installs = set()
+        self.deferred_installs = set()
+
+    def __ior__(self, other):
+        self.pattern_installs.extend(other.pattern_installs)
+        self.installs.extend(other.installs)
+        self.external_installs |= other.external_installs
+        self.deferred_installs |= other.deferred_installs
+        return self
+
+class SupportFilesConverter(object):
+    """Processes a "support-files" entry from a test object, either from
+    a parsed object from a test manifests or its representation in
+    moz.build and returns the installs to perform for this test object.
+
+    Processing the same support files multiple times will not have any further
+    effect, and the structure of the parsed objects from manifests will have a
+    lot of repeated entries, so this class takes care of memoizing.
+    """
+    def __init__(self):
+        self._fields = (('head', set()),
+                        ('tail', set()),
+                        ('support-files', set()),
+                        ('generated-files', set()))
+
+    def convert_support_files(self, test, install_root, manifest_dir, out_dir):
+        # Arguments:
+        #  test - The test object to process.
+        #  install_root - The directory under $objdir/_tests that will contain
+        #                 the tests for this harness (examples are "testing/mochitest",
+        #                 "xpcshell").
+        #  manifest_dir - Absoulute path to the (srcdir) directory containing the
+        #                 manifest that included this test
+        #  out_dir - The path relative to $objdir/_tests used as the destination for the
+        #            test, based on the relative path to the manifest in the srcdir,
+        #            the install_root, and 'install-to-subdir', if present in the manifest.
+        info = TestInstallInfo()
+        for thing, seen in self._fields:
+            value = test.get(thing, '')
+            # We need to memoize on the basis of both the path and the output
+            # directory for the benefit of tests specifying 'install-to-subdir'.
+            if (value, out_dir) in seen:
+                continue
+            seen.add((value, out_dir))
+            for pattern in value.split():
+                if thing == 'generated-files':
+                    info.external_installs.add(mozpath.normpath(mozpath.join(out_dir, pattern)))
+                # '!' indicates our syntax for inter-directory support file
+                # dependencies. These receive special handling in the backend.
+                elif pattern[0] == '!':
+                    info.deferred_installs.add(pattern)
+                # We only support globbing on support-files because
+                # the harness doesn't support * for head and tail.
+                elif '*' in pattern and thing == 'support-files':
+                    info.pattern_installs.append((manifest_dir, pattern, out_dir))
+                # "absolute" paths identify files that are to be
+                # placed in the install_root directory (no globs)
+                elif pattern[0] == '/':
+                    full = mozpath.normpath(mozpath.join(manifest_dir,
+                                                         mozpath.basename(pattern)))
+                    info.installs.append((full, mozpath.join(install_root, pattern[1:])))
+                else:
+                    full = mozpath.normpath(mozpath.join(manifest_dir, pattern))
+                    dest_path = mozpath.join(out_dir, pattern)
+
+                    # If the path resolves to a different directory
+                    # tree, we take special behavior depending on the
+                    # entry type.
+                    if not full.startswith(manifest_dir):
+                        # If it's a support file, we install the file
+                        # into the current destination directory.
+                        # This implementation makes installing things
+                        # with custom prefixes impossible. If this is
+                        # needed, we can add support for that via a
+                        # special syntax later.
+                        if thing == 'support-files':
+                            dest_path = mozpath.join(out_dir,
+                                                     os.path.basename(pattern))
+                        # If it's not a support file, we ignore it.
+                        # This preserves old behavior so things like
+                        # head files doesn't get installed multiple
+                        # times.
+                        else:
+                            continue
+                    info.installs.append((full, mozpath.normpath(dest_path)))
+        return info
+
+def _resolve_installs(paths, topobjdir, manifest):
+    """Using the given paths as keys, find any unresolved installs noted
+    by the build backend corresponding to those keys, and add them
+    to the given manifest.
+    """
+    filename = os.path.join(topobjdir, 'test-installs.json')
+    with open(filename, 'r') as fh:
+        resolved_installs = json.load(fh)
+
+    for path in paths:
+        path = path[2:]
+        if path not in resolved_installs:
+            raise Exception('A cross-directory support file path noted in a '
+                'test manifest does not appear in any other manifest.\n "%s" '
+                'must appear in another test manifest to specify an install '
+                'for "!/%s".' % (path, path))
+        installs = resolved_installs[path]
+        for install_info in installs:
+            try:
+                if len(install_info) == 3:
+                    manifest.add_pattern_symlink(*install_info)
+                if len(install_info) == 2:
+                    manifest.add_symlink(*install_info)
+            except ValueError:
+                # A duplicate value here is pretty likely when running
+                # multiple directories at once, and harmless.
+                pass
+
+def install_test_files(topsrcdir, topobjdir, tests_root, test_objs):
+    """Installs the requested test files to the objdir. This is invoked by
+    test runners to avoid installing tens of thousands of test files when
+    only a few tests need to be run.
+    """
+    flavor_info = {flavor: (root, prefix, install)
+                   for (flavor, root, prefix, install) in TEST_MANIFESTS.values()}
+    objdir_dest = mozpath.join(topobjdir, tests_root)
+
+    converter = SupportFilesConverter()
+    install_info = TestInstallInfo()
+    for o in test_objs:
+        flavor = o['flavor']
+        if flavor not in flavor_info:
+            # This is a test flavor that isn't installed by the build system.
+            continue
+        root, prefix, install = flavor_info[flavor]
+        if not install:
+            # This flavor isn't installed to the objdir.
+            continue
+
+        manifest_path = o['manifest']
+        manifest_dir = mozpath.dirname(manifest_path)
+
+        out_dir = mozpath.join(root, prefix, manifest_dir[len(topsrcdir) + 1:])
+        file_relpath = o['file_relpath']
+        source = mozpath.join(topsrcdir, file_relpath)
+        dest = mozpath.join(root, prefix, file_relpath)
+        if 'install-to-subdir' in o:
+            out_dir = mozpath.join(out_dir, o['install-to-subdir'])
+            manifest_relpath = mozpath.relpath(source, mozpath.dirname(manifest_path))
+            dest = mozpath.join(out_dir, manifest_relpath)
+
+        install_info.installs.append((source, dest))
+        install_info |= converter.convert_support_files(o, root,
+                                                        manifest_dir,
+                                                        out_dir)
+
+    manifest = InstallManifest()
+
+    for source, dest in set(install_info.installs):
+        if dest in install_info.external_installs:
+            continue
+        manifest.add_symlink(source, dest)
+    for base, pattern, dest in install_info.pattern_installs:
+        manifest.add_pattern_symlink(base, pattern, dest)
+
+    _resolve_installs(install_info.deferred_installs, topobjdir, manifest)
+
+    # Harness files are treated as a monolith and installed each time we run tests.
+    # Fortunately there are not very many.
+    manifest |= InstallManifest(mozpath.join(topobjdir,
+                                             '_build_manifests',
+                                             'install', tests_root))
+    copier = FileCopier()
+    manifest.populate_registry(copier)
+    copier.copy(objdir_dest,
+                remove_unaccounted=False)
+
+
 # Convenience methods for test manifest reading.
 def read_manifestparser_manifest(context, manifest_path):
     path = mozpath.normpath(mozpath.join(context.srcdir, manifest_path))
     return manifestparser.TestManifest(manifests=[path], strict=True,
                                        rootdir=context.config.topsrcdir,
                                        finder=context._finder)
 
 def read_reftest_manifest(context, manifest_path):
--- a/services/crypto/tests/unit/xpcshell.ini
+++ b/services/crypto/tests/unit/xpcshell.ini
@@ -1,13 +1,15 @@
 [DEFAULT]
 head = head_helpers.js ../../../common/tests/unit/head_helpers.js
 tail =
 firefox-appdir = browser
 skip-if = toolkit == 'gonk'
+support-files =
+  !/services/common/tests/unit/head_helpers.js
 
 [test_load_modules.js]
 
 [test_crypto_crypt.js]
 [test_crypto_deriveKey.js]
 [test_crypto_random.js]
 # Bug 676977: test hangs consistently on Android
 skip-if = os == "android"
--- a/services/fxaccounts/tests/xpcshell/xpcshell.ini
+++ b/services/fxaccounts/tests/xpcshell/xpcshell.ini
@@ -1,12 +1,15 @@
 [DEFAULT]
 head = head.js ../../../common/tests/unit/head_helpers.js ../../../common/tests/unit/head_http.js
 tail =
 skip-if = (toolkit == 'android' || appname == 'thunderbird')
+support-files =
+  !/services/common/tests/unit/head_helpers.js
+  !/services/common/tests/unit/head_http.js
 
 [test_accounts.js]
 [test_accounts_device_registration.js]
 skip-if = appname == 'b2g'
 [test_client.js]
 skip-if = toolkit == 'gonk' # times out, bug 1073639
 [test_credentials.js]
 [test_loginmgr_storage.js]
--- a/services/sync/tests/unit/xpcshell.ini
+++ b/services/sync/tests/unit/xpcshell.ini
@@ -6,16 +6,18 @@ skip-if = toolkit == 'gonk'
 support-files =
   addon1-search.xml
   bootstrap1-search.xml
   fake_login_manager.js
   missing-sourceuri.xml
   missing-xpi-search.xml
   places_v10_from_v11.sqlite
   rewrite-search.xml
+  !/services/common/tests/unit/head_helpers.js
+  !/toolkit/mozapps/extensions/test/xpcshell/head_addons.js
 
 # The manifest is roughly ordered from low-level to high-level. When making
 # systemic sweeping changes, this makes it easier to identify errors closer to
 # the source.
 
 # Ensure we can import everything.
 [test_load_modules.js]
 
--- a/testing/docker/centos6-build-upd/Dockerfile
+++ b/testing/docker/centos6-build-upd/Dockerfile
@@ -1,9 +1,9 @@
-FROM          taskcluster/centos6-build:0.1.5
+FROM          taskcluster/centos6-build:0.1.6
 MAINTAINER    Dustin J. Mitchell <dustin@mozilla.com>
 
 ### update to latest from upstream repositories
 # if this becomes a long list of packages, consider bumping the
 # centos6-build version
 RUN yum update -y
 
 # Set a default command useful for debugging
--- a/testing/docker/centos6-build-upd/VERSION
+++ b/testing/docker/centos6-build-upd/VERSION
@@ -1,1 +1,1 @@
-0.1.5.20160323120600
+0.1.6.20160329195300
--- a/testing/docker/centos6-build/VERSION
+++ b/testing/docker/centos6-build/VERSION
@@ -1,1 +1,1 @@
-0.1.5
+0.1.6
--- a/testing/docker/centos6-build/system-setup.sh
+++ b/testing/docker/centos6-build/system-setup.sh
@@ -416,18 +416,18 @@ cd $BUILD
 pip2.7 install peep
 
 # remaining Python utilities are installed with `peep` from upstream
 # repositories; peep verifies file integrity for us
 cat >requirements.txt <<'EOF'
 # sha256: 90pZQ6kAXB6Je8-H9-ivfgDAb6l3e5rWkfafn6VKh9g
 virtualenv==13.1.2
 
-# sha256: W6lDjWqw25P3sHhrpjITjrZKncDZPjDd4rF7Mo_cbXo
-mercurial==3.7.2
+# sha256: wJnELXTi1SC2HdNyzZlrD6dgXAZheDT9exPHm5qaWzA
+mercurial==3.7.3
 EOF
 peep install -r requirements.txt
 
 # TC-VCS
 npm install -g taskcluster-vcs@2.3.18
 
 # Ninja
 cd $BUILD
--- a/testing/docker/desktop-build/Dockerfile
+++ b/testing/docker/desktop-build/Dockerfile
@@ -1,9 +1,9 @@
-FROM          taskcluster/centos6-build-upd:0.1.5.20160323120600
+FROM          taskcluster/centos6-build-upd:0.1.6.20160329195300
 MAINTAINER    Dustin J. Mitchell <dustin@mozilla.com>
 
 # Add build scripts; these are the entry points from the taskcluster worker, and
 # operate on environment variables
 ADD             bin /home/worker/bin
 RUN             chmod +x /home/worker/bin/*
 
 # Generate machine uuid file
--- a/testing/docker/desktop-test/Dockerfile
+++ b/testing/docker/desktop-test/Dockerfile
@@ -1,9 +1,9 @@
-FROM          taskcluster/ubuntu1204-test-upd:0.1.8.20160218152601
+FROM          taskcluster/ubuntu1204-test-upd:0.1.9.20160329211700
 MAINTAINER    Jonas Finnemann Jensen <jopsen@gmail.com>
 
 # Add utilities and configuration
 COPY           dot-config                    /home/worker/.config
 COPY           dot-pulse                     /home/worker/.pulse
 COPY           bin                           /home/worker/bin
 # This removes the requirement of a developer to call it with bash
 RUN            chmod +x bin/test.sh
--- a/testing/docker/ubuntu1204-test-upd/Dockerfile
+++ b/testing/docker/ubuntu1204-test-upd/Dockerfile
@@ -1,9 +1,9 @@
-FROM          taskcluster/ubuntu1204-test:0.1.8
+FROM          taskcluster/ubuntu1204-test:0.1.9
 MAINTAINER    Dustin J. Mitchell <dustin@mozilla.com>
 
 ### update to latest from upstream repositories
 # if this becomes a long list of packages, consider bumping the
 # ubunt1204-test version
 RUN apt-get update && apt-get upgrade -y --force-yes
 
 # Set a default command useful for debugging
--- a/testing/docker/ubuntu1204-test-upd/VERSION
+++ b/testing/docker/ubuntu1204-test-upd/VERSION
@@ -1,1 +1,1 @@
-0.1.8.20160218152601
+0.1.9.20160329211700
--- a/testing/docker/ubuntu1204-test/VERSION
+++ b/testing/docker/ubuntu1204-test/VERSION
@@ -1,1 +1,1 @@
-0.1.8
+0.1.9
--- a/testing/docker/ubuntu1204-test/system-setup.sh
+++ b/testing/docker/ubuntu1204-test/system-setup.sh
@@ -150,18 +150,18 @@ pip install peep-2.4.1.tar.gz
 # repositories; peep verifies file integrity for us
 cat >requirements.txt <<'EOF'
 # wheel
 # sha256: 90pZQ6kAXB6Je8-H9-ivfgDAb6l3e5rWkfafn6VKh9g
 # tarball:
 # sha256: qryO8YzdvYoqnH-SvEPi_qVLEUczDWXbkg7zzpgS49w
 virtualenv==13.1.2
 
-# sha256: tQ9peOfTn-DLKY-j-j6c5B0jVnIdFV5SiPnFfl8T6ac
-mercurial==3.5
+# sha256: wJnELXTi1SC2HdNyzZlrD6dgXAZheDT9exPHm5qaWzA
+mercurial==3.7.3
 EOF
 peep install -r requirements.txt
 
 # Install node
 tooltool_fetch <<'EOF'
 [
 {
     "size": 5676610,
--- a/testing/mach_commands.py
+++ b/testing/mach_commands.py
@@ -607,17 +607,16 @@ class PushToTry(MachCommandBase):
 
         The command requires either its own mercurial extension ("push-to-try",
         installable from mach mercurial-setup) or a git repo using git-cinnabar
         (available at https://github.com/glandium/git-cinnabar).
 
         """
 
         from mozbuild.testing import TestResolver
-        from mozbuild.controller.building import BuildDriver
         from autotry import AutoTry
 
         print("mach try is under development, please file bugs blocking 1149670.")
 
         resolver_func = lambda: self._spawn(TestResolver)
         at = AutoTry(self.topsrcdir, resolver_func, self._mach_context)
 
         if kwargs["list"]:
@@ -640,19 +639,16 @@ class PushToTry(MachCommandBase):
             sys.exit(1)
 
         if not any(kwargs[item] for item in ("paths", "tests", "tags")):
             kwargs["paths"], kwargs["tags"] = at.find_paths_and_tags(kwargs["verbose"])
 
         builds, platforms, tests, talos, paths, tags, extra = self.validate_args(**kwargs)
 
         if paths or tags:
-            driver = self._spawn(BuildDriver)
-            driver.install_tests(remove=False)
-
             paths = [os.path.relpath(os.path.normpath(os.path.abspath(item)), self.topsrcdir)
                      for item in paths]
             paths_by_flavor = at.paths_by_flavor(paths=paths, tags=tags)
 
             if not paths_by_flavor and not tests:
                 print("No tests were found when attempting to resolve paths:\n\n\t%s" %
                       paths)
                 sys.exit(1)
--- a/testing/marionette/harness/marionette/tests/unit/unit-tests.ini
+++ b/testing/marionette/harness/marionette/tests/unit/unit-tests.ini
@@ -22,43 +22,38 @@ b2g = false
 [test_expectedfail.py]
 expected = fail
 [test_import_script.py]
 b2g = false
 [test_click.py]
 [test_click_chrome.py]
 b2g = false
 [test_selected.py]
-skip-if = e10s # Bug 1239552
 [test_selected_chrome.py]
 b2g = false
 [test_getattr.py]
 [test_getattr_chrome.py]
 b2g = false
 [test_elementsize.py]
 [test_position.py]
 [test_rendered_element.py]
 [test_chrome_element_css.py]
 b2g = false
 [test_elementState.py]
 [test_elementState_chrome.py]
 b2g = false
 [test_text.py]
-skip-if = e10s # Bug 1239552
 [test_text_chrome.py]
 disabled = "Bug 896046"
 
 [test_clearing.py]
 [test_typing.py]
-skip-if = e10s # Bug 1239552
 
 [test_log.py]
-skip-if = e10s # Bug 1239552
 [test_emulator.py]
-skip-if = e10s # Bug 1239552
 qemu = true
 
 [test_about_pages.py]
 b2g = false
 
 [test_execute_async_script.py]
 [test_execute_script.py]
 [test_simpletest_fail.js]
--- a/testing/mochitest/mach_commands.py
+++ b/testing/mochitest/mach_commands.py
@@ -380,19 +380,16 @@ class MachCommands(MachCommandBase):
                     flavors = [fname]
                     break
         else:
             flavors = [f for f, v in ALL_FLAVORS.iteritems() if buildapp in v['enabled_apps']]
 
         from mozbuild.controller.building import BuildDriver
         self._ensure_state_subdir_exists('.')
 
-        driver = self._spawn(BuildDriver)
-        driver.install_tests(remove=False)
-
         test_paths = kwargs['test_paths']
         kwargs['test_paths'] = []
 
         if test_paths and buildapp == 'b2g':
             # In B2G there is often a 'gecko' directory, though topsrcdir is actually
             # elsewhere. This little hack makes test paths like 'gecko/dom' work, even if
             # GECKO_PATH is set in the .userconfig
             gecko_path = mozpath.abspath(mozpath.join(kwargs['b2gPath'], 'gecko'))
@@ -405,16 +402,19 @@ class MachCommands(MachCommandBase):
                         new_paths.append(tp)
                 test_paths = new_paths
 
         mochitest = self._spawn(MochitestRunner)
         tests = []
         if resolve_tests:
             tests = mochitest.resolve_tests(test_paths, test_objects, cwd=self._mach_context.cwd)
 
+        driver = self._spawn(BuildDriver)
+        driver.install_tests(tests)
+
         subsuite = kwargs.get('subsuite')
         if subsuite == 'default':
             kwargs['subsuite'] = None
 
         suites = defaultdict(list)
         unsupported = set()
         for test in tests:
             # Filter out non-mochitests and unsupported flavors.
@@ -524,26 +524,25 @@ class RobocopCommands(MachCommandBase):
         if not kwargs.get('robocopApk'):
             kwargs['robocopApk'] = os.path.join(self.topobjdir, 'mobile', 'android',
                                                 'tests', 'browser', 'robocop',
                                                 'robocop-debug.apk')
 
         from mozbuild.controller.building import BuildDriver
         self._ensure_state_subdir_exists('.')
 
-        driver = self._spawn(BuildDriver)
-        driver.install_tests(remove=False)
-
         test_paths = kwargs['test_paths']
         kwargs['test_paths'] = []
 
         from mozbuild.testing import TestResolver
         resolver = self._spawn(TestResolver)
         tests = list(resolver.resolve_tests(paths=test_paths, cwd=self._mach_context.cwd,
                                             flavor='instrumentation', subsuite='robocop'))
+        driver = self._spawn(BuildDriver)
+        driver.install_tests(tests)
 
         if len(tests) < 1:
             print(ROBOCOP_TESTS_NOT_FOUND.format('\n'.join(
                 sorted(list(test_paths)))))
             return 1
 
         from mozrunner.devices.android_device import grant_runtime_permissions
         grant_runtime_permissions(self, kwargs['app'])
--- a/testing/mochitest/tests/SimpleTest/SimpleTest.js
+++ b/testing/mochitest/tests/SimpleTest/SimpleTest.js
@@ -1577,13 +1577,13 @@ window.onerror = function simpletestOner
             SimpleTest.info("Exception thrown by gOldOnError(): " + e);
             // Log its stack.
             if (e.stack) {
                 SimpleTest.info("JavaScript error stack:\n" + e.stack);
             }
         }
     }
 
-    if (!SimpleTest._stopOnLoad && !isExpected) {
+    if (!SimpleTest._stopOnLoad && !isExpected && !SimpleTest._alreadyFinished) {
         // Need to finish() manually here, yet let the test actually end first.
         SimpleTest.executeSoon(SimpleTest.finish);
     }
 };
--- a/testing/mozharness/configs/b2g/releng-emulator.py
+++ b/testing/mozharness/configs/b2g/releng-emulator.py
@@ -57,21 +57,16 @@ config = {
         "translate_hg_to_git": True,
         "translate_base_url": "http://cruncher.build.mozilla.org/mapper/{project}/{vcs}/{rev}",
     },
     "env": {
         "CCACHE_DIR": "/builds/ccache",
         "CCACHE_COMPRESS": "1",
         "CCACHE_UMASK": "002",
         "GAIA_OPTIMIZE": "1",
-        "SYMBOL_SERVER_HOST": "symbolpush.mozilla.org",
-        "SYMBOL_SERVER_USER": "b2gbld",
-        "SYMBOL_SERVER_SSH_KEY": "/home/mock_mozilla/.ssh/b2gbld_dsa",
-        "SYMBOL_SERVER_PATH": "/mnt/netapp/breakpad/symbols_b2g/",
-        "POST_SYMBOL_UPLOAD_CMD": "/usr/local/bin/post-symbol-upload.py",
         "WGET_OPTS": "-c -q",
         "PATH": "/tools/python27/bin:%(PATH)s",
     },
     "clobberer_url": "https://api.pub.build.mozilla.org/clobberer/lastclobber",
     "is_automation": True,
     "repo_mirror_dir": "/builds/git-shared/repo",
     "repo_remote_mappings": {
         'https://android.googlesource.com/': 'https://git.mozilla.org/external/aosp',
--- a/testing/mozharness/configs/b2g/releng-fota-eng.py
+++ b/testing/mozharness/configs/b2g/releng-fota-eng.py
@@ -57,21 +57,16 @@ config = {
         "translate_base_url": "http://cruncher.build.mozilla.org/mapper/{project}/{vcs}/{rev}",
         "target_suffix": "-eng",
     },
     "env": {
         "CCACHE_DIR": "/builds/ccache",
         "CCACHE_COMPRESS": "1",
         "CCACHE_UMASK": "002",
         "GAIA_OPTIMIZE": "1",
-        "SYMBOL_SERVER_HOST": "symbolpush.mozilla.org",
-        "SYMBOL_SERVER_USER": "b2gbld",
-        "SYMBOL_SERVER_SSH_KEY": "/home/mock_mozilla/.ssh/b2gbld_dsa",
-        "SYMBOL_SERVER_PATH": "/mnt/netapp/breakpad/symbols_b2g/",
-        "POST_SYMBOL_UPLOAD_CMD": "/usr/local/bin/post-symbol-upload.py",
         "B2G_UPDATER": "1",
         "B2G_SYSTEM_APPS": "1",
         "WGET_OPTS": "-c -q",
         "PATH": "/tools/python27/bin:%(PATH)s",
         "B2G_UPDATE_CHANNEL": "default",
     },
     "clobberer_url": "https://api.pub.build.mozilla.org/clobberer/lastclobber",
     "is_automation": True,
--- a/testing/mozharness/configs/b2g/releng-fota-updates.py
+++ b/testing/mozharness/configs/b2g/releng-fota-updates.py
@@ -56,21 +56,16 @@ config = {
         "translate_hg_to_git": True,
         "translate_base_url": "http://cruncher.build.mozilla.org/mapper/{project}/{vcs}/{rev}",
     },
     "env": {
         "CCACHE_DIR": "/builds/ccache",
         "CCACHE_COMPRESS": "1",
         "CCACHE_UMASK": "002",
         "GAIA_OPTIMIZE": "1",
-        "SYMBOL_SERVER_HOST": "symbolpush.mozilla.org",
-        "SYMBOL_SERVER_USER": "b2gbld",
-        "SYMBOL_SERVER_SSH_KEY": "/home/mock_mozilla/.ssh/b2gbld_dsa",
-        "SYMBOL_SERVER_PATH": "/mnt/netapp/breakpad/symbols_b2g/",
-        "POST_SYMBOL_UPLOAD_CMD": "/usr/local/bin/post-symbol-upload.py",
         "WGET_OPTS": "-c -q",
         "PATH": "/tools/python27/bin:%(PATH)s",
     },
     "clobberer_url": "https://api.pub.build.mozilla.org/clobberer/lastclobber",
     "is_automation": True,
     "repo_mirror_dir": "/builds/git-shared/repo",
     "repo_remote_mappings": {
         'https://android.googlesource.com/': 'https://git.mozilla.org/external/aosp',
--- a/testing/mozharness/configs/b2g/releng-otoro-eng.py
+++ b/testing/mozharness/configs/b2g/releng-otoro-eng.py
@@ -57,21 +57,16 @@ config = {
         "translate_base_url": "http://cruncher.build.mozilla.org/mapper/{project}/{vcs}/{rev}",
         "target_suffix": "-eng",
     },
     "env": {
         "CCACHE_DIR": "/builds/ccache",
         "CCACHE_COMPRESS": "1",
         "CCACHE_UMASK": "002",
         "GAIA_OPTIMIZE": "1",
-        "SYMBOL_SERVER_HOST": "symbolpush.mozilla.org",
-        "SYMBOL_SERVER_USER": "b2gbld",
-        "SYMBOL_SERVER_SSH_KEY": "/home/mock_mozilla/.ssh/b2gbld_dsa",
-        "SYMBOL_SERVER_PATH": "/mnt/netapp/breakpad/symbols_b2g/",
-        "POST_SYMBOL_UPLOAD_CMD": "/usr/local/bin/post-symbol-upload.py",
         "B2G_UPDATER": "1",
         "B2G_SYSTEM_APPS": "1",
         "WGET_OPTS": "-c -q",
         "PATH": "/tools/python27/bin:%(PATH)s",
         "B2G_UPDATE_CHANNEL": "default",
     },
     "clobberer_url": "https://api.pub.build.mozilla.org/clobberer/lastclobber",
     "is_automation": True,
--- a/testing/mozharness/configs/b2g/releng-otoro.py
+++ b/testing/mozharness/configs/b2g/releng-otoro.py
@@ -55,21 +55,16 @@ config = {
         "translate_hg_to_git": True,
         "translate_base_url": "http://cruncher.build.mozilla.org/mapper/{project}/{vcs}/{rev}",
     },
     "env": {
         "CCACHE_DIR": "/builds/ccache",
         "CCACHE_COMPRESS": "1",
         "CCACHE_UMASK": "002",
         "GAIA_OPTIMIZE": "1",
-        "SYMBOL_SERVER_HOST": "symbolpush.mozilla.org",
-        "SYMBOL_SERVER_USER": "b2gbld",
-        "SYMBOL_SERVER_SSH_KEY": "/home/mock_mozilla/.ssh/b2gbld_dsa",
-        "SYMBOL_SERVER_PATH": "/mnt/netapp/breakpad/symbols_b2g/",
-        "POST_SYMBOL_UPLOAD_CMD": "/usr/local/bin/post-symbol-upload.py",
         "WGET_OPTS": "-c -q",
         "PATH": "/tools/python27/bin:%(PATH)s",
     },
     "clobberer_url": "https://api.pub.build.mozilla.org/clobberer/lastclobber",
     "is_automation": True,
     "repo_mirror_dir": "/builds/git-shared/repo",
     "repo_remote_mappings": {
         'https://android.googlesource.com/': 'https://git.mozilla.org/external/aosp',
--- a/testing/mozharness/configs/b2g/releng-private-updates.py
+++ b/testing/mozharness/configs/b2g/releng-private-updates.py
@@ -56,21 +56,16 @@ config = {
         "translate_hg_to_git": True,
         "translate_base_url": "http://cruncher.build.mozilla.org/mapper/{project}/{vcs}/{rev}",
     },
     "env": {
         "CCACHE_DIR": "/builds/ccache",
         "CCACHE_COMPRESS": "1",
         "CCACHE_UMASK": "002",
         "GAIA_OPTIMIZE": "1",
-        "SYMBOL_SERVER_HOST": "symbolpush.mozilla.org",
-        "SYMBOL_SERVER_USER": "b2gbld",
-        "SYMBOL_SERVER_SSH_KEY": "/home/mock_mozilla/.ssh/b2gbld_dsa",
-        "SYMBOL_SERVER_PATH": "/mnt/netapp/breakpad/symbols_b2g/",
-        "POST_SYMBOL_UPLOAD_CMD": "/usr/local/bin/post-symbol-upload.py",
         "WGET_OPTS": "-c -q",
         "PATH": "/tools/python27/bin:%(PATH)s",
     },
     "clobberer_url": "https://api.pub.build.mozilla.org/clobberer/lastclobber",
     "is_automation": True,
     "repo_mirror_dir": "/builds/git-shared/repo",
     "repo_remote_mappings": {
         'https://android.googlesource.com/': 'https://git.mozilla.org/external/aosp',
--- a/testing/mozharness/configs/builds/branch_specifics.py
+++ b/testing/mozharness/configs/builds/branch_specifics.py
@@ -29,25 +29,23 @@
 # }
 
 config = {
     ### release branches
     "mozilla-central": {
         "repo_path": 'mozilla-central',
         "update_channel": "nightly",
         "graph_server_branch_name": "Firefox",
-        'use_branch_in_symbols_extra_buildid': False,
         'stage_server': 'upload.ffxbld.productdelivery.prod.mozaws.net',
     },
     'mozilla-release': {
         'enable_release_promotion': True,
         'repo_path': 'releases/mozilla-release',
         'update_channel': 'release',
         'branch_uses_per_checkin_strategy': True,
-        'use_branch_in_symbols_extra_buildid': False,
         'stage_server': 'upload.ffxbld.productdelivery.prod.mozaws.net',
         'platform_overrides': {
             'linux': {
                 'src_mozconfig': 'browser/config/mozconfigs/linux32/release',
             },
             'linux64': {
                 'src_mozconfig': 'browser/config/mozconfigs/linux64/release',
             },
@@ -107,17 +105,16 @@ config = {
             },
         },
     },
     'mozilla-beta': {
         'enable_release_promotion': 1,
         'repo_path': 'releases/mozilla-beta',
         'update_channel': 'beta',
         'branch_uses_per_checkin_strategy': True,
-        'use_branch_in_symbols_extra_buildid': False,
         'stage_server': 'upload.ffxbld.productdelivery.prod.mozaws.net',
         'platform_overrides': {
             'linux': {
                 'src_mozconfig': 'browser/config/mozconfigs/linux32/beta',
             },
             'linux64': {
                 'src_mozconfig': 'browser/config/mozconfigs/linux64/beta',
             },
@@ -176,28 +173,26 @@ config = {
                 'update_channel': 'default',
             },
         },
     },
     'mozilla-aurora': {
         'repo_path': 'releases/mozilla-aurora',
         'update_channel': 'aurora',
         'branch_uses_per_checkin_strategy': True,
-        'use_branch_in_symbols_extra_buildid': False,
         'stage_server': 'upload.ffxbld.productdelivery.prod.mozaws.net',
     },
     'try': {
         'repo_path': 'try',
         'clone_by_revision': True,
         'clone_with_purge': True,
         'tinderbox_build_dir': '%(who)s-%(got_revision)s',
         'to_tinderbox_dated': False,
         'include_post_upload_builddir': True,
         'release_to_try_builds': True,
-        'use_branch_in_symbols_extra_buildid': False,
         'stage_server': 'upload.trybld.productdelivery.prod.mozaws.net',
         'stage_username': 'trybld',
         'stage_ssh_key': 'trybld_dsa',
         'branch_supports_uploadsymbols': False,
         'use_clobberer': False,
     },
 
     ### project branches
--- a/testing/mozharness/configs/builds/build_pool_specifics.py
+++ b/testing/mozharness/configs/builds/build_pool_specifics.py
@@ -11,42 +11,39 @@ config = {
         # but in production we let the self.branch decide via
         # self._query_graph_server_branch_name()
         "graph_server_branch_name": "MozillaTest",
         'graph_server': 'graphs.allizom.org',
         "hgtool_base_bundle_urls": [
             'http://dev-stage01.build.mozilla.org/pub/mozilla'
             '.org/firefox/bundles',
         ],
-        'symbol_server_host': "dev-stage01.srv.releng.scl3.mozilla.com",
         'stage_server': 'upload.ffxbld.productdelivery.stage.mozaws.net',
         "sendchange_masters": ["dev-master1.srv.releng.scl3.mozilla.com:9038"],
         'taskcluster_index': 'index.garbage.staging',
         'post_upload_extra': ['--bucket-prefix', 'net-mozaws-stage-delivery',
                               '--url-prefix', 'http://ftp.stage.mozaws.net/',
                               ],
     },
     "production": {
         # if not clobberer_url, only clobber 'abs_work_dir'
         # if true: possibly clobber, clobberer
         # see PurgeMixin for clobber() conditions
         'clobberer_url': 'https://api.pub.build.mozilla.org/clobberer/lastclobber',
         'graph_server': 'graphs.mozilla.org',
         "hgtool_base_bundle_urls": [
             'https://ftp-ssl.mozilla.org/pub/mozilla.org/firefox/bundles'
         ],
-        'symbol_server_host': "symbolpush.mozilla.org",
         # bug 1216907, set this at branch level
         # 'stage_server': 'upload.ffxbld.productdelivery.prod.mozaws.net',
         "sendchange_masters": ["buildbot-master81.build.mozilla.org:9301"],
         'taskcluster_index': 'index',
     },
     "taskcluster": {
         'graph_server': 'graphs.mozilla.org',
-        'symbol_server_host': "symbolpush.mozilla.org",
         'stage_server': 'ignored',
         # use the relengapi proxy to talk to tooltool
         "tooltool_servers": ['http://relengapi/tooltool/'],
         "tooltool_url": 'http://relengapi/tooltool/',
         'upload_env': {
             'UPLOAD_HOST': 'localhost',
             'UPLOAD_PATH': '/home/worker/artifacts',
         },
--- a/testing/mozharness/configs/builds/releng_base_android_64_builds.py
+++ b/testing/mozharness/configs/builds/releng_base_android_64_builds.py
@@ -68,22 +68,16 @@ config = {
     'enable_max_vsize': False,
     'use_package_as_marfile': True,
     'env': {
         'MOZBUILD_STATE_PATH': os.path.join(os.getcwd(), '.mozbuild'),
         'MOZ_AUTOMATION': '1',
         'DISPLAY': ':2',
         'HG_SHARE_BASE_DIR': '/builds/hg-shared',
         'MOZ_OBJDIR': 'obj-firefox',
-        # SYMBOL_SERVER_HOST is dictated from build_pool_specifics.py
-        'SYMBOL_SERVER_HOST': '%(symbol_server_host)s',
-        'SYMBOL_SERVER_SSH_KEY': "/home/mock_mozilla/.ssh/ffxbld_rsa",
-        'SYMBOL_SERVER_USER': 'ffxbld',
-        'SYMBOL_SERVER_PATH': '/mnt/netapp/breakpad/symbols_ffx/',
-        'POST_SYMBOL_UPLOAD_CMD': '/usr/local/bin/post-symbol-upload.py',
         'TINDERBOX_OUTPUT': '1',
         'TOOLTOOL_CACHE': '/builds/tooltool_cache',
         'TOOLTOOL_HOME': '/builds',
         'CCACHE_DIR': '/builds/ccache',