Merge inbound to central, a=merge
authorWes Kocher <wkocher@mozilla.com>
Fri, 24 Feb 2017 16:46:12 -0800
changeset 344830 f36062d04d16
parent 344757 c3ea1dcedccd (current diff)
parent 344829 96b7a5189c50 (diff)
child 344831 a6b4617f0c35
child 344858 23bd8be8d881
child 344918 bbdeb164144f
push id31417
push userkwierso@gmail.com
push dateSat, 25 Feb 2017 00:46:36 +0000
treeherdermozilla-central@f36062d04d16 [default view] [failures only]
perfherder[talos] [build metrics] [platform microbench] (compared to previous push)
reviewersmerge
milestone54.0a1
first release with
nightly linux32
f36062d04d16 / 54.0a1 / 20170225110158 / files
nightly linux64
f36062d04d16 / 54.0a1 / 20170225110158 / files
nightly mac
f36062d04d16 / 54.0a1 / 20170225030208 / files
nightly win32
f36062d04d16 / 54.0a1 / 20170225030208 / files
nightly win64
f36062d04d16 / 54.0a1 / 20170225030208 / files
last release without
nightly linux32
nightly linux64
nightly mac
nightly win32
nightly win64
releases
nightly linux32
nightly linux64
nightly mac
nightly win32
nightly win64
Merge inbound to central, a=merge MozReview-Commit-ID: DpCZgRV1csS
.eslintignore
browser/base/content/test/general/browser.ini
dom/plugins/base/nsPluginNativeWindowGtk.cpp
dom/plugins/base/nsPluginNativeWindowGtk.h
js/src/jit-test/tests/wasm/jsapi.js
js/src/jit-test/tests/wasm/spec/address.wast
js/src/jit-test/tests/wasm/spec/address.wast.js
js/src/jit-test/tests/wasm/spec/binary.wast
js/src/jit-test/tests/wasm/spec/binary.wast.js
js/src/jit-test/tests/wasm/spec/block.wast
js/src/jit-test/tests/wasm/spec/block.wast.js
js/src/jit-test/tests/wasm/spec/br.wast
js/src/jit-test/tests/wasm/spec/br.wast.js
js/src/jit-test/tests/wasm/spec/br_if.wast
js/src/jit-test/tests/wasm/spec/br_if.wast.js
js/src/jit-test/tests/wasm/spec/br_table.wast
js/src/jit-test/tests/wasm/spec/br_table.wast.js
js/src/jit-test/tests/wasm/spec/break-drop.wast
js/src/jit-test/tests/wasm/spec/break-drop.wast.js
js/src/jit-test/tests/wasm/spec/call.wast
js/src/jit-test/tests/wasm/spec/call.wast.js
js/src/jit-test/tests/wasm/spec/call_indirect.wast
js/src/jit-test/tests/wasm/spec/call_indirect.wast.js
js/src/jit-test/tests/wasm/spec/comments.wast
js/src/jit-test/tests/wasm/spec/comments.wast.js
js/src/jit-test/tests/wasm/spec/conversions.wast
js/src/jit-test/tests/wasm/spec/conversions.wast.js
js/src/jit-test/tests/wasm/spec/custom_section.wast
js/src/jit-test/tests/wasm/spec/custom_section.wast.js
js/src/jit-test/tests/wasm/spec/directives.txt
js/src/jit-test/tests/wasm/spec/endianness.wast
js/src/jit-test/tests/wasm/spec/endianness.wast.js
js/src/jit-test/tests/wasm/spec/exports.wast
js/src/jit-test/tests/wasm/spec/exports.wast.js
js/src/jit-test/tests/wasm/spec/f32.wast
js/src/jit-test/tests/wasm/spec/f32.wast.js
js/src/jit-test/tests/wasm/spec/f32_cmp.wast
js/src/jit-test/tests/wasm/spec/f32_cmp.wast.js
js/src/jit-test/tests/wasm/spec/f64.wast
js/src/jit-test/tests/wasm/spec/f64.wast.js
js/src/jit-test/tests/wasm/spec/f64_cmp.wast
js/src/jit-test/tests/wasm/spec/f64_cmp.wast.js
js/src/jit-test/tests/wasm/spec/fac.wast
js/src/jit-test/tests/wasm/spec/fac.wast.js
js/src/jit-test/tests/wasm/spec/float_exprs.wast
js/src/jit-test/tests/wasm/spec/float_exprs.wast.js
js/src/jit-test/tests/wasm/spec/float_literals.wast
js/src/jit-test/tests/wasm/spec/float_literals.wast.js
js/src/jit-test/tests/wasm/spec/float_memory.wast
js/src/jit-test/tests/wasm/spec/float_memory.wast.js
js/src/jit-test/tests/wasm/spec/float_misc.wast
js/src/jit-test/tests/wasm/spec/float_misc.wast.js
js/src/jit-test/tests/wasm/spec/forward.wast
js/src/jit-test/tests/wasm/spec/forward.wast.js
js/src/jit-test/tests/wasm/spec/func.wast
js/src/jit-test/tests/wasm/spec/func.wast.js
js/src/jit-test/tests/wasm/spec/func_ptrs.wast
js/src/jit-test/tests/wasm/spec/func_ptrs.wast.js
js/src/jit-test/tests/wasm/spec/get_local.wast
js/src/jit-test/tests/wasm/spec/get_local.wast.js
js/src/jit-test/tests/wasm/spec/globals.wast
js/src/jit-test/tests/wasm/spec/globals.wast.js
js/src/jit-test/tests/wasm/spec/i32.wast
js/src/jit-test/tests/wasm/spec/i32.wast.js
js/src/jit-test/tests/wasm/spec/i64.wast
js/src/jit-test/tests/wasm/spec/i64.wast.js
js/src/jit-test/tests/wasm/spec/import_tests.sh
js/src/jit-test/tests/wasm/spec/imports.wast
js/src/jit-test/tests/wasm/spec/imports.wast.js
js/src/jit-test/tests/wasm/spec/int_exprs.wast
js/src/jit-test/tests/wasm/spec/int_exprs.wast.js
js/src/jit-test/tests/wasm/spec/int_literals.wast
js/src/jit-test/tests/wasm/spec/int_literals.wast.js
js/src/jit-test/tests/wasm/spec/labels.wast
js/src/jit-test/tests/wasm/spec/labels.wast.js
js/src/jit-test/tests/wasm/spec/left-to-right.wast
js/src/jit-test/tests/wasm/spec/left-to-right.wast.js
js/src/jit-test/tests/wasm/spec/linking.wast
js/src/jit-test/tests/wasm/spec/linking.wast.js
js/src/jit-test/tests/wasm/spec/loop.wast
js/src/jit-test/tests/wasm/spec/loop.wast.js
js/src/jit-test/tests/wasm/spec/memory.wast
js/src/jit-test/tests/wasm/spec/memory.wast.js
js/src/jit-test/tests/wasm/spec/memory_redundancy.wast
js/src/jit-test/tests/wasm/spec/memory_redundancy.wast.js
js/src/jit-test/tests/wasm/spec/memory_trap.wast
js/src/jit-test/tests/wasm/spec/memory_trap.wast.js
js/src/jit-test/tests/wasm/spec/names.wast
js/src/jit-test/tests/wasm/spec/names.wast.js
js/src/jit-test/tests/wasm/spec/nop.wast
js/src/jit-test/tests/wasm/spec/nop.wast.js
js/src/jit-test/tests/wasm/spec/resizing.wast
js/src/jit-test/tests/wasm/spec/resizing.wast.js
js/src/jit-test/tests/wasm/spec/return.wast
js/src/jit-test/tests/wasm/spec/return.wast.js
js/src/jit-test/tests/wasm/spec/select.wast
js/src/jit-test/tests/wasm/spec/select.wast.js
js/src/jit-test/tests/wasm/spec/set_local.wast
js/src/jit-test/tests/wasm/spec/set_local.wast.js
js/src/jit-test/tests/wasm/spec/skip-stack-guard-page.wast
js/src/jit-test/tests/wasm/spec/skip-stack-guard-page.wast.js
js/src/jit-test/tests/wasm/spec/stack.wast
js/src/jit-test/tests/wasm/spec/stack.wast.js
js/src/jit-test/tests/wasm/spec/start.wast
js/src/jit-test/tests/wasm/spec/start.wast.js
js/src/jit-test/tests/wasm/spec/store_retval.wast
js/src/jit-test/tests/wasm/spec/store_retval.wast.js
js/src/jit-test/tests/wasm/spec/switch.wast
js/src/jit-test/tests/wasm/spec/switch.wast.js
js/src/jit-test/tests/wasm/spec/tee_local.wast
js/src/jit-test/tests/wasm/spec/tee_local.wast.js
js/src/jit-test/tests/wasm/spec/traps.wast
js/src/jit-test/tests/wasm/spec/traps.wast.js
js/src/jit-test/tests/wasm/spec/typecheck.wast
js/src/jit-test/tests/wasm/spec/typecheck.wast.js
js/src/jit-test/tests/wasm/spec/unreachable.wast
js/src/jit-test/tests/wasm/spec/unreachable.wast.js
js/src/jit-test/tests/wasm/spec/unreached-invalid.wast
js/src/jit-test/tests/wasm/spec/unreached-invalid.wast.js
js/src/jit-test/tests/wasm/spec/unwind.wast
js/src/jit-test/tests/wasm/spec/unwind.wast.js
js/src/jit-test/tests/wasm/wast.js
media/libyuv/AUTHORS
media/libyuv/Android.mk
media/libyuv/BUILD.gn
media/libyuv/CMakeLists.txt
media/libyuv/DEPS
media/libyuv/LICENSE
media/libyuv/LICENSE_THIRD_PARTY
media/libyuv/OWNERS
media/libyuv/PATENTS
media/libyuv/PRESUBMIT.py
media/libyuv/README.chromium
media/libyuv/README.md
media/libyuv/all.gyp
media/libyuv/build/dir_exists.py
media/libyuv/build/mac/find_sdk.py
media/libyuv/build_overrides/build.gni
media/libyuv/chromium/README
media/libyuv/codereview.settings
media/libyuv/docs/environment_variables.md
media/libyuv/docs/filtering.md
media/libyuv/docs/formats.md
media/libyuv/docs/getting_started.md
media/libyuv/docs/rotation.md
media/libyuv/download_vs_toolchain.py
media/libyuv/gyp_libyuv
media/libyuv/gyp_libyuv.py
media/libyuv/include/libyuv.h
media/libyuv/include/libyuv/basic_types.h
media/libyuv/include/libyuv/compare.h
media/libyuv/include/libyuv/compare_row.h
media/libyuv/include/libyuv/convert.h
media/libyuv/include/libyuv/convert_argb.h
media/libyuv/include/libyuv/convert_from.h
media/libyuv/include/libyuv/convert_from_argb.h
media/libyuv/include/libyuv/cpu_id.h
media/libyuv/include/libyuv/mjpeg_decoder.h
media/libyuv/include/libyuv/planar_functions.h
media/libyuv/include/libyuv/rotate.h
media/libyuv/include/libyuv/rotate_argb.h
media/libyuv/include/libyuv/rotate_row.h
media/libyuv/include/libyuv/row.h
media/libyuv/include/libyuv/scale.h
media/libyuv/include/libyuv/scale_argb.h
media/libyuv/include/libyuv/scale_row.h
media/libyuv/include/libyuv/version.h
media/libyuv/include/libyuv/video_common.h
media/libyuv/libyuv.gyp
media/libyuv/libyuv.gypi
media/libyuv/libyuv_nacl.gyp
media/libyuv/libyuv_test.gyp
media/libyuv/linux.mk
media/libyuv/public.mk
media/libyuv/setup_links.py
media/libyuv/source/compare.cc
media/libyuv/source/compare_common.cc
media/libyuv/source/compare_gcc.cc
media/libyuv/source/compare_neon.cc
media/libyuv/source/compare_neon64.cc
media/libyuv/source/compare_win.cc
media/libyuv/source/convert.cc
media/libyuv/source/convert_argb.cc
media/libyuv/source/convert_from.cc
media/libyuv/source/convert_from_argb.cc
media/libyuv/source/convert_jpeg.cc
media/libyuv/source/convert_to_argb.cc
media/libyuv/source/convert_to_i420.cc
media/libyuv/source/cpu_id.cc
media/libyuv/source/mjpeg_decoder.cc
media/libyuv/source/mjpeg_validate.cc
media/libyuv/source/planar_functions.cc
media/libyuv/source/rotate.cc
media/libyuv/source/rotate_any.cc
media/libyuv/source/rotate_argb.cc
media/libyuv/source/rotate_common.cc
media/libyuv/source/rotate_gcc.cc
media/libyuv/source/rotate_mips.cc
media/libyuv/source/rotate_neon.cc
media/libyuv/source/rotate_neon64.cc
media/libyuv/source/rotate_win.cc
media/libyuv/source/row_any.cc
media/libyuv/source/row_common.cc
media/libyuv/source/row_gcc.cc
media/libyuv/source/row_mips.cc
media/libyuv/source/row_neon.cc
media/libyuv/source/row_neon64.cc
media/libyuv/source/row_win.cc
media/libyuv/source/scale.cc
media/libyuv/source/scale_any.cc
media/libyuv/source/scale_argb.cc
media/libyuv/source/scale_common.cc
media/libyuv/source/scale_gcc.cc
media/libyuv/source/scale_mips.cc
media/libyuv/source/scale_neon.cc
media/libyuv/source/scale_neon64.cc
media/libyuv/source/scale_win.cc
media/libyuv/source/video_common.cc
media/libyuv/sync_chromium.py
media/libyuv/third_party/gflags/BUILD.gn
media/libyuv/third_party/gflags/LICENSE
media/libyuv/third_party/gflags/README.libyuv
media/libyuv/third_party/gflags/gen/posix/include/gflags/gflags.h
media/libyuv/third_party/gflags/gen/posix/include/gflags/gflags_completions.h
media/libyuv/third_party/gflags/gen/posix/include/gflags/gflags_declare.h
media/libyuv/third_party/gflags/gen/posix/include/gflags/gflags_gflags.h
media/libyuv/third_party/gflags/gen/posix/include/private/config.h
media/libyuv/third_party/gflags/gen/win/include/gflags/gflags.h
media/libyuv/third_party/gflags/gen/win/include/gflags/gflags_completions.h
media/libyuv/third_party/gflags/gen/win/include/gflags/gflags_declare.h
media/libyuv/third_party/gflags/gen/win/include/gflags/gflags_gflags.h
media/libyuv/third_party/gflags/gen/win/include/private/config.h
media/libyuv/third_party/gflags/gflags.gyp
media/libyuv/tools/OWNERS
media/libyuv/tools/gritsettings/README
media/libyuv/tools/gritsettings/resource_ids
media/libyuv/tools/msan/OWNERS
media/libyuv/tools/msan/blacklist.txt
media/libyuv/tools/ubsan/OWNERS
media/libyuv/tools/ubsan/blacklist.txt
media/libyuv/tools/ubsan/vptr_blacklist.txt
media/libyuv/tools/valgrind-libyuv/libyuv_tests.bat
media/libyuv/tools/valgrind-libyuv/libyuv_tests.py
media/libyuv/tools/valgrind-libyuv/libyuv_tests.sh
media/libyuv/tools/valgrind-libyuv/memcheck/OWNERS
media/libyuv/tools/valgrind-libyuv/memcheck/PRESUBMIT.py
media/libyuv/tools/valgrind-libyuv/memcheck/suppressions.txt
media/libyuv/tools/valgrind-libyuv/memcheck/suppressions_mac.txt
media/libyuv/tools/valgrind-libyuv/memcheck/suppressions_win32.txt
media/libyuv/tools/valgrind-libyuv/tsan/OWNERS
media/libyuv/tools/valgrind-libyuv/tsan/PRESUBMIT.py
media/libyuv/tools/valgrind-libyuv/tsan/suppressions.txt
media/libyuv/tools/valgrind-libyuv/tsan/suppressions_mac.txt
media/libyuv/tools/valgrind-libyuv/tsan/suppressions_win32.txt
media/libyuv/unit_test/basictypes_test.cc
media/libyuv/unit_test/color_test.cc
media/libyuv/unit_test/compare_test.cc
media/libyuv/unit_test/convert_test.cc
media/libyuv/unit_test/cpu_test.cc
media/libyuv/unit_test/math_test.cc
media/libyuv/unit_test/planar_test.cc
media/libyuv/unit_test/rotate_argb_test.cc
media/libyuv/unit_test/rotate_test.cc
media/libyuv/unit_test/scale_argb_test.cc
media/libyuv/unit_test/scale_test.cc
media/libyuv/unit_test/testdata/arm_v7.txt
media/libyuv/unit_test/testdata/juno.txt
media/libyuv/unit_test/testdata/tegra3.txt
media/libyuv/unit_test/unit_test.cc
media/libyuv/unit_test/unit_test.h
media/libyuv/unit_test/video_common_test.cc
media/libyuv/util/Makefile
media/libyuv/util/android/test_runner.py
media/libyuv/util/compare.cc
media/libyuv/util/convert.cc
media/libyuv/util/cpuid.c
media/libyuv/util/psnr.cc
media/libyuv/util/psnr.h
media/libyuv/util/psnr_main.cc
media/libyuv/util/ssim.cc
media/libyuv/util/ssim.h
media/libyuv/winarm.mk
media/webrtc/signaling/signaling.gyp
--- a/.eslintignore
+++ b/.eslintignore
@@ -103,18 +103,16 @@ devtools/client/webconsole/webconsole-co
 devtools/client/webconsole/webconsole.js
 devtools/client/webide/**
 !devtools/client/webide/components/webideCli.js
 devtools/server/actors/webconsole.js
 devtools/server/actors/object.js
 devtools/server/actors/script.js
 devtools/server/actors/styleeditor.js
 devtools/server/actors/stylesheets.js
-devtools/server/tests/browser/**
-!devtools/server/tests/browser/browser_webextension_inspected_window.js
 devtools/server/tests/mochitest/**
 devtools/server/tests/unit/**
 devtools/shared/heapsnapshot/**
 
 # Ignore devtools pre-processed files
 devtools/client/framework/toolbox-process-window.js
 devtools/client/performance/system.js
 devtools/client/webide/webide-prefs.js
--- a/.hgignore
+++ b/.hgignore
@@ -39,16 +39,18 @@
 
 # SpiderMonkey configury
 ^js/src/configure$
 ^js/src/old-configure$
 ^js/src/autom4te.cache$
 # SpiderMonkey test result logs
 ^js/src/tests/results-.*\.(html|txt)$
 ^js/src/devtools/rootAnalysis/t/out
+# SpiderMonkey clone of the webassembly spec repository
+^js/src/wasm/spec
 
 # Java HTML5 parser classes
 ^parser/html/java/(html|java)parser/
 
 # SVN directories
 \.svn/
 
 # Ignore the files and directory that Eclipse IDE creates
--- a/accessible/ipc/DocAccessibleParent.cpp
+++ b/accessible/ipc/DocAccessibleParent.cpp
@@ -393,35 +393,36 @@ DocAccessibleParent::RecvBindChildDoc(PD
 
   MOZ_ASSERT(CheckDocTree());
 
   auto childDoc = static_cast<DocAccessibleParent*>(aChildDoc);
   childDoc->Unbind();
   ipc::IPCResult result = AddChildDoc(childDoc, aID, false);
   MOZ_ASSERT(result);
   MOZ_ASSERT(CheckDocTree());
+#ifdef DEBUG
   if (!result) {
     return result;
   }
-  return IPC_OK();
+#else
+  result = IPC_OK();
+#endif
+
+  return result;
 }
 
 ipc::IPCResult
 DocAccessibleParent::AddChildDoc(DocAccessibleParent* aChildDoc,
                                  uint64_t aParentID, bool aCreating)
 {
   // We do not use GetAccessible here because we want to be sure to not get the
   // document it self.
   ProxyEntry* e = mAccessibles.GetEntry(aParentID);
   if (!e) {
-#ifdef DEBUG
     return IPC_FAIL(this, "binding to nonexistant proxy!");
-#else
-    return IPC_OK();
-#endif
   }
 
   ProxyAccessible* outerDoc = e->mProxy;
   MOZ_ASSERT(outerDoc);
 
   // OuterDocAccessibles are expected to only have a document as a child.
   // However for compatibility we tolerate replacing one document with another
   // here.
--- a/accessible/ipc/win/PlatformChild.cpp
+++ b/accessible/ipc/win/PlatformChild.cpp
@@ -41,16 +41,17 @@ static const mozilla::mscom::ArrayData s
 // Type libraries are thread-neutral, so we can register those from any
 // apartment. OTOH, proxies must be registered from within the apartment where
 // we intend to instantiate them. Therefore RegisterProxy() must be called
 // via EnsureMTA.
 PlatformChild::PlatformChild()
   : mAccTypelib(mozilla::mscom::RegisterTypelib(L"oleacc.dll",
         mozilla::mscom::RegistrationFlags::eUseSystemDirectory))
   , mMiscTypelib(mozilla::mscom::RegisterTypelib(L"Accessible.tlb"))
+  , mSdnTypelib(mozilla::mscom::RegisterTypelib(L"AccessibleMarshal.dll"))
 {
   mozilla::mscom::InterceptorLog::Init();
   mozilla::mscom::RegisterArrayData(sPlatformChildArrayData);
 
 
   UniquePtr<mozilla::mscom::RegisteredProxy> customProxy;
   mozilla::mscom::EnsureMTA([&customProxy]() -> void {
     customProxy = Move(mozilla::mscom::RegisterProxy());
--- a/accessible/ipc/win/PlatformChild.h
+++ b/accessible/ipc/win/PlatformChild.h
@@ -22,15 +22,16 @@ public:
   PlatformChild& operator=(PlatformChild&) = delete;
   PlatformChild& operator=(PlatformChild&&) = delete;
 
 private:
   UniquePtr<mozilla::mscom::RegisteredProxy> mCustomProxy;
   UniquePtr<mozilla::mscom::RegisteredProxy> mIA2Proxy;
   UniquePtr<mozilla::mscom::RegisteredProxy> mAccTypelib;
   UniquePtr<mozilla::mscom::RegisteredProxy> mMiscTypelib;
+  UniquePtr<mozilla::mscom::RegisteredProxy> mSdnTypelib;
 };
 
 } // namespace mozilla
 } // namespace a11y
 
 #endif // mozilla_a11y_PlatformChild_h
 
--- a/browser/base/content/test/general/browser.ini
+++ b/browser/base/content/test/general/browser.ini
@@ -422,16 +422,17 @@ support-files =
 [browser_visibleTabs_bookmarkAllPages.js]
 skip-if = true # Bug 1005420 - fails intermittently. also with e10s enabled: bizarre problem with hidden tab having _mouseenter called, via _setPositionalAttributes, and tab not being found resulting in 'candidate is undefined'
 [browser_visibleTabs_bookmarkAllTabs.js]
 [browser_visibleTabs_contextMenu.js]
 [browser_visibleTabs_tabPreview.js]
 skip-if = (os == "win" && !debug)
 [browser_web_channel.js]
 [browser_windowopen_reflows.js]
+skip-if = os == "mac" # bug 1339317
 [browser_zbug569342.js]
 skip-if = e10s || debug # Bug 1094240 - has findbar-related failures
 [browser_registerProtocolHandler_notification.js]
 [browser_addCertException.js]
 [browser_e10s_about_page_triggeringprincipal.js]
 support-files =
   file_about_child.html
   file_about_parent.html
--- a/browser/base/content/test/webrtc/browser.ini
+++ b/browser/base/content/test/webrtc/browser.ini
@@ -10,10 +10,10 @@ skip-if = (os == "linux" && debug) # lin
 [browser_devices_get_user_media_anim.js]
 [browser_devices_get_user_media_in_frame.js]
 [browser_devices_get_user_media_screen.js]
 skip-if = (e10s && debug) || (os == "linux" && !debug) # bug 1320754 for e10s debug, and bug 1320994 for linux opt
 [browser_devices_get_user_media_tear_off_tab.js]
 [browser_devices_get_user_media_unprompted_access.js]
 [browser_devices_get_user_media_unprompted_access_in_frame.js]
 [browser_devices_get_user_media_unprompted_access_tear_off_tab.js]
-skip-if = (os == "linux") # linux: bug 1331616
+skip-if = (os == "linux") || (os == "win" && bits == 64) # linux: bug 1331616, win8: bug 1334752
 [browser_webrtc_hooks.js]
--- a/build/gyp.mozbuild
+++ b/build/gyp.mozbuild
@@ -30,17 +30,17 @@ gyp_vars.update({
     'build_json': 0,
     'build_libjpeg': 0,
     'build_libyuv': 0,
     'build_libvpx': 0,
     'build_ssl': 0,
     'build_json': 0,
     'build_icu': 0,
     'build_opus': 0,
-    'libyuv_dir': '/media/libyuv',
+    'libyuv_dir': '/media/libyuv/libyuv',
     'yuv_disable_avx2': 0 if CONFIG['HAVE_X86_AVX2'] else 1,
     # don't use openssl
     'use_openssl': 0,
 
     'debug': 1 if CONFIG['DEBUG'] else 0,
 
     'use_x11': 1 if CONFIG['MOZ_X11'] else 0,
     'use_glib': 1 if CONFIG['GLIB_LIBS'] else 0,
--- a/devtools/client/inspector/inspector.xhtml
+++ b/devtools/client/inspector/inspector.xhtml
@@ -17,16 +17,17 @@
   <link rel="stylesheet" href="chrome://devtools/skin/layout.css"/>
   <link rel="stylesheet" href="chrome://devtools/skin/animationinspector.css"/>
   <link rel="stylesheet" href="resource://devtools/client/shared/components/sidebar-toggle.css"/>
   <link rel="stylesheet" href="resource://devtools/client/shared/components/tabs/tabs.css"/>
   <link rel="stylesheet" href="resource://devtools/client/shared/components/tabs/tabbar.css"/>
   <link rel="stylesheet" href="resource://devtools/client/inspector/components/inspector-tab-panel.css"/>
   <link rel="stylesheet" href="resource://devtools/client/shared/components/splitter/split-box.css"/>
   <link rel="stylesheet" href="resource://devtools/client/inspector/layout/components/Accordion.css"/>
+  <link rel="stylesheet" href="resource://devtools/client/shared/components/reps/reps.css"/>
 
   <script type="application/javascript;version=1.8"
           src="chrome://devtools/content/shared/theme-switching.js"></script>
   <script type="text/javascript">
     /* eslint-disable */
     var isInChrome = window.location.href.includes("chrome:");
     if (isInChrome) {
       var exports = {};
--- a/devtools/client/inspector/layout/components/App.js
+++ b/devtools/client/inspector/layout/components/App.js
@@ -25,16 +25,17 @@ const App = createClass({
 
   displayName: "App",
 
   propTypes: {
     boxModel: PropTypes.shape(Types.boxModel).isRequired,
     getSwatchColorPickerTooltip: PropTypes.func.isRequired,
     grids: PropTypes.arrayOf(PropTypes.shape(Types.grid)).isRequired,
     highlighterSettings: PropTypes.shape(Types.highlighterSettings).isRequired,
+    setSelectedNode: PropTypes.func.isRequired,
     showBoxModelProperties: PropTypes.bool.isRequired,
     onHideBoxModelHighlighter: PropTypes.func.isRequired,
     onSetGridOverlayColor: PropTypes.func.isRequired,
     onShowBoxModelEditor: PropTypes.func.isRequired,
     onShowBoxModelHighlighter: PropTypes.func.isRequired,
     onToggleGridHighlighter: PropTypes.func.isRequired,
     onToggleShowGridLineNumbers: PropTypes.func.isRequired,
     onToggleShowInfiniteLines: PropTypes.func.isRequired,
--- a/devtools/client/inspector/layout/components/Grid.js
+++ b/devtools/client/inspector/layout/components/Grid.js
@@ -16,44 +16,53 @@ const { getStr } = require("../utils/l10
 module.exports = createClass({
 
   displayName: "Grid",
 
   propTypes: {
     getSwatchColorPickerTooltip: PropTypes.func.isRequired,
     grids: PropTypes.arrayOf(PropTypes.shape(Types.grid)).isRequired,
     highlighterSettings: PropTypes.shape(Types.highlighterSettings).isRequired,
+    setSelectedNode: PropTypes.func.isRequired,
+    onHideBoxModelHighlighter: PropTypes.func.isRequired,
     onSetGridOverlayColor: PropTypes.func.isRequired,
+    onShowBoxModelHighlighterForNode: PropTypes.func.isRequired,
     onToggleGridHighlighter: PropTypes.func.isRequired,
     onToggleShowGridLineNumbers: PropTypes.func.isRequired,
     onToggleShowInfiniteLines: PropTypes.func.isRequired,
   },
 
   mixins: [ addons.PureRenderMixin ],
 
   render() {
     let {
       getSwatchColorPickerTooltip,
       grids,
       highlighterSettings,
+      setSelectedNode,
+      onHideBoxModelHighlighter,
       onSetGridOverlayColor,
+      onShowBoxModelHighlighterForNode,
       onToggleGridHighlighter,
       onToggleShowGridLineNumbers,
       onToggleShowInfiniteLines,
     } = this.props;
 
     return grids.length ?
       dom.div(
         {
           id: "layout-grid-container",
         },
         GridList({
           getSwatchColorPickerTooltip,
           grids,
+          setSelectedNode,
+          onHideBoxModelHighlighter,
           onSetGridOverlayColor,
+          onShowBoxModelHighlighterForNode,
           onToggleGridHighlighter,
         }),
         GridDisplaySettings({
           highlighterSettings,
           onToggleShowGridLineNumbers,
           onToggleShowInfiniteLines,
         })
       )
--- a/devtools/client/inspector/layout/components/GridItem.js
+++ b/devtools/client/inspector/layout/components/GridItem.js
@@ -1,27 +1,35 @@
 /* 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/. */
 
 "use strict";
 
-const { addons, createClass, DOM: dom, PropTypes } = require("devtools/client/shared/vendor/react");
+const { addons, createClass, createFactory, DOM: dom, PropTypes } = require("devtools/client/shared/vendor/react");
 const { findDOMNode } = require("devtools/client/shared/vendor/react-dom");
 
+// Reps
+const { REPS } = require("devtools/client/shared/components/reps/reps");
+const Rep = createFactory(REPS.Rep);
+const ElementNode = REPS.ElementNode;
+
 const Types = require("../types");
 
 module.exports = createClass({
 
   displayName: "GridItem",
 
   propTypes: {
     getSwatchColorPickerTooltip: PropTypes.func.isRequired,
     grid: PropTypes.shape(Types.grid).isRequired,
+    setSelectedNode: PropTypes.func.isRequired,
+    onHideBoxModelHighlighter: PropTypes.func.isRequired,
     onSetGridOverlayColor: PropTypes.func.isRequired,
+    onShowBoxModelHighlighterForNode: PropTypes.func.isRequired,
     onToggleGridHighlighter: PropTypes.func.isRequired,
   },
 
   mixins: [ addons.PureRenderMixin ],
 
   componentDidMount() {
     let tooltip = this.props.getSwatchColorPickerTooltip();
     let swatchEl = findDOMNode(this).querySelector(".grid-color-swatch");
@@ -45,58 +53,97 @@ module.exports = createClass({
     tooltip.removeSwatch(swatchEl);
   },
 
   setGridColor() {
     let color = findDOMNode(this).querySelector(".grid-color-value").textContent;
     this.props.onSetGridOverlayColor(this.props.grid.nodeFront, color);
   },
 
-  onGridCheckboxClick() {
+  /**
+   * While waiting for a reps fix in https://github.com/devtools-html/reps/issues/92,
+   * translate nodeFront to a grip-like object that can be used with an ElementNode rep.
+   *
+   * @params  {NodeFront} nodeFront
+   *          The NodeFront for which we want to create a grip-like object.
+   * @returns {Object} a grip-like object that can be used with Reps.
+   */
+  translateNodeFrontToGrip(nodeFront) {
+    let { attributes } = nodeFront;
+
+    // The main difference between NodeFront and grips is that attributes are treated as
+    // a map in grips and as an array in NodeFronts.
+    let attributesMap = {};
+    for (let {name, value} of attributes) {
+      attributesMap[name] = value;
+    }
+
+    return {
+      actor: nodeFront.actorID,
+      preview: {
+        attributes: attributesMap,
+        attributesLength: attributes.length,
+        // nodeName is already lowerCased in Node grips
+        nodeName: nodeFront.nodeName.toLowerCase(),
+        nodeType: nodeFront.nodeType,
+      }
+    };
+  },
+
+  onGridCheckboxClick(e) {
+    // If the click was on the svg icon to select the node in the inspector, bail out.
+    let originalTarget = e.nativeEvent && e.nativeEvent.explicitOriginalTarget;
+    if (originalTarget && originalTarget.namespaceURI === "http://www.w3.org/2000/svg") {
+      // We should be able to cancel the click event propagation after the following reps
+      // issue is implemented : https://github.com/devtools-html/reps/issues/95 .
+      e.preventDefault();
+      return;
+    }
+
     let {
       grid,
       onToggleGridHighlighter,
     } = this.props;
 
     onToggleGridHighlighter(grid.nodeFront);
   },
 
   render() {
-    let { grid } = this.props;
+    let {
+      grid,
+      onHideBoxModelHighlighter,
+      onShowBoxModelHighlighterForNode,
+      setSelectedNode,
+    } = this.props;
     let { nodeFront } = grid;
-    let { displayName, attributes } = nodeFront;
-
-    let gridName = displayName;
-
-    let idIndex = attributes.findIndex(({ name }) => name === "id");
-    if (idIndex > -1 && attributes[idIndex].value) {
-      gridName += "#" + attributes[idIndex].value;
-    }
-
-    let classIndex = attributes.findIndex(({name}) => name === "class");
-    if (classIndex > -1 && attributes[classIndex].value) {
-      gridName += "." + attributes[classIndex].value.split(" ").join(".");
-    }
 
     return dom.li(
       {
         key: grid.id,
         className: "grid-item",
       },
       dom.label(
         {},
         dom.input(
           {
             type: "checkbox",
             value: grid.id,
             checked: grid.highlighted,
             onChange: this.onGridCheckboxClick,
           }
         ),
-        gridName
+        Rep(
+          {
+            defaultRep: ElementNode,
+            object: this.translateNodeFrontToGrip(nodeFront),
+            onDOMNodeMouseOut: () => onHideBoxModelHighlighter(),
+            onDOMNodeMouseOver: () => onShowBoxModelHighlighterForNode(nodeFront),
+            onInspectIconClick: () => setSelectedNode(nodeFront),
+          }
+        )
       ),
       dom.div(
         {
           className: "grid-color-swatch",
           style: {
             backgroundColor: grid.color,
           },
           title: grid.color,
--- a/devtools/client/inspector/layout/components/GridList.js
+++ b/devtools/client/inspector/layout/components/GridList.js
@@ -14,43 +14,52 @@ const { getStr } = require("../utils/l10
 
 module.exports = createClass({
 
   displayName: "GridList",
 
   propTypes: {
     getSwatchColorPickerTooltip: PropTypes.func.isRequired,
     grids: PropTypes.arrayOf(PropTypes.shape(Types.grid)).isRequired,
+    setSelectedNode: PropTypes.func.isRequired,
+    onHideBoxModelHighlighter: PropTypes.func.isRequired,
     onSetGridOverlayColor: PropTypes.func.isRequired,
+    onShowBoxModelHighlighterForNode: PropTypes.func.isRequired,
     onToggleGridHighlighter: PropTypes.func.isRequired,
   },
 
   mixins: [ addons.PureRenderMixin ],
 
   render() {
     let {
       getSwatchColorPickerTooltip,
       grids,
+      setSelectedNode,
+      onHideBoxModelHighlighter,
       onSetGridOverlayColor,
+      onShowBoxModelHighlighterForNode,
       onToggleGridHighlighter,
     } = this.props;
 
     return dom.div(
       {
         className: "grid-container",
       },
       dom.span(
         {},
         getStr("layout.overlayGrid")
       ),
       dom.ul(
         {},
         grids.map(grid => GridItem({
           getSwatchColorPickerTooltip,
           grid,
+          setSelectedNode,
+          onHideBoxModelHighlighter,
           onSetGridOverlayColor,
+          onShowBoxModelHighlighterForNode,
           onToggleGridHighlighter,
         }))
       )
     );
   },
 
 });
--- a/devtools/client/inspector/layout/layout.js
+++ b/devtools/client/inspector/layout/layout.js
@@ -95,24 +95,31 @@ LayoutView.prototype = {
       /**
        * Retrieve the shared SwatchColorPicker instance.
        */
       getSwatchColorPickerTooltip: () => {
         return this.swatchColorPickerTooltip;
       },
 
       /**
+       * Set the inspector selection.
+       * @param {NodeFront} nodeFront
+       *        The NodeFront corresponding to the new selection.
+       */
+      setSelectedNode: (nodeFront) => {
+        this.inspector.selection.setNodeFront(nodeFront, "layout-panel");
+      },
+
+      /**
        * Shows the box model properties under the box model if true, otherwise, hidden by
        * default.
        */
       showBoxModelProperties: true,
 
       onHideBoxModelHighlighter,
-      onShowBoxModelEditor,
-      onShowBoxModelHighlighter,
 
       /**
        * Handler for a change in the grid overlay color picker for a grid container.
        *
        * @param  {NodeFront} node
        *         The NodeFront of the grid container element for which the grid color is
        *         being updated.
        * @param  {String} color
@@ -127,16 +134,33 @@ LayoutView.prototype = {
         for (let grid of grids) {
           if (grid.nodeFront === node && grid.highlighted) {
             let highlighterSettings = this.getGridHighlighterSettings(node);
             this.highlighters.showGridHighlighter(node, highlighterSettings);
           }
         }
       },
 
+      onShowBoxModelEditor,
+      onShowBoxModelHighlighter,
+
+     /**
+       * Shows the box-model highlighter on the element corresponding to the provided
+       * NodeFront.
+       *
+       * @param  {NodeFront} nodeFront
+       *         The node to highlight.
+       * @param  {Object} options
+       *         Options passed to the highlighter actor.
+       */
+      onShowBoxModelHighlighterForNode: (nodeFront, options) => {
+        let toolbox = this.inspector.toolbox;
+        toolbox.highlighterUtils.highlightNodeFront(nodeFront, options);
+      },
+
       /**
        * Handler for a change in the input checkboxes in the GridList component.
        * Toggles on/off the grid highlighter for the provided grid container element.
        *
        * @param  {NodeFront} node
        *         The NodeFront of the grid container element for which the grid
        *         highlighter is toggled on/off for.
        */
--- a/devtools/server/tests/browser/animation.html
+++ b/devtools/server/tests/browser/animation.html
@@ -156,15 +156,15 @@
 <div class="long-animation"></div>
 <div class="short-animation"></div>
 <div class="delayed-animation"></div>
 <div class="delayed-transition"></div>
 <div class="delayed-multiple-animations"></div>
 <div class="multiple-animations-2"></div>
 <div class="all-transitions"></div>
 <script type="text/javascript">
+  "use strict";
   // Get the transitions started when the page loads
-  var players;
-  addEventListener("load", function() {
+  addEventListener("load", function () {
     document.querySelector(".transition").classList.add("get-round");
     document.querySelector(".delayed-transition").classList.add("get-round");
   });
 </script>
--- a/devtools/server/tests/browser/browser_animation_getFrames.js
+++ b/devtools/server/tests/browser/browser_animation_getFrames.js
@@ -1,32 +1,30 @@
-/* vim: set ft=javascript ts=2 et sw=2 tw=80: */
-/* Any copyright is dedicated to the Public Domain.
-   http://creativecommons.org/publicdomain/zero/1.0/ */
-
-"use strict";
-
-// Check that the AnimationPlayerActor exposes a getFrames method that returns
-// the list of keyframes in the animation.
-
-const URL = MAIN_DOMAIN + "animation.html";
-
-add_task(function* () {
-  let {client, walker, animations} =
-    yield initAnimationsFrontForUrl(MAIN_DOMAIN + "animation.html");
-
-  info("Get the test node and its animation front");
-  let node = yield walker.querySelector(walker.rootNode, ".simple-animation");
-  let [player] = yield animations.getAnimationPlayersForNode(node);
-
-  ok(player.getFrames, "The front has the getFrames method");
-
-  let frames = yield player.getFrames();
-  is(frames.length, 2, "The correct number of keyframes was retrieved");
-  ok(frames[0].transform, "Frame 0 has the transform property");
-  ok(frames[1].transform, "Frame 1 has the transform property");
-  // Note that we don't really test the content of the frame object here on
-  // purpose. This object comes straight out of the web animations API
-  // unmodified.
-
-  yield client.close();
-  gBrowser.removeCurrentTab();
-});
+/* vim: set ft=javascript ts=2 et sw=2 tw=80: */
+/* Any copyright is dedicated to the Public Domain.
+   http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+// Check that the AnimationPlayerActor exposes a getFrames method that returns
+// the list of keyframes in the animation.
+
+add_task(function* () {
+  let {client, walker, animations} =
+    yield initAnimationsFrontForUrl(MAIN_DOMAIN + "animation.html");
+
+  info("Get the test node and its animation front");
+  let node = yield walker.querySelector(walker.rootNode, ".simple-animation");
+  let [player] = yield animations.getAnimationPlayersForNode(node);
+
+  ok(player.getFrames, "The front has the getFrames method");
+
+  let frames = yield player.getFrames();
+  is(frames.length, 2, "The correct number of keyframes was retrieved");
+  ok(frames[0].transform, "Frame 0 has the transform property");
+  ok(frames[1].transform, "Frame 1 has the transform property");
+  // Note that we don't really test the content of the frame object here on
+  // purpose. This object comes straight out of the web animations API
+  // unmodified.
+
+  yield client.close();
+  gBrowser.removeCurrentTab();
+});
--- a/devtools/server/tests/browser/browser_animation_getProperties.js
+++ b/devtools/server/tests/browser/browser_animation_getProperties.js
@@ -1,36 +1,36 @@
-/* vim: set ft=javascript ts=2 et sw=2 tw=80: */
-/* Any copyright is dedicated to the Public Domain.
-   http://creativecommons.org/publicdomain/zero/1.0/ */
-
-"use strict";
-
-// Check that the AnimationPlayerActor exposes a getProperties method that
-// returns the list of animated properties in the animation.
-
-const URL = MAIN_DOMAIN + "animation.html";
-
-add_task(function* () {
-  let {client, walker, animations} = yield initAnimationsFrontForUrl(URL);
-
-  info("Get the test node and its animation front");
-  let node = yield walker.querySelector(walker.rootNode, ".simple-animation");
-  let [player] = yield animations.getAnimationPlayersForNode(node);
-
-  ok(player.getProperties, "The front has the getProperties method");
-
-  let properties = yield player.getProperties();
-  is(properties.length, 1, "The correct number of properties was retrieved");
-
-  let propertyObject = properties[0];
-  is(propertyObject.name, "transform", "Property 0 is transform");
-
-  is(propertyObject.values.length, 2,
-    "The correct number of property values was retrieved");
-
-  // Note that we don't really test the content of the frame object here on
-  // purpose. This object comes straight out of the web animations API
-  // unmodified.
-
-  yield client.close();
-  gBrowser.removeCurrentTab();
-});
+/* vim: set ft=javascript ts=2 et sw=2 tw=80: */
+/* Any copyright is dedicated to the Public Domain.
+   http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+// Check that the AnimationPlayerActor exposes a getProperties method that
+// returns the list of animated properties in the animation.
+
+const URL = MAIN_DOMAIN + "animation.html";
+
+add_task(function* () {
+  let {client, walker, animations} = yield initAnimationsFrontForUrl(URL);
+
+  info("Get the test node and its animation front");
+  let node = yield walker.querySelector(walker.rootNode, ".simple-animation");
+  let [player] = yield animations.getAnimationPlayersForNode(node);
+
+  ok(player.getProperties, "The front has the getProperties method");
+
+  let properties = yield player.getProperties();
+  is(properties.length, 1, "The correct number of properties was retrieved");
+
+  let propertyObject = properties[0];
+  is(propertyObject.name, "transform", "Property 0 is transform");
+
+  is(propertyObject.values.length, 2,
+    "The correct number of property values was retrieved");
+
+  // Note that we don't really test the content of the frame object here on
+  // purpose. This object comes straight out of the web animations API
+  // unmodified.
+
+  yield client.close();
+  gBrowser.removeCurrentTab();
+});
--- a/devtools/server/tests/browser/browser_animation_refreshTransitions.js
+++ b/devtools/server/tests/browser/browser_animation_refreshTransitions.js
@@ -16,31 +16,36 @@ add_task(function* () {
   let node = yield walker.querySelector(walker.rootNode, ".all-transitions");
 
   info("Retrieve the animation players for the node");
   let players = yield animations.getAnimationPlayersForNode(node);
   is(players.length, 0, "The node has no animation players yet");
 
   info("Play a transition by adding the expand class, wait for mutations");
   let onMutations = expectMutationEvents(animations, 2);
-  let cpow = content.document.querySelector(".all-transitions");
-  cpow.classList.add("expand");
+  yield ContentTask.spawn(gBrowser.selectedBrowser, {}, () => {
+    let el = content.document.querySelector(".all-transitions");
+    el.classList.add("expand");
+  });
   let reportedMutations = yield onMutations;
 
   is(reportedMutations.length, 2, "2 mutation events were received");
   is(reportedMutations[0].type, "added", "The first event was 'added'");
   is(reportedMutations[1].type, "added", "The second event was 'added'");
 
   info("Wait for the transitions to be finished");
   yield waitForEnd(reportedMutations[0].player);
   yield waitForEnd(reportedMutations[1].player);
 
   info("Play the transition back by removing the class, wait for mutations");
   onMutations = expectMutationEvents(animations, 4);
-  cpow.classList.remove("expand");
+  yield ContentTask.spawn(gBrowser.selectedBrowser, {}, () => {
+    let el = content.document.querySelector(".all-transitions");
+    el.classList.remove("expand");
+  });
   reportedMutations = yield onMutations;
 
   is(reportedMutations.length, 4, "4 new mutation events were received");
   is(reportedMutations.filter(m => m.type === "removed").length, 2,
     "2 'removed' events were sent (for the old transitions)");
   is(reportedMutations.filter(m => m.type === "added").length, 2,
     "2 'added' events were sent (for the new transitions)");
 
--- a/devtools/server/tests/browser/browser_animation_setPlaybackRate.js
+++ b/devtools/server/tests/browser/browser_animation_setPlaybackRate.js
@@ -36,16 +36,16 @@ add_task(function* () {
   info("Retrieve several animation players and set their rates");
   node = yield walker.querySelector(walker.rootNode, "body");
   let players = yield animations.getAnimationPlayersForNode(node);
 
   info("Change all animations in <body> to .5 rate");
   yield animations.setPlaybackRates(players, .5);
 
   info("Query their states and check they are correct");
-  for (let player of players) {
-    let state = yield player.getCurrentState();
-    is(state.playbackRate, .5, "The playbackRate was updated");
+  for (let animPlayer of players) {
+    let animPlayerState = yield animPlayer.getCurrentState();
+    is(animPlayerState.playbackRate, .5, "The playbackRate was updated");
   }
 
   yield client.close();
   gBrowser.removeCurrentTab();
 });
--- a/devtools/server/tests/browser/browser_canvasframe_helper_01.js
+++ b/devtools/server/tests/browser/browser_canvasframe_helper_01.js
@@ -14,16 +14,17 @@ const {HighlighterEnvironment} = require
 const {
   CanvasFrameAnonymousContentHelper
 } = require("devtools/server/actors/highlighters/utils/markup");
 
 const TEST_URL = "data:text/html;charset=utf-8,CanvasFrameAnonymousContentHelper test";
 
 add_task(function* () {
   let browser = yield addTab(TEST_URL);
+  // eslint-disable-next-line mozilla/no-cpows-in-tests
   let doc = browser.contentDocument;
 
   let nodeBuilder = () => {
     let root = doc.createElement("div");
     let child = doc.createElement("div");
     child.style = "width:200px;height:200px;background:red;";
     child.id = "child-element";
     child.className = "child-element";
--- a/devtools/server/tests/browser/browser_canvasframe_helper_02.js
+++ b/devtools/server/tests/browser/browser_canvasframe_helper_02.js
@@ -14,16 +14,17 @@ require("devtools/server/actors/inspecto
 const {HighlighterEnvironment} = require("devtools/server/actors/highlighters");
 
 const {
   CanvasFrameAnonymousContentHelper
 } = require("devtools/server/actors/highlighters/utils/markup");
 
 add_task(function* () {
   let browser = yield addTab("about:preferences");
+  // eslint-disable-next-line mozilla/no-cpows-in-tests
   let doc = browser.contentDocument;
 
   let nodeBuilder = () => {
     let root = doc.createElement("div");
     let child = doc.createElement("div");
     child.style = "width:200px;height:200px;background:red;";
     child.id = "child-element";
     child.className = "child-element";
--- a/devtools/server/tests/browser/browser_canvasframe_helper_03.js
+++ b/devtools/server/tests/browser/browser_canvasframe_helper_03.js
@@ -15,16 +15,17 @@ const {HighlighterEnvironment} = require
 const {
   CanvasFrameAnonymousContentHelper
 } = require("devtools/server/actors/highlighters/utils/markup");
 
 const TEST_URL = "data:text/html;charset=utf-8,CanvasFrameAnonymousContentHelper test";
 
 add_task(function* () {
   let browser = yield addTab(TEST_URL);
+  // eslint-disable-next-line mozilla/no-cpows-in-tests
   let doc = browser.contentDocument;
 
   let nodeBuilder = () => {
     let root = doc.createElement("div");
     let child = doc.createElement("div");
     child.style = "pointer-events:auto;width:200px;height:200px;background:red;";
     child.id = "child-element";
     child.className = "child-element";
@@ -92,11 +93,11 @@ add_task(function* () {
 
   gBrowser.removeCurrentTab();
 });
 
 function synthesizeMouseDown(x, y, win) {
   // We need to make sure the inserted anonymous content can be targeted by the
   // event right after having been inserted, and so we need to force a sync
   // reflow.
-  let forceReflow = win.document.documentElement.offsetWidth;
+  win.document.documentElement.offsetWidth;
   EventUtils.synthesizeMouseAtPoint(x, y, {type: "mousedown"}, win);
 }
--- a/devtools/server/tests/browser/browser_canvasframe_helper_04.js
+++ b/devtools/server/tests/browser/browser_canvasframe_helper_04.js
@@ -5,29 +5,31 @@
 "use strict";
 
 // Test the CanvasFrameAnonymousContentHelper re-inserts the content when the
 // page reloads.
 
 // This makes sure the 'domnode' protocol actor type is known when importing
 // highlighter.
 require("devtools/server/actors/inspector");
-const events = require("sdk/event/core");
 
 const {HighlighterEnvironment} = require("devtools/server/actors/highlighters");
 
 const {
   CanvasFrameAnonymousContentHelper
 } = require("devtools/server/actors/highlighters/utils/markup");
 
-const TEST_URL_1 = "data:text/html;charset=utf-8,CanvasFrameAnonymousContentHelper test 1";
-const TEST_URL_2 = "data:text/html;charset=utf-8,CanvasFrameAnonymousContentHelper test 2";
+const TEST_URL_1 =
+  "data:text/html;charset=utf-8,CanvasFrameAnonymousContentHelper test 1";
+const TEST_URL_2 =
+  "data:text/html;charset=utf-8,CanvasFrameAnonymousContentHelper test 2";
 
 add_task(function* () {
-  let browser = yield addTab(TEST_URL_2);
+  let browser = yield addTab(TEST_URL_1);
+  // eslint-disable-next-line mozilla/no-cpows-in-tests
   let doc = browser.contentDocument;
 
   let nodeBuilder = () => {
     let root = doc.createElement("div");
     let child = doc.createElement("div");
     child.style = "pointer-events:auto;width:200px;height:200px;background:red;";
     child.id = "child-element";
     child.className = "child-element";
@@ -61,18 +63,19 @@ add_task(function* () {
   info("Synthesizing an event on the element");
   let onDocMouseDown = once(doc, "mousedown");
   synthesizeMouseDown(100, 100, doc.defaultView);
   yield onDocMouseDown;
   is(mouseDownHandled, 1, "The mousedown event was handled once before navigation");
 
   info("Navigating to a new page");
   let loaded = BrowserTestUtils.browserLoaded(gBrowser.selectedBrowser);
-  content.location = TEST_URL_2;
+  BrowserTestUtils.loadURI(browser, TEST_URL_2);
   yield loaded;
+  // eslint-disable-next-line mozilla/no-cpows-in-tests
   doc = gBrowser.selectedBrowser.contentWindow.document;
 
   info("Try to access the element again");
   is(el.getAttribute("class"), "child-element",
     "The attribute is correct after navigation");
   is(el.getTextContent(), "test content",
     "The text content is correct after navigation");
 
@@ -88,11 +91,11 @@ add_task(function* () {
 
   gBrowser.removeCurrentTab();
 });
 
 function synthesizeMouseDown(x, y, win) {
   // We need to make sure the inserted anonymous content can be targeted by the
   // event right after having been inserted, and so we need to force a sync
   // reflow.
-  let forceReflow = win.document.documentElement.offsetWidth;
+  win.document.documentElement.offsetWidth;
   EventUtils.synthesizeMouseAtPoint(x, y, {type: "mousedown"}, win);
 }
--- a/devtools/server/tests/browser/browser_canvasframe_helper_05.js
+++ b/devtools/server/tests/browser/browser_canvasframe_helper_05.js
@@ -16,16 +16,17 @@ const {HighlighterEnvironment} = require
 const {
   CanvasFrameAnonymousContentHelper
 } = require("devtools/server/actors/highlighters/utils/markup");
 
 const TEST_URL = "data:text/html;charset=utf-8,CanvasFrameAnonymousContentHelper test";
 
 add_task(function* () {
   let browser = yield addTab(TEST_URL);
+  // eslint-disable-next-line mozilla/no-cpows-in-tests
   let doc = browser.contentDocument;
 
   let nodeBuilder = () => {
     let root = doc.createElement("div");
 
     let parent = doc.createElement("div");
     parent.style = "pointer-events:auto;width:300px;height:300px;background:yellow;";
     parent.id = "parent-element";
@@ -102,11 +103,11 @@ add_task(function* () {
 
   gBrowser.removeCurrentTab();
 });
 
 function synthesizeMouseDown(x, y, win) {
   // We need to make sure the inserted anonymous content can be targeted by the
   // event right after having been inserted, and so we need to force a sync
   // reflow.
-  let forceReflow = win.document.documentElement.offsetWidth;
+  win.document.documentElement.offsetWidth;
   EventUtils.synthesizeMouseAtPoint(x, y, {type: "mousedown"}, win);
 }
--- a/devtools/server/tests/browser/browser_canvasframe_helper_06.js
+++ b/devtools/server/tests/browser/browser_canvasframe_helper_06.js
@@ -16,16 +16,17 @@ const {HighlighterEnvironment} = require
 const {
   CanvasFrameAnonymousContentHelper
 } = require("devtools/server/actors/highlighters/utils/markup");
 
 const TEST_URL = "data:text/html;charset=utf-8,CanvasFrameAnonymousContentHelper test";
 
 add_task(function* () {
   let browser = yield addTab(TEST_URL);
+  // eslint-disable-next-line mozilla/no-cpows-in-tests
   let doc = browser.contentDocument;
 
   let nodeBuilder = () => {
     let root = doc.createElement("div");
 
     let parent = doc.createElement("div");
     parent.style = "pointer-events:auto;width:300px;height:300px;background:yellow;";
     parent.id = "parent-element";
@@ -90,11 +91,11 @@ add_task(function* () {
 
   gBrowser.removeCurrentTab();
 });
 
 function synthesizeMouseDown(x, y, win) {
   // We need to make sure the inserted anonymous content can be targeted by the
   // event right after having been inserted, and so we need to force a sync
   // reflow.
-  let forceReflow = win.document.documentElement.offsetWidth;
+  win.document.documentElement.offsetWidth;
   EventUtils.synthesizeMouseAtPoint(x, y, {type: "mousedown"}, win);
 }
--- a/devtools/server/tests/browser/browser_directorscript_actors.js
+++ b/devtools/server/tests/browser/browser_directorscript_actors.js
@@ -3,18 +3,17 @@
    http://creativecommons.org/publicdomain/zero/1.0/ */
 
 "use strict";
 
 const {DirectorManagerFront} = require("devtools/shared/fronts/director-manager");
 const {DirectorRegistry} = require("devtools/server/actors/director-registry");
 
 add_task(function* () {
-  let browser = yield addTab(MAIN_DOMAIN + "director-script-target.html");
-  let doc = browser.contentDocument;
+  yield addTab(MAIN_DOMAIN + "director-script-target.html");
 
   initDebuggerServer();
   let client = new DebuggerClient(DebuggerServer.connectPipe());
   let form = yield connectDebuggerClient(client);
 
   DirectorRegistry.clear();
   let directorManager = DirectorManagerFront(client, form);
 
@@ -45,18 +44,18 @@ function* testDirectorScriptAttachEventA
      "attach event should contains directorScriptId");
   is(url, MAIN_DOMAIN + "director-script-target.html");
 }
 
 function* testDirectorScriptMessagePort(directorManager) {
   let { port } = yield installAndEnableDirectorScript(directorManager, {
     scriptId: "testDirectorScript_MessagePort",
     scriptCode: "(" + (function () {
-      exports.attach = function ({port}) {
-        port.onmessage = function (evt) {
+      exports.attach = function ({port: messagePort}) {
+        messagePort.onmessage = function (evt) {
           // echo messages
           evt.target.postMessage(evt.data);
         };
       };
     }).toString() + ")();",
     scriptOptions: {
       attachMethod: "attach"
     }
@@ -64,32 +63,33 @@ function* testDirectorScriptMessagePort(
 
   ok(port && port.postMessage, "testDirector_MessagePort port received");
 
   // exchange messages over the MessagePort
   let waitForMessagePortEvent = once(port, "message");
   // needs to explicit start the port
   port.start();
 
-  var msg = { k1: "v1", k2: [1, 2, 3] };
+  let msg = { k1: "v1", k2: [1, 2, 3] };
   port.postMessage(msg);
 
-  var reply = yield waitForMessagePortEvent;
+  let reply = yield waitForMessagePortEvent;
 
-  is(JSON.stringify(reply.data), JSON.stringify(msg), "echo reply received on the MessagePortClient");
+  is(JSON.stringify(reply.data), JSON.stringify(msg),
+    "echo reply received on the MessagePortClient");
 }
 
 function* testDirectorScriptWindowEval(directorManager) {
   let { port } = yield installAndEnableDirectorScript(directorManager, {
     scriptId: "testDirectorScript_WindowEval",
     scriptCode: "(" + (function () {
-      exports.attach = function ({window, port}) {
-        var onpageloaded = function () {
-          var globalVarValue = window.eval("globalAccessibleVar;");
-          port.postMessage(globalVarValue);
+      exports.attach = function ({window, port: evalPort}) {
+        let onpageloaded = function () {
+          let globalVarValue = window.eval("globalAccessibleVar;");
+          evalPort.postMessage(globalVarValue);
         };
 
         if (window.document && window.document.readyState === "complete") {
           onpageloaded();
         } else {
           window.addEventListener("load", onpageloaded);
         }
       };
@@ -101,44 +101,46 @@ function* testDirectorScriptWindowEval(d
 
   ok(port, "testDirectorScript_WindowEval port received");
 
   // exchange messages over the MessagePort
   let waitForMessagePortEvent = once(port, "message");
   // needs to explicit start the port
   port.start();
 
-  var portEvent = yield waitForMessagePortEvent;
+  let portEvent = yield waitForMessagePortEvent;
 
   ok(portEvent.data !== "unsecure-eval", "window.eval should be wrapped and safe");
-  is(portEvent.data, "global-value", "globalAccessibleVar should be accessible through window.eval");
+  is(portEvent.data, "global-value",
+    "globalAccessibleVar should be accessible through window.eval");
 }
 
 function* testDirectorScriptUnloadOnDetach(directorManager) {
   let { port } = yield installAndEnableDirectorScript(directorManager, {
     scriptId: "testDirectorScript_unloadOnDetach",
     scriptCode: "(" + (function () {
-      exports.attach = function ({port, onUnload}) {
+      exports.attach = function ({port: unloadPort, onUnload}) {
         onUnload(function () {
-          port.postMessage("ONUNLOAD");
+          unloadPort.postMessage("ONUNLOAD");
         });
       };
     }).toString() + ")();",
     scriptOptions: {
       attachMethod: "attach"
     }
   });
 
   ok(port, "testDirectorScript_unloadOnDetach port received");
   port.start();
 
   let waitForDetach = once(directorManager, "director-script-detach");
   let waitForMessage = once(port, "message");
 
-  directorManager.disableByScriptIds(["testDirectorScript_unloadOnDetach"], {reload: false});
+  directorManager.disableByScriptIds(["testDirectorScript_unloadOnDetach"],
+                                    {reload: false});
 
   let { directorScriptId } = yield waitForDetach;
   is(directorScriptId, "testDirectorScript_unloadOnDetach",
      "detach event should contains directorScriptId");
 
   let portEvent = yield waitForMessage;
   is(portEvent.data, "ONUNLOAD", "director-script's exports.onUnload called on detach");
 }
--- a/devtools/server/tests/browser/browser_directorscript_actors_error_events.js
+++ b/devtools/server/tests/browser/browser_directorscript_actors_error_events.js
@@ -3,18 +3,17 @@
    http://creativecommons.org/publicdomain/zero/1.0/ */
 
 "use strict";
 
 const {DirectorManagerFront} = require("devtools/shared/fronts/director-manager");
 const {DirectorRegistry} = require("devtools/server/actors/director-registry");
 
 add_task(function* () {
-  let browser = yield addTab(MAIN_DOMAIN + "director-script-target.html");
-  let doc = browser.contentDocument;
+  yield addTab(MAIN_DOMAIN + "director-script-target.html");
 
   initDebuggerServer();
   let client = new DebuggerClient(DebuggerServer.connectPipe());
   let form = yield connectDebuggerClient(client);
 
   DirectorRegistry.clear();
   let directorManager = DirectorManagerFront(client, form);
 
@@ -38,71 +37,73 @@ function* testErrorOnRequire(directorMan
       require("fake_module");
     }).toString() + ")();",
     scriptOptions: {}
   });
 
   assertIsDirectorScriptError(errorOnRequire);
 
   let { message } = errorOnRequire;
-  is(message, "Error: NOT IMPLEMENTED", "error.message contains the expected error message");
+  is(message, "Error: NOT IMPLEMENTED",
+    "error.message contains the expected error message");
 }
 
 function* testErrorOnEvaluate(directorManager) {
-  // director scripts should send an error events if the director script raise an exception on
-  // evaluation
+  // director scripts should send an error events if the director script
+  // raise an exception on evaluation
   let errorOnEvaluate = yield installAndEnableDirectorScript(directorManager, {
     scriptId: "testDirectorScript_errorOnEvaluate",
     scriptCode: "(" + (function () {
       // this will raise an exception evaluating
       // the director script
       raise.an_error.during.content_script.load();
     }).toString() + ")();",
     scriptOptions: {}
   });
   assertIsDirectorScriptError(errorOnEvaluate);
 }
 
 function* testErrorOnAttach(directorManager) {
-  // director scripts should send an error events if the director script raise an exception on
-  // evaluation
+  // director scripts should send an error events if the director script
+  // raise an exception on evaluation
   let errorOnAttach = yield installAndEnableDirectorScript(directorManager, {
     scriptId: "testDirectorScript_errorOnAttach",
     scriptCode: "(" + (function () {
       // this will raise an exception on evaluating
       // the director script
       module.exports = function () {
         raise.an_error.during.content_script.load();
       };
     }).toString() + ")();",
     scriptOptions: {}
   });
   assertIsDirectorScriptError(errorOnAttach);
 }
 
 function* testErrorOnDetach(directorManager) {
-  // director scripts should send an error events if the director script raise an exception on
-  // evaluation
-  let attach = yield installAndEnableDirectorScript(directorManager, {
+  // director scripts should send an error events if the director script
+  // raise an exception on evaluation
+  yield installAndEnableDirectorScript(directorManager, {
     scriptId: "testDirectorScript_errorOnDetach",
     scriptCode: "(" + (function () {
       module.exports = function ({onUnload}) {
         // this will raise an exception on unload the director script
         onUnload(function () {
           raise_an_error_onunload();
         });
       };
     }).toString() + ")();",
     scriptOptions: {}
   });
 
   let waitForDetach = once(directorManager, "director-script-detach");
   let waitForError = once(directorManager, "director-script-error");
 
-  directorManager.disableByScriptIds(["testDirectorScript_errorOnDetach"], {reload: false});
+  directorManager.disableByScriptIds(["testDirectorScript_errorOnDetach"],
+                                    {reload: false});
 
   let detach = yield waitForDetach;
   let error = yield waitForError;
   ok(detach, "testDirectorScript_errorOnDetach detach event received");
   ok(error, "testDirectorScript_errorOnDetach detach error received");
   assertIsDirectorScriptError(error);
 }
 
--- a/devtools/server/tests/browser/browser_directorscript_actors_exports.js
+++ b/devtools/server/tests/browser/browser_directorscript_actors_exports.js
@@ -5,18 +5,17 @@
 "use strict";
 
 const {DirectorManagerFront} = require("devtools/shared/fronts/director-manager");
 const {DirectorRegistry} = require("devtools/server/actors/director-registry");
 
 DirectorRegistry.clear();
 
 add_task(function* () {
-  let browser = yield addTab(MAIN_DOMAIN + "director-script-target.html");
-  let doc = browser.contentDocument;
+  yield addTab(MAIN_DOMAIN + "director-script-target.html");
 
   initDebuggerServer();
   let client = new DebuggerClient(DebuggerServer.connectPipe());
   let form = yield connectDebuggerClient(client);
 
   DirectorRegistry.clear();
   let directorManager = DirectorManagerFront(client, form);
 
--- a/devtools/server/tests/browser/browser_markers-cycle-collection.js
+++ b/devtools/server/tests/browser/browser_markers-cycle-collection.js
@@ -1,33 +1,36 @@
 /* Any copyright is dedicated to the Public Domain.
    http://creativecommons.org/publicdomain/zero/1.0/ */
 
 /**
  * Test that we get "nsCycleCollector::Collect" and
  * "nsCycleCollector::ForgetSkippable" markers when we force cycle collection.
  */
+"use strict";
 
 const { PerformanceFront } = require("devtools/shared/fronts/performance");
 
 add_task(function* () {
   // This test runs very slowly on linux32 debug EC2 instances.
   requestLongerTimeout(2);
 
-  let browser = yield addTab(MAIN_DOMAIN + "doc_force_cc.html");
-  let doc = browser.contentDocument;
+  yield addTab(MAIN_DOMAIN + "doc_force_cc.html");
 
   initDebuggerServer();
   let client = new DebuggerClient(DebuggerServer.connectPipe());
   let form = yield connectDebuggerClient(client);
   let front = PerformanceFront(client, form);
   yield front.connect();
   let rec = yield front.startRecording({ withMarkers: true });
 
-  let markers = yield waitForMarkerType(front, ["nsCycleCollector::Collect", "nsCycleCollector::ForgetSkippable"]);
+  let markers = yield waitForMarkerType(front,
+    ["nsCycleCollector::Collect", "nsCycleCollector::ForgetSkippable"]);
   yield front.stopRecording(rec);
 
-  ok(markers.some(m => m.name === "nsCycleCollector::Collect"), "got some nsCycleCollector::Collect markers");
-  ok(markers.some(m => m.name === "nsCycleCollector::ForgetSkippable"), "got some nsCycleCollector::Collect markers");
+  ok(markers.some(m => m.name === "nsCycleCollector::Collect"),
+    "got some nsCycleCollector::Collect markers");
+  ok(markers.some(m => m.name === "nsCycleCollector::ForgetSkippable"),
+    "got some nsCycleCollector::Collect markers");
 
   yield client.close();
   gBrowser.removeCurrentTab();
 });
--- a/devtools/server/tests/browser/browser_markers-docloading-01.js
+++ b/devtools/server/tests/browser/browser_markers-docloading-01.js
@@ -1,20 +1,22 @@
 /* Any copyright is dedicated to the Public Domain.
    http://creativecommons.org/publicdomain/zero/1.0/ */
 
 /**
  * Test that we get DOMContentLoaded and Load markers
  */
+"use strict";
 
 const { TimelineFront } = require("devtools/shared/fronts/timeline");
 const MARKER_NAMES = ["document::DOMContentLoaded", "document::Load"];
 
 add_task(function* () {
   let browser = yield addTab(MAIN_DOMAIN + "doc_innerHTML.html");
+  // eslint-disable-next-line mozilla/no-cpows-in-tests
   let doc = browser.contentDocument;
 
   initDebuggerServer();
   let client = new DebuggerClient(DebuggerServer.connectPipe());
   let form = yield connectDebuggerClient(client);
   let front = TimelineFront(client, form);
   let rec = yield front.start({ withMarkers: true });
 
--- a/devtools/server/tests/browser/browser_markers-docloading-02.js
+++ b/devtools/server/tests/browser/browser_markers-docloading-02.js
@@ -1,20 +1,22 @@
 /* Any copyright is dedicated to the Public Domain.
    http://creativecommons.org/publicdomain/zero/1.0/ */
 
 /**
  * Test that we get DOMContentLoaded and Load markers
  */
+"use strict";
 
 const { TimelineFront } = require("devtools/shared/fronts/timeline");
 const MARKER_NAMES = ["document::DOMContentLoaded", "document::Load"];
 
 add_task(function* () {
   let browser = yield addTab(MAIN_DOMAIN + "doc_innerHTML.html");
+  // eslint-disable-next-line mozilla/no-cpows-in-tests
   let doc = browser.contentDocument;
 
   initDebuggerServer();
   let client = new DebuggerClient(DebuggerServer.connectPipe());
   let form = yield connectDebuggerClient(client);
   let front = TimelineFront(client, form);
   let rec = yield front.start({ withMarkers: true, withDocLoadingEvents: true });
 
--- a/devtools/server/tests/browser/browser_markers-docloading-03.js
+++ b/devtools/server/tests/browser/browser_markers-docloading-03.js
@@ -1,20 +1,22 @@
 /* Any copyright is dedicated to the Public Domain.
    http://creativecommons.org/publicdomain/zero/1.0/ */
 
 /**
  * Test that we get DOMContentLoaded and Load markers
  */
+"use strict";
 
 const { TimelineFront } = require("devtools/shared/fronts/timeline");
 const MARKER_NAMES = ["document::DOMContentLoaded", "document::Load"];
 
 add_task(function* () {
   let browser = yield addTab(MAIN_DOMAIN + "doc_innerHTML.html");
+  // eslint-disable-next-line mozilla/no-cpows-in-tests
   let doc = browser.contentDocument;
 
   initDebuggerServer();
   let client = new DebuggerClient(DebuggerServer.connectPipe());
   let form = yield connectDebuggerClient(client);
   let front = TimelineFront(client, form);
   let rec = yield front.start({ withDocLoadingEvents: true });
 
--- a/devtools/server/tests/browser/browser_markers-gc.js
+++ b/devtools/server/tests/browser/browser_markers-gc.js
@@ -1,21 +1,21 @@
 /* Any copyright is dedicated to the Public Domain.
    http://creativecommons.org/publicdomain/zero/1.0/ */
 
 /**
  * Test that we get "GarbageCollection" markers.
  */
+"use strict";
 
 const { PerformanceFront } = require("devtools/shared/fronts/performance");
 const MARKER_NAME = "GarbageCollection";
 
 add_task(function* () {
-  let browser = yield addTab(MAIN_DOMAIN + "doc_force_gc.html");
-  let doc = browser.contentDocument;
+  yield addTab(MAIN_DOMAIN + "doc_force_gc.html");
 
   initDebuggerServer();
   let client = new DebuggerClient(DebuggerServer.connectPipe());
   let form = yield connectDebuggerClient(client);
   let front = PerformanceFront(client, form);
   yield front.connect();
   let rec = yield front.startRecording({ withMarkers: true });
 
@@ -32,17 +32,18 @@ add_task(function* () {
 
   // Bug 1197646
   let ordered = true;
   markers.reduce((previousStart, current, i) => {
     if (i === 0) {
       return current.start;
     }
     if (current.start < previousStart) {
-      ok(false, `markers must be in order. ${current.name} marker has later start time (${current.start}) thanprevious: ${previousStart}`);
+      ok(false, `markers must be in order. ${current.name} marker has later\
+        start time (${current.start}) thanprevious: ${previousStart}`);
       ordered = false;
     }
     return current.start;
   });
 
   is(ordered, true, "All GC and non-GC markers are in order by start time.");
 
   yield client.close();
--- a/devtools/server/tests/browser/browser_markers-minor-gc.js
+++ b/devtools/server/tests/browser/browser_markers-minor-gc.js
@@ -1,23 +1,24 @@
 /* Any copyright is dedicated to the Public Domain.
    http://creativecommons.org/publicdomain/zero/1.0/ */
 
 /**
  * Test that we get "MinorGC" markers when we continue to steadily allocate
  * objects.
  */
+"use strict";
 
 const { PerformanceFront } = require("devtools/shared/fronts/performance");
 
 add_task(function* () {
   // This test runs very slowly on linux32 debug EC2 instances.
   requestLongerTimeout(2);
 
-  let doc = yield addTab(MAIN_DOMAIN + "doc_allocations.html");
+  yield addTab(MAIN_DOMAIN + "doc_allocations.html");
 
   initDebuggerServer();
   let client = new DebuggerClient(DebuggerServer.connectPipe());
   let form = yield connectDebuggerClient(client);
   let front = PerformanceFront(client, form);
   yield front.connect();
   let rec = yield front.startRecording({ withMarkers: true });
 
--- a/devtools/server/tests/browser/browser_markers-parse-html.js
+++ b/devtools/server/tests/browser/browser_markers-parse-html.js
@@ -1,21 +1,21 @@
 /* Any copyright is dedicated to the Public Domain.
    http://creativecommons.org/publicdomain/zero/1.0/ */
 
 /**
  * Test that we get "Parse HTML" markers.
  */
+"use strict";
 
 const { PerformanceFront } = require("devtools/shared/fronts/performance");
 const MARKER_NAME = "Parse HTML";
 
 add_task(function* () {
-  let browser = yield addTab(MAIN_DOMAIN + "doc_innerHTML.html");
-  let doc = browser.contentDocument;
+  yield addTab(MAIN_DOMAIN + "doc_innerHTML.html");
 
   initDebuggerServer();
   let client = new DebuggerClient(DebuggerServer.connectPipe());
   let form = yield connectDebuggerClient(client);
   let front = PerformanceFront(client, form);
   yield front.connect();
   let rec = yield front.startRecording({ withMarkers: true });
 
--- a/devtools/server/tests/browser/browser_markers-styles.js
+++ b/devtools/server/tests/browser/browser_markers-styles.js
@@ -1,31 +1,31 @@
 /* Any copyright is dedicated to the Public Domain.
    http://creativecommons.org/publicdomain/zero/1.0/ */
 
 /**
  * Test that we get "Styles" markers with correct meta.
  */
+"use strict";
 
 const { PerformanceFront } = require("devtools/shared/fronts/performance");
 const MARKER_NAME = "Styles";
 
 add_task(function* () {
-  let browser = yield addTab(MAIN_DOMAIN + "doc_perf.html");
-  let doc = browser.contentDocument;
+  yield addTab(MAIN_DOMAIN + "doc_perf.html");
 
   initDebuggerServer();
   let client = new DebuggerClient(DebuggerServer.connectPipe());
   let form = yield connectDebuggerClient(client);
   let front = PerformanceFront(client, form);
   yield front.connect();
   let rec = yield front.startRecording({ withMarkers: true });
 
-  let markers = yield waitForMarkerType(front, MARKER_NAME, function (markers) {
-    return markers.some(({restyleHint}) => restyleHint != void 0);
+  let markers = yield waitForMarkerType(front, MARKER_NAME, function (marker) {
+    return marker.some(({restyleHint}) => restyleHint != void 0);
   });
 
   yield front.stopRecording(rec);
 
   ok(markers.some(m => m.name === MARKER_NAME), `got some ${MARKER_NAME} markers`);
   ok(markers.some(({restyleHint}) => restyleHint != void 0),
     "Some markers have a restyleHint.");
 
--- a/devtools/server/tests/browser/browser_markers-timestamp.js
+++ b/devtools/server/tests/browser/browser_markers-timestamp.js
@@ -1,40 +1,43 @@
 /* Any copyright is dedicated to the Public Domain.
    http://creativecommons.org/publicdomain/zero/1.0/ */
 
 /**
  * Test that we get a "TimeStamp" marker.
  */
+"use strict";
 
 const { PerformanceFront } = require("devtools/shared/fronts/performance");
-const { pmmConsoleMethod, pmmLoadFrameScripts, pmmClearFrameScripts } = require("devtools/client/performance/test/helpers/profiler-mm-utils");
+const { pmmConsoleMethod, pmmLoadFrameScripts, pmmClearFrameScripts }
+  = require("devtools/client/performance/test/helpers/profiler-mm-utils");
 const MARKER_NAME = "TimeStamp";
 
 add_task(function* () {
-  let browser = yield addTab(MAIN_DOMAIN + "doc_perf.html");
-  let doc = browser.contentDocument;
+  yield addTab(MAIN_DOMAIN + "doc_perf.html");
 
   initDebuggerServer();
   let client = new DebuggerClient(DebuggerServer.connectPipe());
   let form = yield connectDebuggerClient(client);
   let front = PerformanceFront(client, form);
   yield front.connect();
   let rec = yield front.startRecording({ withMarkers: true });
 
   pmmLoadFrameScripts(gBrowser);
   pmmConsoleMethod("timeStamp");
   pmmConsoleMethod("timeStamp", "myLabel");
 
-  let markers = yield waitForMarkerType(front, MARKER_NAME, markers => markers.length >= 2);
+  let markers = yield waitForMarkerType(front, MARKER_NAME, m => m.length >= 2);
 
   yield front.stopRecording(rec);
 
-  ok(markers.every(({stack}) => typeof stack === "number"), "All markers have stack references.");
-  ok(markers.every(({name}) => name === "TimeStamp"), "All markers found are TimeStamp markers");
+  ok(markers.every(({stack}) => typeof stack === "number"),
+    "All markers have stack references.");
+  ok(markers.every(({name}) => name === "TimeStamp"),
+    "All markers found are TimeStamp markers");
   ok(markers.length === 2, "found 2 TimeStamp markers");
   ok(markers.every(({start, end}) => typeof start === "number" && start === end),
     "All markers have equal start and end times");
   is(markers[0].causeName, void 0, "Unlabeled timestamps have an empty causeName");
   is(markers[1].causeName, "myLabel", "Labeled timestamps have correct causeName");
 
   pmmClearFrameScripts();
 
--- a/devtools/server/tests/browser/browser_navigateEvents.js
+++ b/devtools/server/tests/browser/browser_navigateEvents.js
@@ -5,60 +5,66 @@
 "use strict";
 
 const URL1 = MAIN_DOMAIN + "navigate-first.html";
 const URL2 = MAIN_DOMAIN + "navigate-second.html";
 
 var events = require("sdk/event/core");
 var client;
 
-SpecialPowers.pushPrefEnv({"set": [["dom.require_user_interaction_for_beforeunload", false]]});
+SpecialPowers.pushPrefEnv(
+  {"set": [["dom.require_user_interaction_for_beforeunload", false]]});
 
 // State machine to check events order
 var i = 0;
 function assertEvent(event, data) {
-  let x = 0;
   switch (i++) {
-    case x++:
+    case 0:
       is(event, "request", "Get first page load");
       is(data, URL1);
       break;
-    case x++:
+    case 1:
       is(event, "load-new-document", "Ask to load the second page");
       break;
-    case x++:
+    case 2:
       is(event, "unload-dialog", "We get the dialog on first page unload");
       break;
-    case x++:
+    case 3:
       is(event, "will-navigate", "The very first event is will-navigate on server side");
       is(data.newURI, URL2, "newURI property is correct");
       break;
-    case x++:
-      is(event, "request", "RDP is async with messageManager, the request happens after will-navigate");
+    case 4:
+      is(event, "request",
+        "RDP is async with messageManager, the request happens after will-navigate");
       is(data, URL2);
       break;
-    case x++:
+    case 5:
       is(event, "tabNavigated", "After the request, the client receive tabNavigated");
       is(data.state, "start", "state is start");
       is(data.url, URL2, "url property is correct");
       is(data.nativeConsoleAPI, true, "nativeConsoleAPI is correct");
       break;
-    case x++:
+    case 6:
       is(event, "DOMContentLoaded");
+      // eslint-disable-next-line mozilla/no-cpows-in-tests
       is(content.document.readyState, "interactive");
       break;
-    case x++:
+    case 7:
       is(event, "load");
+      // eslint-disable-next-line mozilla/no-cpows-in-tests
       is(content.document.readyState, "complete");
       break;
-    case x++:
-      is(event, "navigate", "Then once the second doc is loaded, we get the navigate event");
-      is(content.document.readyState, "complete", "navigate is emitted only once the document is fully loaded");
+    case 8:
+      is(event, "navigate",
+        "Then once the second doc is loaded, we get the navigate event");
+      // eslint-disable-next-line mozilla/no-cpows-in-tests
+      is(content.document.readyState, "complete",
+        "navigate is emitted only once the document is fully loaded");
       break;
-    case x++:
+    case 9:
       is(event, "tabNavigated", "Finally, the receive the client event");
       is(data.state, "stop", "state is stop");
       is(data.url, URL2, "url property is correct");
       is(data.nativeConsoleAPI, true, "nativeConsoleAPI is correct");
 
       // End of test!
       cleanup();
       break;
@@ -97,32 +103,31 @@ function getServerTabActor(callback) {
   // Ensure having a minimal server
   initDebuggerServer();
 
   // Connect to this tab
   let transport = DebuggerServer.connectPipe();
   client = new DebuggerClient(transport);
   connectDebuggerClient(client).then(form => {
     let actorID = form.actor;
-    client.attachTab(actorID, function (aResponse, aTabClient) {
+    client.attachTab(actorID, function (response, tabClient) {
       // !Hack! Retrieve a server side object, the BrowserTabActor instance
       let tabActor = DebuggerServer._searchAllConnectionsForActor(actorID);
       callback(tabActor);
     });
   });
 
-  client.addListener("tabNavigated", function (aEvent, aPacket) {
-    assertEvent("tabNavigated", aPacket);
+  client.addListener("tabNavigated", function (event, packet) {
+    assertEvent("tabNavigated", packet);
   });
 }
 
 function test() {
   // Open a test tab
   addTab(URL1).then(function (browser) {
-    let doc = browser.contentDocument;
     getServerTabActor(function (tabActor) {
       // In order to listen to internal will-navigate/navigate events
       events.on(tabActor, "will-navigate", function (data) {
         assertEvent("will-navigate", data);
       });
       events.on(tabActor, "navigate", function (data) {
         assertEvent("navigate", data);
       });
@@ -135,19 +140,18 @@ function test() {
       waitForOnBeforeUnloadDialog(browser, function (btnLeave, btnStay) {
         assertEvent("unload-dialog");
         // accept to quit this page to another
         btnLeave.click();
       });
 
       // Load another document in this doc to dispatch these events
       assertEvent("load-new-document");
-      content.location = URL2;
+      BrowserTestUtils.loadURI(gBrowser.selectedBrowser, URL2);
     });
-
   });
 }
 
 function cleanup() {
   let browser = gBrowser.selectedBrowser;
   browser.removeEventListener("DOMContentLoaded", onDOMContentLoaded);
   browser.removeEventListener("load", onLoad);
   client.close().then(function () {
--- a/devtools/server/tests/browser/browser_perf-allocation-data.js
+++ b/devtools/server/tests/browser/browser_perf-allocation-data.js
@@ -1,38 +1,41 @@
 /* Any copyright is dedicated to the Public Domain.
    http://creativecommons.org/publicdomain/zero/1.0/ */
 
 /**
  * Test that we have allocation data coming from the front.
  */
 
+"use strict";
+
 const { PerformanceFront } = require("devtools/shared/fronts/performance");
 
 add_task(function* () {
-  let browser = yield addTab(MAIN_DOMAIN + "doc_allocations.html");
-  let doc = browser.contentDocument;
+  yield addTab(MAIN_DOMAIN + "doc_allocations.html");
 
   initDebuggerServer();
   let client = new DebuggerClient(DebuggerServer.connectPipe());
   let form = yield connectDebuggerClient(client);
   let front = PerformanceFront(client, form);
   yield front.connect();
 
-  let rec = yield front.startRecording({ withMarkers: true, withAllocations: true, withTicks: true });
+  let rec = yield front.startRecording(
+    { withMarkers: true, withAllocations: true, withTicks: true });
 
   yield waitUntil(() => rec.getAllocations().frames.length);
   yield waitUntil(() => rec.getAllocations().timestamps.length);
   yield waitUntil(() => rec.getAllocations().sizes.length);
   yield waitUntil(() => rec.getAllocations().sites.length);
 
   yield front.stopRecording(rec);
 
-  let { frames, timestamps, sizes, sites } = rec.getAllocations();
+  let { timestamps, sizes } = rec.getAllocations();
 
   is(timestamps.length, sizes.length, "we have the same amount of timestamps and sizes");
-  ok(timestamps.every(time => time > 0 && typeof time === "number"), "all timestamps have numeric values");
+  ok(timestamps.every(time => time > 0 && typeof time === "number"),
+    "all timestamps have numeric values");
   ok(sizes.every(n => n > 0 && typeof n === "number"), "all sizes are positive numbers");
 
   yield front.destroy();
   yield client.close();
   gBrowser.removeCurrentTab();
 });
--- a/devtools/server/tests/browser/browser_perf-profiler-01.js
+++ b/devtools/server/tests/browser/browser_perf-profiler-01.js
@@ -2,22 +2,23 @@
    http://creativecommons.org/publicdomain/zero/1.0/ */
 
 /**
  * Tests if the profiler connection front does not activate the built-in
  * profiler module if not necessary, and doesn't deactivate it when
  * a recording is stopped.
  */
 
+"use strict";
+
 const { PerformanceFront } = require("devtools/shared/fronts/performance");
-const { pmmIsProfilerActive, pmmStopProfiler, pmmLoadFrameScripts } = require("devtools/client/performance/test/helpers/profiler-mm-utils");
+const { pmmIsProfilerActive, pmmLoadFrameScripts } = require("devtools/client/performance/test/helpers/profiler-mm-utils");
 
 add_task(function* () {
-  let browser = yield addTab(MAIN_DOMAIN + "doc_perf.html");
-  let doc = browser.contentDocument;
+  yield addTab(MAIN_DOMAIN + "doc_perf.html");
 
   initDebuggerServer();
   let client = new DebuggerClient(DebuggerServer.connectPipe());
   let form = yield connectDebuggerClient(client);
   let front = PerformanceFront(client, form);
   yield front.connect();
 
   pmmLoadFrameScripts(gBrowser);
--- a/devtools/server/tests/browser/browser_perf-profiler-02.js
+++ b/devtools/server/tests/browser/browser_perf-profiler-02.js
@@ -1,18 +1,20 @@
 /* Any copyright is dedicated to the Public Domain.
    http://creativecommons.org/publicdomain/zero/1.0/ */
 
 /**
  * Tests if the built-in profiler module doesn't deactivate when the toolbox
  * is destroyed if there are other consumers using it.
  */
 
+"use strict";
+
 const { PerformanceFront } = require("devtools/shared/fronts/performance");
-const { pmmIsProfilerActive, pmmStopProfiler, pmmLoadFrameScripts } = require("devtools/client/performance/test/helpers/profiler-mm-utils");
+const { pmmIsProfilerActive, pmmLoadFrameScripts } = require("devtools/client/performance/test/helpers/profiler-mm-utils");
 
 add_task(function* () {
   yield addTab(MAIN_DOMAIN + "doc_perf.html");
   initDebuggerServer();
   let client = new DebuggerClient(DebuggerServer.connectPipe());
   let form = yield connectDebuggerClient(client);
   let firstFront = PerformanceFront(client, form);
   yield firstFront.connect();
--- a/devtools/server/tests/browser/browser_perf-profiler-03.js
+++ b/devtools/server/tests/browser/browser_perf-profiler-03.js
@@ -3,18 +3,20 @@
 
 /**
  * Tests if the built-in profiler module is not reactivated if no other
  * consumer was using it over the remote debugger protocol, and ensures
  * that the actor will work properly even in such cases (e.g. the Gecko Profiler
  * addon was installed and automatically activated the profiler module).
  */
 
+"use strict";
+
 const { PerformanceFront } = require("devtools/shared/fronts/performance");
-const { pmmIsProfilerActive, pmmStartProfiler, pmmStopProfiler, pmmLoadFrameScripts, pmmClearFrameScripts } = require("devtools/client/performance/test/helpers/profiler-mm-utils");
+const { pmmIsProfilerActive, pmmStartProfiler, pmmLoadFrameScripts, pmmClearFrameScripts } = require("devtools/client/performance/test/helpers/profiler-mm-utils");
 
 add_task(function* () {
   // Ensure the profiler is already running when the test starts.
   pmmLoadFrameScripts(gBrowser);
   let entries = 1000000;
   let interval = 1;
   let features = ["js"];
   yield pmmStartProfiler({ entries, interval, features });
@@ -24,17 +26,17 @@ add_task(function* () {
 
   yield addTab(MAIN_DOMAIN + "doc_perf.html");
   initDebuggerServer();
   let client = new DebuggerClient(DebuggerServer.connectPipe());
   let form = yield connectDebuggerClient(client);
   let firstFront = PerformanceFront(client, form);
   yield firstFront.connect();
 
-  let recording = yield firstFront.startRecording();
+  yield firstFront.startRecording();
 
   yield addTab(MAIN_DOMAIN + "doc_perf.html");
   let client2 = new DebuggerClient(DebuggerServer.connectPipe());
   let form2 = yield connectDebuggerClient(client2);
   let secondFront = PerformanceFront(client2, form2);
   yield secondFront.connect();
 
   yield secondFront.destroy();
--- a/devtools/server/tests/browser/browser_perf-realtime-markers.js
+++ b/devtools/server/tests/browser/browser_perf-realtime-markers.js
@@ -1,20 +1,21 @@
 /* Any copyright is dedicated to the Public Domain.
    http://creativecommons.org/publicdomain/zero/1.0/ */
 
 /**
  * Test functionality of real time markers.
  */
 
+"use strict";
+
 const { PerformanceFront } = require("devtools/shared/fronts/performance");
 
 add_task(function* () {
-  let browser = yield addTab(MAIN_DOMAIN + "doc_perf.html");
-  let doc = browser.contentDocument;
+  yield addTab(MAIN_DOMAIN + "doc_perf.html");
 
   initDebuggerServer();
   let client = new DebuggerClient(DebuggerServer.connectPipe());
   let form = yield connectDebuggerClient(client);
   let front = PerformanceFront(client, form);
   yield front.connect();
 
   let lastMemoryDelta = 0;
@@ -29,63 +30,66 @@ add_task(function* () {
   let deferreds = {
     markers: defer(),
     memory: defer(),
     ticks: defer()
   };
 
   front.on("timeline-data", handler);
 
-  let rec = yield front.startRecording({ withMarkers: true, withMemory: true, withTicks: true });
+  let rec = yield front.startRecording(
+    { withMarkers: true, withMemory: true, withTicks: true });
   yield Promise.all(Object.keys(deferreds).map(type => deferreds[type].promise));
   yield front.stopRecording(rec);
   front.off("timeline-data", handler);
 
   is(counters.markers.length, 1, "one marker event fired.");
   is(counters.memory.length, 3, "three memory events fired.");
   is(counters.ticks.length, 3, "three ticks events fired.");
 
   yield front.destroy();
   yield client.close();
   gBrowser.removeCurrentTab();
 
   function handler(name, data) {
     if (name === "markers") {
-      if (counters.markers.length >= 1) { return; }
+      if (counters.markers.length >= 1) {
+        return;
+      }
       ok(data.markers[0].start, "received atleast one marker with `start`");
       ok(data.markers[0].end, "received atleast one marker with `end`");
       ok(data.markers[0].name, "received atleast one marker with `name`");
 
       counters.markers.push(data.markers);
-    }
-    else if (name === "memory") {
-      if (counters.memory.length >= 3) { return; }
+    } else if (name === "memory") {
+      if (counters.memory.length >= 3) {
+        return;
+      }
       let { delta, measurement } = data;
       is(typeof delta, "number", "received `delta` in memory event");
       ok(delta > lastMemoryDelta, "received `delta` in memory event");
       ok(measurement.total, "received `total` in memory event");
 
       counters.memory.push({ delta, measurement });
       lastMemoryDelta = delta;
-    }
-    else if (name === "ticks") {
-      if (counters.ticks.length >= 3) { return; }
+    } else if (name === "ticks") {
+      if (counters.ticks.length >= 3) {
+        return;
+      }
       let { delta, timestamps } = data;
       ok(delta > lastTickDelta, "received `delta` in ticks event");
 
       // Timestamps aren't guaranteed to always contain tick events, since
       // they're dependent on the refresh driver, which may be blocked.
 
       counters.ticks.push({ delta, timestamps });
       lastTickDelta = delta;
-    }
-    else if (name === "frames") {
+    } else if (name === "frames") {
       // Nothing to do here.
-    }
-    else {
+    } else {
       ok(false, `Received unknown event: ${name}`);
     }
 
     if (name === "markers" && counters[name].length === 1 ||
         name === "memory" && counters[name].length === 3 ||
         name === "ticks" && counters[name].length === 3) {
       deferreds[name].resolve();
     }
--- a/devtools/server/tests/browser/browser_perf-recording-actor-01.js
+++ b/devtools/server/tests/browser/browser_perf-recording-actor-01.js
@@ -1,29 +1,31 @@
 /* Any copyright is dedicated to the Public Domain.
    http://creativecommons.org/publicdomain/zero/1.0/ */
 
 /**
  * Tests the state of a recording rec from start to finish for recording,
  * completed, and rec data.
  */
 
+"use strict";
+
 const { PerformanceFront } = require("devtools/shared/fronts/performance");
 
 add_task(function* () {
-  let browser = yield addTab(MAIN_DOMAIN + "doc_perf.html");
-  let doc = browser.contentDocument;
+  yield addTab(MAIN_DOMAIN + "doc_perf.html");
 
   initDebuggerServer();
   let client = new DebuggerClient(DebuggerServer.connectPipe());
   let form = yield connectDebuggerClient(client);
   let front = PerformanceFront(client, form);
   yield front.connect();
 
-  let rec = yield front.startRecording({ withMarkers: true, withTicks: true, withMemory: true });
+  let rec = yield front.startRecording(
+    { withMarkers: true, withTicks: true, withMemory: true });
   ok(rec.isRecording(), "RecordingModel is recording when created");
   yield busyWait(100);
   yield waitUntil(() => rec.getMemory().length);
   ok(true, "RecordingModel populates memory while recording");
   yield waitUntil(() => rec.getTicks().length);
   ok(true, "RecordingModel populates ticks while recording");
   yield waitUntil(() => rec.getMarkers().length);
   ok(true, "RecordingModel populates markers while recording");
@@ -38,17 +40,18 @@ add_task(function* () {
   ok(!rec.isRecording(), "on 'recording-stopping', model is no longer recording");
   // This handler should be called BEFORE "recording-stopped" is called, as
   // there is some delay, but in the event where "recording-stopped" finishes
   // before we check here, ensure that we're atleast in the right state
   if (rec.getProfile()) {
     ok(rec.isCompleted(), "recording is completed once it has profile data");
   } else {
     ok(!rec.isCompleted(), "recording is not yet completed on 'recording-stopping'");
-    ok(rec.isFinalizing(), "recording is considered finalizing between 'recording-stopping' and 'recording-stopped'");
+    ok(rec.isFinalizing(),
+      "recording is finalized between 'recording-stopping' and 'recording-stopped'");
   }
 
   yield stopped;
   ok(!rec.isRecording(), "on 'recording-stopped', model is still no longer recording");
   ok(rec.isCompleted(), "on 'recording-stopped', model is considered 'complete'");
 
   checkSystemInfo(rec, "Host");
   checkSystemInfo(rec, "Client");
--- a/devtools/server/tests/browser/browser_perf-recording-actor-02.js
+++ b/devtools/server/tests/browser/browser_perf-recording-actor-02.js
@@ -1,54 +1,59 @@
 /* Any copyright is dedicated to the Public Domain.
    http://creativecommons.org/publicdomain/zero/1.0/ */
 
 /**
  * Test that buffer status is correctly updated in recording models.
  */
 
+"use strict";
+
 var BUFFER_SIZE = 20000;
 var config = { bufferSize: BUFFER_SIZE };
 
 const { PerformanceFront } = require("devtools/shared/fronts/performance");
 
 add_task(function* () {
-  let browser = yield addTab(MAIN_DOMAIN + "doc_perf.html");
-  let doc = browser.contentDocument;
+  yield addTab(MAIN_DOMAIN + "doc_perf.html");
 
   initDebuggerServer();
   let client = new DebuggerClient(DebuggerServer.connectPipe());
   let form = yield connectDebuggerClient(client);
   let front = PerformanceFront(client, form);
   yield front.connect();
 
   yield front.setProfilerStatusInterval(10);
   let model = yield front.startRecording(config);
   let stats = yield once(front, "profiler-status");
-  is(stats.totalSize, BUFFER_SIZE, `profiler-status event has totalSize: ${stats.totalSize}`);
-  ok(stats.position < BUFFER_SIZE, `profiler-status event has position: ${stats.position}`);
+  is(stats.totalSize, BUFFER_SIZE,
+    `profiler-status event has totalSize: ${stats.totalSize}`);
+  ok(stats.position < BUFFER_SIZE,
+    `profiler-status event has position: ${stats.position}`);
   ok(stats.generation >= 0, `profiler-status event has generation: ${stats.generation}`);
   ok(stats.isActive, "profiler-status event is isActive");
   is(typeof stats.currentTime, "number", "profiler-status event has currentTime");
 
   // Halt once more for a buffer status to ensure we're beyond 0
   yield once(front, "profiler-status");
 
   let lastBufferStatus = 0;
   let checkCount = 0;
   while (lastBufferStatus < 1) {
     let currentBufferStatus = front.getBufferUsageForRecording(model);
-    ok(currentBufferStatus > lastBufferStatus, `buffer is more filled than before: ${currentBufferStatus} > ${lastBufferStatus}`);
+    ok(currentBufferStatus > lastBufferStatus,
+      `buffer is more filled than before: ${currentBufferStatus} > ${lastBufferStatus}`);
     lastBufferStatus = currentBufferStatus;
     checkCount++;
     yield once(front, "profiler-status");
   }
 
   ok(checkCount >= 1, "atleast 1 event were fired until the buffer was filled");
   is(lastBufferStatus, 1, "buffer usage cannot surpass 100%");
   yield front.stopRecording(model);
 
-  is(front.getBufferUsageForRecording(model), null, "buffer usage should be null when no longer recording.");
+  is(front.getBufferUsageForRecording(model), null,
+    "buffer usage should be null when no longer recording.");
 
   yield front.destroy();
   yield client.close();
   gBrowser.removeCurrentTab();
 });
--- a/devtools/server/tests/browser/browser_perf-samples-01.js
+++ b/devtools/server/tests/browser/browser_perf-samples-01.js
@@ -1,63 +1,69 @@
 /* Any copyright is dedicated to the Public Domain.
    http://creativecommons.org/publicdomain/zero/1.0/ */
 
 /**
  * Tests if the retrieved profiler data samples are correctly filtered and
  * normalized before passed to consumers.
  */
 
-const WAIT_TIME = 1000; // ms
+"use strict";
+
+// time in ms
+const WAIT_TIME = 1000;
 
 const { PerformanceFront } = require("devtools/shared/fronts/performance");
 
 add_task(function* () {
-  let browser = yield addTab(MAIN_DOMAIN + "doc_perf.html");
-  let doc = browser.contentDocument;
+  yield addTab(MAIN_DOMAIN + "doc_perf.html");
 
   initDebuggerServer();
   let client = new DebuggerClient(DebuggerServer.connectPipe());
   let form = yield connectDebuggerClient(client);
   let front = PerformanceFront(client, form);
   yield front.connect();
 
   // Perform the first recording...
 
   let firstRecording = yield front.startRecording();
   let firstRecordingStartTime = firstRecording._startTime;
   info("Started profiling at: " + firstRecordingStartTime);
 
-  busyWait(WAIT_TIME); // allow the profiler module to sample some cpu activity
+  // allow the profiler module to sample some cpu activity
+  busyWait(WAIT_TIME);
 
   yield front.stopRecording(firstRecording);
 
   ok(firstRecording.getDuration() >= WAIT_TIME,
     "The first recording duration is correct.");
 
   // Perform the second recording...
 
   let secondRecording = yield front.startRecording();
   let secondRecordingStartTime = secondRecording._startTime;
   info("Started profiling at: " + secondRecordingStartTime);
 
-  busyWait(WAIT_TIME); // allow the profiler module to sample more cpu activity
+  // allow the profiler module to sample more cpu activity
+  busyWait(WAIT_TIME);
 
   yield front.stopRecording(secondRecording);
   let secondRecordingProfile = secondRecording.getProfile();
   let secondRecordingSamples = secondRecordingProfile.threads[0].samples.data;
 
   ok(secondRecording.getDuration() >= WAIT_TIME,
     "The second recording duration is correct.");
 
   const TIME_SLOT = secondRecordingProfile.threads[0].samples.schema.time;
   ok(secondRecordingSamples[0][TIME_SLOT] < secondRecordingStartTime,
     "The second recorded sample times were normalized.");
   ok(secondRecordingSamples[0][TIME_SLOT] > 0,
     "The second recorded sample times were normalized correctly.");
-  ok(!secondRecordingSamples.find(e => e[TIME_SLOT] + secondRecordingStartTime <= firstRecording.getDuration()),
+  ok(!secondRecordingSamples.find(
+        e => e[TIME_SLOT] + secondRecordingStartTime <= firstRecording.getDuration()
+    ),
     "There should be no samples from the first recording in the second one, " +
     "even though the total number of frames did not overflow.");
 
   yield front.destroy();
   yield client.close();
   gBrowser.removeCurrentTab();
 });
--- a/devtools/server/tests/browser/browser_perf-samples-02.js
+++ b/devtools/server/tests/browser/browser_perf-samples-02.js
@@ -2,32 +2,35 @@
    http://creativecommons.org/publicdomain/zero/1.0/ */
 
 /**
  * Tests if the retrieved profiler data samples always have a (root) node.
  * If this ever changes, the |ThreadNode.prototype.insert| function in
  * devtools/client/performance/modules/logic/tree-model.js will have to be changed.
  */
 
-const WAIT_TIME = 1000; // ms
+"use strict";
+
+// Time in ms
+const WAIT_TIME = 1000;
 
 const { PerformanceFront } = require("devtools/shared/fronts/performance");
 
 add_task(function* () {
-  let browser = yield addTab(MAIN_DOMAIN + "doc_perf.html");
-  let doc = browser.contentDocument;
+  yield addTab(MAIN_DOMAIN + "doc_perf.html");
 
   initDebuggerServer();
   let client = new DebuggerClient(DebuggerServer.connectPipe());
   let form = yield connectDebuggerClient(client);
   let front = PerformanceFront(client, form);
   yield front.connect();
 
   let rec = yield front.startRecording();
-  busyWait(WAIT_TIME); // allow the profiler module to sample some cpu activity
+  // allow the profiler module to sample some cpu activity
+  busyWait(WAIT_TIME);
 
   yield front.stopRecording(rec);
   let profile = rec.getProfile();
   let sampleCount = 0;
 
   for (let thread of profile.threads) {
     info("Checking thread: " + thread.name);
 
--- a/devtools/server/tests/browser/browser_register_actor.js
+++ b/devtools/server/tests/browser/browser_register_actor.js
@@ -1,76 +1,74 @@
+"use strict";
+
 var gClient;
 
 function test() {
   waitForExplicitFinish();
-  var {ActorRegistryFront} = require("devtools/shared/fronts/actor-registry");
-  var actorURL = "chrome://mochitests/content/chrome/devtools/server/tests/mochitest/hello-actor.js";
+  let {ActorRegistryFront} = require("devtools/shared/fronts/actor-registry");
+  let actorURL = "chrome://mochitests/content/chrome/devtools/server/tests/mochitest/hello-actor.js";
 
   if (!DebuggerServer.initialized) {
     DebuggerServer.init();
     DebuggerServer.addBrowserActors();
   }
 
   gClient = new DebuggerClient(DebuggerServer.connectPipe());
   gClient.connect()
     .then(() => gClient.listTabs())
-    .then(aResponse => {
-
-      var options = {
+    .then(response => {
+      let options = {
         prefix: "helloActor",
         constructor: "HelloActor",
         type: { tab: true }
       };
 
-      var registry = ActorRegistryFront(gClient, aResponse);
+      let registry = ActorRegistryFront(gClient, response);
       registry.registerActor(actorURL, options).then(actorFront => {
-        gClient.listTabs(response => {
-          var tab = response.tabs[response.selected];
+        gClient.listTabs(res => {
+          let tab = res.tabs[res.selected];
           ok(!!tab.helloActor, "Hello actor must exist");
 
           // Make sure actor's state is maintained across listTabs requests.
-          checkActorState(tab.helloActor, () => {
-
-            // Clean up
-            actorFront.unregister().then(() => {
-              gClient.close().then(() => {
-                DebuggerServer.destroy();
-                gClient = null;
-                finish();
-              });
-            });
-          });
+          checkActorState(tab.helloActor, cleanupActor.bind(this, actorFront));
         });
       });
     });
 }
 
-function checkActorState(helloActor, callback) {
-  getCount(helloActor, response => {
-    ok(!response.error, "No error");
-    is(response.count, 1, "The counter must be valid");
-
-    getCount(helloActor, response => {
-      ok(!response.error, "No error");
-      is(response.count, 2, "The counter must be valid");
-
-      gClient.listTabs(response => {
-        var tab = response.tabs[response.selected];
-        is(tab.helloActor, helloActor, "Hello actor must be valid");
-
-        getCount(helloActor, response => {
-          ok(!response.error, "No error");
-          is(response.count, 3, "The counter must be valid");
-
-          callback();
-        });
-      });
+function cleanupActor(actorFront) {
+  // Clean up
+  actorFront.unregister().then(() => {
+    gClient.close().then(() => {
+      DebuggerServer.destroy();
+      gClient = null;
+      finish();
     });
   });
 }
 
 function getCount(actor, callback) {
-  gClient.request({
+  return gClient.request({
     to: actor,
     type: "count"
   }, callback);
 }
+
+var checkActorState = Task.async(function* (helloActor, callback) {
+  let response = yield getCount(helloActor);
+  ok(!response.error, "No error");
+  is(response.count, 1, "The counter must be valid");
+
+  response = yield getCount(helloActor);
+  ok(!response.error, "No error");
+  is(response.count, 2, "The counter must be valid");
+
+  let {tabs, selected} = yield gClient.listTabs();
+  let tab = tabs[selected];
+  is(tab.helloActor, helloActor, "Hello actor must be valid");
+
+  response = yield getCount(helloActor);
+  ok(!response.error, "No error");
+  is(response.count, 3, "The counter must be valid");
+
+  callback();
+});
--- a/devtools/server/tests/browser/browser_storage_dynamic_windows.js
+++ b/devtools/server/tests/browser/browser_storage_dynamic_windows.js
@@ -158,18 +158,20 @@ function testAddIframe(front) {
 
     let endTestReloaded = () => {
       front.off("stores-update", onStoresUpdate);
       resolve();
     };
 
     front.on("stores-update", onStoresUpdate);
 
+    // eslint-disable-next-line mozilla/no-cpows-in-tests
     let iframe = content.document.createElement("iframe");
     iframe.src = ALT_DOMAIN_SECURED + "storage-secured-iframe.html";
+    // eslint-disable-next-line mozilla/no-cpows-in-tests
     content.document.querySelector("body").appendChild(iframe);
   });
 }
 
 function testRemoveIframe(front) {
   info("Testing if iframe removal works properly");
   return new Promise(resolve => {
     let shouldBeEmpty = {
@@ -224,22 +226,24 @@ function testRemoveIframe(front) {
 
     let endTestReloaded = () => {
       front.off("stores-update", onStoresUpdate);
       resolve();
     };
 
     front.on("stores-update", onStoresUpdate);
 
-    for (let iframe of content.document.querySelectorAll("iframe")) {
-      if (iframe.src.startsWith("http:")) {
-        iframe.remove();
-        break;
+    ContentTask.spawn(gBrowser.selectedBrowser, {}, () => {
+      for (let iframe of content.document.querySelectorAll("iframe")) {
+        if (iframe.src.startsWith("http:")) {
+          iframe.remove();
+          break;
+        }
       }
-    }
+    });
   });
 }
 
 add_task(function* () {
   yield openTabAndSetupStorage(MAIN_DOMAIN + "storage-dynamic-windows.html");
 
   initDebuggerServer();
   let client = new DebuggerClient(DebuggerServer.connectPipe());
--- a/devtools/server/tests/browser/browser_storage_listings.js
+++ b/devtools/server/tests/browser/browser_storage_listings.js
@@ -223,17 +223,17 @@ const IDBValues = {
               keyPath: "name2",
               "unique": true,
               multiEntry: false,
             }
           ]
         },
       ]
     },
-    "http://sectest1.example.org" : {},
+    "http://sectest1.example.org": {},
     "https://sectest1.example.org": {
       "idb-s1 (default)": [
         {
           objectStore: "obj-s1",
           keyPath: "id",
           autoIncrement: false,
           indexes: []
         },
@@ -292,17 +292,17 @@ const IDBValues = {
             name: "foo",
             email: "foo@bar.com",
             extra: "baz"
           }
         }
       ],
       "idb2 (default)#obj3": []
     },
-    "http://sectest1.example.org" : {},
+    "http://sectest1.example.org": {},
     "https://sectest1.example.org": {
       "idb-s1 (default)#obj-s1": [
         {
           name: 6,
           value: {
             id: 6,
             name: "foo",
             email: "foo@bar.com",
@@ -326,23 +326,16 @@ const IDBValues = {
             email: "foo@bar.com",
           }
         }
       ]
     }
   }
 };
 
-function finishTests(client) {
-
-  let closeConnection = () => {
-
-  };
-}
-
 function* testStores(data) {
   ok(data.cookies, "Cookies storage actor is present");
   ok(data.localStorage, "Local Storage storage actor is present");
   ok(data.sessionStorage, "Session Storage storage actor is present");
   ok(data.indexedDB, "Indexed DB storage actor is present");
   yield testCookies(data.cookies);
   yield testLocalStorage(data.localStorage);
   yield testSessionStorage(data.sessionStorage);
@@ -509,18 +502,18 @@ var testIndexedDBs = Task.async(function
   ok(!!IDBValues.dbDetails[host], "Host is present in the list : " + host);
   matchItems(yield indexedDBActor.getStoreObjects(host));
   if (index == Object.keys(hosts).length - 1) {
     return;
   }
   yield testIndexedDBs(++index, hosts, indexedDBActor);
 });
 
-var testObjectStores = Task.async(function* (index, hosts, indexedDBActor) {
-  let host = Object.keys(hosts)[index];
+var testObjectStores = Task.async(function* (ix, hosts, indexedDBActor) {
+  let host = Object.keys(hosts)[ix];
   let matchItems = (data, db) => {
     is(data.total, IDBValues.objectStoreDetails[host][db].length,
        "Number of object stores in host " + host + " matches");
     for (let item of data.data) {
       let found = false;
       for (let toMatch of IDBValues.objectStoreDetails[host][db]) {
         if (item.objectStore == toMatch.objectStore) {
           found = true;
@@ -554,20 +547,20 @@ var testObjectStores = Task.async(functi
 
   ok(!!IDBValues.objectStoreDetails[host], "Host is present in the list : " + host);
   for (let name of hosts[host]) {
     let objName = JSON.parse(name).slice(0, 1);
     matchItems((
       yield indexedDBActor.getStoreObjects(host, [JSON.stringify(objName)])
     ), objName[0]);
   }
-  if (index == Object.keys(hosts).length - 1) {
+  if (ix == Object.keys(hosts).length - 1) {
     return;
   }
-  yield testObjectStores(++index, hosts, indexedDBActor);
+  yield testObjectStores(++ix, hosts, indexedDBActor);
 });
 
 var testIDBEntries = Task.async(function* (index, hosts, indexedDBActor) {
   let host = Object.keys(hosts)[index];
   let matchItems = (data, obj) => {
     is(data.total, IDBValues.entries[host][obj].length,
        "Number of items in object store " + obj + " matches");
     for (let item of data.data) {
--- a/devtools/server/tests/browser/browser_storage_updates.js
+++ b/devtools/server/tests/browser/browser_storage_updates.js
@@ -1,20 +1,15 @@
 /* vim: set ft=javascript ts=2 et sw=2 tw=80: */
 /* Any copyright is dedicated to the Public Domain.
    http://creativecommons.org/publicdomain/zero/1.0/ */
 
 "use strict";
 
 const {StorageFront} = require("devtools/shared/fronts/storage");
-const beforeReload = {
-  cookies: ["http://test1.example.org", "https://sectest1.example.org"],
-  localStorage: ["http://test1.example.org", "http://sectest1.example.org"],
-  sessionStorage: ["http://test1.example.org", "http://sectest1.example.org"],
-};
 
 const TESTS = [
   // index 0
   {
     action: function (win) {
       info('win.addCookie("c1", "foobar1")');
       win.addCookie("c1", "foobar1");
 
@@ -298,16 +293,17 @@ function storesCleared(data) {
 function* finishTests(client) {
   yield client.close();
   DebuggerServer.destroy();
   finish();
 }
 
 add_task(function* () {
   let browser = yield addTab(MAIN_DOMAIN + "storage-updates.html");
+  // eslint-disable-next-line mozilla/no-cpows-in-tests
   let doc = browser.contentDocument;
 
   initDebuggerServer();
 
   let client = new DebuggerClient(DebuggerServer.connectPipe());
   let form = yield connectDebuggerClient(client);
   let front = StorageFront(client, form);
   let win = doc.defaultView.wrappedJSObject;
--- a/devtools/server/tests/browser/browser_stylesheets_nested-iframes.js
+++ b/devtools/server/tests/browser/browser_stylesheets_nested-iframes.js
@@ -5,18 +5,17 @@
 "use strict";
 
 // Test that StyleSheetsActor.getStyleSheets() works if an iframe does not have
 // a content document.
 
 const {StyleSheetsFront} = require("devtools/shared/fronts/stylesheets");
 
 add_task(function* () {
-  let browser = yield addTab(MAIN_DOMAIN + "stylesheets-nested-iframes.html");
-  let doc = browser.contentDocument;
+  yield addTab(MAIN_DOMAIN + "stylesheets-nested-iframes.html");
 
   info("Initialising the debugger server and client.");
   initDebuggerServer();
   let client = new DebuggerClient(DebuggerServer.connectPipe());
   let form = yield connectDebuggerClient(client);
 
   info("Attaching to the active tab.");
   yield client.attachTab(form.actor);
--- a/devtools/server/tests/browser/browser_timeline.js
+++ b/devtools/server/tests/browser/browser_timeline.js
@@ -8,52 +8,61 @@
 // simple use case, and that markers events are sent when operations occur.
 // Note that this test isn't concerned with which markers are actually recorded,
 // just that markers are recorded at all.
 // Trying to check marker types here may lead to intermittents, see bug 1066474.
 
 const {TimelineFront} = require("devtools/shared/fronts/timeline");
 
 add_task(function* () {
-  let browser = yield addTab("data:text/html;charset=utf-8,mop");
-  let doc = browser.contentDocument;
+  yield addTab("data:text/html;charset=utf-8,mop");
 
   initDebuggerServer();
   let client = new DebuggerClient(DebuggerServer.connectPipe());
   let form = yield connectDebuggerClient(client);
   let front = TimelineFront(client, form);
 
   ok(front, "The TimelineFront was created");
 
   let isActive = yield front.isRecording();
   ok(!isActive, "The TimelineFront is not initially recording");
 
   info("Flush any pending reflows");
-  let forceSyncReflow = doc.body.innerHeight;
+  ContentTask.spawn(gBrowser.selectedBrowser, {}, () => {
+    // forceSyncReflow
+    content.document.body.innerHeight;
+  });
 
   info("Start recording");
   yield front.start({ withMarkers: true });
 
   isActive = yield front.isRecording();
   ok(isActive, "The TimelineFront is now recording");
 
   info("Change some style on the page to cause style/reflow/paint");
   let onMarkers = once(front, "markers");
-  doc.body.style.padding = "10px";
+  ContentTask.spawn(gBrowser.selectedBrowser, {}, () => {
+    content.document.body.style.padding = "10px";
+  });
   let markers = yield onMarkers;
 
   ok(true, "The markers event was fired");
   ok(markers.length > 0, "Markers were returned");
 
   info("Flush pending reflows again");
-  forceSyncReflow = doc.body.innerHeight;
+  ContentTask.spawn(gBrowser.selectedBrowser, {}, () => {
+    // forceSyncReflow
+    content.document.body.innerHeight;
+  });
 
   info("Change some style on the page to cause style/paint");
   onMarkers = once(front, "markers");
-  doc.body.style.backgroundColor = "red";
+  ContentTask.spawn(gBrowser.selectedBrowser, {}, () => {
+    content.document.body.style.backgroundColor = "red";
+  });
   markers = yield onMarkers;
 
   ok(markers.length > 0, "markers were returned");
 
   yield front.stop();
 
   isActive = yield front.isRecording();
   ok(!isActive, "Not recording after stop()");
--- a/devtools/server/tests/browser/browser_timeline_actors.js
+++ b/devtools/server/tests/browser/browser_timeline_actors.js
@@ -5,18 +5,17 @@
 "use strict";
 
 // Test that the timeline can also record data from the memory and framerate
 // actors, emitted as events in tadem with the markers.
 
 const {TimelineFront} = require("devtools/shared/fronts/timeline");
 
 add_task(function* () {
-  let browser = yield addTab("data:text/html;charset=utf-8,mop");
-  let doc = browser.contentDocument;
+  yield addTab("data:text/html;charset=utf-8,mop");
 
   initDebuggerServer();
   let client = new DebuggerClient(DebuggerServer.connectPipe());
   let form = yield connectDebuggerClient(client);
   let front = TimelineFront(client, form);
 
   info("Start timeline marker recording");
   yield front.start({ withMemory: true, withTicks: true });
--- a/devtools/server/tests/browser/browser_timeline_iframes.js
+++ b/devtools/server/tests/browser/browser_timeline_iframes.js
@@ -5,31 +5,31 @@
 "use strict";
 
 // Test the timeline front receives markers events for operations that occur in
 // iframes.
 
 const {TimelineFront} = require("devtools/shared/fronts/timeline");
 
 add_task(function* () {
-  let browser = yield addTab(MAIN_DOMAIN + "timeline-iframe-parent.html");
-  let doc = browser.contentDocument;
+  yield addTab(MAIN_DOMAIN + "timeline-iframe-parent.html");
 
   initDebuggerServer();
   let client = new DebuggerClient(DebuggerServer.connectPipe());
   let form = yield connectDebuggerClient(client);
   let front = TimelineFront(client, form);
 
   info("Start timeline marker recording");
   yield front.start({ withMarkers: true });
 
   // Check that we get markers for a few iterations of the timer that runs in
   // the child frame.
   for (let i = 0; i < 3; i++) {
-    yield wait(300); // That's the time the child frame waits before changing styles.
+    // That's the time the child frame waits before changing styles.
+    yield wait(300);
     let markers = yield once(front, "markers");
     ok(markers.length, "Markers were received for operations in the child frame");
   }
 
   info("Stop timeline marker recording");
   yield front.stop();
   yield client.close();
   gBrowser.removeCurrentTab();
--- a/devtools/server/tests/browser/director-script-target.html
+++ b/devtools/server/tests/browser/director-script-target.html
@@ -1,15 +1,17 @@
 <html>
   <head>
     <script>
-      // change the eval function to ensure the window object in the debug-script is correctly wrapped
+      /* exported globalAccessibleVar */
+      "use strict";
+      // change the eval function to ensure the window object
+      // in the debug-script is correctly wrapped
       window.eval = function () {
         return "unsecure-eval-called";
       };
-
       var globalAccessibleVar = "global-value";
     </script>
   </head>
   <body>
     <h1>debug script target</h1>
   </body>
 </html>
--- a/devtools/server/tests/browser/doc_allocations.html
+++ b/devtools/server/tests/browser/doc_allocations.html
@@ -1,20 +1,22 @@
 <!DOCTYPE HTML>
 <html>
 <head>
   <meta charset="utf-8">
 </head>
 <body>
 <script>
+"use strict";
+
 window.allocs = [];
-window.onload = function() {
+window.onload = function () {
   function allocator() {
-    for (var i = 0; i < 1000; i++) {
-      window.allocs.push(new Object);
+    for (let i = 0; i < 1000; i++) {
+      window.allocs.push(new Object());
     }
   }
 
   window.setInterval(allocator, 1);
 };
 </script>
 </pre>
 </body>
--- a/devtools/server/tests/browser/doc_force_cc.html
+++ b/devtools/server/tests/browser/doc_force_cc.html
@@ -5,16 +5,18 @@
 <html>
   <head>
     <meta charset="utf-8"/>
     <title>Performance tool + cycle collection test page</title>
   </head>
 
   <body>
     <script type="text/javascript">
+    "use strict";
+
     window.test = function () {
       document.body.expando1 = { cycle: document.body };
       SpecialPowers.Cu.forceCC();
 
       document.body.expando2 = { cycle: document.body };
       SpecialPowers.Cu.forceCC();
 
       document.body.expando3 = { cycle: document.body };
--- a/devtools/server/tests/browser/doc_force_gc.html
+++ b/devtools/server/tests/browser/doc_force_gc.html
@@ -5,22 +5,25 @@
 <html>
   <head>
     <meta charset="utf-8"/>
     <title>Performance tool + garbage collection test page</title>
   </head>
 
   <body>
     <script type="text/javascript">
+    "use strict";
+
     var x = 1;
     window.test = function () {
       SpecialPowers.Cu.forceGC();
       document.body.style.borderTop = x + "px solid red";
-      x = 1^x;
-      document.body.innerHeight; // flush pending reflows
+      x = 1 ^ x;
+      // flush pending reflows
+      document.body.innerHeight;
 
       // Prevent this script from being garbage collected.
       setTimeout(window.test, 100);
     };
     test();
     </script>
   </body>
 
--- a/devtools/server/tests/browser/doc_perf.html
+++ b/devtools/server/tests/browser/doc_perf.html
@@ -5,21 +5,24 @@
 <html>
   <head>
     <meta charset="utf-8"/>
     <title>Performance test page</title>
   </head>
 
   <body>
     <script type="text/javascript">
+      "use strict";
+
       var x = 1;
       function test() {
         document.body.style.borderTop = x + "px solid red";
-        x = 1^x;
-        document.body.innerHeight; // flush pending reflows
+        x = 1 ^ x;
+        // flush pending reflows
+        document.body.innerHeight;
       }
 
       // Prevent this script from being garbage collected.
       window.setInterval(test, 1);
     </script>
   </body>
 
 </html>
--- a/devtools/server/tests/browser/navigate-first.html
+++ b/devtools/server/tests/browser/navigate-first.html
@@ -1,15 +1,15 @@
 <!DOCTYPE HTML>
 <html>
 <head>
   <meta charset="utf-8">
 </head>
 <body>
 First
 <script>
-
-window.onbeforeunload=function(e){
-  e.returnValue="?";
+"use strict";
+window.onbeforeunload = function (e) {
+  e.returnValue = "?";
 };
 </script>
 </body>
 </html>
--- a/devtools/server/tests/browser/storage-helpers.js
+++ b/devtools/server/tests/browser/storage-helpers.js
@@ -1,11 +1,13 @@
 /* Any copyright is dedicated to the Public Domain.
    http://creativecommons.org/publicdomain/zero/1.0/ */
 
+/* exported openTabAndSetupStorage, clearStorage */
+
 "use strict";
 
 /**
  * This generator function opens the given url in a new tab, then sets up the
  * page by waiting for all cookies, indexedDB items etc. to be created.
  *
  * @param url {String} The url to be opened in the new tab
  *
--- a/devtools/server/tests/browser/storage-unsecured-iframe.html
+++ b/devtools/server/tests/browser/storage-unsecured-iframe.html
@@ -3,24 +3,26 @@
 <!--
 Iframe for testing multiple host detetion in storage actor
 -->
 <head>
   <meta charset="utf-8">
 </head>
 <body>
 <script>
+"use strict";
 
 document.cookie = "uc1=foobar; domain=.example.org; path=/; secure=true";
 localStorage.setItem("iframe-u-ls1", "foobar");
 sessionStorage.setItem("iframe-u-ss1", "foobar1");
 sessionStorage.setItem("iframe-u-ss2", "foobar2");
 console.log("added cookies and stuff from unsecured iframe");
 
-window.clear = function*() {
+window.clear = function* () {
   document.cookie = "uc1=; expires=Thu, 01 Jan 1970 00:00:00 GMT";
   localStorage.clear();
   sessionStorage.clear();
   console.log("removed cookies and stuff from unsecured iframe");
-}
+};
+
 </script>
 </body>
 </html>
--- a/devtools/server/tests/browser/timeline-iframe-child.html
+++ b/devtools/server/tests/browser/timeline-iframe-child.html
@@ -2,18 +2,19 @@
 <html>
 <head>
   <meta charset="utf-8">
   <title>Timeline iframe test - child frame</title>
 </head>
 <body>
   <h1>Child frame</h1>
   <script>
+    "use strict";
     var h1 = document.querySelector("h1");
-    setInterval(function() {
-      h1.style.backgroundColor = "rgb(" + ((Math.random()*255)|0) + "," +
-                                          ((Math.random()*255)|0) + "," +
-                                          ((Math.random()*255)|0) +")";
-      h1.style.width = ((Math.random()*500)|0) + "px";
+    setInterval(function () {
+      h1.style.backgroundColor = "rgb(" + ((Math.random() * 255)|0) + "," +
+                                          ((Math.random() * 255)|0) + "," +
+                                          ((Math.random() * 255)|0) + ")";
+      h1.style.width = ((Math.random() * 500)|0) + "px";
     }, 300);
   </script>
 </body>
 </html>
--- a/dom/base/nsFrameLoader.cpp
+++ b/dom/base/nsFrameLoader.cpp
@@ -71,18 +71,16 @@
 #include "nsIDOMChromeWindow.h"
 #include "nsInProcessTabChildGlobal.h"
 
 #include "Layers.h"
 #include "ClientLayerManager.h"
 
 #include "ContentParent.h"
 #include "TabParent.h"
-#include "mozilla/plugins/PPluginWidgetParent.h"
-#include "../plugins/ipc/PluginWidgetParent.h"
 #include "mozilla/AsyncEventDispatcher.h"
 #include "mozilla/BasePrincipal.h"
 #include "mozilla/GuardObjects.h"
 #include "mozilla/Preferences.h"
 #include "mozilla/Unused.h"
 #include "mozilla/dom/Element.h"
 #include "mozilla/jsipc/CrossProcessObjectWrappers.h"
 #include "mozilla/layout/RenderFrameParent.h"
@@ -97,16 +95,21 @@
 #include "mozilla/dom/ipc/StructuredCloneData.h"
 #include "mozilla/WebBrowserPersistLocalDocument.h"
 #include "mozilla/dom/GroupedHistoryEvent.h"
 #include "mozilla/dom/Promise.h"
 #include "mozilla/dom/PromiseNativeHandler.h"
 
 #include "nsPrincipal.h"
 
+#ifdef XP_WIN
+#include "mozilla/plugins/PPluginWidgetParent.h"
+#include "../plugins/ipc/PluginWidgetParent.h"
+#endif
+
 #ifdef MOZ_XUL
 #include "nsXULPopupManager.h"
 #endif
 
 #ifdef NS_PRINTING
 #include "mozilla/embedding/printingui/PrintingParent.h"
 #include "nsIWebBrowserPrint.h"
 #endif
@@ -1419,25 +1422,27 @@ nsFrameLoader::SwapWithOtherRemoteLoader
   }
   if (!OwnerIsMozBrowserFrame() && aOther->OwnerIsMozBrowserFrame()) {
     aOther->DestroyBrowserFrameScripts();
   }
 
   aOther->mRemoteBrowser->SetBrowserDOMWindow(browserDOMWindow);
   mRemoteBrowser->SetBrowserDOMWindow(otherBrowserDOMWindow);
 
+#ifdef XP_WIN
   // Native plugin windows used by this remote content need to be reparented.
   if (nsPIDOMWindowOuter* newWin = ourDoc->GetWindow()) {
     RefPtr<nsIWidget> newParent = nsGlobalWindow::Cast(newWin)->GetMainWidget();
     const ManagedContainer<mozilla::plugins::PPluginWidgetParent>& plugins =
       aOther->mRemoteBrowser->ManagedPPluginWidgetParent();
     for (auto iter = plugins.ConstIter(); !iter.Done(); iter.Next()) {
       static_cast<mozilla::plugins::PluginWidgetParent*>(iter.Get()->GetKey())->SetParent(newParent);
     }
   }
+#endif // XP_WIN
 
   MaybeUpdatePrimaryTabParent(eTabParentRemoved);
   aOther->MaybeUpdatePrimaryTabParent(eTabParentRemoved);
 
   SetOwnerContent(otherContent);
   aOther->SetOwnerContent(ourContent);
 
   mRemoteBrowser->SetOwnerElement(otherContent);
--- a/dom/base/nsStyledElement.cpp
+++ b/dom/base/nsStyledElement.cpp
@@ -63,18 +63,16 @@ nsStyledElement::SetInlineStyleDeclarati
                                          this);
 
   // There's no point in comparing the stylerule pointers since we're always
   // getting a new stylerule here. And we can't compare the stringvalues of
   // the old and the new rules since both will point to the same declaration
   // and thus will be the same.
   if (hasListeners) {
     // save the old attribute so we can set up the mutation event properly
-    // XXXbz if the old rule points to the same declaration as the new one,
-    // this is getting the new attr value, not the old one....
     nsAutoString oldValueStr;
     modification = GetAttr(kNameSpaceID_None, nsGkAtoms::style,
                            oldValueStr);
     if (modification) {
       oldValue.SetTo(oldValueStr);
     }
   }
   else if (aNotify && IsInUncomposedDoc()) {
--- a/dom/browser-element/mochitest/chrome.ini
+++ b/dom/browser-element/mochitest/chrome.ini
@@ -60,17 +60,17 @@ skip-if = toolkit == 'android'
 tags = audiochannel
 [test_browserElement_inproc_AudioPlayback.html]
 skip-if = true # bug 1332850, bug 1332862
 [test_browserElement_inproc_AudioChannel.html]
 tags = audiochannel
 skip-if = true # bug 1332862
 [test_browserElement_inproc_AudioChannel_nested.html]
 tags = audiochannel
-skip-if = toolkit == 'android' # bug 1332850
+skip-if = true # bug 1332850, 1332862
 [test_browserElement_inproc_BackForward.html]
 [test_browserElement_inproc_BadScreenshot.html]
 [test_browserElement_inproc_DocumentFirstPaint.html]
 [test_browserElement_inproc_DOMRequestError.html]
 [test_browserElement_inproc_ExecuteScript.html]
 [test_browserElement_inproc_Find.html]
 [test_browserElement_inproc_GetContentDimensions.html]
 [test_browserElement_inproc_GetScreenshot.html]
--- a/dom/canvas/gtest/moz.build
+++ b/dom/canvas/gtest/moz.build
@@ -12,12 +12,12 @@ with Files('*WebGL*'):
 
 UNIFIED_SOURCES += [
     'TestImageBitmapColorUtils.cpp',
     'TestWebGLElementArrayCache.cpp',
 ]
 
 LOCAL_INCLUDES += [
     '/dom/canvas',
-    '/media/libyuv/include'
+    '/media/libyuv/libyuv/include'
 ]
 
 FINAL_LIBRARY = 'xul-gtest'
--- a/dom/canvas/moz.build
+++ b/dom/canvas/moz.build
@@ -205,17 +205,17 @@ LOCAL_INCLUDES += [
     '/dom/workers',
     '/dom/xul',
     '/gfx/gl',
     '/image',
     '/js/xpconnect/src',
     '/layout/generic',
     '/layout/style',
     '/layout/xul',
-    '/media/libyuv/include',
+    '/media/libyuv/libyuv/include',
 ]
 
 CXXFLAGS += CONFIG['MOZ_CAIRO_CFLAGS']
 CXXFLAGS += CONFIG['TK_CFLAGS']
 
 LOCAL_INCLUDES += CONFIG['SKIA_INCLUDES']
 
 if CONFIG['GNU_CXX']:
--- a/dom/html/test/file_fullscreen-plugins.html
+++ b/dom/html/test/file_fullscreen-plugins.html
@@ -1,20 +1,21 @@
 <!DOCTYPE HTML>
 <html>
 <!--
 https://bugzilla.mozilla.org/show_bug.cgi?id=545812
 
 Test plugins with DOM full-screen API:
-* Presence of plugins has no effect on request for full-screen on MacOS.
 * Request for full-screen is denied when windowed plugin in current doc is present.
 * Request for full-screen is denied when windowed plugin in subdocument is present.
 * Request for full-screen is not denied when the only plugin present is windowless.
 * Adding an existing (out-of-doc) windowed plugin to a full-screen document causes document to exit full-screen.
 * Create windowed plugin and adding it to full-screen document caused exit from full-screen.
+* On non-Windows, plugins can only be windowless, so the presence of plugins
+  should have no effect on request for full-screen.
 
 -->
 <head>
   <title>Test for Bug 545812</title>
   <script type="application/javascript" src="/tests/SimpleTest/EventUtils.js"></script>
   <script type="application/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
   <script type="application/javascript" src="plugin-utils.js"></script>
   <script type="application/javascript">
@@ -60,17 +61,17 @@ function is(a, b, msg) {
 function e(id) {
   return document.getElementById(id);
 }
 
 function removeElement(e) {
   e.remove();
 }
 
-const isMacOs = navigator.appVersion.indexOf("Macintosh") != -1;
+const supportsWindowedMode = navigator.appVersion.indexOf("Windows") != -1;
 
 var windowedPlugin = null;
 
 function begin() {
   // Delay test startup long enough for the windowed plugin in the subframe to
   // start up and create its window.
   opener.SimpleTest.executeSoon(function() {
     opener.SimpleTest.executeSoon(function() {
@@ -78,47 +79,48 @@ function begin() {
     })
   });
 }
 
 function startTest() {
   ok(!document.fullscreenElement, "Should not be in full-screen mode initially");
   document.body.requestFullscreen();
 
-  // Focus the windowed plugin. On MacOS we should still enter full-screen mode,
-  // on windows the pending request for full-screen should be denied.
+  // Focus the windowed plugin. On non-Windows we should still enter
+  // full-screen mode, on Windows the pending request for full-screen should
+  // be denied.
   e("windowed-plugin").focus();
-  
-  if (isMacOs) {
-    // Running on MacOS, all plugins are effectively windowless, request for full-screen should be granted.
-    // Continue test in the (mac-specific) "fullscreenchange" handler.
-    addFullscreenChangeContinuation("enter", macFullScreenChange1);
+
+  if (!supportsWindowedMode) {
+    // If all plugins are effectively windowless, request for full-screen should be granted.
+    // Continue test in the "fullscreenchange" handler.
+    addFullscreenChangeContinuation("enter", windowlessFullScreenChange1);
   } else {
-    // Non-MacOS, request should be denied, carry on the test after receiving error event.
-    addFullscreenErrorContinuation(nonMacTest);
+    // On Windows, request should be denied, carry on the test after receiving error event.
+    addFullscreenErrorContinuation(windowsTest);
   }
 }
 
-function nonMacTest() {
+function windowsTest() {
   ok(!document.fullscreenElement, "Request for full-screen with focused windowed plugin should be denied.");
 
   // Focus a regular html element, and re-request full-screen, request should be granted.
   e("windowless-plugin").focus();
-  addFullscreenChangeContinuation("enter", nonMacTest2);
+  addFullscreenChangeContinuation("enter", windowsTest2);
   document.body.requestFullscreen();
 }
 
-function nonMacTest2() {
+function windowsTest2() {
   ok(document.fullscreenElement, "Request for full-screen with non-plugin focused should be granted.");
   // Focus a windowed plugin, full-screen should be revoked.
-  addFullscreenChangeContinuation("exit", nonMacTest3);
+  addFullscreenChangeContinuation("exit", windowsTest3);
   e("windowed-plugin").focus();
 }
 
-function nonMacTest3() {
+function windowsTest3() {
   ok(!document.fullscreenElement, "Full-screen should have been revoked when windowed-plugin was focused.");
   // Remove windowed plugins before closing the window
   // to work around bug 1237853.
   removeElement(e("windowed-plugin"));
   removeElement(e("subdoc-plugin").contentDocument.getElementById("windowed-plugin"));
   opener.nextTest();
 }
 
@@ -126,35 +128,35 @@ var fullScreenChangeCount = 0;
 
 function createWindowedPlugin() {
   var p = document.createElement("embed");
   p.setAttribute("type", "application/x-test");
   p.setAttribute("wmode", "window");
   return p;
 }
 
-function macFullScreenChange1(event) {
-  ok(document.fullscreenElement, "Requests for full-screen with focused windowed plugins should be granted on MacOS");
+function windowlessFullScreenChange1(event) {
+  ok(document.fullscreenElement, "Requests for full-screen with focused windowed plugins should be granted on non-Windows");
   
-  // Create a new windowed plugin, and add that to the document. Should *not* exit full-screen mode on MacOS.
+  // Create a new windowed plugin, and add that to the document. Should *not* exit full-screen mode on MacOS/Linux.
   windowedPlugin = createWindowedPlugin();
   document.body.appendChild(windowedPlugin);
   
-  // Focus windowed plugin. Should not exit full-screen mode on MacOS.
+  // Focus windowed plugin. Should not exit full-screen mode on MacOS/Linux.
   windowedPlugin.focus();
   
   setTimeout(
     function() {
-      ok(document.fullscreenElement, "Adding & focusing a windowed plugin to document should not cause full-screen to exit on MacOS.");
-      addFullscreenChangeContinuation("exit", macFullScreenChange2);
+      ok(document.fullscreenElement, "Adding & focusing a windowed plugin to document should not cause full-screen to exit on MacOS/Linux.");
+      addFullscreenChangeContinuation("exit", windowlessFullScreenChange2);
       document.exitFullscreen();
     }, 0);
 }
 
-function macFullScreenChange2(event) {
+function windowlessFullScreenChange2(event) {
   ok(!document.fullscreenElement, "Should have left full-screen mode after calling document.exitFullscreen().");
   opener.nextTest();
 }
 
 </script>
 </pre>
 </body>
 </html>
--- a/dom/indexedDB/test/mochitest.ini
+++ b/dom/indexedDB/test/mochitest.ini
@@ -126,18 +126,21 @@ support-files =
 [test_advance.html]
 [test_autoIncrement.html]
 [test_autoIncrement_indexes.html]
 [test_bfcache.html]
 [test_blob_archive.html]
 [test_blob_file_backed.html]
 [test_blob_simple.html]
 [test_blob_worker_crash.html]
+skip-if = e10s && os == 'win' && os_version == '6.1' # Bug 1342415
 [test_blob_worker_xhr_post.html]
+skip-if = e10s && os == 'win' && os_version == '6.1' # Bug 1342415
 [test_blob_worker_xhr_post_multifile.html]
+skip-if = e10s && os == 'win' && os_version == '6.1' # Bug 1342415
 [test_blob_worker_xhr_read.html]
 [test_blob_worker_xhr_read_slice.html]
 [test_blocked_order.html]
 [test_bug937006.html]
 [test_clear.html]
 [test_complex_keyPaths.html]
 [test_count.html]
 [test_create_index.html]
--- a/dom/ipc/PPluginWidget.ipdl
+++ b/dom/ipc/PPluginWidget.ipdl
@@ -1,24 +1,24 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
+        /* 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 protocol PBrowser;
 
 include "mozilla/GfxMessageUtils.h";
 
 using nsIntRect from "nsRect.h";
 
 namespace mozilla {
 namespace plugins {
 
 /**
  * PPluginWidget - a nsIWidget'ish protocol for windowed plugins in e10s.
- * On windows and linux we create native widgets in chrome which we then manage
+ * On windows we create native widgets in chrome which we then manage
  * from content.  On the content side there's PluginWidgetProxy which
  * implements nsIWidget. We hand this around layout and plugins code. Anything
  * not dealt with via PluginWidgetProxy falls through to PuppetWidget. Native
  * widget exists on the chrome side (PluginWidgetParent) attached to the
  * browser window as a child. Window management calls are forwarded from
  * PluginWidgetProxy to PluginWidgetParent over this interface.
  *
  * Note lifetime management for PluginWidgetProxy (the plugin widget) and the
--- a/dom/ipc/TabChild.cpp
+++ b/dom/ipc/TabChild.cpp
@@ -15,17 +15,16 @@
 #include "Layers.h"
 #include "ContentChild.h"
 #include "TabParent.h"
 #include "mozilla/Preferences.h"
 #include "mozilla/BrowserElementParent.h"
 #include "mozilla/ClearOnShutdown.h"
 #include "mozilla/EventListenerManager.h"
 #include "mozilla/dom/indexedDB/PIndexedDBPermissionRequestChild.h"
-#include "mozilla/plugins/PluginWidgetChild.h"
 #include "mozilla/IMEStateManager.h"
 #include "mozilla/ipc/DocumentRendererChild.h"
 #include "mozilla/ipc/URIUtils.h"
 #include "mozilla/layers/APZChild.h"
 #include "mozilla/layers/APZCCallbackHelper.h"
 #include "mozilla/layers/APZCTreeManager.h"
 #include "mozilla/layers/APZCTreeManagerChild.h"
 #include "mozilla/layers/APZEventState.h"
@@ -34,16 +33,17 @@
 #include "mozilla/layers/DoubleTapToZoom.h"
 #include "mozilla/layers/IAPZCTreeManager.h"
 #include "mozilla/layers/ImageBridgeChild.h"
 #include "mozilla/layers/InputAPZContext.h"
 #include "mozilla/layers/ShadowLayers.h"
 #include "mozilla/layers/WebRenderLayerManager.h"
 #include "mozilla/layout/RenderFrameChild.h"
 #include "mozilla/layout/RenderFrameParent.h"
+#include "mozilla/plugins/PPluginWidgetChild.h"
 #include "mozilla/LookAndFeel.h"
 #include "mozilla/MouseEvents.h"
 #include "mozilla/Move.h"
 #include "mozilla/PresShell.h"
 #include "mozilla/ProcessHangMonitor.h"
 #include "mozilla/ScopeExit.h"
 #include "mozilla/Services.h"
 #include "mozilla/StaticPtr.h"
@@ -118,16 +118,20 @@
 #include "nsISHistory.h"
 #include "nsQueryObject.h"
 #include "GroupedSHistory.h"
 #include "nsIHttpChannel.h"
 #include "mozilla/dom/DocGroup.h"
 #include "nsISupportsPrimitives.h"
 #include "mozilla/Telemetry.h"
 
+#ifdef XP_WIN
+#include "mozilla/plugins/PluginWidgetChild.h"
+#endif
+
 #ifdef NS_PRINTING
 #include "nsIPrintSession.h"
 #include "nsIPrintSettings.h"
 #include "nsIPrintSettingsService.h"
 #include "nsIWebBrowserPrint.h"
 #endif
 
 #define BROWSER_ELEMENT_CHILD_SCRIPT \
@@ -3138,26 +3142,32 @@ TabChild::StopAwaitingLargeAlloc()
   bool awaiting = mAwaitingLA;
   mAwaitingLA = false;
   return awaiting;
 }
 
 mozilla::plugins::PPluginWidgetChild*
 TabChild::AllocPPluginWidgetChild()
 {
-    return new mozilla::plugins::PluginWidgetChild();
+#ifdef XP_WIN
+  return new mozilla::plugins::PluginWidgetChild();
+#else
+  MOZ_ASSERT_UNREACHABLE();
+  return nullptr;
+#endif
 }
 
 bool
 TabChild::DeallocPPluginWidgetChild(mozilla::plugins::PPluginWidgetChild* aActor)
 {
-    delete aActor;
-    return true;
+  delete aActor;
+  return true;
 }
 
+#ifdef XP_WIN
 nsresult
 TabChild::CreatePluginWidget(nsIWidget* aParent, nsIWidget** aOut)
 {
   *aOut = nullptr;
   mozilla::plugins::PluginWidgetChild* child =
     static_cast<mozilla::plugins::PluginWidgetChild*>(SendPPluginWidgetConstructor());
   if (!child) {
     NS_ERROR("couldn't create PluginWidgetChild");
@@ -3178,16 +3188,17 @@ TabChild::CreatePluginWidget(nsIWidget* 
                                      LayoutDeviceIntRect(0, 0, 0, 0),
                                      &initData);
   if (NS_FAILED(rv)) {
     NS_WARNING("Creating native plugin widget on the chrome side failed.");
   }
   pluginWidget.forget(aOut);
   return rv;
 }
+#endif // XP_WIN
 
 ScreenIntSize
 TabChild::GetInnerSize()
 {
   LayoutDeviceIntSize innerSize =
     RoundedToInt(mUnscaledInnerSize * mPuppetWidget->GetDefaultScale());
   return ViewAs<ScreenPixel>(innerSize, PixelCastJustification::LayoutDeviceIsScreenForTabDims);
 };
--- a/dom/ipc/TabChild.h
+++ b/dom/ipc/TabChild.h
@@ -57,20 +57,16 @@ class AsyncDragMetrics;
 class IAPZCTreeManager;
 class ImageCompositeNotification;
 } // namespace layers
 
 namespace widget {
 struct AutoCacheNativeKeyCommands;
 } // namespace widget
 
-namespace plugins {
-class PluginWidgetChild;
-} // namespace plugins
-
 namespace dom {
 
 class TabChild;
 class TabGroup;
 class ClonedMessageData;
 class TabChildBase;
 
 class TabChildGlobal : public DOMEventTargetHelper,
@@ -604,17 +600,19 @@ public:
 
   /**
    * Native widget remoting protocol for use with windowed plugins with e10s.
    */
   PPluginWidgetChild* AllocPPluginWidgetChild() override;
 
   bool DeallocPPluginWidgetChild(PPluginWidgetChild* aActor) override;
 
+#ifdef XP_WIN
   nsresult CreatePluginWidget(nsIWidget* aParent, nsIWidget** aOut);
+#endif
 
   LayoutDeviceIntPoint GetClientOffset() const { return mClientOffset; }
   LayoutDeviceIntPoint GetChromeDisplacement() const { return mChromeDisp; };
 
   bool IPCOpen() const { return mIPCOpen; }
 
   bool ParentIsActive() const
   {
--- a/dom/ipc/TabParent.cpp
+++ b/dom/ipc/TabParent.cpp
@@ -15,28 +15,28 @@
 #endif
 #include "mozilla/BrowserElementParent.h"
 #include "mozilla/dom/ContentBridgeParent.h"
 #include "mozilla/dom/ContentParent.h"
 #include "mozilla/dom/DataTransfer.h"
 #include "mozilla/dom/Event.h"
 #include "mozilla/dom/indexedDB/ActorsParent.h"
 #include "mozilla/dom/ipc/BlobParent.h"
-#include "mozilla/plugins/PluginWidgetParent.h"
 #include "mozilla/EventStateManager.h"
 #include "mozilla/gfx/2D.h"
 #include "mozilla/gfx/DataSurfaceHelpers.h"
 #include "mozilla/gfx/GPUProcessManager.h"
 #include "mozilla/Hal.h"
 #include "mozilla/IMEStateManager.h"
 #include "mozilla/ipc/DocumentRendererParent.h"
 #include "mozilla/jsipc/CrossProcessObjectWrappers.h"
 #include "mozilla/layers/AsyncDragMetrics.h"
 #include "mozilla/layers/InputAPZContext.h"
 #include "mozilla/layout/RenderFrameParent.h"
+#include "mozilla/plugins/PPluginWidgetParent.h"
 #include "mozilla/LookAndFeel.h"
 #include "mozilla/MouseEvents.h"
 #include "mozilla/net/NeckoChild.h"
 #include "mozilla/Preferences.h"
 #include "mozilla/PresShell.h"
 #include "mozilla/TextEvents.h"
 #include "mozilla/TouchEvents.h"
 #include "mozilla/UniquePtr.h"
@@ -95,16 +95,20 @@
 #include "gfxDrawable.h"
 #include "ImageOps.h"
 #include "UnitTransforms.h"
 #include <algorithm>
 #include "mozilla/WebBrowserPersistDocumentParent.h"
 #include "nsIGroupedSHistory.h"
 #include "PartialSHistory.h"
 
+#ifdef XP_WIN
+#include "mozilla/plugins/PluginWidgetParent.h"
+#endif
+
 #if defined(XP_WIN) && defined(ACCESSIBILITY)
 #include "mozilla/a11y/AccessibleWrap.h"
 #include "mozilla/a11y/nsWinUtils.h"
 #endif
 
 using namespace mozilla::dom;
 using namespace mozilla::ipc;
 using namespace mozilla::layers;
@@ -381,25 +385,27 @@ TabParent::DestroyInternal()
   // destroy itself and send back __delete__().
   Unused << SendDestroy();
 
   if (RenderFrameParent* frame = GetRenderFrame()) {
     RemoveTabParentFromTable(frame->GetLayersId());
     frame->Destroy();
   }
 
+#ifdef XP_WIN
   // Let all PluginWidgets know we are tearing down. Prevents
   // these objects from sending async events after the child side
   // is shut down.
   const ManagedContainer<PPluginWidgetParent>& kids =
     ManagedPPluginWidgetParent();
   for (auto iter = kids.ConstIter(); !iter.Done(); iter.Next()) {
     static_cast<mozilla::plugins::PluginWidgetParent*>(
        iter.Get()->GetKey())->ParentDestroy();
   }
+#endif
 }
 
 void
 TabParent::Destroy()
 {
   // Aggressively release the window to avoid leaking the world in shutdown
   // corner cases.
   mBrowserDOMWindow = nullptr;
@@ -932,28 +938,32 @@ TabParent::RecvPDocAccessibleConstructor
     // document containing the child.
     MOZ_ASSERT(aParentID);
     if (!aParentID) {
       return IPC_FAIL_NO_REASON(this);
     }
 
     auto parentDoc = static_cast<a11y::DocAccessibleParent*>(aParentDoc);
     mozilla::ipc::IPCResult added = parentDoc->AddChildDoc(doc, aParentID);
+    if (!added) {
+#ifdef DEBUG
+      return added;
+#else
+      return IPC_OK();
+#endif
+    }
+
 #ifdef XP_WIN
     MOZ_ASSERT(aDocCOMProxy.IsNull());
-    if (added) {
-      a11y::WrapperFor(doc)->SetID(aMsaaID);
-      if (a11y::nsWinUtils::IsWindowEmulationStarted()) {
-        doc->SetEmulatedWindowHandle(parentDoc->GetEmulatedWindowHandle());
-      }
+    a11y::WrapperFor(doc)->SetID(aMsaaID);
+    if (a11y::nsWinUtils::IsWindowEmulationStarted()) {
+      doc->SetEmulatedWindowHandle(parentDoc->GetEmulatedWindowHandle());
     }
 #endif
-    if (!added) {
-      return added;
-    }
+
     return IPC_OK();
   } else {
     // null aParentDoc means this document is at the top level in the child
     // process.  That means it makes no sense to get an id for an accessible
     // that is its parent.
     MOZ_ASSERT(!aParentID);
     if (aParentID) {
       return IPC_FAIL_NO_REASON(this);
@@ -2880,17 +2890,22 @@ TabParent::RecvRemotePaintIsReady()
   bool dummy;
   mFrameElement->DispatchEvent(event, &dummy);
   return IPC_OK();
 }
 
 mozilla::plugins::PPluginWidgetParent*
 TabParent::AllocPPluginWidgetParent()
 {
+#ifdef XP_WIN
   return new mozilla::plugins::PluginWidgetParent();
+#else
+  MOZ_ASSERT_UNREACHABLE();
+  return nullptr;
+#endif
 }
 
 bool
 TabParent::DeallocPPluginWidgetParent(mozilla::plugins::PPluginWidgetParent* aActor)
 {
   delete aActor;
   return true;
 }
--- a/dom/media/GraphDriver.cpp
+++ b/dom/media/GraphDriver.cpp
@@ -648,17 +648,16 @@ AudioCallbackDriver::Init()
   output.layout = CUBEB_LAYOUT_STEREO;
 
   Maybe<uint32_t> latencyPref = CubebUtils::GetCubebMSGLatencyInFrames();
   if (latencyPref) {
     latency_frames = latencyPref.value();
   } else {
     if (cubeb_get_min_latency(cubebContext, output, &latency_frames) != CUBEB_OK) {
       NS_WARNING("Could not get minimal latency from cubeb.");
-      return false;
     }
   }
 
   // Macbook and MacBook air don't have enough CPU to run very low latency
   // MediaStreamGraphs, cap the minimal latency to 512 frames int this case.
   if (IsMacbookOrMacbookAir()) {
     latency_frames = std::max((uint32_t) 512, latency_frames);
   }
@@ -710,22 +709,26 @@ AudioCallbackDriver::Init()
 #endif
       NS_WARNING("Could not create a cubeb stream for MediaStreamGraph, falling back to a SystemClockDriver");
       // Only report failures when we're not coming from a driver that was
       // created itself as a fallback driver because of a previous audio driver
       // failure.
       if (!mFromFallback) {
         CubebUtils::ReportCubebStreamInitFailure(firstStream);
       }
-      // Fall back to a driver using a normal thread.
+      // Fall back to a driver using a normal thread. If needed,
+      // the graph will try to re-open an audio stream later.
       MonitorAutoLock lock(GraphImpl()->GetMonitor());
       SystemClockDriver* nextDriver = new SystemClockDriver(GraphImpl());
       SetNextDriver(nextDriver);
       nextDriver->MarkAsFallback();
       nextDriver->SetGraphTime(this, mIterationStart, mIterationEnd);
+      // We're not using SwitchAtNextIteration here, because there
+      // won't be a next iteration if we don't restart things manually:
+      // the audio stream just signaled that it's in error state.
       mGraphImpl->SetCurrentDriver(nextDriver);
       nextDriver->Start();
       return true;
     }
   }
   bool aec;
   Unused << mGraphImpl->AudioTrackPresent(aec);
   SetMicrophoneActive(aec);
@@ -1044,16 +1047,31 @@ AudioCallbackDriver::DataCallback(const 
   }
   return aFrames;
 }
 
 void
 AudioCallbackDriver::StateCallback(cubeb_state aState)
 {
   LOG(LogLevel::Debug, ("AudioCallbackDriver State: %d", aState));
+  if (aState == CUBEB_STATE_ERROR) {
+    // Fall back to a driver using a normal thread. If needed,
+    // the graph will try to re-open an audio stream later.
+    MonitorAutoLock lock(GraphImpl()->GetMonitor());
+    SystemClockDriver* nextDriver = new SystemClockDriver(GraphImpl());
+    SetNextDriver(nextDriver);
+    RemoveCallback();
+    nextDriver->MarkAsFallback();
+    nextDriver->SetGraphTime(this, mIterationStart, mIterationEnd);
+    // We're not using SwitchAtNextIteration here, because there
+    // won't be a next iteration if we don't restart things manually:
+    // the audio stream just signaled that it's in error state.
+    mGraphImpl->SetCurrentDriver(nextDriver);
+    nextDriver->Start();
+  }
 }
 
 void
 AudioCallbackDriver::MixerCallback(AudioDataValue* aMixedBuffer,
                                    AudioSampleFormat aFormat,
                                    uint32_t aChannels,
                                    uint32_t aFrames,
                                    uint32_t aSampleRate)
--- a/dom/media/MediaDecoder.cpp
+++ b/dom/media/MediaDecoder.cpp
@@ -1808,23 +1808,24 @@ MediaDecoder::DumpDebugInfo()
     str += readerStr;
   }
 
   if (!GetStateMachine()) {
     DUMP_LOG("%s", str.get());
     return;
   }
 
+  RefPtr<MediaDecoder> self = this;
   GetStateMachine()->RequestDebugInfo()->Then(
     AbstractThread::MainThread(), __func__,
-    [this, str] (const nsACString& aString) {
+    [this, self, str] (const nsACString& aString) {
       DUMP_LOG("%s", str.get());
       DUMP_LOG("%s", aString.Data());
     },
-    [this, str] () {
+    [this, self, str] () {
       DUMP_LOG("%s", str.get());
     });
 }
 
 RefPtr<MediaDecoder::DebugInfoPromise>
 MediaDecoder::RequestDebugInfo()
 {
   MOZ_DIAGNOSTIC_ASSERT(!IsShutdown());
--- a/dom/media/MediaDecoderStateMachine.cpp
+++ b/dom/media/MediaDecoderStateMachine.cpp
@@ -2800,16 +2800,21 @@ MediaDecoderStateMachine::IsVideoDecodin
 }
 
 bool MediaDecoderStateMachine::IsPlaying() const
 {
   MOZ_ASSERT(OnTaskQueue());
   return mMediaSink->IsPlaying();
 }
 
+void MediaDecoderStateMachine::SetMediaNotSeekable()
+{
+  mMediaSeekable = false;
+}
+
 nsresult MediaDecoderStateMachine::Init(MediaDecoder* aDecoder)
 {
   MOZ_ASSERT(NS_IsMainThread());
 
   // Dispatch initialization that needs to happen on that task queue.
   nsCOMPtr<nsIRunnable> r = NewRunnableMethod<RefPtr<MediaDecoder>>(
     this, &MediaDecoderStateMachine::InitializationTask, aDecoder);
   mTaskQueue->Dispatch(r.forget());
@@ -2817,19 +2822,17 @@ nsresult MediaDecoderStateMachine::Init(
   mAudioQueueListener = AudioQueue().PopEvent().Connect(
     mTaskQueue, this, &MediaDecoderStateMachine::OnAudioPopped);
   mVideoQueueListener = VideoQueue().PopEvent().Connect(
     mTaskQueue, this, &MediaDecoderStateMachine::OnVideoPopped);
 
   mMetadataManager.Connect(mReader->TimedMetadataEvent(), OwnerThread());
 
   mOnMediaNotSeekable = mReader->OnMediaNotSeekable().Connect(
-    OwnerThread(), [this] () {
-      mMediaSeekable = false;
-    });
+    OwnerThread(), this, &MediaDecoderStateMachine::SetMediaNotSeekable);
 
   mMediaSink = CreateMediaSink(mAudioCaptured);
 
   aDecoder->RequestCDMProxy()->Then(
     OwnerThread(), __func__, this,
     &MediaDecoderStateMachine::OnCDMProxyReady,
     &MediaDecoderStateMachine::OnCDMProxyNotReady)
   ->Track(mCDMProxyPromise);
@@ -3107,29 +3110,30 @@ MediaDecoderStateMachine::RequestAudioDa
 {
   MOZ_ASSERT(OnTaskQueue());
   MOZ_ASSERT(IsAudioDecoding());
   MOZ_ASSERT(!IsRequestingAudioData());
   MOZ_ASSERT(!IsWaitingAudioData());
   SAMPLE_LOG("Queueing audio task - queued=%" PRIuSIZE ", decoder-queued=%" PRIuSIZE,
              AudioQueue().GetSize(), mReader->SizeOfAudioQueueInFrames());
 
+  RefPtr<MediaDecoderStateMachine> self = this;
   mReader->RequestAudioData()->Then(
     OwnerThread(), __func__,
-    [this] (MediaData* aAudio) {
+    [this, self] (MediaData* aAudio) {
       MOZ_ASSERT(aAudio);
       mAudioDataRequest.Complete();
       // audio->GetEndTime() is not always mono-increasing in chained ogg.
       mDecodedAudioEndTime =
         std::max(aAudio->GetEndTime(), mDecodedAudioEndTime);
       SAMPLE_LOG("OnAudioDecoded [%" PRId64 ",%" PRId64 "]", aAudio->mTime,
                  aAudio->GetEndTime());
       mStateObj->HandleAudioDecoded(aAudio);
     },
-    [this] (const MediaResult& aError) {
+    [this, self] (const MediaResult& aError) {
       SAMPLE_LOG("OnAudioNotDecoded aError=%" PRIu32, static_cast<uint32_t>(aError.Code()));
       mAudioDataRequest.Complete();
       switch (aError.Code()) {
         case NS_ERROR_DOM_MEDIA_WAITING_FOR_DATA:
           mStateObj->HandleWaitingForAudio();
           break;
         case NS_ERROR_DOM_MEDIA_CANCELED:
           mStateObj->HandleAudioCanceled();
@@ -3153,29 +3157,30 @@ MediaDecoderStateMachine::RequestVideoDa
   MOZ_ASSERT(!IsWaitingVideoData());
   SAMPLE_LOG(
     "Queueing video task - queued=%" PRIuSIZE ", decoder-queued=%" PRIoSIZE
     ", skip=%i, time=%" PRId64,
     VideoQueue().GetSize(), mReader->SizeOfVideoQueueInFrames(),
     aSkipToNextKeyframe, aCurrentTime.ToMicroseconds());
 
   TimeStamp videoDecodeStartTime = TimeStamp::Now();
+  RefPtr<MediaDecoderStateMachine> self = this;
   mReader->RequestVideoData(aSkipToNextKeyframe, aCurrentTime)->Then(
     OwnerThread(), __func__,
-    [this, videoDecodeStartTime] (MediaData* aVideo) {
+    [this, self, videoDecodeStartTime] (MediaData* aVideo) {
       MOZ_ASSERT(aVideo);
       mVideoDataRequest.Complete();
       // Handle abnormal or negative timestamps.
       mDecodedVideoEndTime =
         std::max(mDecodedVideoEndTime, aVideo->GetEndTime());
       SAMPLE_LOG("OnVideoDecoded [%" PRId64 ",%" PRId64 "]", aVideo->mTime,
                  aVideo->GetEndTime());
       mStateObj->HandleVideoDecoded(aVideo, videoDecodeStartTime);
     },
-    [this] (const MediaResult& aError) {
+    [this, self] (const MediaResult& aError) {
       SAMPLE_LOG("OnVideoNotDecoded aError=%" PRIu32 , static_cast<uint32_t>(aError.Code()));
       mVideoDataRequest.Complete();
       switch (aError.Code()) {
         case NS_ERROR_DOM_MEDIA_WAITING_FOR_DATA:
           mStateObj->HandleWaitingForVideo();
           break;
         case NS_ERROR_DOM_MEDIA_CANCELED:
           mStateObj->HandleVideoCanceled();
@@ -3189,39 +3194,40 @@ MediaDecoderStateMachine::RequestVideoDa
     })->Track(mVideoDataRequest);
 }
 
 void
 MediaDecoderStateMachine::WaitForData(MediaData::Type aType)
 {
   MOZ_ASSERT(OnTaskQueue());
   MOZ_ASSERT(aType == MediaData::AUDIO_DATA || aType == MediaData::VIDEO_DATA);
+  RefPtr<MediaDecoderStateMachine> self = this;
   if (aType == MediaData::AUDIO_DATA) {
     mReader->WaitForData(MediaData::AUDIO_DATA)->Then(
       OwnerThread(), __func__,
-      [this] (MediaData::Type aType) {
-        mAudioWaitRequest.Complete();
+      [self] (MediaData::Type aType) {
+        self->mAudioWaitRequest.Complete();
         MOZ_ASSERT(aType == MediaData::AUDIO_DATA);
-        mStateObj->HandleAudioWaited(aType);
+        self->mStateObj->HandleAudioWaited(aType);
       },
-      [this] (const WaitForDataRejectValue& aRejection) {
-        mAudioWaitRequest.Complete();
-        DecodeError(NS_ERROR_DOM_MEDIA_WAITING_FOR_DATA);
+      [self] (const WaitForDataRejectValue& aRejection) {
+        self->mAudioWaitRequest.Complete();
+        self->DecodeError(NS_ERROR_DOM_MEDIA_WAITING_FOR_DATA);
       })->Track(mAudioWaitRequest);
   } else {
     mReader->WaitForData(MediaData::VIDEO_DATA)->Then(
       OwnerThread(), __func__,
-      [this] (MediaData::Type aType) {
-        mVideoWaitRequest.Complete();
+      [self] (MediaData::Type aType) {
+        self->mVideoWaitRequest.Complete();
         MOZ_ASSERT(aType == MediaData::VIDEO_DATA);
-        mStateObj->HandleVideoWaited(aType);
+        self->mStateObj->HandleVideoWaited(aType);
       },
-      [this] (const WaitForDataRejectValue& aRejection) {
-        mVideoWaitRequest.Complete();
-        DecodeError(NS_ERROR_DOM_MEDIA_WAITING_FOR_DATA);
+      [self] (const WaitForDataRejectValue& aRejection) {
+        self->mVideoWaitRequest.Complete();
+        self->DecodeError(NS_ERROR_DOM_MEDIA_WAITING_FOR_DATA);
       })->Track(mVideoWaitRequest);
   }
 }
 
 void
 MediaDecoderStateMachine::StartMediaSink()
 {
   MOZ_ASSERT(OnTaskQueue());
@@ -3572,19 +3578,20 @@ MediaDecoderStateMachine::ScheduleStateM
     return;
   }
 
   TimeStamp now = TimeStamp::Now();
   TimeStamp target = now + TimeDuration::FromMicroseconds(aMicroseconds);
 
   // It is OK to capture 'this' without causing UAF because the callback
   // always happens before shutdown.
-  mDelayedScheduler.Ensure(target, [this] () {
-    mDelayedScheduler.CompleteRequest();
-    RunStateMachine();
+  RefPtr<MediaDecoderStateMachine> self = this;
+  mDelayedScheduler.Ensure(target, [self] () {
+    self->mDelayedScheduler.CompleteRequest();
+    self->RunStateMachine();
   }, [] () {
     MOZ_DIAGNOSTIC_ASSERT(false);
   });
 }
 
 bool MediaDecoderStateMachine::OnTaskQueue() const
 {
   return OwnerThread()->IsCurrentThreadIn();
@@ -3791,18 +3798,19 @@ MediaDecoderStateMachine::GetDebugInfo()
          + mMediaSink->GetDebugInfo();
 }
 
 RefPtr<MediaDecoder::DebugInfoPromise>
 MediaDecoderStateMachine::RequestDebugInfo()
 {
   using PromiseType = MediaDecoder::DebugInfoPromise;
   RefPtr<PromiseType::Private> p = new PromiseType::Private(__func__);
-  OwnerThread()->Dispatch(NS_NewRunnableFunction([this, p] () {
-    p->Resolve(GetDebugInfo(), __func__);
+  RefPtr<MediaDecoderStateMachine> self = this;
+  OwnerThread()->Dispatch(NS_NewRunnableFunction([self, p] () {
+    p->Resolve(self->GetDebugInfo(), __func__);
   }), AbstractThread::AssertDispatchSuccess, AbstractThread::TailDispatch);
   return p.forget();
 }
 
 void MediaDecoderStateMachine::AddOutputStream(ProcessedMediaStream* aStream,
                                                bool aFinishWhenEnded)
 {
   MOZ_ASSERT(NS_IsMainThread());
--- a/dom/media/MediaDecoderStateMachine.h
+++ b/dom/media/MediaDecoderStateMachine.h
@@ -292,16 +292,19 @@ private:
 
   // True if shutdown process has begun.
   bool IsShutdown() const;
 
   // Returns true if we're currently playing. The decoder monitor must
   // be held.
   bool IsPlaying() const;
 
+  // Sets mMediaSeekable to false.
+  void SetMediaNotSeekable();
+
   // Resets all states related to decoding and aborts all pending requests
   // to the decoders.
   void ResetDecode(TrackSet aTracks = TrackSet(TrackInfo::kAudioTrack,
                                                TrackInfo::kVideoTrack));
 
 protected:
   virtual ~MediaDecoderStateMachine();
 
--- a/dom/media/MediaManager.cpp
+++ b/dom/media/MediaManager.cpp
@@ -2290,33 +2290,33 @@ if (privileged) {
       Preferences::GetBool("media.navigator.streams.fake");
 
   bool askPermission =
       (!privileged || Preferences::GetBool("media.navigator.permission.force")) &&
       (!fake || Preferences::GetBool("media.navigator.permission.fake"));
 
   RefPtr<PledgeSourceSet> p = EnumerateDevicesImpl(windowID, videoType,
                                                    audioType, fake);
-  p->Then([this, onSuccess, onFailure, windowID, c, listener, askPermission,
+  RefPtr<MediaManager> self = this;
+  p->Then([self, onSuccess, onFailure, windowID, c, listener, askPermission,
            prefs, isHTTPS, callID, principalInfo,
            isChrome](SourceSet*& aDevices) mutable {
 
     RefPtr<Refcountable<UniquePtr<SourceSet>>> devices(
          new Refcountable<UniquePtr<SourceSet>>(aDevices)); // grab result
 
-    // Ensure that the captured 'this' pointer and our windowID are still good.
-    if (!MediaManager::Exists() ||
-        !nsGlobalWindow::GetInnerWindowWithId(windowID)) {
+    // Ensure that our windowID is still good.
+    if (!nsGlobalWindow::GetInnerWindowWithId(windowID)) {
       return;
     }
 
     // Apply any constraints. This modifies the passed-in list.
-    RefPtr<PledgeChar> p2 = SelectSettings(c, isChrome, devices);
-
-    p2->Then([this, onSuccess, onFailure, windowID, c,
+    RefPtr<PledgeChar> p2 = self->SelectSettings(c, isChrome, devices);
+
+    p2->Then([self, onSuccess, onFailure, windowID, c,
               listener, askPermission, prefs, isHTTPS, callID, principalInfo,
               isChrome, devices](const char*& badConstraint) mutable {
 
       // Ensure that the captured 'this' pointer and our windowID are still good.
       auto* globalWindow = nsGlobalWindow::GetInnerWindowWithId(windowID);
       RefPtr<nsPIDOMWindowInner> window = globalWindow ? globalWindow->AsInner()
                                                        : nullptr;
       if (!MediaManager::Exists() || !window) {
@@ -2354,23 +2354,23 @@ if (privileged) {
       // Pass callbacks and MediaStreamListener along to GetUserMediaTask.
       RefPtr<GetUserMediaTask> task (new GetUserMediaTask(c, onSuccess.forget(),
                                                           onFailure.forget(),
                                                           windowID, listener,
                                                           prefs, principalInfo,
                                                           isChrome,
                                                           devices->release()));
       // Store the task w/callbacks.
-      mActiveCallbacks.Put(callID, task.forget());
+      self->mActiveCallbacks.Put(callID, task.forget());
 
       // Add a WindowID cross-reference so OnNavigation can tear things down
       nsTArray<nsString>* array;
-      if (!mCallIds.Get(windowID, &array)) {
+      if (!self->mCallIds.Get(windowID, &array)) {
         array = new nsTArray<nsString>();
-        mCallIds.Put(windowID, array);
+        self->mCallIds.Put(windowID, array);
       }
       array->AppendElement(callID);
 
       nsCOMPtr<nsIObserverService> obs = services::GetObserverService();
       if (!askPermission) {
         obs->NotifyObservers(devicesCopy, "getUserMedia:privileged:allow",
                              callID.BeginReading());
       } else {
@@ -2997,17 +2997,19 @@ MediaManager::Shutdown()
   // Post ShutdownTask to execute on mMediaThread and pass in a lambda
   // callback to be executed back on this thread once it is done.
   //
   // The lambda callback "captures" the 'this' pointer for member access.
   // This is safe since this is guaranteed to be here since sSingleton isn't
   // cleared until the lambda function clears it.
 
   // note that this == sSingleton
-  RefPtr<MediaManager> that(sSingleton);
+  MOZ_ASSERT(this == sSingleton);
+  RefPtr<MediaManager> that = this;
+
   // Release the backend (and call Shutdown()) from within the MediaManager thread
   // Don't use MediaManager::PostTask() because we're sInShutdown=true here!
   RefPtr<ShutdownTask> shutdown = new ShutdownTask(this,
       media::NewRunnableFrom([this, that]() mutable {
     LOG(("MediaManager shutdown lambda running, releasing MediaManager singleton and thread"));
     if (mMediaThread) {
       mMediaThread->Stop();
     }
--- a/dom/media/encoder/moz.build
+++ b/dom/media/encoder/moz.build
@@ -25,17 +25,17 @@ UNIFIED_SOURCES += [
     'TrackEncoder.cpp',
 ]
 
 if CONFIG['MOZ_WEBM_ENCODER']:
     EXPORTS += ['VP8TrackEncoder.h',
     ]
     UNIFIED_SOURCES += ['VP8TrackEncoder.cpp',
     ]
-    LOCAL_INCLUDES += ['/media/libyuv/include']
+    LOCAL_INCLUDES += ['/media/libyuv/libyuv/include']
 
 FINAL_LIBRARY = 'xul'
 
 # These includes are from Android JB, for use of MediaCodec.
 LOCAL_INCLUDES += ['/ipc/chromium/src']
 
 if CONFIG['MOZ_WIDGET_TOOLKIT'] == 'gonk' and CONFIG['ANDROID_VERSION'] > '15':
     LOCAL_INCLUDES += [
--- a/dom/media/mediasink/DecodedStream.cpp
+++ b/dom/media/mediasink/DecodedStream.cpp
@@ -65,19 +65,20 @@ public:
   void DoNotifyFinished()
   {
     MOZ_ASSERT(NS_IsMainThread());
     mFinishPromise.ResolveIfExists(true, __func__);
   }
 
   void Forget()
   {
-    mAbstractMainThread->Dispatch(NS_NewRunnableFunction([this] () {
+    RefPtr<DecodedStreamGraphListener> self = this;
+    mAbstractMainThread->Dispatch(NS_NewRunnableFunction([self] () {
       MOZ_ASSERT(NS_IsMainThread());
-      mFinishPromise.ResolveIfExists(true, __func__);
+      self->mFinishPromise.ResolveIfExists(true, __func__);
     }));
     MutexAutoLock lock(mMutex);
     mStream = nullptr;
   }
 
   MediaEventSource<int64_t>& OnOutput()
   {
     return mOnOutput;
--- a/dom/media/ogg/OggDemuxer.cpp
+++ b/dom/media/ogg/OggDemuxer.cpp
@@ -123,18 +123,23 @@ OggDemuxer::~OggDemuxer()
 {
   MOZ_COUNT_DTOR(OggDemuxer);
   Reset(TrackInfo::kAudioTrack);
   Reset(TrackInfo::kVideoTrack);
   if (HasAudio() || HasVideo()) {
     // If we were able to initialize our decoders, report whether we encountered
     // a chained stream or not.
     bool isChained = mIsChained;
-    nsCOMPtr<nsIRunnable> task = NS_NewRunnableFunction([=]() -> void {
-      OGG_DEBUG("Reporting telemetry MEDIA_OGG_LOADED_IS_CHAINED=%d", isChained);
+    void* ptr = this;
+    nsCOMPtr<nsIRunnable> task = NS_NewRunnableFunction([ptr, isChained]() -> void {
+      // We can't use OGG_DEBUG here because it implicitly refers to `this`,
+      // which we can't capture in this runnable.
+      MOZ_LOG(gMediaDemuxerLog, mozilla::LogLevel::Debug,
+              ("OggDemuxer(%p)::%s: Reporting telemetry MEDIA_OGG_LOADED_IS_CHAINED=%d",
+               ptr, __func__, isChained));
       Telemetry::Accumulate(Telemetry::HistogramID::MEDIA_OGG_LOADED_IS_CHAINED, isChained);
     });
     // Non-DocGroup version of AbstractThread::MainThread is fine for Telemetry.
     AbstractThread::MainThread()->Dispatch(task.forget());
   }
 }
 
 void
--- a/dom/media/systemservices/CamerasChild.cpp
+++ b/dom/media/systemservices/CamerasChild.cpp
@@ -280,38 +280,30 @@ CamerasChild::DispatchToParent(nsIRunnab
 int
 CamerasChild::NumberOfCapabilities(CaptureEngine aCapEngine,
                                    const char* deviceUniqueIdUTF8)
 {
   LOG((__PRETTY_FUNCTION__));
   LOG(("NumberOfCapabilities for %s", deviceUniqueIdUTF8));
   nsCString unique_id(deviceUniqueIdUTF8);
   nsCOMPtr<nsIRunnable> runnable =
-    media::NewRunnableFrom([this, aCapEngine, unique_id]() -> nsresult {
-      if (this->SendNumberOfCapabilities(aCapEngine, unique_id)) {
-        return NS_OK;
-      }
-      return NS_ERROR_FAILURE;
-    });
+    mozilla::NewNonOwningRunnableMethod<CaptureEngine, nsCString>
+    (this, &CamerasChild::SendNumberOfCapabilities, aCapEngine, unique_id);
   LockAndDispatch<> dispatcher(this, __func__, runnable, 0, mReplyInteger);
   LOG(("Capture capability count: %d", dispatcher.ReturnValue()));
   return dispatcher.ReturnValue();
 }
 
 int
 CamerasChild::NumberOfCaptureDevices(CaptureEngine aCapEngine)
 {
   LOG((__PRETTY_FUNCTION__));
   nsCOMPtr<nsIRunnable> runnable =
-    media::NewRunnableFrom([this, aCapEngine]() -> nsresult {
-      if (this->SendNumberOfCaptureDevices(aCapEngine)) {
-        return NS_OK;
-      }
-      return NS_ERROR_FAILURE;
-    });
+    mozilla::NewNonOwningRunnableMethod<CaptureEngine>
+    (this, &CamerasChild::SendNumberOfCaptureDevices, aCapEngine);
   LockAndDispatch<> dispatcher(this, __func__, runnable, 0, mReplyInteger);
   LOG(("Capture Devices: %d", dispatcher.ReturnValue()));
   return dispatcher.ReturnValue();
 }
 
 mozilla::ipc::IPCResult
 CamerasChild::RecvReplyNumberOfCaptureDevices(const int& numdev)
 {
@@ -324,42 +316,34 @@ CamerasChild::RecvReplyNumberOfCaptureDe
   return IPC_OK();
 }
 
 int
 CamerasChild::EnsureInitialized(CaptureEngine aCapEngine)
 {
   LOG((__PRETTY_FUNCTION__));
   nsCOMPtr<nsIRunnable> runnable =
-    media::NewRunnableFrom([this, aCapEngine]() -> nsresult {
-      if (this->SendEnsureInitialized(aCapEngine)) {
-        return NS_OK;
-      }
-      return NS_ERROR_FAILURE;
-    });
+    mozilla::NewNonOwningRunnableMethod<CaptureEngine>
+    (this, &CamerasChild::SendEnsureInitialized, aCapEngine);
   LockAndDispatch<> dispatcher(this, __func__, runnable, 0, mReplyInteger);
   LOG(("Capture Devices: %d", dispatcher.ReturnValue()));
   return dispatcher.ReturnValue();
 }
 
 int
 CamerasChild::GetCaptureCapability(CaptureEngine aCapEngine,
                                    const char* unique_idUTF8,
                                    const unsigned int capability_number,
                                    webrtc::VideoCaptureCapability& capability)
 {
   LOG(("GetCaptureCapability: %s %d", unique_idUTF8, capability_number));
   nsCString unique_id(unique_idUTF8);
   nsCOMPtr<nsIRunnable> runnable =
-    media::NewRunnableFrom([this, aCapEngine, unique_id, capability_number]() -> nsresult {
-      if (this->SendGetCaptureCapability(aCapEngine, unique_id, capability_number)) {
-        return NS_OK;
-      }
-      return NS_ERROR_FAILURE;
-    });
+    mozilla::NewNonOwningRunnableMethod<CaptureEngine, nsCString, unsigned int>
+    (this, &CamerasChild::SendGetCaptureCapability, aCapEngine, unique_id, capability_number);
   LockAndDispatch<> dispatcher(this, __func__, runnable);
   if (dispatcher.Success()) {
     capability = mReplyCapability;
   }
   return dispatcher.ReturnValue();
 }
 
 mozilla::ipc::IPCResult
@@ -385,22 +369,18 @@ CamerasChild::GetCaptureDevice(CaptureEn
                                unsigned int list_number, char* device_nameUTF8,
                                const unsigned int device_nameUTF8Length,
                                char* unique_idUTF8,
                                const unsigned int unique_idUTF8Length,
                                bool* scary)
 {
   LOG((__PRETTY_FUNCTION__));
   nsCOMPtr<nsIRunnable> runnable =
-    media::NewRunnableFrom([this, aCapEngine, list_number]() -> nsresult {
-      if (this->SendGetCaptureDevice(aCapEngine, list_number)) {
-        return NS_OK;
-      }
-      return NS_ERROR_FAILURE;
-    });
+    mozilla::NewNonOwningRunnableMethod<CaptureEngine, unsigned int>
+    (this, &CamerasChild::SendGetCaptureDevice, aCapEngine, list_number);
   LockAndDispatch<> dispatcher(this, __func__, runnable);
   if (dispatcher.Success()) {
     base::strlcpy(device_nameUTF8, mReplyDeviceName.get(), device_nameUTF8Length);
     base::strlcpy(unique_idUTF8, mReplyDeviceID.get(), unique_idUTF8Length);
     if (scary) {
       *scary = mReplyScary;
     }
     LOG(("Got %s name %s id", device_nameUTF8, unique_idUTF8));
@@ -429,22 +409,18 @@ CamerasChild::AllocateCaptureDevice(Capt
                                     const char* unique_idUTF8,
                                     const unsigned int unique_idUTF8Length,
                                     int& aStreamId,
                                     const mozilla::ipc::PrincipalInfo& aPrincipalInfo)
 {
   LOG((__PRETTY_FUNCTION__));
   nsCString unique_id(unique_idUTF8);
   nsCOMPtr<nsIRunnable> runnable =
-    media::NewRunnableFrom([this, aCapEngine, unique_id, aPrincipalInfo]() -> nsresult {
-      if (this->SendAllocateCaptureDevice(aCapEngine, unique_id, aPrincipalInfo)) {
-        return NS_OK;
-      }
-      return NS_ERROR_FAILURE;
-    });
+    mozilla::NewNonOwningRunnableMethod<CaptureEngine, nsCString, const mozilla::ipc::PrincipalInfo&>
+    (this, &CamerasChild::SendAllocateCaptureDevice, aCapEngine, unique_id, aPrincipalInfo);
   LockAndDispatch<> dispatcher(this, __func__, runnable);
   if (dispatcher.Success()) {
     LOG(("Capture Device allocated: %d", mReplyInteger));
     aStreamId = mReplyInteger;
   }
   return dispatcher.ReturnValue();
 }
 
@@ -462,22 +438,18 @@ CamerasChild::RecvReplyAllocateCaptureDe
 }
 
 int
 CamerasChild::ReleaseCaptureDevice(CaptureEngine aCapEngine,
                                    const int capture_id)
 {
   LOG((__PRETTY_FUNCTION__));
   nsCOMPtr<nsIRunnable> runnable =
-    media::NewRunnableFrom([this, aCapEngine, capture_id]() -> nsresult {
-      if (this->SendReleaseCaptureDevice(aCapEngine, capture_id)) {
-        return NS_OK;
-      }
-      return NS_ERROR_FAILURE;
-    });
+    mozilla::NewNonOwningRunnableMethod<CaptureEngine, int>
+    (this, &CamerasChild::SendReleaseCaptureDevice, aCapEngine, capture_id);
   LockAndDispatch<> dispatcher(this, __func__, runnable);
   return dispatcher.ReturnValue();
 }
 
 void
 CamerasChild::AddCallback(const CaptureEngine aCapEngine, const int capture_id,
                           FrameRelay* render)
 {
@@ -513,37 +485,29 @@ CamerasChild::StartCapture(CaptureEngine
   VideoCaptureCapability capCap(webrtcCaps.width,
                            webrtcCaps.height,
                            webrtcCaps.maxFPS,
                            webrtcCaps.expectedCaptureDelay,
                            webrtcCaps.rawType,
                            webrtcCaps.codecType,
                            webrtcCaps.interlaced);
   nsCOMPtr<nsIRunnable> runnable =
-    media::NewRunnableFrom([this, aCapEngine, capture_id, capCap]() -> nsresult {
-      if (this->SendStartCapture(aCapEngine, capture_id, capCap)) {
-        return NS_OK;
-      }
-      return NS_ERROR_FAILURE;
-    });
+    mozilla::NewNonOwningRunnableMethod<CaptureEngine, int, VideoCaptureCapability>
+    (this, &CamerasChild::SendStartCapture, aCapEngine, capture_id, capCap);
   LockAndDispatch<> dispatcher(this, __func__, runnable);
   return dispatcher.ReturnValue();
 }
 
 int
 CamerasChild::StopCapture(CaptureEngine aCapEngine, const int capture_id)
 {
   LOG((__PRETTY_FUNCTION__));
   nsCOMPtr<nsIRunnable> runnable =
-    media::NewRunnableFrom([this, aCapEngine, capture_id]() -> nsresult {
-      if (this->SendStopCapture(aCapEngine, capture_id)) {
-        return NS_OK;
-      }
-      return NS_ERROR_FAILURE;
-    });
+    mozilla::NewNonOwningRunnableMethod<CaptureEngine, int>
+    (this, &CamerasChild::SendStopCapture, aCapEngine, capture_id);
   LockAndDispatch<> dispatcher(this, __func__, runnable);
   if (dispatcher.Success()) {
     RemoveCallback(aCapEngine, capture_id);
   }
   return dispatcher.ReturnValue();
 }
 
 void
@@ -594,23 +558,20 @@ CamerasChild::ShutdownParent()
   {
     MonitorAutoLock monitor(mReplyMonitor);
     mIPCIsAlive = false;
     monitor.NotifyAll();
   }
   if (CamerasSingleton::Thread()) {
     LOG(("Dispatching actor deletion"));
     // Delete the parent actor.
-    RefPtr<Runnable> deleteRunnable =
-      // CamerasChild (this) will remain alive and is only deleted by the
-      // IPC layer when SendAllDone returns.
-      media::NewRunnableFrom([this]() -> nsresult {
-        Unused << this->SendAllDone();
-        return NS_OK;
-      });
+    // CamerasChild (this) will remain alive and is only deleted by the
+    // IPC layer when SendAllDone returns.
+    nsCOMPtr<nsIRunnable> deleteRunnable =
+      mozilla::NewNonOwningRunnableMethod(this, &CamerasChild::SendAllDone);
     CamerasSingleton::Thread()->Dispatch(deleteRunnable, NS_DISPATCH_NORMAL);
   } else {
     LOG(("ShutdownParent called without PBackground thread"));
   }
 }
 
 void
 CamerasChild::ShutdownChild()
--- a/dom/media/webrtc/MediaEngineRemoteVideoSource.cpp
+++ b/dom/media/webrtc/MediaEngineRemoteVideoSource.cpp
@@ -311,20 +311,20 @@ void
 MediaEngineRemoteVideoSource::SetLastCapability(
     const webrtc::CaptureCapability& aCapability)
 {
   mLastCapability = mCapability;
 
   webrtc::CaptureCapability cap = aCapability;
   RefPtr<MediaEngineRemoteVideoSource> that = this;
 
-  NS_DispatchToMainThread(media::NewRunnableFrom([this, that, cap]() mutable {
-    mSettings.mWidth.Value() = cap.width;
-    mSettings.mHeight.Value() = cap.height;
-    mSettings.mFrameRate.Value() = cap.maxFPS;
+  NS_DispatchToMainThread(media::NewRunnableFrom([that, cap]() mutable {
+    that->mSettings.mWidth.Value() = cap.width;
+    that->mSettings.mHeight.Value() = cap.height;
+    that->mSettings.mFrameRate.Value() = cap.maxFPS;
     return NS_OK;
   }));
 }
 
 void
 MediaEngineRemoteVideoSource::NotifyPull(MediaStreamGraph* aGraph,
                                          SourceMediaStream* aSource,
                                          TrackID aID, StreamTime aDesiredTime,
--- a/dom/media/webrtc/MediaEngineWebRTCAudio.cpp
+++ b/dom/media/webrtc/MediaEngineWebRTCAudio.cpp
@@ -368,20 +368,20 @@ MediaEngineWebRTCMicrophoneSource::Updat
 void
 MediaEngineWebRTCMicrophoneSource::SetLastPrefs(
     const MediaEnginePrefs& aPrefs)
 {
   mLastPrefs = aPrefs;
 
   RefPtr<MediaEngineWebRTCMicrophoneSource> that = this;
 
-  NS_DispatchToMainThread(media::NewRunnableFrom([this, that, aPrefs]() mutable {
-    mSettings.mEchoCancellation.Value() = aPrefs.mAecOn;
-    mSettings.mMozAutoGainControl.Value() = aPrefs.mAgcOn;
-    mSettings.mMozNoiseSuppression.Value() = aPrefs.mNoiseOn;
+  NS_DispatchToMainThread(media::NewRunnableFrom([that, aPrefs]() mutable {
+    that->mSettings.mEchoCancellation.Value() = aPrefs.mAecOn;
+    that->mSettings.mMozAutoGainControl.Value() = aPrefs.mAgcOn;
+    that->mSettings.mMozNoiseSuppression.Value() = aPrefs.mNoiseOn;
     return NS_OK;
   }));
 }
 
 
 nsresult
 MediaEngineWebRTCMicrophoneSource::Deallocate(AllocationHandle* aHandle)
 {
--- a/dom/media/webrtc/moz.build
+++ b/dom/media/webrtc/moz.build
@@ -37,17 +37,17 @@ if CONFIG['MOZ_WEBRTC']:
         'RTCIdentityProviderRegistrar.cpp',
     ]
     # MediaEngineWebRTC.cpp needs to be built separately.
     SOURCES += [
         'MediaEngineWebRTC.cpp',
     ]
     LOCAL_INCLUDES += [
         '/dom/base',
-        '/media/libyuv/include',
+        '/media/libyuv/libyuv/include',
         '/media/webrtc/signaling/src/common',
         '/media/webrtc/signaling/src/common/browser_logging',
         '/media/webrtc/trunk',
     ]
 
 XPIDL_SOURCES += [
     'nsITabSource.idl'
 ]
--- a/dom/plugins/base/PluginPRLibrary.cpp
+++ b/dom/plugins/base/PluginPRLibrary.cpp
@@ -185,25 +185,25 @@ PluginPRLibrary::NP_GetEntryPoints(NPPlu
   mNPP_ClearSiteData = pFuncs->clearsitedata;
   mNPP_GetSitesWithData = pFuncs->getsiteswithdata;
   return NS_OK;
 }
 #endif
 
 nsresult
 PluginPRLibrary::NPP_New(NPMIMEType pluginType, NPP instance,
-			 uint16_t mode, int16_t argc, char* argn[],
+			 int16_t argc, char* argn[],
 			 char* argv[], NPSavedData* saved,
 			 NPError* error)
 {
   if (!mNPP_New)
     return NS_ERROR_FAILURE;
 
   MAIN_THREAD_JNI_REF_GUARD;
-  *error = mNPP_New(pluginType, instance, mode, argc, argn, argv, saved);
+  *error = mNPP_New(pluginType, instance, NP_EMBED, argc, argn, argv, saved);
   return NS_OK;
 }
 
 nsresult
 PluginPRLibrary::NPP_ClearSiteData(const char* site, uint64_t flags,
                                    uint64_t maxAge, nsCOMPtr<nsIClearSiteDataCallback> callback)
 {
   if (!mNPP_ClearSiteData) {
--- a/dom/plugins/base/PluginPRLibrary.h
+++ b/dom/plugins/base/PluginPRLibrary.h
@@ -95,17 +95,17 @@ public:
     virtual nsresult NP_GetValue(void* aFuture, NPPVariable aVariable,
                                  void* aValue, NPError* aError) override;
 
 #if defined(XP_WIN) || defined(XP_MACOSX)
     virtual nsresult NP_GetEntryPoints(NPPluginFuncs* aFuncs, NPError* aError) override;
 #endif
 
     virtual nsresult NPP_New(NPMIMEType aPluginType, NPP aInstance,
-                             uint16_t aMode, int16_t aArgc, char* aArgn[],
+                             int16_t aArgc, char* aArgn[],
                              char* aArgv[], NPSavedData* aSaved,
                              NPError* aError) override;
 
     virtual nsresult NPP_ClearSiteData(const char* aSite, uint64_t aFlags,
                                        uint64_t aMaxAge, nsCOMPtr<nsIClearSiteDataCallback> callback) override;
     virtual nsresult NPP_GetSitesWithData(nsCOMPtr<nsIGetSitesWithDataCallback> callback) override;
 
     virtual nsresult AsyncSetWindow(NPP aInstance, NPWindow* aWindow) override;
--- a/dom/plugins/base/moz.build
+++ b/dom/plugins/base/moz.build
@@ -26,17 +26,16 @@ EXPORTS += [
     'nptypes.h',
     'nsJSNPRuntime.h',
     'nsNPAPIPluginInstance.h',
     'nsPluginDirServiceProvider.h',
     'nsPluginHost.h',
     'nsPluginInstanceOwner.h',
     'nsPluginLogging.h',
     'nsPluginNativeWindow.h',
-    'nsPluginNativeWindowGtk.h',
     'nsPluginsCID.h',
     'nsPluginsDir.h',
     'nsPluginTags.h',
 ]
 
 EXPORTS.mozilla += [
     'PluginPRLibrary.h',
 ]
@@ -65,27 +64,19 @@ if CONFIG['OS_ARCH'] == 'WINNT':
     ]
 elif CONFIG['MOZ_WIDGET_TOOLKIT'] == 'cocoa':
     UNIFIED_SOURCES += [
         'nsPluginNativeWindow.cpp',
         'nsPluginsDirDarwin.cpp',
     ]
 else:
     UNIFIED_SOURCES += [
+        'nsPluginNativeWindow.cpp',
         'nsPluginsDirUnix.cpp',
     ]
-    if 'gtk' in CONFIG['MOZ_WIDGET_TOOLKIT']:
-        # This file cannot be built in unified mode because of name clashes in X11 headers.
-        SOURCES += [
-            'nsPluginNativeWindowGtk.cpp',
-        ]
-    else:
-        UNIFIED_SOURCES += [
-            'nsPluginNativeWindow.cpp',
-        ]
 
 LOCAL_INCLUDES += [
     '/dom/base',
     '/dom/plugins/ipc',
     '/layout/generic',
     '/layout/xul',
     '/netwerk/base',
     '/widget',
--- a/dom/plugins/base/nsNPAPIPluginInstance.cpp
+++ b/dom/plugins/base/nsNPAPIPluginInstance.cpp
@@ -336,25 +336,16 @@ nsNPAPIPluginInstance::GetTagType(nsPlug
 {
   if (!mOwner) {
     return NS_ERROR_FAILURE;
   }
 
   return mOwner->GetTagType(result);
 }
 
-nsresult
-nsNPAPIPluginInstance::GetMode(int32_t *result)
-{
-  if (mOwner)
-    return mOwner->GetMode(result);
-  else
-    return NS_ERROR_FAILURE;
-}
-
 nsTArray<nsNPAPIPluginStreamListener*>*
 nsNPAPIPluginInstance::StreamListeners()
 {
   return &mStreamListeners;
 }
 
 nsTArray<nsPluginStreamListenerPeer*>*
 nsNPAPIPluginInstance::FileCachedStreamListeners()
@@ -413,21 +404,19 @@ nsNPAPIPluginInstance::Start()
   #endif
 
   for (uint32_t i = 0, pos = attributes.Length() + 1; i < params.Length(); i ++) {
     mCachedParamNames[pos] = ToNewUTF8String(params[i].mName);
     mCachedParamValues[pos] = ToNewUTF8String(params[i].mValue);
     pos++;
   }
 
-  int32_t       mode;
   const char*   mimetype;
   NPError       error = NPERR_GENERIC_ERROR;
 
-  GetMode(&mode);
   GetMIMEType(&mimetype);
 
   CheckJavaC2PJSObjectQuirk(quirkParamLength, mCachedParamNames, mCachedParamValues);
 
   bool oldVal = mInPluginInitCall;
   mInPluginInitCall = true;
 
   // Need this on the stack before calling NPP_New otherwise some callbacks that
@@ -441,24 +430,24 @@ nsNPAPIPluginInstance::Start()
   if (!library)
     return NS_ERROR_FAILURE;
 
   // Mark this instance as running before calling NPP_New because the plugin may
   // call other NPAPI functions, like NPN_GetURLNotify, that assume this is set
   // before returning. If the plugin returns failure, we'll clear it out below.
   mRunning = RUNNING;
 
-  nsresult newResult = library->NPP_New((char*)mimetype, &mNPP, (uint16_t)mode,
+  nsresult newResult = library->NPP_New((char*)mimetype, &mNPP,
                                         quirkParamLength, mCachedParamNames,
                                         mCachedParamValues, nullptr, &error);
   mInPluginInitCall = oldVal;
 
   NPP_PLUGIN_LOG(PLUGIN_LOG_NORMAL,
-  ("NPP New called: this=%p, npp=%p, mime=%s, mode=%d, argc=%d, return=%d\n",
-  this, &mNPP, mimetype, mode, quirkParamLength, error));
+  ("NPP New called: this=%p, npp=%p, mime=%s, argc=%d, return=%d\n",
+  this, &mNPP, mimetype, quirkParamLength, error));
 
   if (NS_FAILED(newResult) || error != NPERR_NO_ERROR) {
     mRunning = DESTROYED;
     nsJSNPRuntime::OnPluginDestroy(&mNPP);
     return NS_ERROR_FAILURE;
   }
 
   return newResult;
@@ -1584,59 +1573,16 @@ nsNPAPIPluginInstance::FinalizeAsyncSurf
 void
 nsNPAPIPluginInstance::SetCurrentAsyncSurface(NPAsyncSurface *surface, NPRect *changed)
 {
   if (mOwner) {
     mOwner->SetCurrentAsyncSurface(surface, changed);
   }
 }
 
-class CarbonEventModelFailureEvent : public Runnable {
-public:
-  nsCOMPtr<nsIContent> mContent;
-
-  explicit CarbonEventModelFailureEvent(nsIContent* aContent)
-    : mContent(aContent)
-  {}
-
-  ~CarbonEventModelFailureEvent() {}
-
-  NS_IMETHOD Run();
-};
-
-NS_IMETHODIMP
-CarbonEventModelFailureEvent::Run()
-{
-  nsString type = NS_LITERAL_STRING("npapi-carbon-event-model-failure");
-  nsContentUtils::DispatchTrustedEvent(mContent->GetComposedDoc(), mContent,
-                                       type, true, true);
-  return NS_OK;
-}
-
-void
-nsNPAPIPluginInstance::CarbonNPAPIFailure()
-{
-  nsCOMPtr<nsIDOMElement> element;
-  GetDOMElement(getter_AddRefs(element));
-  if (!element) {
-    return;
-  }
-
-  nsCOMPtr<nsIContent> content(do_QueryInterface(element));
-  if (!content) {
-    return;
-  }
-
-  nsCOMPtr<nsIRunnable> e = new CarbonEventModelFailureEvent(content);
-  nsresult rv = NS_DispatchToCurrentThread(e);
-  if (NS_FAILED(rv)) {
-    NS_WARNING("Failed to dispatch CarbonEventModelFailureEvent.");
-  }
-}
-
 static bool
 GetJavaVersionFromMimetype(nsPluginTag* pluginTag, nsCString& version)
 {
   for (uint32_t i = 0; i < pluginTag->MimeTypes().Length(); ++i) {
     nsCString type = pluginTag->MimeTypes()[i];
     nsAutoCString jpi("application/x-java-applet;jpi-version=");
 
     int32_t idx = type.Find(jpi, false, 0, -1);
--- a/dom/plugins/base/nsNPAPIPluginInstance.h
+++ b/dom/plugins/base/nsNPAPIPluginInstance.h
@@ -297,20 +297,16 @@ public:
 
   void URLRedirectResponse(void* notifyData, NPBool allow);
 
   NPError InitAsyncSurface(NPSize *size, NPImageFormat format,
                            void *initData, NPAsyncSurface *surface);
   NPError FinalizeAsyncSurface(NPAsyncSurface *surface);
   void SetCurrentAsyncSurface(NPAsyncSurface *surface, NPRect *changed);
 
-  // Called when the instance fails to instantiate beceause the Carbon
-  // event model is not supported.
-  void CarbonNPAPIFailure();
-
   // Returns the contents scale factor of the screen the plugin is drawn on.
   double GetContentsScaleFactor();
 
   // Returns the css zoom factor of the document the plugin is drawn on.
   float GetCSSZoomFactor();
 
   nsresult GetRunID(uint32_t *aRunID);
 
@@ -329,17 +325,16 @@ public:
     }
   }
 
 protected:
 
   virtual ~nsNPAPIPluginInstance();
 
   nsresult GetTagType(nsPluginTagType *result);
-  nsresult GetMode(int32_t *result);
 
   // check if this is a Java applet and affected by bug 750480
   void CheckJavaC2PJSObjectQuirk(uint16_t paramCount,
                                  const char* const* names,
                                  const char* const* values);
 
   // The structure used to communicate between the plugin instance and
   // the browser.
--- a/dom/plugins/base/nsPluginInstanceOwner.cpp
+++ b/dom/plugins/base/nsPluginInstanceOwner.cpp
@@ -3339,61 +3339,62 @@ void* nsPluginInstanceOwner::GetPluginPo
 void nsPluginInstanceOwner::ReleasePluginPort(void * pluginPort)
 {
 }
 
 NS_IMETHODIMP nsPluginInstanceOwner::CreateWidget(void)
 {
   NS_ENSURE_TRUE(mPluginWindow, NS_ERROR_NULL_POINTER);
 
-  nsresult rv = NS_ERROR_FAILURE;
-
   // Can't call this twice!
   if (mWidget) {
     NS_WARNING("Trying to create a plugin widget twice!");
     return NS_ERROR_FAILURE;
   }
 
   bool windowless = false;
   mInstance->IsWindowless(&windowless);
   if (!windowless) {
+#ifndef XP_WIN
+    // Only Windows supports windowed mode!
+    MOZ_ASSERT_UNREACHABLE();
+    return NS_ERROR_FAILURE;
+#else
     // Try to get a parent widget, on some platforms widget creation will fail without
     // a parent.
+    nsresult rv = NS_ERROR_FAILURE;
+
     nsCOMPtr<nsIWidget> parentWidget;
     nsIDocument *doc = nullptr;
     nsCOMPtr<nsIContent> content = do_QueryReferent(mContent);
     if (content) {
       doc = content->OwnerDoc();
       parentWidget = nsContentUtils::WidgetForDocument(doc);
-#ifndef XP_MACOSX
       // If we're running in the content process, we need a remote widget created in chrome.
       if (XRE_IsContentProcess()) {
         if (nsCOMPtr<nsPIDOMWindowOuter> window = doc->GetWindow()) {
           if (nsCOMPtr<nsPIDOMWindowOuter> topWindow = window->GetTop()) {
             dom::TabChild* tc = dom::TabChild::GetFrom(topWindow);
             if (tc) {
               // This returns a PluginWidgetProxy which remotes a number of calls.
               rv = tc->CreatePluginWidget(parentWidget.get(), getter_AddRefs(mWidget));
               if (NS_FAILED(rv)) {
                 return rv;
               }
             }
           }
         }
       }
-#endif // XP_MACOSX
     }
 
-#ifndef XP_MACOSX
     // A failure here is terminal since we can't fall back on the non-e10s code
     // path below.
     if (!mWidget && XRE_IsContentProcess()) {
       return NS_ERROR_UNEXPECTED;
     }
-#endif // XP_MACOSX
 
     if (!mWidget) {
       // native (single process)
       mWidget = do_CreateInstance(kWidgetCID, &rv);
       nsWidgetInitData initData;
       initData.mWindowType = eWindowType_plugin;
       initData.mUnicode = false;
       initData.clipChildren = true;
@@ -3405,16 +3406,17 @@ NS_IMETHODIMP nsPluginInstanceOwner::Cre
         mWidget = nullptr;
         return rv;
       }
     }
 
     mWidget->EnableDragDrop(true);
     mWidget->Show(false);
     mWidget->Enable(false);
+#endif // XP_WIN
   }
 
   if (mPluginFrame) {
     // nullptr widget is fine, will result in windowless setup.
     mPluginFrame->PrepForDrawing(mWidget);
   }
 
   if (windowless) {
--- a/dom/plugins/base/nsPluginNativeWindow.cpp
+++ b/dom/plugins/base/nsPluginNativeWindow.cpp
@@ -7,47 +7,59 @@
  *  This file is the default implementation of plugin native window
  *  empty stubs, it should be replaced with real platform implementation
  *  for every platform
  */
 
 #include "nsDebug.h"
 #include "nsPluginNativeWindow.h"
 
-class nsPluginNativeWindowPLATFORM : public nsPluginNativeWindow {
-public: 
-  nsPluginNativeWindowPLATFORM();
-  virtual ~nsPluginNativeWindowPLATFORM();
+class nsPluginNativeWindowImpl : public nsPluginNativeWindow
+{
+public:
+  nsPluginNativeWindowImpl();
+  virtual ~nsPluginNativeWindowImpl();
+
+#ifdef MOZ_WIDGET_GTK
+  NPSetWindowCallbackStruct mWsInfo;
+#endif
 };
 
-nsPluginNativeWindowPLATFORM::nsPluginNativeWindowPLATFORM() : nsPluginNativeWindow()
+nsPluginNativeWindowImpl::nsPluginNativeWindowImpl() : nsPluginNativeWindow()
 {
   // initialize the struct fields
-  window = nullptr; 
-  x = 0; 
-  y = 0; 
-  width = 0; 
-  height = 0; 
+  window = nullptr;
+  x = 0;
+  y = 0;
+  width = 0;
+  height = 0;
   memset(&clipRect, 0, sizeof(clipRect));
-#if defined(XP_UNIX) && !defined(XP_MACOSX)
+  type = NPWindowTypeWindow;
+
+#ifdef MOZ_WIDGET_GTK
+  ws_info = &mWsInfo;
+  mWsInfo.type = 0;
+  mWsInfo.display = nullptr;
+  mWsInfo.visual = nullptr;
+  mWsInfo.colormap = 0;
+  mWsInfo.depth = 0;
+#elif defined(XP_UNIX) && !defined(XP_MACOSX)
   ws_info = nullptr;
 #endif
-  type = NPWindowTypeWindow;
 }
 
-nsPluginNativeWindowPLATFORM::~nsPluginNativeWindowPLATFORM() 
+nsPluginNativeWindowImpl::~nsPluginNativeWindowImpl()
 {
 }
 
 nsresult PLUG_NewPluginNativeWindow(nsPluginNativeWindow ** aPluginNativeWindow)
 {
   NS_ENSURE_ARG_POINTER(aPluginNativeWindow);
-  *aPluginNativeWindow = new nsPluginNativeWindowPLATFORM();
+  *aPluginNativeWindow = new nsPluginNativeWindowImpl();
   return NS_OK;
 }
 
 nsresult PLUG_DeletePluginNativeWindow(nsPluginNativeWindow * aPluginNativeWindow)
 {
   NS_ENSURE_ARG_POINTER(aPluginNativeWindow);
-  nsPluginNativeWindowPLATFORM *p = (nsPluginNativeWindowPLATFORM *)aPluginNativeWindow;
-  delete p;
+  delete static_cast<nsPluginNativeWindowImpl*>(aPluginNativeWindow);
   return NS_OK;
 }
deleted file mode 100644
--- a/dom/plugins/base/nsPluginNativeWindowGtk.cpp
+++ /dev/null
@@ -1,356 +0,0 @@
-/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
-/* vim:expandtab:shiftwidth=2:tabstop=2:
-*/
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-/**
- *  This file is the Gtk2 implementation of plugin native window.
- */
-
-#include "nsDebug.h"
-#include "nsPluginNativeWindowGtk.h"
-#include "nsNPAPIPlugin.h"
-#include "npapi.h"
-#include <gtk/gtk.h>
-#include <gdk/gdkx.h>
-#include <gdk/gdk.h>
-
-#if (GTK_MAJOR_VERSION == 3)
-#include <gtk/gtkx.h>
-#else
-#include "gtk2xtbin.h"
-#endif
-#include "mozilla/X11Util.h"
-
-static void plug_added_cb(GtkWidget *widget, gpointer data);
-static gboolean plug_removed_cb   (GtkWidget *widget, gpointer data);
-static void socket_unrealize_cb   (GtkWidget *widget, gpointer data);
-
-nsPluginNativeWindowGtk::nsPluginNativeWindowGtk() : nsPluginNativeWindow()
-{
-  // initialize the struct fields
-  window = nullptr; 
-  x = 0; 
-  y = 0; 
-  width = 0; 
-  height = 0; 
-  memset(&clipRect, 0, sizeof(clipRect));
-  ws_info = &mWsInfo;
-  type = NPWindowTypeWindow;
-  mSocketWidget = 0;
-  mWsInfo.type = 0;
-  mWsInfo.display = nullptr;
-  mWsInfo.visual = nullptr;
-  mWsInfo.colormap = 0;
-  mWsInfo.depth = 0;
-}
-
-nsPluginNativeWindowGtk::~nsPluginNativeWindowGtk() 
-{
-  if(mSocketWidget) {
-    gtk_widget_destroy(mSocketWidget);
-  }
-}
-
-nsresult PLUG_NewPluginNativeWindow(nsPluginNativeWindow ** aPluginNativeWindow)
-{
-  NS_ENSURE_ARG_POINTER(aPluginNativeWindow);
-  *aPluginNativeWindow = new nsPluginNativeWindowGtk();
-  return NS_OK;
-}
-
-nsresult PLUG_DeletePluginNativeWindow(nsPluginNativeWindow * aPluginNativeWindow)
-{
-  NS_ENSURE_ARG_POINTER(aPluginNativeWindow);
-  nsPluginNativeWindowGtk *p = (nsPluginNativeWindowGtk *)aPluginNativeWindow;
-  delete p;
-  return NS_OK;
-}
-
-nsresult nsPluginNativeWindowGtk::CallSetWindow(RefPtr<nsNPAPIPluginInstance> &aPluginInstance)
-{
-  if (aPluginInstance) {
-    if (type == NPWindowTypeWindow &&
-        XRE_IsContentProcess()) {
-      // In this case, most of the initialization code here has already happened
-      // in the chrome process. The window we have in content is the XID of the
-      // socket widget we need to hand to plugins.
-      SetWindow((XID)window);
-	  } else if (type == NPWindowTypeWindow) {
-      if (!mSocketWidget) {
-        nsresult rv;
-
-        // The documentation on the types for many variables in NP(N|P)_GetValue
-        // is vague.  Often boolean values are NPBool (1 byte), but
-        // https://developer.mozilla.org/en/XEmbed_Extension_for_Mozilla_Plugins
-        // treats NPPVpluginNeedsXEmbed as PRBool (int), and
-        // on x86/32-bit, flash stores to this using |movl 0x1,&needsXEmbed|.
-        // thus we can't use NPBool for needsXEmbed, or the three bytes above
-        // it on the stack would get clobbered. so protect with the larger bool.
-        int needsXEmbed = 0;
-        rv = aPluginInstance->GetValueFromPlugin(NPPVpluginNeedsXEmbed, &needsXEmbed);
-        // If the call returned an error code make sure we still use our default value.
-        if (NS_FAILED(rv)) {
-          needsXEmbed = 0;
-        }
-#ifdef DEBUG
-        printf("nsPluginNativeWindowGtk: NPPVpluginNeedsXEmbed=%d\n", needsXEmbed);
-#endif
-
-        bool isOOPPlugin = aPluginInstance->GetPlugin()->GetLibrary()->IsOOP();
-        if (needsXEmbed || isOOPPlugin) {        
-          bool enableXtFocus = !needsXEmbed;
-          rv = CreateXEmbedWindow(enableXtFocus);
-        }
-        else {
-#if (MOZ_WIDGET_GTK == 2)
-          rv = CreateXtWindow();
-#else
-          return NS_ERROR_FAILURE;
-#endif
-        }
-
-        if (NS_FAILED(rv)) {
-          return NS_ERROR_FAILURE;
-        }
-      }
-
-      if (!mSocketWidget) {
-        return NS_ERROR_FAILURE;
-      }
-
-      // Make sure to resize and re-place the window if required.
-      SetAllocation();
-      // Need to reset "window" each time as nsPluginFrame::DidReflow sets it
-      // to the ancestor window.
-#if (MOZ_WIDGET_GTK == 2)
-      if (GTK_IS_XTBIN(mSocketWidget)) {
-        // Point the NPWindow structures window to the actual X window
-        SetWindow(GTK_XTBIN(mSocketWidget)->xtwindow);
-      }
-      else { // XEmbed or OOP&Xt
-        SetWindow(gtk_socket_get_id(GTK_SOCKET(mSocketWidget)));
-      }
-#else
-      // Gtk3 supports only OOP by GtkSocket
-      SetWindow(gtk_socket_get_id(GTK_SOCKET(mSocketWidget)));
-#endif
-
-#ifdef DEBUG
-      printf("nsPluginNativeWindowGtk: call SetWindow with xid=%p\n", (void *)window);
-#endif
-    } // NPWindowTypeWindow
-    aPluginInstance->SetWindow(this);
-  } else if (mPluginInstance) {
-    mPluginInstance->SetWindow(nullptr);
-  }
-
-  SetPluginInstance(aPluginInstance);
-  return NS_OK;
-}
-
-nsresult nsPluginNativeWindowGtk::CreateXEmbedWindow(bool aEnableXtFocus) {
-  NS_ASSERTION(!mSocketWidget,"Already created a socket widget!");
-  GdkDisplay *display = gdk_display_get_default();
-  GdkWindow *parent_win = gdk_x11_window_lookup_for_display(display, GetWindow());
-  mSocketWidget = gtk_socket_new();
-
-  //attach the socket to the container widget
-  gtk_widget_set_parent_window(mSocketWidget, parent_win);
-
-  // enable/disable focus event handlers,
-  // see plugin_window_filter_func() for details
-  g_object_set_data(G_OBJECT(mSocketWidget), "enable-xt-focus", (void *)aEnableXtFocus);
-
-  g_signal_connect(mSocketWidget, "plug_added",
-                   G_CALLBACK(plug_added_cb), nullptr);
-
-  // Make sure to handle the plug_removed signal.  If we don't the
-  // socket will automatically be destroyed when the plug is
-  // removed, which means we're destroying it more than once.
-  // SYNTAX ERROR.
-  g_signal_connect(mSocketWidget, "plug_removed",
-                   G_CALLBACK(plug_removed_cb), nullptr);
-
-  g_signal_connect(mSocketWidget, "unrealize",
-                   G_CALLBACK(socket_unrealize_cb), nullptr);
-
-  g_signal_connect(mSocketWidget, "destroy",
-                   G_CALLBACK(gtk_widget_destroyed), &mSocketWidget);
-
-  gpointer user_data = nullptr;
-  gdk_window_get_user_data(parent_win, &user_data);
-
-  GtkContainer *container = GTK_CONTAINER(user_data);
-  gtk_container_add(container, mSocketWidget);
-  gtk_widget_realize(mSocketWidget);
-
-  // The GtkSocket has a visible window, but the plugin's XEmbed plug will
-  // cover this window.  Normally GtkSockets let the X server paint their
-  // background and this would happen immediately (before the plug is
-  // created).  Setting the background to None prevents the server from
-  // painting this window, avoiding flicker.
-  // TODO GTK3
-#if (MOZ_WIDGET_GTK == 2)
-  gdk_window_set_back_pixmap(gtk_widget_get_window(mSocketWidget), nullptr, FALSE);
-#endif
-
-  // Resize before we show
-  SetAllocation();
-
-  gtk_widget_show(mSocketWidget);
-
-  gdk_flush();
-  SetWindow(gtk_socket_get_id(GTK_SOCKET(mSocketWidget)));
-
-  // Fill out the ws_info structure.
-  // (The windowless case is done in nsPluginFrame.cpp.)
-  GdkWindow *gdkWindow = gdk_x11_window_lookup_for_display(display, GetWindow());
-  if(!gdkWindow)
-    return NS_ERROR_FAILURE;
-
-  mWsInfo.display = GDK_WINDOW_XDISPLAY(gdkWindow);
-#if (MOZ_WIDGET_GTK == 2)
-  mWsInfo.colormap = GDK_COLORMAP_XCOLORMAP(gdk_drawable_get_colormap(gdkWindow));
-  GdkVisual* gdkVisual = gdk_drawable_get_visual(gdkWindow);
-  mWsInfo.depth = gdkVisual->depth;
-#else
-  mWsInfo.colormap = X11None;
-  GdkVisual* gdkVisual = gdk_window_get_visual(gdkWindow);
-  mWsInfo.depth = gdk_visual_get_depth(gdkVisual);
-#endif
-  mWsInfo.visual = GDK_VISUAL_XVISUAL(gdkVisual);
-    
-  return NS_OK;
-}
-
-void nsPluginNativeWindowGtk::SetAllocation() {
-  if (!mSocketWidget)
-    return;
-
-  GtkAllocation new_allocation;
-  new_allocation.x = 0;
-  new_allocation.y = 0;
-  new_allocation.width = width;
-  new_allocation.height = height;
-  gtk_widget_size_allocate(mSocketWidget, &new_allocation);
-}
-
-#if (MOZ_WIDGET_GTK == 2)
-nsresult nsPluginNativeWindowGtk::CreateXtWindow() {
-  NS_ASSERTION(!mSocketWidget,"Already created a socket widget!");
-
-#ifdef DEBUG      
-  printf("About to create new xtbin of %i X %i from %p...\n",
-         width, height, (void*)window);
-#endif
-  GdkDisplay *display = gdk_display_get_default();
-  GdkWindow *gdkWindow = gdk_x11_window_lookup_for_display(display, GetWindow());
-  mSocketWidget = gtk_xtbin_new(gdkWindow, 0);
-  // Check to see if creating the xtbin failed for some reason.
-  // if it did, we can't go any further.
-  if (!mSocketWidget)
-    return NS_ERROR_FAILURE;
-
-  g_signal_connect(mSocketWidget, "destroy",
-                   G_CALLBACK(gtk_widget_destroyed), &mSocketWidget);
-
-  gtk_widget_set_size_request(mSocketWidget, width, height);
-
-#ifdef DEBUG
-  printf("About to show xtbin(%p)...\n", (void*)mSocketWidget); fflush(nullptr);
-#endif
-  gtk_widget_show(mSocketWidget);
-#ifdef DEBUG
-  printf("completed gtk_widget_show(%p)\n", (void*)mSocketWidget); fflush(nullptr);
-#endif
-
-  // Fill out the ws_info structure.
-  GtkXtBin* xtbin = GTK_XTBIN(mSocketWidget);
-  // The xtbin has its own Display structure.
-  mWsInfo.display = xtbin->xtdisplay;
-  mWsInfo.colormap = xtbin->xtclient.xtcolormap;
-  mWsInfo.visual = xtbin->xtclient.xtvisual;
-  mWsInfo.depth = xtbin->xtclient.xtdepth;
-  // Leave mWsInfo.type = 0 - Who knows what this is meant to be?
-
-  XFlush(mWsInfo.display);
-
-  return NS_OK;
-}
-#endif
-
-static void
-plug_window_finalize_cb(gpointer socket, GObject* plug_window)
-{
-  g_object_unref(socket);
-}
-
-static void
-plug_added_cb(GtkWidget *socket, gpointer data)
-{
-  // The plug window has been embedded, and gtk_socket_add_window() has added
-  // a filter to the socket's plug_window, passing the socket as data for the
-  // filter, so the socket must live as long as events may be received on the
-  // plug window.
-  //
-  // https://git.gnome.org/browse/gtk+/tree/gtk/gtksocket.c?h=3.18.7#n1124
-  g_object_ref(socket);
-  // When the socket is unrealized, perhaps during gtk_widget_destroy() from
-  // ~nsPluginNativeWindowGtk, the plug is removed.  The plug in the child
-  // process then destroys its widget and window.  When the browser process
-  // receives the DestroyNotify event for the plug window, GDK releases its
-  // reference to plugWindow.  This is typically the last reference and so the
-  // weak ref callback triggers release of the socket.
-  GdkWindow* plugWindow = gtk_socket_get_plug_window(GTK_SOCKET(socket));
-  g_object_weak_ref(G_OBJECT(plugWindow), plug_window_finalize_cb, socket);
-}
-
-/* static */
-gboolean
-plug_removed_cb (GtkWidget *widget, gpointer data)
-{
-  // Gee, thanks for the info!
-  return TRUE;
-}
-
-static void
-socket_unrealize_cb(GtkWidget *widget, gpointer data)
-{
-  // Unmap and reparent any child windows that GDK does not yet know about.
-  // (See bug 540114 comment 10.)
-  GdkWindow* socket_window =  gtk_widget_get_window(widget);
-  GdkDisplay* gdkDisplay = gdk_display_get_default();
-  Display* display = GDK_DISPLAY_XDISPLAY(gdkDisplay);
-
-  // Ignore X errors that may happen if windows get destroyed (possibly
-  // requested by the plugin) between XQueryTree and when we operate on them.
-  gdk_error_trap_push();
-
-  Window root, parent;
-  Window* children;
-  unsigned int nchildren;
-  if (!XQueryTree(display, gdk_x11_window_get_xid(socket_window),
-                  &root, &parent, &children, &nchildren))
-    return;
-
-  for (unsigned int i = 0; i < nchildren; ++i) {
-    Window child = children[i];
-    if (!gdk_x11_window_lookup_for_display(gdkDisplay, child)) {
-      // This window is not known to GDK.
-      XUnmapWindow(display, child);
-      XReparentWindow(display, child, DefaultRootWindow(display), 0, 0);
-    }
-  }
-
-  if (children) XFree(children);
-
-  mozilla::FinishX(display);
-#if (MOZ_WIDGET_GTK == 3)
-  gdk_error_trap_pop_ignored();
-#else
-  gdk_error_trap_pop();
-#endif
-}
deleted file mode 100644
--- a/dom/plugins/base/nsPluginNativeWindowGtk.h
+++ /dev/null
@@ -1,51 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-#ifndef _nsPluginNativeWindowGdk_h_
-#define _nsPluginNativeWindowGdk_h_
-
-#include "nsPluginNativeWindow.h"
-#include "npapi.h"
-#include <gtk/gtk.h>
-#include <gdk/gdkx.h>
-#include <gdk/gdk.h>
-#if (GTK_MAJOR_VERSION == 3)
-#include <gtk/gtkx.h>
-#else
-#include "gtk2xtbin.h"
-#endif
-#include "mozilla/X11Util.h"
-
-class nsPluginNativeWindowGtk : public nsPluginNativeWindow {
-public:
-  nsPluginNativeWindowGtk();
-  virtual ~nsPluginNativeWindowGtk();
-
-  virtual nsresult CallSetWindow(RefPtr<nsNPAPIPluginInstance> &aPluginInstance);
-  nsresult CreateXEmbedWindow(bool aEnableXtFocus);
-  void SetAllocation();
-
-  XID GetWindow() const
-  {
-    return static_cast<XID>(reinterpret_cast<uintptr_t>(window));
-  }
-
-private:
-  void SetWindow(XID aWindow)
-  {
-    window = reinterpret_cast<void*>(static_cast<uintptr_t>(aWindow));
-  }
-
-  NPSetWindowCallbackStruct mWsInfo;
-  /**
-   * Either a GtkSocket or a special GtkXtBin widget (derived from GtkSocket)
-   * that encapsulates the Xt toolkit within a Gtk Application.
-   */
-  GtkWidget* mSocketWidget;
-#if (MOZ_WIDGET_GTK == 2)
-  nsresult  CreateXtWindow();
-#endif
-};
-
-#endif
--- a/dom/plugins/ipc/PPluginInstance.ipdl
+++ b/dom/plugins/ipc/PPluginInstance.ipdl
@@ -82,20 +82,16 @@ child:
   // This is only used on Windows and, for windowless plugins.
   async CreateChildPopupSurrogate(NativeWindowHandle netscapeWindow);
 
   intr NPP_SetWindow(NPRemoteWindow window);
 
   intr NPP_GetValue_NPPVpluginWantsAllNetworkStreams()
     returns (bool value, NPError result);
 
-  // this message is not used on non-X platforms
-  intr NPP_GetValue_NPPVpluginNeedsXEmbed()
-    returns (bool value, NPError result);
-
   intr NPP_GetValue_NPPVpluginScriptableNPObject()
     returns (nullable PPluginScriptableObject value, NPError result);
 
   intr NPP_SetValue_NPNVprivateModeBool(bool value) returns (NPError result);
   intr NPP_GetValue_NPPVpluginNativeAccessibleAtkPlugId()
     returns (nsCString plug_id, NPError result);
 
   intr NPP_SetValue_NPNVCSSZoomFactor(double value) returns (NPError result);
@@ -257,21 +253,16 @@ parent:
     returns (nsCString username, nsCString password, NPError result);
 
   intr NPN_ConvertPoint(double sourceX, bool ignoreDestX, double sourceY, bool ignoreDestY, NPCoordinateSpace sourceSpace,
                        NPCoordinateSpace destSpace)
     returns (double destX, double destY, bool result);
 
   async RedrawPlugin();
 
-  // Send notification that a plugin tried to negotiate Carbon NPAPI so that
-  // users can be notified that restarting the browser in i386 mode may allow
-  // them to use the plugin.
-  sync NegotiatedCarbon();
-
   // Notifies the parent of its NPP_New result code.
   async AsyncNPP_NewResult(NPError aResult);
 
   // Sends a native window to be adopted by the native window that would be
   // returned by NPN_GetValue_NPNVnetscapeWindow. Only used on Windows.
   async SetNetscapeWindowAsParent(NativeWindowHandle childWindow);
 
   sync GetCompositionString(uint32_t aType)
--- a/dom/plugins/ipc/PPluginModule.ipdl
+++ b/dom/plugins/ipc/PPluginModule.ipdl
@@ -58,17 +58,16 @@ child:
     returns (NPError rv);
 
   intr NP_Initialize(PluginSettings settings)
     returns (NPError rv);
 
   async AsyncNP_Initialize(PluginSettings settings);
 
   async PPluginInstance(nsCString aMimeType,
-                        uint16_t aMode,
                         nsCString[] aNames,
                         nsCString[] aValues);
 
   // Implements the synchronous version of NPP_New for when async plugin init
   // is preffed off.
   intr SyncNPP_New(PPluginInstance aActor)
     returns (NPError rv);
 
--- a/dom/plugins/ipc/PluginAsyncSurrogate.cpp
+++ b/dom/plugins/ipc/PluginAsyncSurrogate.cpp
@@ -96,56 +96,54 @@ private:
   bool        mIsRecursive;
   static bool sHasEntered;
 };
 
 bool RecursionGuard::sHasEntered = false;
 
 PluginAsyncSurrogate::PluginAsyncSurrogate(PluginModuleParent* aParent)
   : mParent(aParent)
-  , mMode(0)
   , mWindow(nullptr)
   , mAcceptCalls(false)
   , mInstantiated(false)
   , mAsyncSetWindow(false)
   , mInitCancelled(false)
   , mDestroyPending(false)
   , mAsyncCallsInFlight(0)
 {
   MOZ_ASSERT(aParent);
 }
 
 PluginAsyncSurrogate::~PluginAsyncSurrogate()
 {
 }
 
 bool
-PluginAsyncSurrogate::Init(NPMIMEType aPluginType, NPP aInstance, uint16_t aMode,
+PluginAsyncSurrogate::Init(NPMIMEType aPluginType, NPP aInstance,
                            int16_t aArgc, char* aArgn[], char* aArgv[])
 {
   mMimeType = aPluginType;
   nsNPAPIPluginInstance* instance =
     static_cast<nsNPAPIPluginInstance*>(aInstance->ndata);
   MOZ_ASSERT(instance);
   mInstance = instance;
-  mMode = aMode;
   for (int i = 0; i < aArgc; ++i) {
     mNames.AppendElement(NullableString(aArgn[i]));
     mValues.AppendElement(NullableString(aArgv[i]));
   }
   return true;
 }
 
 /* static */ bool
 PluginAsyncSurrogate::Create(PluginModuleParent* aParent, NPMIMEType aPluginType,
-                             NPP aInstance, uint16_t aMode, int16_t aArgc,
+                             NPP aInstance, int16_t aArgc,
                              char* aArgn[], char* aArgv[])
 {
   RefPtr<PluginAsyncSurrogate> surrogate(new PluginAsyncSurrogate(aParent));
-  if (!surrogate->Init(aPluginType, aInstance, aMode, aArgc, aArgn, aArgv)) {
+  if (!surrogate->Init(aPluginType, aInstance, aArgc, aArgn, aArgv)) {
     return false;
   }
   PluginAsyncSurrogate* rawSurrogate = nullptr;
   surrogate.forget(&rawSurrogate);
   aInstance->pdata = static_cast<PluginDataResolver*>(rawSurrogate);
   return true;
 }
 
@@ -164,17 +162,17 @@ PluginAsyncSurrogate::Cast(NPP aInstance
 nsresult
 PluginAsyncSurrogate::NPP_New(NPError* aError)
 {
   if (!mInstance) {
     return NS_ERROR_NULL_POINTER;
   }
 
   nsresult rv = mParent->NPP_NewInternal(mMimeType.BeginWriting(), GetNPP(),
-                                         mMode, mNames, mValues, nullptr,
+                                         mNames, mValues, nullptr,
                                          aError);
   if (NS_FAILED(rv)) {
     return rv;
   }
   return NS_OK;
 }
 
 void
--- a/dom/plugins/ipc/PluginAsyncSurrogate.h
+++ b/dom/plugins/ipc/PluginAsyncSurrogate.h
@@ -24,33 +24,33 @@ struct ParentNPObject;
 class PluginInstanceParent;
 class PluginModuleParent;
 
 class PluginAsyncSurrogate : public PluginDataResolver
 {
 public:
   NS_INLINE_DECL_REFCOUNTING(PluginAsyncSurrogate)
 
-  bool Init(NPMIMEType aPluginType, NPP aInstance, uint16_t aMode,
+  bool Init(NPMIMEType aPluginType, NPP aInstance,
             int16_t aArgc, char* aArgn[], char* aArgv[]);
   nsresult NPP_New(NPError* aError);
   NPError NPP_Destroy(NPSavedData** aSave);
   NPError NPP_GetValue(NPPVariable aVariable, void* aRetval);
   NPError NPP_SetValue(NPNVariable aVariable, void* aValue);
   NPError NPP_NewStream(NPMIMEType aType, NPStream* aStream, NPBool aSeekable,
                         uint16_t* aStype);
   NPError NPP_SetWindow(NPWindow* aWindow);
   nsresult AsyncSetWindow(NPWindow* aWindow);
   void NPP_Print(NPPrint* aPrintInfo);
   int16_t NPP_HandleEvent(void* aEvent);
   int32_t NPP_WriteReady(NPStream* aStream);
   NPError NPP_DestroyStream(NPStream* aStream, NPReason aReason);
   void OnInstanceCreated(PluginInstanceParent* aInstance);
   static bool Create(PluginModuleParent* aParent, NPMIMEType aPluginType,
-                     NPP aInstance, uint16_t aMode, int16_t aArgc,
+                     NPP aInstance, int16_t aArgc,
                      char* aArgn[], char* aArgv[]);
   static const NPClass* GetClass() { return &sNPClass; }
   static void NP_GetEntryPoints(NPPluginFuncs* aFuncs);
   static PluginAsyncSurrogate* Cast(NPP aInstance);
   static void NotifyDestroyPending(NPP aInstance);
   void NotifyDestroyPending();
 
   virtual PluginAsyncSurrogate*
@@ -136,17 +136,16 @@ private:
     NPBool      mSeekable;
   };
 
 private:
   PluginModuleParent*             mParent;
   // These values are used to construct the plugin instance
   nsCString                       mMimeType;
   mozilla::WeakPtr<nsNPAPIPluginInstance> mInstance;
-  uint16_t                        mMode;
   InfallibleTArray<nsCString>     mNames;
   InfallibleTArray<nsCString>     mValues;
   // This is safe to store as a pointer because the spec says it will remain
   // valid until destruction or a subsequent NPP_SetWindow call.
   NPWindow*                       mWindow;
   nsTArray<PendingNewStreamCall>  mPendingNewStreamCalls;
   UniquePtr<PluginDestructionGuard> mPluginDestructionGuard;
 
--- a/dom/plugins/ipc/PluginInstanceChild.cpp
+++ b/dom/plugins/ipc/PluginInstanceChild.cpp
@@ -128,38 +128,33 @@ CreateDrawTargetForSurface(gfxASurface *
   }
   return drawTarget;
 }
 
 bool PluginInstanceChild::sIsIMEComposing = false;
 
 PluginInstanceChild::PluginInstanceChild(const NPPluginFuncs* aPluginIface,
                                          const nsCString& aMimeType,
-                                         const uint16_t& aMode,
                                          const InfallibleTArray<nsCString>& aNames,
                                          const InfallibleTArray<nsCString>& aValues)
     : mPluginIface(aPluginIface)
     , mMimeType(aMimeType)
-    , mMode(aMode)
     , mNames(aNames)
     , mValues(aValues)
 #if defined(XP_DARWIN) || defined (XP_WIN)
     , mContentsScaleFactor(1.0)
 #endif
     , mPostingKeyEvents(0)
     , mPostingKeyEventsOutdated(0)
     , mDrawingModel(kDefaultDrawingModel)
     , mCurrentDirectSurface(nullptr)
     , mAsyncInvalidateMutex("PluginInstanceChild::mAsyncInvalidateMutex")
     , mAsyncInvalidateTask(0)
     , mCachedWindowActor(nullptr)
     , mCachedElementActor(nullptr)
-#ifdef MOZ_WIDGET_GTK
-    , mXEmbed(false)
-#endif // MOZ_WIDGET_GTK
 #if defined(OS_WIN)
     , mPluginWindowHWND(0)
     , mPluginWndProc(0)
     , mPluginParentHWND(0)
     , mCachedWinlessPluginHWND(0)
     , mWinlessPopupSurrogateHWND(0)
     , mWinlessThrottleOldWndProc(0)
     , mWinlessHiddenMsgHWND(0)
@@ -196,17 +191,16 @@ PluginInstanceChild::PluginInstanceChild
     mWindow.type = NPWindowTypeWindow;
     mData.ndata = (void*) this;
     mData.pdata = nullptr;
 #if defined(MOZ_X11) && defined(XP_UNIX) && !defined(XP_MACOSX)
     mWindow.ws_info = &mWsInfo;
     memset(&mWsInfo, 0, sizeof(mWsInfo));
 #ifdef MOZ_WIDGET_GTK
     mWsInfo.display = nullptr;
-    mXtClient.top_widget = nullptr;
 #else
     mWsInfo.display = DefaultXDisplay();
 #endif
 #endif // MOZ_X11 && XP_UNIX && !XP_MACOSX
 #if defined(OS_WIN)
     InitPopupMenuHook();
     InitImm32Hook();
 #endif // OS_WIN
@@ -254,40 +248,24 @@ PluginInstanceChild::DoNPP_New()
     for (int i = 0; i < argc; ++i) {
         argn[i] = const_cast<char*>(NullableStringGet(mNames[i]));
         argv[i] = const_cast<char*>(NullableStringGet(mValues[i]));
     }
 
     NPP npp = GetNPP();
 
     NPError rv = mPluginIface->newp((char*)NullableStringGet(mMimeType), npp,
-                                    mMode, argc, argn.get(), argv.get(), 0);
+                                    NP_EMBED, argc, argn.get(), argv.get(), 0);
     if (NPERR_NO_ERROR != rv) {
         return rv;
     }
 
-    Initialize();
-
-#if defined(XP_MACOSX) && defined(__i386__)
-    // If an i386 Mac OS X plugin has selected the Carbon event model then
-    // we have to fail. We do not support putting Carbon event model plugins
-    // out of process. Note that Carbon is the default model so out of process
-    // plugins need to actively negotiate something else in order to work
-    // out of process.
-    if (EventModel() == NPEventModelCarbon) {
-      // Send notification that a plugin tried to negotiate Carbon NPAPI so that
-      // users can be notified that restarting the browser in i386 mode may allow
-      // them to use the plugin.
-      SendNegotiatedCarbon();
-
-      // Fail to instantiate.
-      rv = NPERR_MODULE_LOAD_FAILED_ERROR;
+    if (!Initialize()) {
+        rv = NPERR_MODULE_LOAD_FAILED_ERROR;
     }
-#endif
-
     return rv;
 }
 
 int
 PluginInstanceChild::GetQuirks()
 {
     return PluginModuleChild::GetChrome()->GetQuirks();
 }
@@ -384,22 +362,24 @@ PluginInstanceChild::NPN_GetValue(NPNVar
 #if defined(MOZ_X11)
     case NPNVToolkit:
         *((NPNToolkitType*)aValue) = NPNVGtk2;
         return NPERR_NO_ERROR;
 
     case NPNVxDisplay:
         if (!mWsInfo.display) {
             // We are called before Initialize() so we have to call it now.
-           Initialize();
+           if (!Initialize()) {
+               return NPERR_GENERIC_ERROR;
+           }
            NS_ASSERTION(mWsInfo.display, "We should have a valid display!");
         }
         *(void **)aValue = mWsInfo.display;
         return NPERR_NO_ERROR;
-    
+
 #elif defined(OS_WIN)
     case NPNVToolkit:
         return NPERR_GENERIC_ERROR;
 #endif
     case NPNVprivateModeBool: {
         bool v = false;
         NPError result;
         if (!CallNPN_GetValue_NPNVprivateModeBool(&v, &result)) {
@@ -590,34 +570,24 @@ PluginInstanceChild::NPN_SetValue(NPPVar
 
     AutoStackHelper guard(this);
 
     switch (aVar) {
     case NPPVpluginWindowBool: {
         NPError rv;
         bool windowed = (NPBool) (intptr_t) aValue;
 
+        if (windowed) {
+            return NPERR_GENERIC_ERROR;
+        }
+
         if (!CallNPN_SetValue_NPPVpluginWindow(windowed, &rv))
             return NPERR_GENERIC_ERROR;
 
-        NPWindowType newWindowType = windowed ? NPWindowTypeWindow : NPWindowTypeDrawable;
-#ifdef MOZ_WIDGET_GTK
-        if (mWindow.type != newWindowType && mWsInfo.display) {
-           // plugin type has been changed but we already have a valid display
-           // so update it for the recent plugin mode
-           if (mXEmbed || !windowed) {
-               // Use default GTK display for XEmbed and windowless plugins
-               mWsInfo.display = DefaultXDisplay();
-           }
-           else {
-               mWsInfo.display = xt_client_get_display();
-           }
-        }
-#endif
-        mWindow.type = newWindowType;
+        mWindow.type = NPWindowTypeDrawable;
         return rv;
     }
 
     case NPPVpluginTransparentBool: {
         NPError rv;
         mIsTransparent = (!!aValue);
 
         if (!CallNPN_SetValue_NPPVpluginTransparent(mIsTransparent, &rv))
@@ -721,50 +691,16 @@ PluginInstanceChild::AnswerNPP_GetValue_
         *rv = mPluginIface->getvalue(GetNPP(), NPPVpluginWantsAllNetworkStreams,
                                      &value);
     }
     *wantsAllStreams = value;
     return IPC_OK();
 }
 
 mozilla::ipc::IPCResult
-PluginInstanceChild::AnswerNPP_GetValue_NPPVpluginNeedsXEmbed(
-    bool* needs, NPError* rv)
-{
-    AssertPluginThread();
-    AutoStackHelper guard(this);
-
-#ifdef MOZ_X11
-    // The documentation on the types for many variables in NP(N|P)_GetValue
-    // is vague.  Often boolean values are NPBool (1 byte), but
-    // https://developer.mozilla.org/en/XEmbed_Extension_for_Mozilla_Plugins
-    // treats NPPVpluginNeedsXEmbed as PRBool (int), and
-    // on x86/32-bit, flash stores to this using |movl 0x1,&needsXEmbed|.
-    // thus we can't use NPBool for needsXEmbed, or the three bytes above
-    // it on the stack would get clobbered. so protect with the larger bool.
-    int needsXEmbed = 0;
-    if (!mPluginIface->getvalue) {
-        *rv = NPERR_GENERIC_ERROR;
-    }
-    else {
-        *rv = mPluginIface->getvalue(GetNPP(), NPPVpluginNeedsXEmbed,
-                                     &needsXEmbed);
-    }
-    *needs = needsXEmbed;
-    return IPC_OK();
-
-#else
-
-    NS_RUNTIMEABORT("shouldn't be called on non-X11 platforms");
-    return IPC_FAIL_NO_REASON(this);               // not reached
-
-#endif
-}
-
-mozilla::ipc::IPCResult
 PluginInstanceChild::AnswerNPP_GetValue_NPPVpluginScriptableNPObject(
                                           PPluginScriptableObjectChild** aValue,
                                           NPError* aResult)
 {
     AssertPluginThread();
     AutoStackHelper guard(this);
 
     NPObject* object = nullptr;
@@ -1176,68 +1112,16 @@ PluginInstanceChild::RecvContentsScaleFa
 #endif
     return IPC_OK();
 #else
     NS_RUNTIMEABORT("ContentsScaleFactorChanged is an Windows or OSX only message");
     return IPC_FAIL_NO_REASON(this);
 #endif
 }
 
-#if defined(MOZ_X11) && defined(XP_UNIX) && !defined(XP_MACOSX)
-// Create a new window from NPWindow
-bool PluginInstanceChild::CreateWindow(const NPRemoteWindow& aWindow)
-{ 
-    PLUGIN_LOG_DEBUG(("%s (aWindow=<window: 0x%" PRIx64 ", x: %d, y: %d, width: %d, height: %d>)",
-                      FULLFUNCTION,
-                      aWindow.window,
-                      aWindow.x, aWindow.y,
-                      aWindow.width, aWindow.height));
-
-#ifdef MOZ_WIDGET_GTK
-    if (mXEmbed) {
-        mWindow.window = reinterpret_cast<void*>(aWindow.window);
-    }
-    else {
-        Window browserSocket = (Window)(aWindow.window);
-        xt_client_init(&mXtClient, mWsInfo.visual, mWsInfo.colormap, mWsInfo.depth);
-        xt_client_create(&mXtClient, browserSocket, mWindow.width, mWindow.height); 
-        mWindow.window = (void *)XtWindow(mXtClient.child_widget);
-    }  
-#else
-    mWindow.window = reinterpret_cast<void*>(aWindow.window);
-#endif
-
-    return true;
-}
-
-// Destroy window
-void PluginInstanceChild::DeleteWindow()
-{
-  PLUGIN_LOG_DEBUG(("%s (aWindow=<window: 0x%p, x: %d, y: %d, width: %d, height: %d>)",
-                    FULLFUNCTION,
-                    mWindow.window,
-                    mWindow.x, mWindow.y,
-                    mWindow.width, mWindow.height));
-
-  if (!mWindow.window)
-      return;
-
-#ifdef MOZ_WIDGET_GTK
-  if (mXtClient.top_widget) {     
-      xt_client_unrealize(&mXtClient);
-      xt_client_destroy(&mXtClient); 
-      mXtClient.top_widget = nullptr;
-  }
-#endif
-
-  // We don't have to keep the plug-in window ID any longer.
-  mWindow.window = nullptr;
-}
-#endif
-
 mozilla::ipc::IPCResult
 PluginInstanceChild::AnswerCreateChildPluginWindow(NativeWindowHandle* aChildPluginWindow)
 {
 #if defined(XP_WIN)
     MOZ_ASSERT(!mPluginWindowHWND);
 
     if (!CreatePluginWindow()) {
         return IPC_FAIL_NO_REASON(this);
@@ -1293,55 +1177,16 @@ PluginInstanceChild::AnswerNPP_SetWindow
     mWindow.type = aWindow.type;
 
     mWsInfo.colormap = aWindow.colormap;
     int depth;
     FindVisualAndDepth(mWsInfo.display, aWindow.visualID,
                        &mWsInfo.visual, &depth);
     mWsInfo.depth = depth;
 
-    if (!mWindow.window && mWindow.type == NPWindowTypeWindow) {
-        CreateWindow(aWindow);
-    }
-
-#ifdef MOZ_WIDGET_GTK
-    if (mXEmbed && gtk_check_version(2,18,7) != nullptr) { // older
-        if (aWindow.type == NPWindowTypeWindow) {
-            GdkWindow* socket_window = gdk_window_lookup(static_cast<GdkNativeWindow>(aWindow.window));
-            if (socket_window) {
-                // A GdkWindow for the socket already exists.  Need to
-                // workaround https://bugzilla.gnome.org/show_bug.cgi?id=607061
-                // See wrap_gtk_plug_embedded in PluginModuleChild.cpp.
-                g_object_set_data(G_OBJECT(socket_window),
-                                  "moz-existed-before-set-window",
-                                  GUINT_TO_POINTER(1));
-            }
-        }
-
-        if (aWindow.visualID != X11None
-            && gtk_check_version(2, 12, 10) != nullptr) { // older
-            // Workaround for a bug in Gtk+ (prior to 2.12.10) where deleting
-            // a foreign GdkColormap will also free the XColormap.
-            // http://git.gnome.org/browse/gtk+/log/gdk/x11/gdkcolor-x11.c?id=GTK_2_12_10
-            GdkVisual *gdkvisual = gdkx_visual_get(aWindow.visualID);
-            GdkColormap *gdkcolor =
-                gdk_x11_colormap_foreign_new(gdkvisual, aWindow.colormap);
-
-            if (g_object_get_data(G_OBJECT(gdkcolor), "moz-have-extra-ref")) {
-                // We already have a ref to keep the object alive.
-                g_object_unref(gdkcolor);
-            } else {
-                // leak and mark as already leaked
-                g_object_set_data(G_OBJECT(gdkcolor),
-                                  "moz-have-extra-ref", GUINT_TO_POINTER(1));
-            }
-        }
-    }
-#endif
-
     PLUGIN_LOG_DEBUG(
         ("[InstanceChild][%p] Answer_SetWindow w=<x=%d,y=%d, w=%d,h=%d>, clip=<l=%d,t=%d,r=%d,b=%d>",
          this, mWindow.x, mWindow.y, mWindow.width, mWindow.height,
          mWindow.clipRect.left, mWindow.clipRect.top, mWindow.clipRect.right, mWindow.clipRect.bottom));
 
     if (mPluginIface->setwindow)
         (void) mPluginIface->setwindow(&mData, &mWindow);
 
@@ -1421,41 +1266,39 @@ PluginInstanceChild::AnswerNPP_SetWindow
 
     return IPC_OK();
 }
 
 bool
 PluginInstanceChild::Initialize()
 {
 #ifdef MOZ_WIDGET_GTK
-    NPError rv;
-
     if (mWsInfo.display) {
         // Already initialized
-        return false;
+        return true;
     }
 
     // Request for windowless plugins is set in newp(), before this call.
     if (mWindow.type == NPWindowTypeWindow) {
-        AnswerNPP_GetValue_NPPVpluginNeedsXEmbed(&mXEmbed, &rv);
-
-        // Set up Xt loop for windowed plugins without XEmbed support
-        if (!mXEmbed) {
-           xt_client_xloop_create();
-        }
+        return false;
     }
 
-    // Use default GTK display for XEmbed and windowless plugins
-    if (mXEmbed || mWindow.type != NPWindowTypeWindow) {
-        mWsInfo.display = DefaultXDisplay();
+    mWsInfo.display = DefaultXDisplay();
+#endif
+
+#if defined(XP_MACOSX) && defined(__i386__)
+    // If an i386 Mac OS X plugin has selected the Carbon event model then
+    // we have to fail. We do not support putting Carbon event model plugins
+    // out of process. Note that Carbon is the default model so out of process
+    // plugins need to actively negotiate something else in order to work
+    // out of process.
+    if (EventModel() == NPEventModelCarbon) {
+        return false;
     }
-    else {
-        mWsInfo.display = xt_client_get_display();
-    }
-#endif 
+#endif
 
     return true;
 }
 
 mozilla::ipc::IPCResult
 PluginInstanceChild::RecvHandledWindowedPluginKeyEvent(
                        const NativeEventData& aKeyEventData,
                        const bool& aIsConsumed)
@@ -4502,25 +4345,16 @@ PluginInstanceChild::Destroy()
 #endif
 
     // Pending async calls are discarded, not delivered. This matches the
     // in-process behavior.
     for (uint32_t i = 0; i < mPendingAsyncCalls.Length(); ++i)
         mPendingAsyncCalls[i]->Cancel();
 
     mPendingAsyncCalls.Clear();
-    
-#ifdef MOZ_WIDGET_GTK
-    if (mWindow.type == NPWindowTypeWindow && !mXEmbed) {
-      xt_client_xloop_destroy();
-    }
-#endif
-#if defined(MOZ_X11) && defined(XP_UNIX) && !defined(XP_MACOSX)
-    DeleteWindow();
-#endif
 }
 
 mozilla::ipc::IPCResult
 PluginInstanceChild::AnswerNPP_Destroy(NPError* aResult)
 {
     PLUGIN_LOG_DEBUG_METHOD;
     AssertPluginThread();
     *aResult = NPERR_NO_ERROR;
--- a/dom/plugins/ipc/PluginInstanceChild.h
+++ b/dom/plugins/ipc/PluginInstanceChild.h
@@ -74,18 +74,16 @@ protected:
     RecvCreateChildPopupSurrogate(const NativeWindowHandle& aNetscapeWindow) override;
 
     virtual mozilla::ipc::IPCResult
     AnswerNPP_SetWindow(const NPRemoteWindow& window) override;
 
     virtual mozilla::ipc::IPCResult
     AnswerNPP_GetValue_NPPVpluginWantsAllNetworkStreams(bool* wantsAllStreams, NPError* rv) override;
     virtual mozilla::ipc::IPCResult
-    AnswerNPP_GetValue_NPPVpluginNeedsXEmbed(bool* needs, NPError* rv) override;
-    virtual mozilla::ipc::IPCResult
     AnswerNPP_GetValue_NPPVpluginScriptableNPObject(PPluginScriptableObjectChild** value,
                                                     NPError* result) override;
     virtual mozilla::ipc::IPCResult
     AnswerNPP_GetValue_NPPVpluginNativeAccessibleAtkPlugId(nsCString* aPlugId,
                                                            NPError* aResult) override;
     virtual mozilla::ipc::IPCResult
     AnswerNPP_SetValue_NPNVprivateModeBool(const bool& value, NPError* result) override;
     virtual mozilla::ipc::IPCResult
@@ -204,25 +202,19 @@ protected:
     AnswerSetPluginFocus() override;
 
     virtual mozilla::ipc::IPCResult
     AnswerUpdateWindow() override;
 
     virtual mozilla::ipc::IPCResult
     RecvNPP_DidComposite() override;
 
-#if defined(MOZ_X11) && defined(XP_UNIX) && !defined(XP_MACOSX)
-    bool CreateWindow(const NPRemoteWindow& aWindow);
-    void DeleteWindow();
-#endif
-
 public:
     PluginInstanceChild(const NPPluginFuncs* aPluginIface,
                         const nsCString& aMimeType,
-                        const uint16_t& aMode,
                         const InfallibleTArray<nsCString>& aNames,
                         const InfallibleTArray<nsCString>& aValues);
 
     virtual ~PluginInstanceChild();
 
     NPError DoNPP_New();
 
     // Common sync+async implementation of NPP_NewStream
@@ -402,17 +394,16 @@ private:
         bool                 mWindowed;
     };
 
     bool ShouldPostKeyMessage(UINT message, WPARAM wParam, LPARAM lParam);
     bool MaybePostKeyMessage(UINT message, WPARAM wParam, LPARAM lParam);
 #endif // #if defined(OS_WIN)
     const NPPluginFuncs* mPluginIface;
     nsCString                   mMimeType;
-    uint16_t                    mMode;
     InfallibleTArray<nsCString> mNames;
     InfallibleTArray<nsCString> mValues;
     NPP_t mData;
     NPWindow mWindow;
 #if defined(XP_DARWIN) || defined(XP_WIN)
     double mContentsScaleFactor;
 #endif
     double mCSSZoomFactor;
@@ -452,17 +443,16 @@ private:
 
     // Cached scriptable actors to avoid IPC churn
     PluginScriptableObjectChild* mCachedWindowActor;
     PluginScriptableObjectChild* mCachedElementActor;
 
 #if defined(MOZ_X11) && defined(XP_UNIX) && !defined(XP_MACOSX)
     NPSetWindowCallbackStruct mWsInfo;
 #ifdef MOZ_WIDGET_GTK
-    bool mXEmbed;
     XtClient mXtClient;
 #endif
 #elif defined(OS_WIN)
     HWND mPluginWindowHWND;
     WNDPROC mPluginWndProc;
     HWND mPluginParentHWND;
     int mNestedEventLevelDepth;
     HWND mCachedWinlessPluginHWND;
--- a/dom/plugins/ipc/PluginInstanceParent.cpp
+++ b/dom/plugins/ipc/PluginInstanceParent.cpp
@@ -1435,34 +1435,16 @@ PluginInstanceParent::NPP_GetValue(NPPVa
         if (NPERR_NO_ERROR != rv) {
             return rv;
         }
 
         (*(NPBool*)_retval) = wantsAllStreams;
         return NPERR_NO_ERROR;
     }
 
-#ifdef MOZ_X11
-    case NPPVpluginNeedsXEmbed: {
-        bool needsXEmbed;
-        NPError rv;
-
-        if (!CallNPP_GetValue_NPPVpluginNeedsXEmbed(&needsXEmbed, &rv)) {
-            return NPERR_GENERIC_ERROR;
-        }
-
-        if (NPERR_NO_ERROR != rv) {
-            return rv;
-        }
-
-        (*(NPBool*)_retval) = needsXEmbed;
-        return NPERR_NO_ERROR;
-    }
-#endif
-
     case NPPVpluginScriptableNPObject: {
         PPluginScriptableObjectParent* actor;
         NPError rv;
         if (!CallNPP_GetValue_NPPVpluginScriptableNPObject(&actor, &rv)) {
             return NPERR_GENERIC_ERROR;
         }
 
         if (NPERR_NO_ERROR != rv) {
@@ -2081,27 +2063,16 @@ PluginInstanceParent::RecvRedrawPlugin()
     if (!inst) {
         return IPC_FAIL_NO_REASON(this);
     }
 
     inst->RedrawPlugin();
     return IPC_OK();
 }
 
-mozilla::ipc::IPCResult
-PluginInstanceParent::RecvNegotiatedCarbon()
-{
-    nsNPAPIPluginInstance *inst = static_cast<nsNPAPIPluginInstance*>(mNPP->ndata);
-    if (!inst) {
-        return IPC_FAIL_NO_REASON(this);
-    }
-    inst->CarbonNPAPIFailure();
-    return IPC_OK();
-}
-
 nsPluginInstanceOwner*
 PluginInstanceParent::GetOwner()
 {
     nsNPAPIPluginInstance* inst = static_cast<nsNPAPIPluginInstance*>(mNPP->ndata);
     if (!inst) {
         return nullptr;
     }
     return inst->GetOwner();
--- a/dom/plugins/ipc/PluginInstanceParent.h
+++ b/dom/plugins/ipc/PluginInstanceParent.h
@@ -247,19 +247,16 @@ public:
                            double *destX,
                            double *destY,
                            bool *result) override;
 
     virtual mozilla::ipc::IPCResult
     RecvRedrawPlugin() override;
 
     virtual mozilla::ipc::IPCResult
-    RecvNegotiatedCarbon() override;
-
-    virtual mozilla::ipc::IPCResult
     RecvAsyncNPP_NewResult(const NPError& aResult) override;
 
     virtual mozilla::ipc::IPCResult
     RecvSetNetscapeWindowAsParent(const NativeWindowHandle& childWindow) override;
 
     NPError NPP_SetWindow(const NPWindow* aWindow);
 
     NPError NPP_GetValue(NPPVariable variable, void* retval);
--- a/dom/plugins/ipc/PluginLibrary.h
+++ b/dom/plugins/ipc/PluginLibrary.h
@@ -65,17 +65,17 @@ public:
   virtual nsresult NP_Shutdown(NPError* error) = 0;
   virtual nsresult NP_GetMIMEDescription(const char** mimeDesc) = 0;
   virtual nsresult NP_GetValue(void *future, NPPVariable aVariable,
                                void *aValue, NPError* error) = 0;
 #if defined(XP_WIN) || defined(XP_MACOSX)
   virtual nsresult NP_GetEntryPoints(NPPluginFuncs* pFuncs, NPError* error) = 0;
 #endif
   virtual nsresult NPP_New(NPMIMEType pluginType, NPP instance,
-                           uint16_t mode, int16_t argc, char* argn[],
+                           int16_t argc, char* argn[],
                            char* argv[], NPSavedData* saved,
                            NPError* error) = 0;
 
   virtual nsresult NPP_ClearSiteData(const char* site, uint64_t flags,
                                      uint64_t maxAge, nsCOMPtr<nsIClearSiteDataCallback> callback) = 0;
   virtual nsresult NPP_GetSitesWithData(nsCOMPtr<nsIGetSitesWithDataCallback> callback) = 0;
 
   virtual nsresult AsyncSetWindow(NPP instance, NPWindow* window) = 0;
--- a/dom/plugins/ipc/PluginModuleChild.cpp
+++ b/dom/plugins/ipc/PluginModuleChild.cpp
@@ -1100,29 +1100,30 @@ NPError
             return NPERR_NO_ERROR;
         case NPNVasdEnabledBool:
             *(NPBool*)aValue = PluginModuleChild::GetChrome()->Settings().asdEnabled();
             return NPERR_NO_ERROR;
         case NPNVisOfflineBool:
             *(NPBool*)aValue = PluginModuleChild::GetChrome()->Settings().isOffline();
             return NPERR_NO_ERROR;
         case NPNVSupportsXEmbedBool:
-            *(NPBool*)aValue = PluginModuleChild::GetChrome()->Settings().supportsXembed();
+            // We don't support windowed xembed any more. But we still deliver
+            // events based on X/GTK, not Xt, so we continue to return true
+            // (and Flash requires that we return true).
+            *(NPBool*)aValue = true;
             return NPERR_NO_ERROR;
         case NPNVSupportsWindowless:
-            *(NPBool*)aValue = PluginModuleChild::GetChrome()->Settings().supportsWindowless();
+            *(NPBool*)aValue = true;
             return NPERR_NO_ERROR;
 #if defined(MOZ_WIDGET_GTK)
         case NPNVxDisplay: {
-            if (aNPP) {
-                return InstCast(aNPP)->NPN_GetValue(aVariable, aValue);
+            if (!aNPP) {
+                return NPERR_INVALID_INSTANCE_ERROR;
             }
-            *(void
-              **)aValue = xt_client_get_display();
-            return NPERR_NO_ERROR;
+            return InstCast(aNPP)->NPN_GetValue(aVariable, aValue);
         }
         case NPNVxtAppContext:
             return NPERR_GENERIC_ERROR;
 #endif
         default: {
             if (aNPP) {
                 return InstCast(aNPP)->NPN_GetValue(aVariable, aValue);
             }
@@ -2239,17 +2240,16 @@ BOOL WINAPI
 PMCGetOpenFileNameW(LPOPENFILENAMEW aLpofn)
 {
     return PMCGetFileNameW(OPEN_FUNC, aLpofn);
 }
 #endif
 
 PPluginInstanceChild*
 PluginModuleChild::AllocPPluginInstanceChild(const nsCString& aMimeType,
-                                             const uint16_t& aMode,
                                              const InfallibleTArray<nsCString>& aNames,
                                              const InfallibleTArray<nsCString>& aValues)
 {
     PLUGIN_LOG_DEBUG_METHOD;
     AssertPluginThread();
 
     // In e10s, gChromeInstance hands out quirks to instances, but never
     // allocates an instance on its own. Make sure it gets the latest copy
@@ -2280,17 +2280,17 @@ PluginModuleChild::AllocPPluginInstanceC
     }
 
     if (!sGetOpenFileNameWPtrStub) {
         sComDlg32Intercept.AddHook("GetOpenFileNameW", reinterpret_cast<intptr_t>(PMCGetOpenFileNameW),
                                  (void**) &sGetOpenFileNameWPtrStub);
     }
 #endif
 
-    return new PluginInstanceChild(&mFunctions, aMimeType, aMode, aNames,
+    return new PluginInstanceChild(&mFunctions, aMimeType, aNames,
                                    aValues);
 }
 
 void
 PluginModuleChild::InitQuirksModes(const nsCString& aMimeType)
 {
     if (mQuirks != QUIRKS_NOT_INITIALIZED) {
       return;
@@ -2309,17 +2309,16 @@ PluginModuleChild::AnswerModuleSupportsA
     NS_NOTREACHED("Shouldn't get here!");
     return IPC_FAIL_NO_REASON(this);
 #endif
 }
 
 mozilla::ipc::IPCResult
 PluginModuleChild::RecvPPluginInstanceConstructor(PPluginInstanceChild* aActor,
                                                   const nsCString& aMimeType,
-                                                  const uint16_t& aMode,
                                                   InfallibleTArray<nsCString>&& aNames,
                                                   InfallibleTArray<nsCString>&& aValues)
 {
     PLUGIN_LOG_DEBUG_METHOD;
     AssertPluginThread();
 
     NS_ASSERTION(aActor, "Null actor!");
     return IPC_OK();
--- a/dom/plugins/ipc/PluginModuleChild.h
+++ b/dom/plugins/ipc/PluginModuleChild.h
@@ -73,28 +73,26 @@ protected:
                                    override;
     virtual mozilla::ipc::IPCResult RecvAsyncNPP_New(PPluginInstanceChild* aActor) override;
 
     virtual mozilla::ipc::IPCResult
     RecvInitPluginModuleChild(Endpoint<PPluginModuleChild>&& endpoint) override;
 
     virtual PPluginInstanceChild*
     AllocPPluginInstanceChild(const nsCString& aMimeType,
-                              const uint16_t& aMode,
                               const InfallibleTArray<nsCString>& aNames,
                               const InfallibleTArray<nsCString>& aValues)
                               override;
 
     virtual bool
     DeallocPPluginInstanceChild(PPluginInstanceChild* aActor) override;
 
     virtual mozilla::ipc::IPCResult
     RecvPPluginInstanceConstructor(PPluginInstanceChild* aActor,
                                    const nsCString& aMimeType,
-                                   const uint16_t& aMode,
                                    InfallibleTArray<nsCString>&& aNames,
                                    InfallibleTArray<nsCString>&& aValues)
                                    override;
     virtual mozilla::ipc::IPCResult
     AnswerNP_Shutdown(NPError *rv) override;
 
     virtual mozilla::ipc::IPCResult
     AnswerOptionalFunctionsSupported(bool *aURLRedirectNotify,
--- a/dom/plugins/ipc/PluginModuleParent.cpp
+++ b/dom/plugins/ipc/PluginModuleParent.cpp
@@ -1681,17 +1681,16 @@ PluginModuleParent::NotifyPluginCrashed(
         dumpID = mCrashReporter->MinidumpID();
     }
 #endif
     mPlugin->PluginCrashed(dumpID, browserDumpID);
 }
 
 PPluginInstanceParent*
 PluginModuleParent::AllocPPluginInstanceParent(const nsCString& aMimeType,
-                                               const uint16_t& aMode,
                                                const InfallibleTArray<nsCString>& aNames,
                                                const InfallibleTArray<nsCString>& aValues)
 {
     NS_ERROR("Not reachable!");
     return nullptr;
 }
 
 bool
@@ -2628,29 +2627,29 @@ PluginModuleChromeParent::NP_GetEntryPoi
 
     return PluginModuleParent::NP_GetEntryPoints(pFuncs, error);
 }
 
 #endif
 
 nsresult
 PluginModuleParent::NPP_New(NPMIMEType pluginType, NPP instance,
-                            uint16_t mode, int16_t argc, char* argn[],
+                            int16_t argc, char* argn[],
                             char* argv[], NPSavedData* saved,
                             NPError* error)
 {
     PLUGIN_LOG_DEBUG_METHOD;
 
     if (mShutdown) {
         *error = NPERR_GENERIC_ERROR;
         return NS_ERROR_FAILURE;
     }
 
     if (mIsStartingAsync) {
-        if (!PluginAsyncSurrogate::Create(this, pluginType, instance, mode,
+        if (!PluginAsyncSurrogate::Create(this, pluginType, instance,
                                           argc, argn, argv)) {
             *error = NPERR_GENERIC_ERROR;
             return NS_ERROR_FAILURE;
         }
 
         if (!mNPInitialized) {
             RefPtr<PluginAsyncSurrogate> surrogate =
                 PluginAsyncSurrogate::Cast(instance);
@@ -2664,17 +2663,17 @@ PluginModuleParent::NPP_New(NPMIMEType p
     InfallibleTArray<nsCString> names;
     InfallibleTArray<nsCString> values;
 
     for (int i = 0; i < argc; ++i) {
         names.AppendElement(NullableString(argn[i]));
         values.AppendElement(NullableString(argv[i]));
     }
 
-    nsresult rv = NPP_NewInternal(pluginType, instance, mode, names, values,
+    nsresult rv = NPP_NewInternal(pluginType, instance, names, values,
                                   saved, error);
     if (NS_FAILED(rv) || !mIsStartingAsync) {
         return rv;
     }
     return NS_PLUGIN_INIT_PENDING;
 }
 
 class nsCaseInsensitiveUTF8StringArrayComparator
@@ -2736,17 +2735,16 @@ ForceDirect(InfallibleTArray<nsCString>&
         names.AppendElement(wmodeAttributeName);
         values.AppendElement(directAttributeValue);
     }
 }
 #endif // windows
 
 nsresult
 PluginModuleParent::NPP_NewInternal(NPMIMEType pluginType, NPP instance,
-                                    uint16_t mode,
                                     InfallibleTArray<nsCString>& names,
                                     InfallibleTArray<nsCString>& values,
                                     NPSavedData* saved, NPError* error)
 {
     MOZ_ASSERT(names.Length() == values.Length());
     if (mPluginName.IsEmpty()) {
         GetPluginDetails();
         InitQuirksModes(nsDependentCString(pluginType));
@@ -2823,17 +2821,17 @@ PluginModuleParent::NPP_NewInternal(NPMI
         nsCOMPtr<nsIDocument> doc = node->OwnerDoc();
         if (doc) {
             nsCOMPtr<nsIEventTarget> eventTarget = doc->EventTargetFor(TaskCategory::Other);
             SetEventTargetForActor(parentInstance, eventTarget);
         }
     }
 
     if (!SendPPluginInstanceConstructor(parentInstance,
-                                        nsDependentCString(pluginType), mode,
+                                        nsDependentCString(pluginType),
                                         names, values)) {
         // |parentInstance| is automatically deleted.
         instance->pdata = nullptr;
         *error = NPERR_GENERIC_ERROR;
         return NS_ERROR_FAILURE;
     }
 
     {   // Scope for timer
--- a/dom/plugins/ipc/PluginModuleParent.h
+++ b/dom/plugins/ipc/PluginModuleParent.h
@@ -81,17 +81,16 @@ class PluginModuleParent
     , public CrashReporter::InjectorCrashCallback
 #endif
 {
 protected:
     typedef mozilla::PluginLibrary PluginLibrary;
 
     PPluginInstanceParent*
     AllocPPluginInstanceParent(const nsCString& aMimeType,
-                               const uint16_t& aMode,
                                const InfallibleTArray<nsCString>& aNames,
                                const InfallibleTArray<nsCString>& aValues)
                                override;
 
     virtual bool
     DeallocPPluginInstanceParent(PPluginInstanceParent* aActor) override;
 
 public:
@@ -215,17 +214,17 @@ protected:
     virtual mozilla::ipc::IPCResult RecvReturnClearSiteData(const NPError& aRv,
                                                             const uint64_t& aCallbackId) override;
 
     virtual mozilla::ipc::IPCResult RecvReturnSitesWithData(nsTArray<nsCString>&& aSites,
                                                             const uint64_t& aCallbackId) override;
 
     void SetPluginFuncs(NPPluginFuncs* aFuncs);
 
-    nsresult NPP_NewInternal(NPMIMEType pluginType, NPP instance, uint16_t mode,
+    nsresult NPP_NewInternal(NPMIMEType pluginType, NPP instance,
                              InfallibleTArray<nsCString>& names,
                              InfallibleTArray<nsCString>& values,
                              NPSavedData* saved, NPError* error);
 
     // NPP-like API that Gecko calls are trampolined into.  These 
     // messages then get forwarded along to the plugin instance,
     // and then eventually the child process.
 
@@ -283,17 +282,17 @@ protected:
 
     virtual nsresult NP_GetMIMEDescription(const char** mimeDesc) override;
     virtual nsresult NP_GetValue(void *future, NPPVariable aVariable,
                                  void *aValue, NPError* error) override;
 #if defined(XP_WIN) || defined(XP_MACOSX)
     virtual nsresult NP_GetEntryPoints(NPPluginFuncs* pFuncs, NPError* error) override;
 #endif
     virtual nsresult NPP_New(NPMIMEType pluginType, NPP instance,
-                             uint16_t mode, int16_t argc, char* argn[],
+                             int16_t argc, char* argn[],
                              char* argv[], NPSavedData* saved,
                              NPError* error) override;
     virtual nsresult NPP_ClearSiteData(const char* site, uint64_t flags, uint64_t maxAge,
                                        nsCOMPtr<nsIClearSiteDataCallback> callback) override;
     virtual nsresult NPP_GetSitesWithData(nsCOMPtr<nsIGetSitesWithDataCallback> callback) override;
 
 private:
     std::map<uint64_t, nsCOMPtr<nsIClearSiteDataCallback>> mClearSiteDataCallbacks;
--- a/dom/plugins/ipc/PluginWidgetChild.cpp
+++ b/dom/plugins/ipc/PluginWidgetChild.cpp
@@ -7,19 +7,17 @@
 #include "mozilla/dom/TabChild.h"
 #include "mozilla/plugins/PluginWidgetParent.h"
 #include "PluginWidgetProxy.h"
 
 #include "mozilla/Unused.h"
 #include "mozilla/DebugOnly.h"
 #include "nsDebug.h"
 
-#if defined(XP_WIN)
 #include "mozilla/plugins/PluginInstanceParent.h"
-#endif
 
 #define PWLOG(...)
 //#define PWLOG(...) printf_stderr(__VA_ARGS__)
 
 namespace mozilla {
 namespace plugins {
 
 PluginWidgetChild::PluginWidgetChild() :
--- a/dom/plugins/ipc/PluginWidgetChild.h
+++ b/dom/plugins/ipc/PluginWidgetChild.h
@@ -1,15 +1,19 @@
 /* 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 mozilla_plugins_PluginWidgetChild_h
 #define mozilla_plugins_PluginWidgetChild_h
 
+#ifndef XP_WIN
+#error "This header should be Windows-only."
+#endif
+
 #include "mozilla/plugins/PPluginWidgetChild.h"
 
 namespace mozilla {
 namespace widget {
 class PluginWidgetProxy;
 } // namespace widget
 namespace plugins {
 
--- a/dom/plugins/ipc/PluginWidgetParent.cpp
+++ b/dom/plugins/ipc/PluginWidgetParent.cpp
@@ -7,34 +7,28 @@
 #include "mozilla/dom/ContentParent.h"
 #include "nsComponentManagerUtils.h"
 #include "nsWidgetsCID.h"
 
 #include "mozilla/Unused.h"
 #include "mozilla/DebugOnly.h"
 #include "nsDebug.h"
 
-#if defined(MOZ_WIDGET_GTK)
-#include "nsPluginNativeWindowGtk.h"
-#endif
-
 using namespace mozilla;
 using namespace mozilla::widget;
 
 #define PWLOG(...)
 //#define PWLOG(...) printf_stderr(__VA_ARGS__)
 
-#if defined(XP_WIN)
 namespace mozilla {
 namespace dom {
 // For nsWindow
 const wchar_t* kPluginWidgetContentParentProperty =
   L"kPluginWidgetParentProperty";
 } }
-#endif
 
 namespace mozilla {
 namespace plugins {
 
 static NS_DEFINE_CID(kWidgetCID, NS_CHILD_CID);
 
 // This macro returns IPC_OK() to prevent an abort in the child process when
 // ipc message delivery fails.
@@ -90,29 +84,16 @@ PluginWidgetParent::RecvCreate(nsresult*
   PWLOG("PluginWidgetParent::RecvCreate()\n");
 
   *aScrollCaptureId = 0;
   *aPluginInstanceId = 0;
 
   mWidget = do_CreateInstance(kWidgetCID, aResult);
   NS_ASSERTION(NS_SUCCEEDED(*aResult), "widget create failure");
 
-#if defined(MOZ_WIDGET_GTK)
-  // We need this currently just for GTK in setting up a socket widget
-  // we can send over to content -> plugin.
-  PLUG_NewPluginNativeWindow((nsPluginNativeWindow**)&mWrapper);
-  if (!mWrapper) {
-    KillWidget();
-    return IPC_FAIL_NO_REASON(this);
-  }
-  // Give a copy of this to the widget, which handles some update
-  // work for us.
-  mWidget->SetNativeData(NS_NATIVE_PLUGIN_OBJECT_PTR, (uintptr_t)mWrapper.get());
-#endif
-
   // This returns the top level window widget
   nsCOMPtr<nsIWidget> parentWidget = GetTabParent()->GetWidget();
   // If this fails, bail.
   if (!parentWidget) {
     *aResult = NS_ERROR_NOT_AVAILABLE;
     KillWidget();
     return IPC_OK();
   }
@@ -127,58 +108,34 @@ PluginWidgetParent::RecvCreate(nsresult*
   if (NS_FAILED(*aResult)) {
     KillWidget();
     // This should never fail, abort.
     return IPC_FAIL_NO_REASON(this);
   }
 
   mWidget->EnableDragDrop(true);
 
-#if defined(MOZ_WIDGET_GTK)
-  // For setup, initially GTK code expects 'window' to hold the parent.
-  mWrapper->window = mWidget->GetNativeData(NS_NATIVE_PLUGIN_PORT);
-  DebugOnly<nsresult> drv = mWrapper->CreateXEmbedWindow(false);
-  NS_ASSERTION(NS_SUCCEEDED(drv), "widget call failure");
-  mWrapper->SetAllocation();
-  PWLOG("Plugin XID=%p\n", (void*)mWrapper->window);
-#elif defined(XP_WIN)
-  DebugOnly<DWORD> winres =
-    ::SetPropW((HWND)mWidget->GetNativeData(NS_NATIVE_WINDOW),
-               mozilla::dom::kPluginWidgetContentParentProperty,
-               GetTabParent()->Manager()->AsContentParent());
-  NS_ASSERTION(winres, "SetPropW call failure");
-
-  *aScrollCaptureId = mWidget->CreateScrollCaptureContainer();
-  *aPluginInstanceId =
-    reinterpret_cast<uintptr_t>(mWidget->GetNativeData(NS_NATIVE_PLUGIN_ID));
-#endif
-
   // This is a special call we make to nsBaseWidget to register this
   // window as a remote plugin window which is expected to receive
   // visibility updates from the compositor, which ships this data
   // over with corresponding layer updates.
   mWidget->RegisterPluginWindowForRemoteUpdates();
 
   return IPC_OK();
 }
 
 void
 PluginWidgetParent::KillWidget()
 {
   PWLOG("PluginWidgetParent::KillWidget() widget=%p\n", (void*)mWidget.get());
   if (mWidget) {
     mWidget->UnregisterPluginWindowForRemoteUpdates();
     mWidget->Destroy();
-#if defined(MOZ_WIDGET_GTK)
-    mWidget->SetNativeData(NS_NATIVE_PLUGIN_OBJECT_PTR, (uintptr_t)0);
-    mWrapper = nullptr;
-#elif defined(XP_WIN)
     ::RemovePropW((HWND)mWidget->GetNativeData(NS_NATIVE_WINDOW),
                   mozilla::dom::kPluginWidgetContentParentProperty);
-#endif
     mWidget = nullptr;
   }
 }
 
 void
 PluginWidgetParent::ActorDestroy(ActorDestroyReason aWhy)
 {
   PWLOG("PluginWidgetParent::ActorDestroy(%d)\n", aWhy);
@@ -202,36 +159,26 @@ PluginWidgetParent::RecvSetFocus(const b
   mWidget->SetFocus(aRaise);
   return IPC_OK();
 }
 
 mozilla::ipc::IPCResult
 PluginWidgetParent::RecvGetNativePluginPort(uintptr_t* value)
 {
   ENSURE_CHANNEL;
-#if defined(MOZ_WIDGET_GTK)
-  *value = (uintptr_t)mWrapper->window;
-  NS_ASSERTION(*value, "no xid??");
-#else
   *value = (uintptr_t)mWidget->GetNativeData(NS_NATIVE_PLUGIN_PORT);
   NS_ASSERTION(*value, "no native port??");
-#endif
   PWLOG("PluginWidgetParent::RecvGetNativeData() %p\n", (void*)*value);
   return IPC_OK();
 }
 
 mozilla::ipc::IPCResult
 PluginWidgetParent::RecvSetNativeChildWindow(const uintptr_t& aChildWindow)
 {
-#if defined(XP_WIN)
   ENSURE_CHANNEL;
   PWLOG("PluginWidgetParent::RecvSetNativeChildWindow(%p)\n",
         (void*)aChildWindow);
   mWidget->SetNativeData(NS_NATIVE_CHILD_WINDOW, aChildWindow);
   return IPC_OK();
-#else
-  NS_NOTREACHED("PluginWidgetParent::RecvSetNativeChildWindow not implemented!");
-  return IPC_FAIL_NO_REASON(this);
-#endif
 }
 
 } // namespace plugins
 } // namespace mozilla
--- a/dom/plugins/ipc/PluginWidgetParent.h
+++ b/dom/plugins/ipc/PluginWidgetParent.h
@@ -1,24 +1,24 @@
 /* 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 mozilla_plugins_PluginWidgetParent_h
 #define mozilla_plugins_PluginWidgetParent_h
 
+#ifndef XP_WIN
+#error "This header should be Windows-only."
+#endif
+
 #include "mozilla/plugins/PPluginWidgetParent.h"
 #include "nsAutoPtr.h"
 #include "nsIWidget.h"
 #include "nsCOMPtr.h"
 
-#if defined(MOZ_WIDGET_GTK)
-class nsPluginNativeWindowGtk;
-#endif
-
 namespace mozilla {
 
 namespace dom {
 class TabParent;
 } // namespace dom
 
 namespace plugins {
 
@@ -48,18 +48,15 @@ private:
   // The tab our connection is associated with.
   mozilla::dom::TabParent* GetTabParent();
 
 private:
   void KillWidget();
 
   // The chrome side native widget.
   nsCOMPtr<nsIWidget> mWidget;
-#if defined(MOZ_WIDGET_GTK)
-  nsAutoPtr<nsPluginNativeWindowGtk> mWrapper;
-#endif
 };
 
 } // namespace plugins
 } // namespace mozilla
 
 #endif // mozilla_plugins_PluginWidgetParent_h
 
--- a/dom/plugins/ipc/moz.build
+++ b/dom/plugins/ipc/moz.build
@@ -34,18 +34,16 @@ EXPORTS.mozilla.plugins += [
     'PluginQuirks.h',
     'PluginScriptableObjectChild.h',
     'PluginScriptableObjectParent.h',
     'PluginScriptableObjectUtils-inl.h',
     'PluginScriptableObjectUtils.h',
     'PluginStreamChild.h',
     'PluginStreamParent.h',
     'PluginUtilsOSX.h',
-    'PluginWidgetChild.h',
-    'PluginWidgetParent.h',
     'StreamNotifyChild.h',
     'StreamNotifyParent.h',
 ]
 
 if CONFIG['OS_ARCH'] == 'WINNT':
     EXPORTS.mozilla.plugins += [
         'PluginSurfaceParent.h',
     ]
@@ -84,31 +82,37 @@ UNIFIED_SOURCES += [
     'PluginScriptableObjectParent.cpp',
     'PluginStreamChild.cpp',
     'PluginStreamParent.cpp',
 ]
 
 SOURCES += [
     'PluginInstanceChild.cpp', # 'PluginThreadCallback' : ambiguous symbol
     'PluginModuleChild.cpp',   # Redefinition of mozilla::WindowsDllInterceptor sUser32Intercept
-    'PluginWidgetChild.cpp',
-    'PluginWidgetParent.cpp',
 ]
 
 if CONFIG['MOZ_WIDGET_TOOLKIT'] == 'cocoa':
     UNIFIED_SOURCES += [
         'PluginInterposeOSX.mm',
         'PluginUtilsOSX.mm',
     ]
 
 if CONFIG['MOZ_WIDGET_TOOLKIT'] == 'windows':
+    EXPORTS.mozilla.plugins += [
+        'PluginWidgetChild.h',
+        'PluginWidgetParent.h',
+    ]
     UNIFIED_SOURCES += [
         'D3D11SurfaceHolder.cpp',
         'PluginUtilsWin.cpp'
     ]
+    SOURCES += [
+        'PluginWidgetChild.cpp',
+        'PluginWidgetParent.cpp',
+    ]
 
 IPDL_SOURCES += [
     'PBrowserStream.ipdl',
     'PluginTypes.ipdlh',
     'PPluginBackgroundDestroyer.ipdl',
     'PPluginInstance.ipdl',
     'PPluginModule.ipdl',
     'PPluginScriptableObject.ipdl',
--- a/dom/plugins/test/mochitest/test_wmode.xul
+++ b/dom/plugins/test/mochitest/test_wmode.xul
@@ -16,23 +16,23 @@
 </body>
 <script class="testbody" type="application/javascript">
 <![CDATA[
 SimpleTest.waitForExplicitFinish();
 
 function runTests() {
   var p1 = document.getElementById("plugin1");
   is(p1.hasWidget(), false, "Plugin should be windowless by default");
-  
+
   var p2 = document.getElementById("plugin2");
   if (navigator.platform.indexOf("Mac") >= 0) {
     is(p2.hasWidget(), false, "Mac does not support windowed plugins");
   } else if (navigator.platform.indexOf("Win") >= 0) {
     is(p2.hasWidget(), true, "Windows supports windowed plugins");
   } else if (navigator.platform.indexOf("Linux") >= 0) {
-    is(p2.hasWidget(), true, "Linux supports windowed plugins");
+    is(p2.hasWidget(), false, "Linux does not support windowed plugins");
   }
 
   SimpleTest.finish();
 }
 ]]>
 </script>
 </window>
--- a/dom/plugins/test/testplugin/nptest.cpp
+++ b/dom/plugins/test/testplugin/nptest.cpp
@@ -871,22 +871,16 @@ NPP_New(NPMIMEType pluginType, NPP insta
   }
   scriptableObject->npp = instance;
   scriptableObject->drawMode = DM_DEFAULT;
   scriptableObject->drawColor = 0;
   instanceData->scriptableObject = scriptableObject;
 
   instanceData->instanceCountWatchGeneration = sCurrentInstanceCountWatchGeneration;
 
-  if (NP_FULL == mode) {
-    instanceData->streamMode = NP_SEEK;
-    instanceData->frame = "testframe";
-    addRange(instanceData, "100,100");
-  }
-
   AsyncDrawing requestAsyncDrawing = AD_NONE;
 
   bool requestWindow = false;
   bool alreadyHasSalign = false;
   // handle extra params
   for (int i = 0; i < argc; i++) {
     if (strcmp(argn[i], "drawmode") == 0) {
       if (strcmp(argv[i], "solid") == 0)
@@ -1010,17 +1004,26 @@ NPP_New(NPMIMEType pluginType, NPP insta
       if (alreadyHasSalign) {
         // If salign came before this parameter, error out now.
         return NPERR_GENERIC_ERROR;
       }
     }
     if (strcmp(argn[i], "salign") == 0) {
       alreadyHasSalign = true;
     }
-}
+
+    // We don't support NP_FULL any more, but name="plugin" is an indication
+    // that we're a full-page plugin. We use default seek parameters for
+    // test_fullpage.html
+    if (strcmp(argn[i], "name") == 0 && strcmp(argv[i], "plugin") == 0) {
+      instanceData->streamMode = NP_SEEK;
+      instanceData->frame = "testframe";
+      addRange(instanceData, "100,100");
+    }
+  }
 
   if (!browserSupportsWindowless || !pluginSupportsWindowlessMode()) {
     requestWindow = true;
   } else if (!pluginSupportsWindowMode()) {
     requestWindow = false;
   }
   if (requestWindow) {
     instanceData->hasWidget = true;
--- a/dom/plugins/test/testplugin/nptest_gtk2.cpp
+++ b/dom/plugins/test/testplugin/nptest_gtk2.cpp
@@ -56,17 +56,17 @@ struct _PlatformData {
   Colormap colormap;
 #endif
   GtkWidget* plug;
 };
 
 bool
 pluginSupportsWindowMode()
 {
-  return true;
+  return false;
 }
 
 bool
 pluginSupportsWindowlessMode()
 {
   return true;
 }
 
@@ -136,43 +136,43 @@ SetCairoRGBA(cairo_t* cairoWindow, uint3
 }
 
 static void
 pluginDrawSolid(InstanceData* instanceData, GdkDrawable* gdkWindow,
                 int x, int y, int width, int height)
 {
   cairo_t* cairoWindow = gdk_cairo_create(gdkWindow);
 
-  if (!instanceData->hasWidget) {
-    NPRect* clip = &instanceData->window.clipRect;
-    cairo_rectangle(cairoWindow, clip->left, clip->top,
-                    clip->right - clip->left, clip->bottom - clip->top);
-    cairo_clip(cairoWindow);
-  }
+  MOZ_RELEASE_ASSERT(!instanceData->hasWidget);
+
+  NPRect* clip = &instanceData->window.clipRect;
+  cairo_rectangle(cairoWindow, clip->left, clip->top,
+                  clip->right - clip->left, clip->bottom - clip->top);
+  cairo_clip(cairoWindow);
 
   GdkRectangle windowRect = { x, y, width, height };
   gdk_cairo_rectangle(cairoWindow, &windowRect);
   SetCairoRGBA(cairoWindow, instanceData->scriptableObject->drawColor);
 
   cairo_fill(cairoWindow);
   cairo_destroy(cairoWindow);
 }
 
 static void
 pluginDrawWindow(InstanceData* instanceData, GdkDrawable* gdkWindow,
                  const GdkRectangle& invalidRect)
 {
   NPWindow& window = instanceData->window;
-  // When we have a widget, window.x/y are meaningless since our
-  // widget is always positioned correctly and we just draw into it at 0,0
-  int x = instanceData->hasWidget ? 0 : window.x;
-  int y = instanceData->hasWidget ? 0 : window.y;
+  MOZ_RELEASE_ASSERT(!instanceData->hasWidget);
+
+  int x = window.x;
+  int y = window.y;
   int width = window.width;
   int height = window.height;
-  
+
   notifyDidPaint(instanceData);
 
   if (instanceData->scriptableObject->drawMode == DM_SOLID_COLOR) {
     // drawing a solid color for reftests
     pluginDrawSolid(instanceData, gdkWindow,
                     invalidRect.x, invalidRect.y,
                     invalidRect.width, invalidRect.height);
     return;
@@ -185,22 +185,20 @@ pluginDrawWindow(InstanceData* instanceD
   const char* uaString = NPN_UserAgent(npp);
   if (!uaString)
     return;
 
   GdkGC* gdkContext = gdk_gc_new(gdkWindow);
   if (!gdkContext)
     return;
 
-  if (!instanceData->hasWidget) {
-    NPRect* clip = &window.clipRect;
-    GdkRectangle gdkClip = { clip->left, clip->top, clip->right - clip->left,
-                             clip->bottom - clip->top };
-    gdk_gc_set_clip_rectangle(gdkContext, &gdkClip);
-  }
+  NPRect* clip = &window.clipRect;
+  GdkRectangle gdkClip = { clip->left, clip->top, clip->right - clip->left,
+                           clip->bottom - clip->top };
+  gdk_gc_set_clip_rectangle(gdkContext, &gdkClip);
 
   // draw a grey background for the plugin frame
   GdkColor grey;
   grey.red = grey.blue = grey.green = 32767;
   gdk_gc_set_rgb_fg_color(gdkContext, &grey);
   gdk_draw_rectangle(gdkWindow, gdkContext, TRUE, x, y, width, height);
 
   // draw a 3-pixel-thick black frame around the plugin
@@ -425,18 +423,20 @@ pluginHandleEvent(InstanceData* instance
   }
 #endif
 
   return 0;
 }
 
 int32_t pluginGetEdge(InstanceData* instanceData, RectEdge edge)
 {
+  MOZ_RELEASE_ASSERT(!instanceData->hasWidget);
   if (!instanceData->hasWidget)
     return NPTEST_INT32_ERROR;
+
   GtkWidget* plug = instanceData->platformData->plug;
   if (!plug)
     return NPTEST_INT32_ERROR;
   GdkWindow* plugWnd = plug->window;
   if (!plugWnd)
     return NPTEST_INT32_ERROR;
 
   GdkWindow* toplevelGdk = 0;
@@ -503,16 +503,17 @@ static void intersectWithShapeRects(Disp
 
   gdk_region_intersect(region, shapeRegion);
   gdk_region_destroy(shapeRegion);
 }
 #endif
 
 static GdkRegion* computeClipRegion(InstanceData* instanceData)
 {
+  MOZ_RELEASE_ASSERT(!instanceData->hasWidget);
   if (!instanceData->hasWidget)
     return 0;
 
   GtkWidget* plug = instanceData->platformData->plug;
   if (!plug)
     return 0;
   GdkWindow* plugWnd = plug->window;
   if (!plugWnd)
--- a/dom/presentation/PresentationConnection.cpp
+++ b/dom/presentation/PresentationConnection.cpp
@@ -730,35 +730,36 @@ PresentationConnection::RemoveFromLoadGr
 void
 PresentationConnection::AsyncCloseConnectionWithErrorMsg(const nsAString& aMessage)
 {
   if (mState == PresentationConnectionState::Terminated) {
     return;
   }
 
   nsString message = nsString(aMessage);
+  RefPtr<PresentationConnection> self = this;
   nsCOMPtr<nsIRunnable> r =
-    NS_NewRunnableFunction([this, message]() -> void {
+    NS_NewRunnableFunction([self, message]() -> void {
       // Set |mState| to |PresentationConnectionState::Closed| here to avoid
       // calling |ProcessStateChanged|.
-      mState = PresentationConnectionState::Closed;
+      self->mState = PresentationConnectionState::Closed;
 
       // Make sure dispatching the event and closing the connection are invoked
       // at the same time by setting |aDispatchNow| to true.
       Unused << NS_WARN_IF(NS_FAILED(
-        DispatchConnectionCloseEvent(PresentationConnectionClosedReason::Error,
-                                      message,
-                                      true)));
+        self->DispatchConnectionCloseEvent(PresentationConnectionClosedReason::Error,
+                                           message,
+                                           true)));
 
       nsCOMPtr<nsIPresentationService> service =
         do_GetService(PRESENTATION_SERVICE_CONTRACTID);
       if(NS_WARN_IF(!service)) {
         return;
       }
 
       Unused << NS_WARN_IF(NS_FAILED(
-        service->CloseSession(mId,
-                              mRole,
+        service->CloseSession(self->mId,
+                              self->mRole,
                               nsIPresentationService::CLOSED_REASON_ERROR)));
     });
 
   Unused << NS_WARN_IF(NS_FAILED(NS_DispatchToMainThread(r)));
 }
--- a/dom/security/test/csp/mochitest.ini
+++ b/dom/security/test/csp/mochitest.ini
@@ -244,17 +244,17 @@ skip-if = toolkit == 'android' # Times o
 [test_subframe_run_js_if_allowed.html]
 [test_leading_wildcard.html]
 [test_multi_policy_injection_bypass.html]
 [test_null_baseuri.html]
 [test_referrerdirective.html]
 [test_dual_header.html]
 [test_upgrade_insecure.html]
 # no ssl support as well as websocket tests do not work (see test_websocket.html)
-skip-if = toolkit == 'android'
+skip-if = toolkit == 'android' || (os=="mac" && !debug) # osx: bug 1316305
 [test_upgrade_insecure_reporting.html]
 skip-if = toolkit == 'android'
 [test_upgrade_insecure_referrer.html]
 skip-if = toolkit == 'android'
 [test_upgrade_insecure_cors.html]
 skip-if = toolkit == 'android'
 [test_report_for_import.html]
 [test_blocked_uri_in_reports.html]
--- a/dom/tests/mochitest/chrome/chrome.ini
+++ b/dom/tests/mochitest/chrome/chrome.ini
@@ -49,16 +49,17 @@ skip-if = os != 'mac' || os_version == '
 tags = openwindow
 # synthesizeNativeOSXClick does not work on 10.6
 skip-if = os != 'mac' || os_version == '10.6'
 [test_callback_wrapping.xul]
 [test_clonewrapper.xul]
 [test_cyclecollector.xul]
 [test_docshell_swap.xul]
 [test_focus.xul]
+skip-if = os == 'linux' && !debug # bug 1296622
 [test_focus_docnav.xul]
 [test_focus_switchbinding.xul]
 [test_focused_link_scroll.xul]
 [test_fullscreen.xul]
 tags = fullscreen
 # disabled on linux for timeouts--bug-867745
 skip-if = os == 'linux'
 [test_geolocation.xul]
--- a/gfx/layers/ipc/CompositorBridgeParent.cpp
+++ b/gfx/layers/ipc/CompositorBridgeParent.cpp
@@ -1311,18 +1311,19 @@ CompositorBridgeParent::FlushApzRepaints
 {
   MOZ_ASSERT(mApzcTreeManager);
   uint64_t layersId = aLayerTree->GetId();
   if (layersId == 0) {
     // The request is coming from the parent-process layer tree, so we should
     // use the compositor's root layer tree id.
     layersId = mRootLayerTreeID;
   }
+  RefPtr<CompositorBridgeParent> self = this;
   APZThreadUtils::RunOnControllerThread(NS_NewRunnableFunction([=] () {
-    mApzcTreeManager->FlushApzRepaints(layersId);
+    self->mApzcTreeManager->FlushApzRepaints(layersId);
   }));
 }
 
 void
 CompositorBridgeParent::GetAPZTestData(const LayerTransactionParent* aLayerTree,
                                        APZTestData* aOutData)
 {
   MonitorAutoLock lock(*sIndirectLayerTreesLock);
--- a/gfx/layers/moz.build
+++ b/gfx/layers/moz.build
@@ -447,17 +447,17 @@ IPDL_SOURCES += [
 ]
 
 include('/ipc/chromium/chromium-config.mozbuild')
 
 LOCAL_INCLUDES += [
     '/docshell/base',  # for nsDocShell.h
     '/layout/base',    # for TouchManager.h
     '/layout/generic', # for nsTextFrame.h
-    '/media/libyuv/include', # for libyuv.h
+    '/media/libyuv/libyuv/include', # for libyuv.h
 ]
 
 FINAL_LIBRARY = 'xul'
 
 if CONFIG['MOZ_DEBUG']:
     DEFINES['D3D_DEBUG_INFO'] = True
 
 if CONFIG['MOZ_ENABLE_D3D10_LAYER']:
--- a/gfx/ycbcr/moz.build
+++ b/gfx/ycbcr/moz.build
@@ -55,11 +55,11 @@ else:
 if CONFIG['CPU_ARCH'] == 'arm' and CONFIG['HAVE_ARM_NEON']:
     SOURCES += [
         'yuv_row_arm.s',
     ]
     SOURCES += [
         'yuv_convert_arm.cpp',
     ]
 
-LOCAL_INCLUDES += ['/media/libyuv/include']
+LOCAL_INCLUDES += ['/media/libyuv/libyuv/include']
 
 FINAL_LIBRARY = 'xul'
--- a/gfx/ycbcr/yuv_convert.cpp
+++ b/gfx/ycbcr/yuv_convert.cpp
@@ -97,57 +97,74 @@ void ConvertYCbCrToRGB32(const uint8* y_
   }
   if (use_deprecated) {
     ConvertYCbCrToRGB32_deprecated(y_buf, u_buf, v_buf, rgb_buf,
                                    pic_x, pic_y, pic_width, pic_height,
                                    y_pitch, uv_pitch, rgb_pitch, yuv_type);
     return;
   }
 
-  libyuv::YuvConstants* yuvconstants = nullptr;
-  if (yuv_color_space == mozilla::YUVColorSpace::BT709) {
-    yuvconstants = const_cast<libyuv::YuvConstants*>(&libyuv::kYuvH709Constants);
-  } else {
-    yuvconstants = const_cast<libyuv::YuvConstants*>(&libyuv::kYuvI601Constants);
-  }
-                                    
   if (yuv_type == YV24) {
     const uint8* src_y = y_buf + y_pitch * pic_y + pic_x;
     const uint8* src_u = u_buf + uv_pitch * pic_y + pic_x;
     const uint8* src_v = v_buf + uv_pitch * pic_y + pic_x;
-    DebugOnly<int> err = libyuv::I444ToARGBMatrix(src_y, y_pitch,
-                                                  src_u, uv_pitch,
-                                                  src_v, uv_pitch,
-                                                  rgb_buf, rgb_pitch,
-                                                  yuvconstants,
-                                                  pic_width, pic_height);
-    MOZ_ASSERT(!err);
+    if (yuv_color_space == mozilla::YUVColorSpace::BT709) {
+      DebugOnly<int> err = libyuv::H444ToARGB(src_y, y_pitch,
+                                              src_u, uv_pitch,
+                                              src_v, uv_pitch,
+                                              rgb_buf, rgb_pitch,
+                                              pic_width, pic_height);
+      MOZ_ASSERT(!err);
+    } else {
+      DebugOnly<int> err = libyuv::I444ToARGB(src_y, y_pitch,
+                                              src_u, uv_pitch,
+                                              src_v, uv_pitch,
+                                              rgb_buf, rgb_pitch,
+                                              pic_width, pic_height);
+      MOZ_ASSERT(!err);
+    }
   } else if (yuv_type == YV16) {
     const uint8* src_y = y_buf + y_pitch * pic_y + pic_x;
     const uint8* src_u = u_buf + uv_pitch * pic_y + pic_x / 2;
     const uint8* src_v = v_buf + uv_pitch * pic_y + pic_x / 2;
-    DebugOnly<int> err = libyuv::I422ToARGBMatrix(src_y, y_pitch,
-                                                  src_u, uv_pitch,
-                                                  src_v, uv_pitch,
-                                                  rgb_buf, rgb_pitch,
-                                                  yuvconstants,
-                                                  pic_width, pic_height);
-    MOZ_ASSERT(!err);
+    if (yuv_color_space == mozilla::YUVColorSpace::BT709) {
+      DebugOnly<int> err = libyuv::H422ToARGB(src_y, y_pitch,
+                                              src_u, uv_pitch,
+                                              src_v, uv_pitch,
+                                              rgb_buf, rgb_pitch,
+                                              pic_width, pic_height);
+      MOZ_ASSERT(!err);
+    } else {
+      DebugOnly<int> err = libyuv::I422ToARGB(src_y, y_pitch,
+                                              src_u, uv_pitch,
+                                              src_v, uv_pitch,
+                                              rgb_buf, rgb_pitch,
+                                              pic_width, pic_height);
+      MOZ_ASSERT(!err);
+    }
   } else {
     MOZ_ASSERT(yuv_type == YV12);
     const uint8* src_y = y_buf + y_pitch * pic_y + pic_x;
     const uint8* src_u = u_buf + (uv_pitch * pic_y + pic_x) / 2;
     const uint8* src_v = v_buf + (uv_pitch * pic_y + pic_x) / 2;
-    DebugOnly<int> err = libyuv::I420ToARGBMatrix(src_y, y_pitch,
-                                                  src_u, uv_pitch,
-                                                  src_v, uv_pitch,
-                                                  rgb_buf, rgb_pitch,
-                                                  yuvconstants,
-                                                  pic_width, pic_height);
-    MOZ_ASSERT(!err);
+    if (yuv_color_space == mozilla::YUVColorSpace::BT709) {
+      DebugOnly<int> err = libyuv::H420ToARGB(src_y, y_pitch,
+                                              src_u, uv_pitch,
+                                              src_v, uv_pitch,
+                                              rgb_buf, rgb_pitch,
+                                              pic_width, pic_height);
+      MOZ_ASSERT(!err);
+    } else {
+      DebugOnly<int> err = libyuv::I420ToARGB(src_y, y_pitch,
+                                              src_u, uv_pitch,
+                                              src_v, uv_pitch,
+                                              rgb_buf, rgb_pitch,
+                                              pic_width, pic_height);
+      MOZ_ASSERT(!err);
+    }
   }
 }
 
 // Convert a frame of YUV to 32 bit ARGB.
 void ConvertYCbCrToRGB32_deprecated(const uint8* y_buf,
                                     const uint8* u_buf,
                                     const uint8* v_buf,
                                     uint8* rgb_buf,
--- a/gfx/ycbcr/yuv_row.h
+++ b/gfx/ycbcr/yuv_row.h
@@ -111,21 +111,33 @@ void LinearScaleYUVToRGB32Row(const uint
 void LinearScaleYUVToRGB32Row_C(const uint8* y_buf,
                                 const uint8* u_buf,
                                 const uint8* v_buf,
                                 uint8* rgb_buf,
                                 int width,
                                 int source_dx);
 
 
-#if defined(_MSC_VER)
+#if defined(_MSC_VER) && !defined(__CLR_VER) && !defined(__clang__)
+#if defined(VISUALC_HAS_AVX2)
+#define SIMD_ALIGNED(var) __declspec(align(32)) var
+#else
 #define SIMD_ALIGNED(var) __declspec(align(16)) var
+#endif
+#elif defined(__GNUC__) || defined(__clang__)
+// Caveat GCC 4.2 to 4.7 have a known issue using vectors with const.
+#if defined(CLANG_HAS_AVX2) || defined(GCC_HAS_AVX2)
+#define SIMD_ALIGNED(var) var __attribute__((aligned(32)))
 #else
 #define SIMD_ALIGNED(var) var __attribute__((aligned(16)))
 #endif
+#else
+#define SIMD_ALIGNED(var) var
+#endif
+
 extern SIMD_ALIGNED(const int16 kCoefficientsRgbY[768][4]);
 
 // x64 uses MMX2 (SSE) so emms is not required.
 // Warning C4799: function has no EMMS instruction.
 // EMMS() is slow and should be called by the calling function once per image.
 #if defined(ARCH_CPU_X86) && !defined(ARCH_CPU_X86_64)
 #if defined(_MSC_VER)
 #define EMMS() __asm emms
--- a/intl/locale/nsIScriptableDateFormat.idl
+++ b/intl/locale/nsIScriptableDateFormat.idl
@@ -4,23 +4,24 @@
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #include "nsISupports.idl"
 
 typedef long nsDateFormatSelector;
 %{ C++
 enum
 {
+    // Do not change the order of the values below (see bug 1225696).
     kDateFormatNone = 0,            // do not include the date  in the format string
     kDateFormatLong,                // provides the long date format for the given locale
     kDateFormatShort,               // provides the short date format for the given locale
-    kDateFormatYearMonth,           // formats using only the year and month 
+    kDateFormatYearMonth,           // formats using only the year and month
+    kDateFormatWeekday,             // week day (e.g. Mon, Tue)
     kDateFormatYearMonthLong,       // long version of kDateFormatYearMonth
-    kDateFormatMonthLong,           // long format of month name only
-    kDateFormatWeekday              // week day (e.g. Mon, Tue)
+    kDateFormatMonthLong            // long format of month name only
 };
 %}
 
 typedef long nsTimeFormatSelector;
 %{ C++
 enum
 {
     kTimeFormatNone = 0,            // don't include the time in the format string
--- a/ipc/mscom/MainThreadHandoff.cpp
+++ b/ipc/mscom/MainThreadHandoff.cpp
@@ -8,16 +8,17 @@
 
 #include "mozilla/Move.h"
 #include "mozilla/mscom/InterceptorLog.h"
 #include "mozilla/mscom/Registration.h"
 #include "mozilla/mscom/Utils.h"
 #include "mozilla/Assertions.h"
 #include "mozilla/DebugOnly.h"
 #include "nsThreadUtils.h"
+#include "nsProxyRelease.h"
 
 using mozilla::DebugOnly;
 
 namespace {
 
 class HandoffRunnable : public mozilla::Runnable
 {
 public:
@@ -102,22 +103,21 @@ MainThreadHandoff::Release()
 {
   ULONG newRefCnt = (ULONG) InterlockedDecrement((LONG*)&mRefCnt);
   if (newRefCnt == 0) {
     // It is possible for the last Release() call to happen off-main-thread.
     // If so, we need to dispatch an event to delete ourselves.
     if (NS_IsMainThread()) {
       delete this;
     } else {
-      mozilla::DebugOnly<nsresult> rv =
-        NS_DispatchToMainThread(NS_NewRunnableFunction([=]() -> void
-        {
-          delete this;
-        }));
-      MOZ_ASSERT(NS_SUCCEEDED(rv));
+      // We need to delete this object on the main thread, but we aren't on the
+      // main thread right now, so we send a reference to ourselves to the main
+      // thread to be re-released there.
+      RefPtr<MainThreadHandoff> self = this;
+      NS_ReleaseOnMainThread(self.forget());
     }
   }
   return newRefCnt;
 }
 
 HRESULT
 MainThreadHandoff::OnCall(ICallFrame* aFrame)
 {
--- a/ipc/mscom/WeakRef.cpp
+++ b/ipc/mscom/WeakRef.cpp
@@ -6,16 +6,17 @@
 
 #define INITGUID
 #include "mozilla/mscom/WeakRef.h"
 
 #include "mozilla/DebugOnly.h"
 #include "mozilla/Mutex.h"
 #include "nsThreadUtils.h"
 #include "nsWindowsHelpers.h"
+#include "nsProxyRelease.h"
 
 static void
 InitializeCS(CRITICAL_SECTION& aCS)
 {
   DWORD flags = 0;
 #if defined(RELEASE_OR_BETA)
   flags |= CRITICAL_SECTION_NO_DEBUG_INFO;
 #endif
@@ -65,17 +66,16 @@ SharedRef::Resolve(REFIID aIid, void** a
 
   return strongRef->QueryInterface(aIid, aOutStrongReference);
 }
 
 void
 SharedRef::Clear()
 {
   AutoCriticalSection lock(&mCS);
-  MOZ_ASSERT(mSupport);
   mSupport = nullptr;
 }
 
 } // namespace detail
 
 typedef BaseAutoLock<detail::SharedRef> SharedRefAutoLock;
 typedef BaseAutoUnlock<detail::SharedRef> SharedRefAutoUnlock;
 
@@ -142,24 +142,21 @@ WeakReferenceSupport::Release()
       mSharedRef->Clear();
     }
   }
   NS_LOG_RELEASE(this, newRefCnt, "mscom::WeakReferenceSupport");
   if (newRefCnt == 0) {
     if (mFlags != Flags::eDestroyOnMainThread || NS_IsMainThread()) {
       delete this;
     } else {
-      // It is possible for the last Release() call to happen off-main-thread.
-      // If so, we need to dispatch an event to delete ourselves.
-      mozilla::DebugOnly<nsresult> rv =
-        NS_DispatchToMainThread(NS_NewRunnableFunction([this]() -> void
-        {
-          delete this;
-        }));
-      MOZ_ASSERT(NS_SUCCEEDED(rv));
+      // We need to delete this object on the main thread, but we aren't on the
+      // main thread right now, so we send a reference to ourselves to the main
+      // thread to be re-released there.
+      RefPtr<WeakReferenceSupport> self = this;
+      NS_ReleaseOnMainThread(self.forget());
     }
   }
   return newRefCnt;
 }
 
 HRESULT
 WeakReferenceSupport::GetWeakReference(IWeakReference** aOutWeakRef)
 {
--- a/ipc/testshell/TestShellParent.cpp
+++ b/ipc/testshell/TestShellParent.cpp
@@ -12,17 +12,16 @@
 #include "mozilla/dom/ScriptSettings.h"
 
 #include "xpcpublic.h"
 
 using namespace mozilla;
 using mozilla::ipc::TestShellParent;
 using mozilla::ipc::TestShellCommandParent;
 using mozilla::ipc::PTestShellCommandParent;
-using mozilla::dom::ContentParent;
 
 void
 TestShellParent::ActorDestroy(ActorDestroyReason aWhy)
 {
   // Implement me! Bug 1005177
 }
 
 PTestShellCommandParent*
--- a/js/public/GCVector.h
+++ b/js/public/GCVector.h
@@ -63,27 +63,27 @@ class GCVector
 
     T& operator[](size_t i) { return vector[i]; }
     const T& operator[](size_t i) const { return vector[i]; }
 
     T& back() { return vector.back(); }
     const T& back() const { return vector.back(); }
 
     bool initCapacity(size_t cap) { return vector.initCapacity(cap); }
-    bool reserve(size_t req) { return vector.reserve(req); }
+    MOZ_MUST_USE bool reserve(size_t req) { return vector.reserve(req); }
     void shrinkBy(size_t amount) { return vector.shrinkBy(amount); }
-    bool growBy(size_t amount) { return vector.growBy(amount); }
-    bool resize(size_t newLen) { return vector.resize(newLen); }
+    MOZ_MUST_USE bool growBy(size_t amount) { return vector.growBy(amount); }
+    MOZ_MUST_USE bool resize(size_t newLen) { return vector.resize(newLen); }
 
     void clear() { return vector.clear(); }
 
     template<typename U> bool append(U&& item) { return vector.append(mozilla::Forward<U>(item)); }
 
     template<typename... Args>
-    bool
+    MOZ_MUST_USE bool
     emplaceBack(Args&&... args) {
         return vector.emplaceBack(mozilla::Forward<Args>(args)...);
     }
 
     template<typename U>
     void infallibleAppend(U&& aU) {
         return vector.infallibleAppend(mozilla::Forward<U>(aU));
     }
@@ -94,26 +94,30 @@ class GCVector
     infallibleAppend(const U* aBegin, const U* aEnd) {
         return vector.infallibleAppend(aBegin, aEnd);
     }
     template<typename U> void infallibleAppend(const U* aBegin, size_t aLength) {
         return vector.infallibleAppend(aBegin, aLength);
     }
 
     template<typename U, size_t O, class BP>
-    bool appendAll(const mozilla::Vector<U, O, BP>& aU) { return vector.appendAll(aU); }
+    MOZ_MUST_USE bool appendAll(const mozilla::Vector<U, O, BP>& aU) { return vector.appendAll(aU); }
     template<typename U, size_t O, class BP>
-    bool appendAll(const GCVector<U, O, BP>& aU) { return vector.append(aU.begin(), aU.length()); }
+    MOZ_MUST_USE bool appendAll(const GCVector<U, O, BP>& aU) {
+        return vector.append(aU.begin(), aU.length());
+    }
 
-    bool appendN(const T& val, size_t count) { return vector.appendN(val, count); }
+    MOZ_MUST_USE bool appendN(const T& val, size_t count) { return vector.appendN(val, count); }
 
-    template<typename U> bool append(const U* aBegin, const U* aEnd) {
+    template<typename U>
+    MOZ_MUST_USE bool append(const U* aBegin, const U* aEnd) {
         return vector.append(aBegin, aEnd);
     }
-    template<typename U> bool append(const U* aBegin, size_t aLength) {
+    template<typename U>
+    MOZ_MUST_USE bool append(const U* aBegin, size_t aLength) {
         return vector.append(aBegin, aLength);
     }
 
     void popBack() { return vector.popBack(); }
     T popCopy() { return vector.popCopy(); }
 
     size_t sizeOfExcludingThis(mozilla::MallocSizeOf mallocSizeOf) const {
         return vector.sizeOfExcludingThis(mallocSizeOf);
@@ -124,16 +128,30 @@ class GCVector
     }
 
     static void trace(GCVector* vec, JSTracer* trc) { vec->trace(trc); }
 
     void trace(JSTracer* trc) {
         for (auto& elem : vector)
             GCPolicy<T>::trace(trc, &elem, "vector element");
     }
+
+    void sweep() {
+        uint32_t src, dst = 0;
+        for (src = 0; src < length(); src++) {
+            if (!GCPolicy<T>::needsSweep(&vector[src])) {
+                if (dst != src)
+                    vector[dst] = vector[src].unbarrieredGet();
+                dst++;
+            }
+        }
+
+        if (dst != length())
+            vector.shrinkTo(dst);
+    }
 };
 
 } // namespace JS
 
 namespace js {
 
 template <typename Wrapper, typename T, size_t Capacity, typename AllocPolicy>
 class WrappedPtrOperations<JS::GCVector<T, Capacity, AllocPolicy>, Wrapper>
@@ -175,39 +193,43 @@ class MutableWrappedPtrOperations<JS::GC
 
     JS::Handle<T> operator[](size_t aIndex) const {
         return JS::Handle<T>::fromMarkedLocation(&vec().operator[](aIndex));
     }
     JS::MutableHandle<T> operator[](size_t aIndex) {
         return JS::MutableHandle<T>::fromMarkedLocation(&vec().operator[](aIndex));
     }
 
-    bool initCapacity(size_t aRequest) { return vec().initCapacity(aRequest); }
-    bool reserve(size_t aRequest) { return vec().reserve(aRequest); }
+    MOZ_MUST_USE bool initCapacity(size_t aRequest) { return vec().initCapacity(aRequest); }
+    MOZ_MUST_USE bool reserve(size_t aRequest) { return vec().reserve(aRequest); }
     void shrinkBy(size_t aIncr) { vec().shrinkBy(aIncr); }
-    bool growBy(size_t aIncr) { return vec().growBy(aIncr); }
-    bool resize(size_t aNewLength) { return vec().resize(aNewLength); }
-    bool growByUninitialized(size_t aIncr) { return vec().growByUninitialized(aIncr); }
+    MOZ_MUST_USE bool growBy(size_t aIncr) { return vec().growBy(aIncr); }
+    MOZ_MUST_USE bool resize(size_t aNewLength) { return vec().resize(aNewLength); }
+    MOZ_MUST_USE bool growByUninitialized(size_t aIncr) { return vec().growByUninitialized(aIncr); }
     void infallibleGrowByUninitialized(size_t aIncr) { vec().infallibleGrowByUninitialized(aIncr); }
-    bool resizeUninitialized(size_t aNewLength) { return vec().resizeUninitialized(aNewLength); }
+    MOZ_MUST_USE bool resizeUninitialized(size_t aNewLength) { return vec().resizeUninitialized(aNewLength); }
     void clear() { vec().clear(); }
     void clearAndFree() { vec().clearAndFree(); }
-    template<typename U> bool append(U&& aU) { return vec().append(mozilla::Forward<U>(aU)); }
-    template<typename... Args> bool emplaceBack(Args&&... aArgs) {
+    template<typename U>
+    MOZ_MUST_USE bool append(U&& aU) { return vec().append(mozilla::Forward<U>(aU)); }
+    template<typename... Args>
+    MOZ_MUST_USE bool emplaceBack(Args&&... aArgs) {
         return vec().emplaceBack(mozilla::Forward<Args...>(aArgs...));
     }
     template<typename U, size_t O, class BP>
-    bool appendAll(const mozilla::Vector<U, O, BP>& aU) { return vec().appendAll(aU); }
+    MOZ_MUST_USE bool appendAll(const mozilla::Vector<U, O, BP>& aU) { return vec().appendAll(aU); }
     template<typename U, size_t O, class BP>
-    bool appendAll(const JS::GCVector<U, O, BP>& aU) { return vec().appendAll(aU); }
-    bool appendN(const T& aT, size_t aN) { return vec().appendN(aT, aN); }
-    template<typename U> bool append(const U* aBegin, const U* aEnd) {
+    MOZ_MUST_USE bool appendAll(const JS::GCVector<U, O, BP>& aU) { return vec().appendAll(aU); }
+    MOZ_MUST_USE bool appendN(const T& aT, size_t aN) { return vec().appendN(aT, aN); }
+    template<typename U>
+    MOZ_MUST_USE bool append(const U* aBegin, const U* aEnd) {
         return vec().append(aBegin, aEnd);
     }
-    template<typename U> bool append(const U* aBegin, size_t aLength) {
+    template<typename U>
+    MOZ_MUST_USE bool append(const U* aBegin, size_t aLength) {
         return vec().append(aBegin, aLength);
     }
     template<typename U> void infallibleAppend(U&& aU) {
         vec().infallibleAppend(mozilla::Forward<U>(aU));
     }
     void infallibleAppendN(const T& aT, size_t aN) { vec().infallibleAppendN(aT, aN); }
     template<typename U> void infallibleAppend(const U* aBegin, const U* aEnd) {
         vec().infallibleAppend(aBegin, aEnd);
--- a/js/src/devtools/automation/autospider.py
+++ b/js/src/devtools/automation/autospider.py
@@ -41,16 +41,19 @@ parser.add_argument('--dep', action='sto
 parser.add_argument('--platform', '-p', type=str, metavar='PLATFORM',
                     default='', help='build platform')
 parser.add_argument('--timeout', '-t', type=int, metavar='TIMEOUT',
                     default=10800,
                     help='kill job after TIMEOUT seconds')
 parser.add_argument('--objdir', type=str, metavar='DIR',
                     default=env.get('OBJDIR', 'obj-spider'),
                     help='object directory')
+parser.add_argument('--optimize', type=bool, metavar='OPT',
+                    default=None,
+                    help='whether to generate an optimized build. Overrides variant setting.')
 parser.add_argument('--run-tests', '--tests', type=str, metavar='TESTSUITE',
                     default='',
                     help="comma-separated set of test suites to add to the variant's default set")
 parser.add_argument('--skip-tests', '--skip', type=str, metavar='TESTSUITE',
                     default='',
                     help="comma-separated set of test suites to remove from the variant's default set")
 parser.add_argument('--build-only', '--build',
                     dest='skip_tests', action='store_const', const='all',
@@ -128,18 +131,24 @@ if args.variant == 'nonunified':
                                    os.path.join(dirpath, 'moz.build')])
 
 OBJDIR = os.path.join(DIR.source, args.objdir)
 OUTDIR = os.path.join(OBJDIR, "out")
 POBJDIR = posixpath.join(PDIR.source, args.objdir)
 AUTOMATION = env.get('AUTOMATION', False)
 MAKE = env.get('MAKE', 'make')
 MAKEFLAGS = env.get('MAKEFLAGS', '-j6')
+UNAME_M = subprocess.check_output(['uname', '-m']).strip()
+
 CONFIGURE_ARGS = variant['configure-args']
-UNAME_M = subprocess.check_output(['uname', '-m']).strip()
+opt = args.optimize
+if opt is None:
+    opt = variant.get('optimize')
+if opt is not None:
+    CONFIGURE_ARGS += (" --enable-optimize" if opt else " --disable-optimize")
 
 # Any jobs that wish to produce additional output can save them into the upload
 # directory if there is such a thing, falling back to OBJDIR.
 env.setdefault('MOZ_UPLOAD_DIR', OBJDIR)
 ensure_dir_exists(env['MOZ_UPLOAD_DIR'], clobber=False)
 
 # Some of the variants request a particular word size (eg ARM simulators).
 word_bits = variant.get('bits')
--- a/js/src/devtools/automation/variants/arm-sim
+++ b/js/src/devtools/automation/variants/arm-sim
@@ -1,4 +1,5 @@
 {
-    "configure-args": "--enable-optimize --enable-debug --enable-stdcxx-compat --enable-simulator=arm --target=i686-pc-linux --host=i686-pc-linux",
+    "configure-args": "--enable-debug --enable-stdcxx-compat --enable-simulator=arm --target=i686-pc-linux --host=i686-pc-linux",
+    "optimize": true,
     "bits": 32
 }
--- a/js/src/devtools/automation/variants/arm-sim-osx
+++ b/js/src/devtools/automation/variants/arm-sim-osx
@@ -1,4 +1,5 @@
 {
-    "configure-args": "--enable-optimize --enable-debug --enable-stdcxx-compat --enable-simulator=arm --target=i686-apple-darwin10.0.0 --host=i686-apple-darwin10.0.0",
+    "configure-args": "--enable-debug --enable-stdcxx-compat --enable-simulator=arm --target=i686-apple-darwin10.0.0 --host=i686-apple-darwin10.0.0",
+    "optimize": true,
     "bits": 32
 }
--- a/js/src/devtools/automation/variants/arm64-sim
+++ b/js/src/devtools/automation/variants/arm64-sim
@@ -1,8 +1,9 @@
 {
-    "configure-args": "--enable-optimize --enable-debug --enable-stdcxx-compat --enable-simulator=arm64",
+    "configure-args": "--enable-debug --enable-stdcxx-compat --enable-simulator=arm64",
+    "optimize": true,
     "env": {
         "JSTESTS_EXTRA_ARGS": "--exclude-file={DIR}/arm64-jstests-slow.txt",
         "JITTEST_EXTRA_ARGS": "--jitflags=none --args=--baseline-eager -x ion/ -x asm.js/"
     },
     "bits": 64
 }
--- a/js/src/devtools/automation/variants/asan
+++ b/js/src/devtools/automation/variants/asan
@@ -1,7 +1,8 @@
 {
-    "configure-args": "--disable-debug --enable-optimize --enable-debug-symbols='-gline-tables-only' --disable-jemalloc --enable-address-sanitizer",
+    "configure-args": "--disable-debug --enable-debug-symbols='-gline-tables-only' --disable-jemalloc --enable-address-sanitizer",
+    "optimize": true,
     "compiler": "clang",
     "env": {
         "LLVM_SYMBOLIZER": "{TOOLTOOL_CHECKOUT}/clang/bin/llvm-symbolizer"
     }
 }
--- a/js/src/devtools/automation/variants/compacting
+++ b/js/src/devtools/automation/variants/compacting
@@ -1,10 +1,11 @@
 {
-    "configure-args": "--enable-optimize --enable-debug --enable-stdcxx-compat --enable-ctypes",
+    "configure-args": "--enable-debug --enable-stdcxx-compat --enable-ctypes",
+    "optimize": true,
     "env": {
         "JS_GC_ZEAL": "Compact",
         "JITTEST_EXTRA_ARGS": "--jitflags=debug --ignore-timeouts={DIR}/cgc-jittest-timeouts.txt",
         "JSTESTS_EXTRA_ARGS": "--exclude-file={DIR}/cgc-jstests-slow.txt"
     },
     "skip-tests": {
         "win32": ["jstests"],
         "win64": ["jstests"]
--- a/js/src/devtools/automation/variants/dtrace
+++ b/js/src/devtools/automation/variants/dtrace
@@ -1,3 +1,4 @@
 {
-    "configure-args": "--enable-optimize --enable-debug --enable-dtrace --enable-debug-symbols"
+    "configure-args": "--enable-debug --enable-dtrace --enable-debug-symbols",
+    "optimize": true
 }
--- a/js/src/devtools/automation/variants/msan
+++ b/js/src/devtools/automation/variants/msan
@@ -1,10 +1,11 @@
 {
-    "configure-args": "--disable-debug --enable-optimize --enable-debug-symbols='-gline-tables-only' --disable-jemalloc --enable-memory-sanitizer",
+    "configure-args": "--disable-debug --enable-debug-symbols='-gline-tables-only' --disable-jemalloc --enable-memory-sanitizer",
+    "optimize": true,
     "compiler": "clang",
     "env": {
         "JITTEST_EXTRA_ARGS": "--jitflags=interp --ignore-timeouts={DIR}/cgc-jittest-timeouts.txt",
         "JSTESTS_EXTRA_ARGS": "--jitflags=interp --exclude-file={DIR}/cgc-jstests-slow.txt",
         "MSAN_OPTIONS": "external_symbolizer_path={TOOLTOOL_CHECKOUT}/clang/bin/llvm-symbolizer:log_path={OUTDIR}/sanitize_log"
     },
     "ignore-test-failures": "true",
     "max-errors": 2
--- a/js/src/devtools/automation/variants/plain
+++ b/js/src/devtools/automation/variants/plain
@@ -1,6 +1,7 @@
 {
-    "configure-args": "--enable-optimize",
+    "configure-args": "",
+    "optimize": true,
     "env": {
         "JSTESTS_EXTRA_ARGS": "--jitflags=all"
     }
 }
--- a/js/src/devtools/automation/variants/rootanalysis
+++ b/js/src/devtools/automation/variants/rootanalysis
@@ -1,7 +1,8 @@
 {
-    "configure-args": "--enable-optimize --enable-debug --enable-stdcxx-compat --enable-ctypes",
+    "configure-args": "--enable-debug --enable-stdcxx-compat --enable-ctypes",
+    "optimize": true,
     "env": {
         "JS_GC_ZEAL": "GenerationalGC",
         "JSTESTS_EXTRA_ARGS": "--jitflags=debug"
     }
 }
--- a/js/src/devtools/automation/variants/tsan
+++ b/js/src/devtools/automation/variants/tsan
@@ -1,10 +1,11 @@
 {
-    "configure-args": "--disable-debug --enable-optimize --enable-debug-symbols='-gline-tables-only' --disable-jemalloc --enable-thread-sanitizer",
+    "configure-args": "--disable-debug --enable-debug-symbols='-gline-tables-only' --disable-jemalloc --enable-thread-sanitizer",
+    "optimize": true,
     "compiler": "clang",
     "env": {
         "LLVM_SYMBOLIZER": "{TOOLTOOL_CHECKOUT}/clang/bin/llvm-symbolizer",
         "JITTEST_EXTRA_ARGS": "--jitflags=debug --ignore-timeouts={DIR}/cgc-jittest-timeouts.txt",
         "JSTESTS_EXTRA_ARGS": "--exclude-file={DIR}/cgc-jstests-slow.txt",
         "TSAN_OPTIONS": "log_path={OUTDIR}/sanitize_log"
     },
     "max-errors": 14
--- a/js/src/gc/Heap.h
+++ b/js/src/gc/Heap.h
@@ -1368,11 +1368,57 @@ TenuredCell::isAligned() const
     return Arena::isAligned(address(), arena()->getThingSize());
 }
 #endif
 
 static const int32_t ChunkLocationOffsetFromLastByte =
     int32_t(gc::ChunkLocationOffset) - int32_t(gc::ChunkMask);
 
 } /* namespace gc */
+
+namespace debug {
+
+// Utility functions meant to be called from an interactive debugger.
+enum class MarkInfo : int {
+    BLACK = js::gc::BLACK,
+    GRAY = js::gc::GRAY,
+    UNMARKED = -1,
+    NURSERY = -2,
+};
+
+// Get the mark color for a cell, in a way easily usable from a debugger.
+MOZ_NEVER_INLINE MarkInfo
+GetMarkInfo(js::gc::Cell* cell);
+
+// Sample usage from gdb:
+//
+//   (gdb) p $word = js::debug::GetMarkWordAddress(obj)
+//   $1 = (uintptr_t *) 0x7fa56d5fe360
+//   (gdb) p/x $mask = js::debug::GetMarkMask(obj, js::gc::GRAY)
+//   $2 = 0x200000000
+//   (gdb) watch *$word
+//   Hardware watchpoint 7: *$word
+//   (gdb) cond 7 *$word & $mask
+//   (gdb) cont
+//
+// Note that this is *not* a watchpoint on a single bit. It is a watchpoint on
+// the whole word, which will trigger whenever the word changes and the
+// selected bit is set after the change.
+//
+// So if the bit changing is the desired one, this is exactly what you want.
+// But if a different bit changes (either set or cleared), you may still stop
+// execution if the $mask bit happened to already be set. gdb does not expose
+// enough information to restrict the watchpoint to just a single bit.
+
+// Return the address of the word containing the mark bits for the given cell,
+// or nullptr if the cell is in the nursery.
+MOZ_NEVER_INLINE uintptr_t*
+GetMarkWordAddress(js::gc::Cell* cell);
+
+// Return the mask for the given cell and color, or 0 if the cell is in the
+// nursery.
+MOZ_NEVER_INLINE uintptr_t
+GetMarkMask(js::gc::Cell* cell, uint32_t color);
+
+} /* namespace debug */
 } /* namespace js */
 
 #endif /* gc_Heap_h */
--- a/js/src/gc/Marking.cpp
+++ b/js/src/gc/Marking.cpp
@@ -3368,8 +3368,52 @@ js::UnmarkGrayShapeRecursively(Shape* sh
     return TypedUnmarkGrayCellRecursively(shape);
 }
 
 JS_FRIEND_API(bool)
 JS::UnmarkGrayGCThingRecursively(JS::GCCellPtr thing)
 {
     return js::UnmarkGrayCellRecursively(thing.asCell(), thing.kind());
 }
+
+namespace js {
+namespace debug {
+
+MarkInfo
+GetMarkInfo(Cell* rawCell)
+{
+    if (!rawCell->isTenured())
+        return MarkInfo::NURSERY;
+
+    TenuredCell* cell = &rawCell->asTenured();
+    if (cell->isMarked(GRAY))
+        return MarkInfo::GRAY;
+    if (cell->isMarked(BLACK))
+        return MarkInfo::BLACK;
+    return MarkInfo::UNMARKED;
+}
+
+uintptr_t*
+GetMarkWordAddress(Cell* cell)
+{
+    if (!cell->isTenured())
+        return nullptr;
+
+    uintptr_t* wordp;
+    uintptr_t mask;
+    js::gc::detail::GetGCThingMarkWordAndMask(uintptr_t(cell), js::gc::BLACK, &wordp, &mask);
+    return wordp;
+}
+
+uintptr_t
+GetMarkMask(Cell* cell, uint32_t color)
+{
+    if (!cell->isTenured())
+        return 0;
+
+    uintptr_t* wordp;
+    uintptr_t mask;
+    js::gc::detail::GetGCThingMarkWordAndMask(uintptr_t(cell), color, &wordp, &mask);
+    return mask;
+}
+
+}
+}
new file mode 100644
--- /dev/null
+++ b/js/src/jit-test/lib/wasm-testharness.js
@@ -0,0 +1,45 @@
+if (!wasmIsSupported())
+    quit();
+
+load(scriptdir + 'harness/index.js');
+load(scriptdir + 'harness/wasm-constants.js');
+load(scriptdir + 'harness/wasm-module-builder.js');
+
+function test(func, description) {
+    let maybeErr;
+    try {
+        func();
+    } catch(e) {
+        maybeErr = e;
+    }
+
+    if (typeof maybeErr !== 'undefined') {
+        throw new Error(`${description}: FAIL.
+${maybeErr}
+${maybeErr.stack}`);
+    } else {
+        print(`${description}: PASS.`);
+    }
+}
+
+function promise_test(func, description) {
+    func()
+    .then(_ => {
+        print(`${description}: PASS.`);
+    })
+    .catch(err => {
+        print(`${description}: FAIL.
+${err}`);
+    });
+    drainJobQueue();
+}
+
+let assert_equals = assertEq;
+let assert_true = (x, errMsg) => { assertEq(x, true); }
+let assert_false = (x, errMsg) => { assertEq(x, false); }
+
+function assert_unreached(description) {
+    throw new Error(`unreachable:\n${description}`);
+}
+
+setJitCompilerOption('wasm.test-mode', 1);
--- a/js/src/jit-test/tests/wasm/backtrace.js
+++ b/js/src/jit-test/tests/wasm/backtrace.js
@@ -1,10 +1,8 @@
-load(libdir + "wasm.js");
-
 var code = `(module
   (import $i "env" "test")
   (func $t (call $i))
   (export "test" $t)
 )`;
 var mod = wasmEvalText(code, {
   env: {
     test: function() {
--- a/js/src/jit-test/tests/wasm/baseline-abs-addr-opt.js
+++ b/js/src/jit-test/tests/wasm/baseline-abs-addr-opt.js
@@ -2,18 +2,16 @@
 // This is intended to verify a bounds check elimination optimization in
 // the baseline compiler.
 
 // This can be only a functional test, we can't really see whether
 // the optimization is being applied.  However, manual inspection
 // of the generated code has verified that the optimization is
 // being applied.
 
-load(libdir + "wasm.js");
-
 // Memory is one page and minimum memory is one page, so accesses across
 // the end of the first page should fail.
 
 function gen(base, offset) {
   return wasmEvalText(`(module
 			(memory 1)
 			(data (i32.const 65528) "aaaaaaaa")
 			(func (result i32)
--- a/js/src/jit-test/tests/wasm/baseline-opt.js
+++ b/js/src/jit-test/tests/wasm/baseline-opt.js
@@ -1,12 +1,10 @@
 // Point-testing various optimizations in the wasm baseline compiler.
 
-load(libdir + "wasm.js");
-
 // Boolean optimization for control (bug 1286816).
 //
 // These optimizations combine a test (a comparison or Eqz) with an
 // immediately following conditional branch (BrIf, If, and Select), to
 // avoid generating a boolean value that is then tested with a
 // compare-to-zero.
 //
 // On AngryBots as of November 2016, 84% of all test instructions
--- a/js/src/jit-test/tests/wasm/basic.js
+++ b/js/src/jit-test/tests/wasm/basic.js
@@ -1,10 +1,8 @@
-load(libdir + "wasm.js");
-
 const LinkError = WebAssembly.LinkError;
 
 // ----------------------------------------------------------------------------
 // exports
 
 var o = wasmEvalText('(module)').exports;
 assertEq(Object.getOwnPropertyNames(o).length, 0);
 
--- a/js/src/jit-test/tests/wasm/bce.js
+++ b/js/src/jit-test/tests/wasm/bce.js
@@ -1,10 +1,9 @@
 // |jit-test| test-also-wasm-check-bce
-load(libdir + "wasm.js");
 
 mem='\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f'+
     '\xf0\xf1\xf2\xf3\xf4\xf5\xf6\xf7\xf8\xf9\xfa\xfb\xfc\xfd\xfe\xff'+
     '\x00'.repeat(65488) +
     '\xf0\xf1\xf2\xf3\xf4\xf5\xf6\xf7\xf8\xf9\xfa\xfb\xfc\xfd\xfe\xff'
 
 let accessWidth = {
   '8_s':  1,
--- a/js/src/jit-test/tests/wasm/big-resize.js
+++ b/js/src/jit-test/tests/wasm/big-resize.js
@@ -1,10 +1,8 @@
-load(libdir + "wasm.js");
-
 wasmFullPass(`(module
     (memory 1 32768)
     (func $test (result i32)
         (if (i32.eq (grow_memory (i32.const 16384)) (i32.const -1)) (return (i32.const 42)))
         (i32.store (i32.const 1073807356) (i32.const 42))
         (i32.load (i32.const 1073807356)))
     (export "run" $test)
 )`, 42);
--- a/js/src/jit-test/tests/wasm/binary.js
+++ b/js/src/jit-test/tests/wasm/binary.js
@@ -1,9 +1,8 @@
-load(libdir + "wasm.js");
 load(libdir + "wasm-binary.js");
 
 const Module = WebAssembly.Module;
 const CompileError = WebAssembly.CompileError;
 
 const magicError = /failed to match magic number/;
 const unknownSection = /expected custom section/;
 
--- a/js/src/jit-test/tests/wasm/comments.js
+++ b/js/src/jit-test/tests/wasm/comments.js
@@ -1,10 +1,8 @@
-load(libdir + "wasm.js");
-
 // sanity check
 assertErrorMessage(() => wasmEvalText(''), SyntaxError, /parsing wasm text/);
 
 // single line comment
 var o = wasmEvalText('(module (func)) ;; end');
 var o = wasmEvalText('(module (func)) ;; end\n');
 var o = wasmEvalText('(module (func))\n;; end');
 var o = wasmEvalText('(module (func))\n;; end');
--- a/js/src/jit-test/tests/wasm/compiler-frame-depth.js
+++ b/js/src/jit-test/tests/wasm/compiler-frame-depth.js
@@ -1,10 +1,8 @@
-load(libdir + "wasm.js");
-
 // Ensures that the postorder allows us to have very deep expression trees.
 
 var expr = '(get_local 0)';
 
 for (var i = 1000; i --> 0; ) {
     expr = `(f32.neg ${expr})`;
 }
 
--- a/js/src/jit-test/tests/wasm/const.js
+++ b/js/src/jit-test/tests/wasm/const.js
@@ -1,10 +1,8 @@
-load(libdir + "wasm.js");
-
 function testConst(type, str, expect) {
     if (type === 'i64')
         wasmFullPassI64(`(module (func (result i64) (i64.const ${str})) (export "run" 0))`, expect);
     else
         wasmFullPass(`(module (func (result ${type}) (${type}.const ${str})) (export "run" 0))`, expect);
 }
 
 function testConstError(type, str) {
--- a/js/src/jit-test/tests/wasm/control-flow.js
+++ b/js/src/jit-test/tests/wasm/control-flow.js
@@ -1,10 +1,8 @@
-load(libdir + "wasm.js");
-
 const RuntimeError = WebAssembly.RuntimeError;
 
 // ----------------------------------------------------------------------------
 // if
 
 // Condition is an int32
 wasmFailValidateText('(module (func (local f32) (if (get_local 0) (i32.const 1))))', mismatchError("f32", "i32"));
 wasmFailValidateText('(module (func (local f32) (if (get_local 0) (i32.const 1) (i32.const 0))))', mismatchError("f32", "i32"));
--- a/js/src/jit-test/tests/wasm/conversion.js
+++ b/js/src/jit-test/tests/wasm/conversion.js
@@ -1,10 +1,8 @@
-load(libdir + "wasm.js");
-
 function testConversion(resultType, opcode, paramType, op, expect) {
   if (paramType === 'i64') {
     // i64 cannot be imported, so we use a wrapper function.
     wasmFullPass(`(module
                     (func (param i64) (result ${resultType}) (${resultType}.${opcode}/i64 (get_local 0)))
                     (export "run" 0))`, expect, {}, createI64(op));
     // The same, but now the input is a constant.
     wasmFullPass(`(module
--- a/js/src/jit-test/tests/wasm/cross-global.js
+++ b/js/src/jit-test/tests/wasm/cross-global.js
@@ -1,10 +1,8 @@
-load(libdir + "wasm.js");
-
 const Module = WebAssembly.Module;
 
 // Create cross-compartment wrappers to typed arrays and array buffers.
 var g = newGlobal();
 var code1 = g.eval("wasmTextToBinary('(module)')");
 var code2 = g.eval("wasmTextToBinary('(module)').buffer");
 
 // Should get unwrapped.
--- a/js/src/jit-test/tests/wasm/directives.txt
+++ b/js/src/jit-test/tests/wasm/directives.txt
@@ -1,1 +1,1 @@
-|jit-test| test-also-wasm-baseline
+|jit-test| test-also-wasm-baseline; include:wasm.js
--- a/js/src/jit-test/tests/wasm/drop.js
+++ b/js/src/jit-test/tests/wasm/drop.js
@@ -1,10 +1,8 @@
-load(libdir + "wasm.js");
-
 for (let type of ['i32', 'f32', 'f64']) {
     assertEq(wasmEvalText(`
         (module
          (func $test (result ${type}) (param $p ${type}) (param $p2 ${type})
             get_local $p
             get_local $p2
             (block)
             drop
--- a/js/src/jit-test/tests/wasm/errors.js
+++ b/js/src/jit-test/tests/wasm/errors.js
@@ -1,9 +1,8 @@
-load(libdir + "wasm.js");
 load(libdir + "wasm-binary.js");
 
 const Module = WebAssembly.Module;
 const Instance = WebAssembly.Instance;
 const CompileError = WebAssembly.CompileError;
 const RuntimeError = WebAssembly.RuntimeError;
 
 function isWasmFunction(name) {
--- a/js/src/jit-test/tests/wasm/extract-code.js
+++ b/js/src/jit-test/tests/wasm/extract-code.js
@@ -1,10 +1,8 @@
-load(libdir + "wasm.js");
-
 var module = new WebAssembly.Module(wasmTextToBinary(`(module (func (nop)))`));
 var exp = wasmExtractCode(module);
 assertEq(exp.code instanceof Uint8Array, true);
 assertEq(Array.isArray(exp.segments), true);
 var funcs = exp.segments.filter(s => s.kind === 0);
 assertEq(funcs.length, 1);
 assertEq(funcs[0].funcIndex, 0);
 assertEq(funcs[0].begin >= 0, true);
--- a/js/src/jit-test/tests/wasm/fac.js
+++ b/js/src/jit-test/tests/wasm/fac.js
@@ -1,10 +1,8 @@
-load(libdir + "wasm.js");
-
 // This is fac-opt from fac.wast in the official testsuite, changed to use
 // i32 instead of i64.
 assertEq(wasmEvalText(`(module
   (func $fac-opt (param i32) (result i32)
     (local i32)
     (set_local 1 (i32.const 1))
     (block
       (br_if 0 (i32.lt_s (get_local 0) (i32.const 2)))
--- a/js/src/jit-test/tests/wasm/float.js
+++ b/js/src/jit-test/tests/wasm/float.js
@@ -1,10 +1,8 @@
-load(libdir + "wasm.js");
-
 wasmFullPass('(module (func (result f32) (f32.const -1)) (export "run" 0))', -1);
 wasmFullPass('(module (func (result f32) (f32.const 1)) (export "run" 0))', 1);
 wasmFullPass('(module (func (result f64) (f64.const -2)) (export "run" 0))', -2);
 wasmFullPass('(module (func (result f64) (f64.const 2)) (export "run" 0))', 2);
 wasmFullPass('(module (func (result f64) (f64.const 4294967296)) (export "run" 0))', 4294967296);
 wasmFullPass('(module (func (result f32) (f32.const 1.5)) (export "run" 0))', 1.5);
 wasmFullPass('(module (func (result f64) (f64.const 2.5)) (export "run" 0))', 2.5);
 wasmFullPass('(module (func (result f64) (f64.const 10e2)) (export "run" 0))', 10e2);
--- a/js/src/jit-test/tests/wasm/full-cycle.js
+++ b/js/src/jit-test/tests/wasm/full-cycle.js
@@ -1,10 +1,8 @@
-load(libdir + "wasm.js");
-
 wasmFullPass(`(module
     (func $test (result i32) (param i32) (param i32) (i32.add (get_local 0) (get_local 1)))
     (func $run (result i32) (call $test (i32.const 1) (i32.const ${Math.pow(2, 31) - 1})))
     (export "run" $run)
 )`, -Math.pow(2, 31));
 
 wasmFullPass(`(module
     (func (result i32)
--- a/js/src/jit-test/tests/wasm/globals.js
+++ b/js/src/jit-test/tests/wasm/globals.js
@@ -1,10 +1,8 @@
-load(libdir + "wasm.js");
-
 const { Instance, Module } = WebAssembly;
 
 // Locally-defined globals
 assertErrorMessage(() => wasmEvalText(`(module (global))`), SyntaxError, /parsing/);
 assertErrorMessage(() => wasmEvalText(`(module (global i32))`), SyntaxError, /parsing/);
 assertErrorMessage(() => wasmEvalText(`(module (global (mut i32)))`), SyntaxError, /parsing/);
 
 // Initializer expressions.
--- a/js/src/jit-test/tests/wasm/grow-memory.js
+++ b/js/src/jit-test/tests/wasm/grow-memory.js
@@ -1,10 +1,8 @@
-load(libdir + "wasm.js");
-
 function linearModule(min, max, ops) {
   var opsText = ops.map(function (op) {
     if (op[0] == "CM") {
       res = `(if i32 (i32.ne (current_memory) (i32.const ${op[1]}))
                   (i32.load offset=10 (i32.const 4294967295))
                   (i32.const 0))`
     } else if (op[0] == "GM") {
       res = `(if i32 (i32.ne (grow_memory (i32.const ${op[1]})) (i32.const ${op[2]}))
--- a/js/src/jit-test/tests/wasm/import-export.js
+++ b/js/src/jit-test/tests/wasm/import-export.js
@@ -1,10 +1,8 @@
-load(libdir + 'wasm.js');
-
 const Module = WebAssembly.Module;
 const Instance = WebAssembly.Instance;
 const Memory = WebAssembly.Memory;
 const Table = WebAssembly.Table;
 const LinkError = WebAssembly.LinkError;
 
 const mem1Page = new Memory({initial:1});
 const mem1PageMax1 = new Memory({initial:1, maximum: 1});
--- a/js/src/jit-test/tests/wasm/import-gc.js
+++ b/js/src/jit-test/tests/wasm/import-gc.js
@@ -1,14 +1,12 @@
 // |jit-test| --no-baseline
 // Turn off baseline and since it messes up the GC finalization assertions by
 // adding spurious edges to the GC graph.
 
-load(libdir + 'wasm.js');
-
 const Module = WebAssembly.Module;
 const Instance = WebAssembly.Instance;
 
 const m1 = new Module(wasmTextToBinary(`(module (func $f) (export "f" $f))`));
 const m2 = new Module(wasmTextToBinary(`(module (import "a" "f") (func $f) (export "g" $f))`));
 
 // Imported instance objects should stay alive as long as any importer is alive.
 resetFinalizeCount();
--- a/js/src/jit-test/tests/wasm/integer.js
+++ b/js/src/jit-test/tests/wasm/integer.js
@@ -1,10 +1,8 @@
-load(libdir + "wasm.js");
-
 assertEq(wasmEvalText('(module (func (result i32) (i32.const -1)) (export "" 0))').exports[""](), -1);
 assertEq(wasmEvalText('(module (func (result i32) (i32.const -2147483648)) (export "" 0))').exports[""](), -2147483648);
 assertEq(wasmEvalText('(module (func (result i32) (i32.const 4294967295)) (export "" 0))').exports[""](), -1);
 
 function testUnary(type, opcode, op, expect) {
     var fullPass = wasmFullPass;
     if (type === 'i64') {
         expect = createI64(expect);
--- a/js/src/jit-test/tests/wasm/js-reexport.js
+++ b/js/src/jit-test/tests/wasm/js-reexport.js
@@ -1,10 +1,8 @@
-load(libdir + "wasm.js");
-
 const Module = WebAssembly.Module;
 const Instance = WebAssembly.Instance;
 const Memory = WebAssembly.Memory;
 const Table = WebAssembly.Table;
 
 function accum(...args) {
     var sum = 0;
     for (var i = 0; i < args.length; i++)
deleted file mode 100644
--- a/js/src/jit-test/tests/wasm/jsapi.js
+++ /dev/null
@@ -1,541 +0,0 @@
-load(libdir + 'wasm.js');
-
-const WasmPage = 64 * 1024;
-
-const emptyModuleBinary = wasmTextToBinary('(module)');
-const exportingModuleBinary = wasmTextToBinary('(module (func (export "f") (result i32) (i32.const 42)))');
-const importingModuleBinary = wasmTextToBinary('(module (func (import "" "f")))');
-
-// 'WebAssembly' data property on global object
-const wasmDesc = Object.getOwnPropertyDescriptor(this, 'WebAssembly');
-assertEq(typeof wasmDesc.value, "object");
-assertEq(wasmDesc.writable, true);
-assertEq(wasmDesc.enumerable, false);
-assertEq(wasmDesc.configurable, true);
-
-// 'WebAssembly' object
-assertEq(WebAssembly, wasmDesc.value);
-assertEq(String(WebAssembly), "[object WebAssembly]");
-
-// 'WebAssembly.(Compile|Link|Runtime)Error' data property
-const compileErrorDesc = Object.getOwnPropertyDescriptor(WebAssembly, 'CompileError');
-const linkErrorDesc = Object.getOwnPropertyDescriptor(WebAssembly, 'LinkError');
-const runtimeErrorDesc = Object.getOwnPropertyDescriptor(WebAssembly, 'RuntimeError');
-assertEq(typeof compileErrorDesc.value, "function");
-assertEq(typeof linkErrorDesc.value, "function");
-assertEq(typeof runtimeErrorDesc.value, "function");
-assertEq(compileErrorDesc.writable, true);
-assertEq(linkErrorDesc.writable, true);
-assertEq(runtimeErrorDesc.writable, true);
-assertEq(compileErrorDesc.enumerable, false);
-assertEq(linkErrorDesc.enumerable, false);
-assertEq(runtimeErrorDesc.enumerable, false);
-assertEq(compileErrorDesc.configurable, true);
-assertEq(linkErrorDesc.configurable, true);
-assertEq(runtimeErrorDesc.configurable, true);
-
-// 'WebAssembly.(Compile|Runtime)Error' constructor function
-const CompileError = WebAssembly.CompileError;
-const LinkError = WebAssembly.LinkError;
-const RuntimeError = WebAssembly.RuntimeError;
-assertEq(CompileError, compileErrorDesc.value);
-assertEq(LinkError, linkErrorDesc.value);
-assertEq(RuntimeError, runtimeErrorDesc.value);
-assertEq(CompileError.length, 1);
-assertEq(LinkError.length, 1);
-assertEq(RuntimeError.length, 1);
-assertEq(CompileError.name, "CompileError");
-assertEq(LinkError.name, "LinkError");
-assertEq(RuntimeError.name, "RuntimeError");
-
-// 'WebAssembly.(Compile|Runtime)Error' instance objects
-const compileError = new CompileError;
-const runtimeError = new RuntimeError;
-assertEq(compileError instanceof CompileError, true);
-assertEq(runtimeError instanceof RuntimeError, true);
-assertEq(compileError instanceof Error, true);
-assertEq(runtimeError instanceof Error, true);
-assertEq(compileError instanceof TypeError, false);
-assertEq(runtimeError instanceof TypeError, false);
-assertEq(compileError.message, "");
-assertEq(runtimeError.message, "");
-assertEq(new CompileError("hi").message, "hi");
-assertEq(new RuntimeError("hi").message, "hi");
-
-// 'WebAssembly.Module' data property
-const moduleDesc = Object.getOwnPropertyDescriptor(WebAssembly, 'Module');
-assertEq(typeof moduleDesc.value, "function");
-assertEq(moduleDesc.writable, true);
-assertEq(moduleDesc.enumerable, false);
-assertEq(moduleDesc.configurable, true);
-
-// 'WebAssembly.Module' constructor function
-const Module = WebAssembly.Module;
-assertEq(Module, moduleDesc.value);
-assertEq(Module.length, 1);
-assertEq(Module.name, "Module");
-assertErrorMessage(() => Module(), TypeError, /constructor without new is forbidden/);
-assertErrorMessage(() => new Module(), TypeError, /requires more than 0 arguments/);
-assertErrorMessage(() => new Module(undefined), TypeError, "first argument must be an ArrayBuffer or typed array object");
-assertErrorMessage(() => new Module(1), TypeError, "first argument must be an ArrayBuffer or typed array object");
-assertErrorMessage(() => new Module({}), TypeError, "first argument must be an ArrayBuffer or typed array object");
-assertErrorMessage(() => new Module(new Uint8Array()), CompileError, /failed to match magic number/);
-assertErrorMessage(() => new Module(new ArrayBuffer()), CompileError, /failed to match magic number/);
-assertEq(new Module(emptyModuleBinary) instanceof Module, true);
-assertEq(new Module(emptyModuleBinary.buffer) instanceof Module, true);
-
-// 'WebAssembly.Module.prototype' data property
-const moduleProtoDesc = Object.getOwnPropertyDescriptor(Module, 'prototype');
-assertEq(typeof moduleProtoDesc.value, "object");
-assertEq(moduleProtoDesc.writable, false);
-assertEq(moduleProtoDesc.enumerable, false);
-assertEq(moduleProtoDesc.configurable, false);
-
-// 'WebAssembly.Module.prototype' object
-const moduleProto = Module.prototype;
-assertEq(moduleProto, moduleProtoDesc.value);
-assertEq(String(moduleProto), "[object Object]");
-assertEq(Object.getPrototypeOf(moduleProto), Object.prototype);
-
-// 'WebAssembly.Module' instance objects
-const emptyModule = new Module(emptyModuleBinary);
-const importingModule = new Module(importingModuleBinary);
-const exportingModule = new Module(exportingModuleBinary);
-assertEq(typeof emptyModule, "object");
-assertEq(String(emptyModule), "[object WebAssembly.Module]");
-assertEq(Object.getPrototypeOf(emptyModule), moduleProto);
-
-// 'WebAssembly.Module.imports' data property
-const moduleImportsDesc = Object.getOwnPropertyDescriptor(Module, 'imports');
-assertEq(typeof moduleImportsDesc.value, "function");
-assertEq(moduleImportsDesc.writable, true);
-assertEq(moduleImportsDesc.enumerable, false);
-assertEq(moduleImportsDesc.configurable, true);
-
-// 'WebAssembly.Module.imports' method
-const moduleImports = moduleImportsDesc.value;
-assertEq(moduleImports.length, 1);
-assertErrorMessage(() => moduleImports(), TypeError, /requires more than 0 arguments/);
-assertErrorMessage(() => moduleImports(undefined), TypeError, /first argument must be a WebAssembly.Module/);
-assertErrorMessage(() => moduleImports({}), TypeError, /first argument must be a WebAssembly.Module/);
-var arr = moduleImports(new Module(wasmTextToBinary('(module)')));
-assertEq(arr instanceof Array, true);
-assertEq(arr.length, 0);
-var arr = moduleImports(new Module(wasmTextToBinary('(module (func (import "a" "b")) (memory (import "c" "d") 1) (table (import "e" "f") 1 anyfunc) (global (import "g" "⚡") i32))')));
-assertEq(arr instanceof Array, true);
-assertEq(arr.length, 4);
-assertEq(arr[0].kind, "function");
-assertEq(arr[0].module, "a");
-assertEq(arr[0].name, "b");
-assertEq(arr[1].kind, "memory");
-assertEq(arr[1].module, "c");
-assertEq(arr[1].name, "d");
-assertEq(arr[2].kind, "table");
-assertEq(arr[2].module, "e");
-assertEq(arr[2].name, "f");
-assertEq(arr[3].kind, "global");
-assertEq(arr[3].module, "g");
-assertEq(arr[3].name, "⚡");
-
-// 'WebAssembly.Module.exports' data property
-const moduleExportsDesc = Object.getOwnPropertyDescriptor(Module, 'exports');
-assertEq(typeof moduleExportsDesc.value, "function");
-assertEq(moduleExportsDesc.writable, true);
-assertEq(moduleExportsDesc.enumerable, false);
-assertEq(moduleExportsDesc.configurable, true);
-
-// 'WebAssembly.Module.exports' method
-const moduleExports = moduleExportsDesc.value;
-assertEq(moduleExports.length, 1);
-assertErrorMessage(() => moduleExports(), TypeError, /requires more than 0 arguments/);
-assertErrorMessage(() => moduleExports(undefined), TypeError, /first argument must be a WebAssembly.Module/);
-assertErrorMessage(() => moduleExports({}), TypeError, /first argument must be a WebAssembly.Module/);
-var arr = moduleExports(emptyModule);
-assertEq(arr instanceof Array, true);
-assertEq(arr.length, 0);
-var arr = moduleExports(new Module(wasmTextToBinary('(module (func (export "a")) (memory (export "b") 1) (table (export "c") 1 anyfunc) (global (export "⚡") i32 (i32.const 0)))')));
-assertEq(arr instanceof Array, true);
-assertEq(arr.length, 4);
-assertEq(arr[0].kind, "function");
-assertEq(arr[0].name, "a");
-assertEq(arr[1].kind, "memory");
-assertEq(arr[1].name, "b");
-assertEq(arr[2].kind, "table");
-assertEq(arr[2].name, "c");
-assertEq(arr[3].kind, "global");
-assertEq(arr[3].name, "⚡");
-
-// 'WebAssembly.Module.customSections' data property
-const customSectionsDesc = Object.getOwnPropertyDescriptor(Module, 'customSections');
-assertEq(typeof customSectionsDesc.value, "function");
-assertEq(customSectionsDesc.writable, true);
-assertEq(customSectionsDesc.enumerable, false);
-assertEq(customSectionsDesc.configurable, true);
-
-// 'WebAssembly.Module.customSections' method
-const moduleCustomSections = customSectionsDesc.value;
-assertEq(moduleCustomSections.length, 2);
-assertErrorMessage(() => moduleCustomSections(), TypeError, /requires more than 0 arguments/);
-assertErrorMessage(() => moduleCustomSections(undefined), TypeError, /first argument must be a WebAssembly.Module/);
-assertErrorMessage(() => moduleCustomSections({}), TypeError, /first argument must be a WebAssembly.Module/);
-var arr = moduleCustomSections(emptyModule);
-assertEq(arr instanceof Array, true);
-assertEq(arr.length, 0);
-
-// 'WebAssembly.Instance' data property
-const instanceDesc = Object.getOwnPropertyDescriptor(WebAssembly, 'Instance');
-assertEq(typeof instanceDesc.value, "function");
-assertEq(instanceDesc.writable, true);
-assertEq(instanceDesc.enumerable, false);
-assertEq(instanceDesc.configurable, true);
-
-// 'WebAssembly.Instance' constructor function
-const Instance = WebAssembly.Instance;
-assertEq(Instance, instanceDesc.value);
-assertEq(Instance.length, 1);
-assertEq(Instance.name, "Instance");
-assertErrorMessage(() => Instance(), TypeError, /constructor without new is forbidden/);
-assertErrorMessage(() => new Instance(1), TypeError, "first argument must be a WebAssembly.Module");
-assertErrorMessage(() => new Instance({}), TypeError, "first argument must be a WebAssembly.Module");
-assertErrorMessage(() => new Instance(emptyModule, null), TypeError, "second argument must be an object");
-assertEq(new Instance(emptyModule) instanceof Instance, true);
-assertEq(new Instance(emptyModule, {}) instanceof Instance, true);
-
-// 'WebAssembly.Instance.prototype' data property
-const instanceProtoDesc = Object.getOwnPropertyDescriptor(Instance, 'prototype');
-assertEq(typeof instanceProtoDesc.value, "object");
-assertEq(instanceProtoDesc.writable, false);
-assertEq(instanceProtoDesc.enumerable, false);
-assertEq(instanceProtoDesc.configurable, false);
-
-// 'WebAssembly.Instance.prototype' object
-const instanceProto = Instance.prototype;
-assertEq(instanceProto, instanceProtoDesc.value);
-assertEq(String(instanceProto), "[object Object]");
-assertEq(Object.getPrototypeOf(instanceProto), Object.prototype);
-
-// 'WebAssembly.Instance' instance objects
-const exportingInstance = new Instance(exportingModule);
-assertEq(typeof exportingInstance, "object");
-assertEq(String(exportingInstance), "[object WebAssembly.Instance]");
-assertEq(Object.getPrototypeOf(exportingInstance), instanceProto);
-
-// 'WebAssembly.Instance' 'exports' data property
-const instanceExportsDesc = Object.getOwnPropertyDescriptor(exportingInstance, 'exports');
-assertEq(typeof instanceExportsDesc.value, "object");
-assertEq(instanceExportsDesc.writable, true);
-assertEq(instanceExportsDesc.enumerable, true);
-assertEq(instanceExportsDesc.configurable, true);
-
-// 'WebAssembly.Instance' 'exports' object
-const exportsObj = exportingInstance.exports;
-assertEq(typeof exportsObj, "object");
-assertEq(Object.isExtensible(exportsObj), false);
-assertEq(Object.getPrototypeOf(exportsObj), null);
-assertEq(Object.keys(exportsObj).join(), "f");
-exportsObj.g = 1;
-assertEq(Object.keys(exportsObj).join(), "f");
-assertErrorMessage(() => Object.setPrototypeOf(exportsObj, {}), TypeError, /can't set prototype of this object/);
-assertEq(Object.getPrototypeOf(exportsObj), null);
-assertErrorMessage(() => Object.defineProperty(exportsObj, 'g', {}), TypeError, /Object is not extensible/);
-assertEq(Object.keys(exportsObj).join(), "f");
-
-// Exported WebAssembly functions
-const f = exportsObj.f;
-assertEq(f instanceof Function, true);
-assertEq(f.length, 0);
-assertEq('name' in f, true);
-assertEq(Function.prototype.call.call(f), 42);
-assertErrorMessage(() => new f(), TypeError, /is not a constructor/);
-
-// 'WebAssembly.Memory' data property
-const memoryDesc = Object.getOwnPropertyDescriptor(WebAssembly, 'Memory');
-assertEq(typeof memoryDesc.value, "function");
-assertEq(memoryDesc.writable, true);
-assertEq(memoryDesc.enumerable, false);
-assertEq(memoryDesc.configurable, true);
-
-// 'WebAssembly.Memory' constructor function
-const Memory = WebAssembly.Memory;
-assertEq(Memory, memoryDesc.value);
-assertEq(Memory.length, 1);
-assertEq(Memory.name, "Memory");
-assertErrorMessage(() => Memory(), TypeError, /constructor without new is forbidden/);
-assertErrorMessage(() => new Memory(1), TypeError, "first argument must be a memory descriptor");
-assertErrorMessage(() => new Memory({initial:{valueOf() { throw new Error("here")}}}), Error, "here");
-assertErrorMessage(() => new Memory({initial:-1}), RangeError, /bad Memory initial size/);
-assertErrorMessage(() => new Memory({initial:Math.pow(2,32)}), RangeError, /bad Memory initial size/);
-assertErrorMessage(() => new Memory({initial:1, maximum: Math.pow(2,32)/Math.pow(2,14) }), RangeError, /bad Memory maximum size/);
-assertErrorMessage(() => new Memory({initial:2, maximum:1 }), RangeError, /bad Memory maximum size/);
-assertErrorMessage(() => new Memory({maximum: -1 }), RangeError, /bad Memory maximum size/);
-assertEq(new Memory({initial:1}) instanceof Memory, true);
-assertEq(new Memory({initial:1.5}).buffer.byteLength, WasmPage);
-
-// 'WebAssembly.Memory.prototype' data property
-const memoryProtoDesc = Object.getOwnPropertyDescriptor(Memory, 'prototype');
-assertEq(typeof memoryProtoDesc.value, "object");
-assertEq(memoryProtoDesc.writable, false);
-assertEq(memoryProtoDesc.enumerable, false);
-assertEq(memoryProtoDesc.configurable, false);
-
-// 'WebAssembly.Memory.prototype' object
-const memoryProto = Memory.prototype;
-assertEq(memoryProto, memoryProtoDesc.value);
-assertEq(String(memoryProto), "[object Object]");
-assertEq(Object.getPrototypeOf(memoryProto), Object.prototype);
-
-// 'WebAssembly.Memory' instance objects
-const mem1 = new Memory({initial:1});
-assertEq(typeof mem1, "object");
-assertEq(String(mem1), "[object WebAssembly.Memory]");
-assertEq(Object.getPrototypeOf(mem1), memoryProto);
-
-// 'WebAssembly.Memory.prototype.buffer' accessor property
-const bufferDesc = Object.getOwnPropertyDescriptor(memoryProto, 'buffer');
-assertEq(typeof bufferDesc.get, "function");
-assertEq(bufferDesc.set, undefined);
-assertEq(bufferDesc.enumerable, false);
-assertEq(bufferDesc.configurable, true);
-
-// 'WebAssembly.Memory.prototype.buffer' getter
-const bufferGetter = bufferDesc.get;
-assertErrorMessage(() => bufferGetter.call(), TypeError, /called on incompatible undefined/);
-assertErrorMessage(() => bufferGetter.call({}), TypeError, /called on incompatible Object/);
-assertEq(bufferGetter.call(mem1) instanceof ArrayBuffer, true);
-assertEq(bufferGetter.call(mem1).byteLength, WasmPage);
-
-// 'WebAssembly.Memory.prototype.grow' data property
-const memGrowDesc = Object.getOwnPropertyDescriptor(memoryProto, 'grow');
-assertEq(typeof memGrowDesc.value, "function");
-assertEq(memGrowDesc.enumerable, false);
-assertEq(memGrowDesc.configurable, true);
-
-// 'WebAssembly.Memory.prototype.grow' method
-const memGrow = memGrowDesc.value;
-assertEq(memGrow.length, 1);
-assertErrorMessage(() => memGrow.call(), TypeError, /called on incompatible undefined/);
-assertErrorMessage(() => memGrow.call({}), TypeError, /called on incompatible Object/);
-assertErrorMessage(() => memGrow.call(mem1, -1), RangeError, /bad Memory grow delta/);
-assertErrorMessage(() => memGrow.call(mem1, Math.pow(2,32)), RangeError, /bad Memory grow delta/);
-var mem = new Memory({initial:1, maximum:2});
-var buf = mem.buffer;
-assertEq(buf.byteLength, WasmPage);
-assertEq(mem.grow(0), 1);
-assertEq(buf !== mem.buffer, true);
-assertEq(buf.byteLength, 0);
-buf = mem.buffer;
-assertEq(buf.byteLength, WasmPage);
-assertEq(mem.grow(1), 1);
-assertEq(buf !== mem.buffer, true);
-assertEq(buf.byteLength, 0);
-buf = mem.buffer;
-assertEq(buf.byteLength, 2 * WasmPage);
-assertErrorMessage(() => mem.grow(1), Error, /failed to grow memory/);
-assertEq(buf, mem.buffer);
-
-// 'WebAssembly.Table' data property
-const tableDesc = Object.getOwnPropertyDescriptor(WebAssembly, 'Table');
-assertEq(typeof tableDesc.value, "function");
-assertEq(tableDesc.writable, true);
-assertEq(tableDesc.enumerable, false);
-assertEq(tableDesc.configurable, true);
-
-// 'WebAssembly.Table' constructor function
-const Table = WebAssembly.Table;
-assertEq(Table, tableDesc.value);
-assertEq(Table.length, 1);
-assertEq(Table.name, "Table");
-assertErrorMessage(() => Table(), TypeError, /constructor without new is forbidden/);
-assertErrorMessage(() => new Table(1), TypeError, "first argument must be a table descriptor");
-assertErrorMessage(() => new Table({initial:1, element:1}), TypeError, /must be "anyfunc"/);
-assertErrorMessage(() => new Table({initial:1, element:"any"}), TypeError, /must be "anyfunc"/);
-assertErrorMessage(() => new Table({initial:1, element:{valueOf() { return "anyfunc" }}}), TypeError, /must be "anyfunc"/);
-assertErrorMessage(() => new Table({initial:{valueOf() { throw new Error("here")}}, element:"anyfunc"}), Error, "here");
-assertErrorMessage(() => new Table({initial:-1, element:"anyfunc"}), RangeError, /bad Table initial size/);
-assertErrorMessage(() => new Table({initial:Math.pow(2,32), element:"anyfunc"}), RangeError, /bad Table initial size/);
-assertErrorMessage(() => new Table({initial:2, maximum:1, element:"anyfunc"}), RangeError, /bad Table maximum size/);
-assertErrorMessage(() => new Table({initial:2, maximum:Math.pow(2,32), element:"anyfunc"}), RangeError, /bad Table maximum size/);
-assertEq(new Table({initial:1, element:"anyfunc"}) instanceof Table, true);
-assertEq(new Table({initial:1.5, element:"anyfunc"}) instanceof Table, true);
-assertEq(new Table({initial:1, maximum:1.5, element:"anyfunc"}) instanceof Table, true);
-assertEq(new Table({initial:1, maximum:Math.pow(2,32)-1, element:"anyfunc"}) instanceof Table, true);
-
-// 'WebAssembly.Table.prototype' data property
-const tableProtoDesc = Object.getOwnPropertyDescriptor(Table, 'prototype');
-assertEq(typeof tableProtoDesc.value, "object");
-assertEq(tableProtoDesc.writable, false);
-assertEq(tableProtoDesc.enumerable, false);
-assertEq(tableProtoDesc.configurable, false);
-
-// 'WebAssembly.Table.prototype' object
-const tableProto = Table.prototype;
-assertEq(tableProto, tableProtoDesc.value);
-assertEq(String(tableProto), "[object Object]");
-assertEq(Object.getPrototypeOf(tableProto), Object.prototype);
-
-// 'WebAssembly.Table' instance objects
-const tbl1 = new Table({initial:2, element:"anyfunc"});
-assertEq(typeof tbl1, "object");
-assertEq(String(tbl1), "[object WebAssembly.Table]");
-assertEq(Object.getPrototypeOf(tbl1), tableProto);
-
-// 'WebAssembly.Table.prototype.length' accessor data property
-const lengthDesc = Object.getOwnPropertyDescriptor(tableProto, 'length');
-assertEq(typeof lengthDesc.get, "function");
-assertEq(lengthDesc.set, undefined);
-assertEq(lengthDesc.enumerable, false);
-assertEq(lengthDesc.configurable, true);
-
-// 'WebAssembly.Table.prototype.length' getter
-const lengthGetter = lengthDesc.get;
-assertEq(lengthGetter.length, 0);
-assertErrorMessage(() => lengthGetter.call(), TypeError, /called on incompatible undefined/);
-assertErrorMessage(() => lengthGetter.call({}), TypeError, /called on incompatible Object/);
-assertEq(typeof lengthGetter.call(tbl1), "number");
-assertEq(lengthGetter.call(tbl1), 2);
-
-// 'WebAssembly.Table.prototype.get' data property
-const getDesc = Object.getOwnPropertyDescriptor(tableProto, 'get');
-assertEq(typeof getDesc.value, "function");
-assertEq(getDesc.enumerable, false);
-assertEq(getDesc.configurable, true);
-
-// 'WebAssembly.Table.prototype.get' method
-const get = getDesc.value;
-assertEq(get.length, 1);
-assertErrorMessage(() => get.call(), TypeError, /called on incompatible undefined/);
-assertErrorMessage(() => get.call({}), TypeError, /called on incompatible Object/);
-assertEq(get.call(tbl1, 0), null);
-assertEq(get.call(tbl1, 1), null);
-assertEq(get.call(tbl1, 1.5), null);
-assertErrorMessage(() => get.call(tbl1, 2), RangeError, /bad Table get index/);
-assertErrorMessage(() => get.call(tbl1, 2.5), RangeError, /bad Table get index/);
-assertErrorMessage(() => get.call(tbl1, -1), RangeError, /bad Table get index/);
-assertErrorMessage(() => get.call(tbl1, Math.pow(2,33)), RangeError, /bad Table get index/);
-assertErrorMessage(() => get.call(tbl1, {valueOf() { throw new Error("hi") }}), Error, "hi");
-
-// 'WebAssembly.Table.prototype.set' data property
-const setDesc = Object.getOwnPropertyDescriptor(tableProto, 'set');
-assertEq(typeof setDesc.value, "function");
-assertEq(setDesc.enumerable, false);
-assertEq(setDesc.configurable, true);
-
-// 'WebAssembly.Table.prototype.set' method
-const set = setDesc.value;
-assertEq(set.length, 2);
-assertErrorMessage(() => set.call(), TypeError, /called on incompatible undefined/);
-assertErrorMessage(() => set.call({}), TypeError, /called on incompatible Object/);
-assertErrorMessage(() => set.call(tbl1, 0), TypeError, /requires more than 1 argument/);
-assertErrorMessage(() => set.call(tbl1, 2, null), RangeError, /bad Table set index/);
-assertErrorMessage(() => set.call(tbl1, -1, null), RangeError, /bad Table set index/);
-assertErrorMessage(() => set.call(tbl1, Math.pow(2,33), null), RangeError, /bad Table set index/);
-assertErrorMessage(() => set.call(tbl1, 0, undefined), TypeError, /can only assign WebAssembly exported functions to Table/);
-assertErrorMessage(() => set.call(tbl1, 0, {}), TypeError, /can only assign WebAssembly exported functions to Table/);
-assertErrorMessage(() => set.call(tbl1, 0, function() {}), TypeError, /can only assign WebAssembly exported functions to Table/);
-assertErrorMessage(() => set.call(tbl1, 0, Math.sin), TypeError, /can only assign WebAssembly exported functions to Table/);
-assertErrorMessage(() => set.call(tbl1, {valueOf() { throw Error("hai") }}, null), Error, "hai");
-assertEq(set.call(tbl1, 0, null), undefined);
-assertEq(set.call(tbl1, 1, null), undefined);
-
-// 'WebAssembly.Table.prototype.grow' data property
-const tblGrowDesc = Object.getOwnPropertyDescriptor(tableProto, 'grow');
-assertEq(typeof tblGrowDesc.value, "function");
-assertEq(tblGrowDesc.enumerable, false);
-assertEq(tblGrowDesc.configurable, true);
-
-// 'WebAssembly.Table.prototype.grow' method
-const tblGrow = tblGrowDesc.value;
-assertEq(tblGrow.length, 1);
-assertErrorMessage(() => tblGrow.call(), TypeError, /called on incompatible undefined/);
-assertErrorMessage(() => tblGrow.call({}), TypeError, /called on incompatible Object/);
-assertErrorMessage(() => tblGrow.call(tbl1, -1), RangeError, /bad Table grow delta/);
-assertErrorMessage(() => tblGrow.call(tbl1, Math.pow(2,32)), RangeError, /bad Table grow delta/);
-var tbl = new Table({element:"anyfunc", initial:1, maximum:2});
-assertEq(tbl.length, 1);
-assertEq(tbl.grow(0), 1);
-assertEq(tbl.length, 1);
-assertEq(tbl.grow(1), 1);
-assertEq(tbl.length, 2);
-assertErrorMessage(() => tbl.grow(1), Error, /failed to grow table/);
-
-// 'WebAssembly.compile' data property
-const compileDesc = Object.getOwnPropertyDescriptor(WebAssembly, 'compile');
-assertEq(typeof compileDesc.value, "function");
-assertEq(compileDesc.writable, true);
-assertEq(compileDesc.enumerable, false);
-assertEq(compileDesc.configurable, true);
-
-// 'WebAssembly.compile' function
-const compile = WebAssembly.compile;
-assertEq(compile, compileDesc.value);
-assertEq(compile.length, 1);
-assertEq(compile.name, "compile");
-function assertCompileError(args, err, msg) {
-    var error = null;
-    compile(...args).catch(e => error = e);
-    drainJobQueue();
-    assertEq(error instanceof err, true);
-    assertEq(Boolean(error.stack.match("jsapi.js")), true);
-    assertEq(Boolean(error.message.match(msg)), true);
-}
-assertCompileError([], TypeError, /requires more than 0 arguments/);
-assertCompileError([undefined], TypeError, /first argument must be an ArrayBuffer or typed array object/);
-assertCompileError([1], TypeError, /first argument must be an ArrayBuffer or typed array object/);
-assertCompileError([{}], TypeError, /first argument must be an ArrayBuffer or typed array object/);
-assertCompileError([new Uint8Array()], CompileError, /failed to match magic number/);
-assertCompileError([new ArrayBuffer()], CompileError, /failed to match magic number/);
-function assertCompileSuccess(bytes) {
-    var module = null;
-    compile(bytes).then(m => module = m);
-    drainJobQueue();
-    assertEq(module instanceof Module, true);
-}
-assertCompileSuccess(emptyModuleBinary);
-assertCompileSuccess(emptyModuleBinary.buffer);
-
-// 'WebAssembly.instantiate' data property
-const instantiateDesc = Object.getOwnPropertyDescriptor(WebAssembly, 'instantiate');
-assertEq(typeof instantiateDesc.value, "function");
-assertEq(instantiateDesc.writable, true);
-assertEq(instantiateDesc.enumerable, false);
-assertEq(instantiateDesc.configurable, true);
-
-// 'WebAssembly.instantiate' function
-const instantiate = WebAssembly.instantiate;
-assertEq(instantiate, instantiateDesc.value);
-assertEq(instantiate.length, 2);
-assertEq(instantiate.name, "instantiate");
-function assertInstantiateError(args, err, msg) {
-    var error = null;
-    instantiate(...args).catch(e => error = e);
-    drainJobQueue();
-    assertEq(error instanceof err, true);
-    assertEq(Boolean(error.stack.match("jsapi.js")), true);
-    assertEq(Boolean(error.message.match(msg)), true);
-}
-assertInstantiateError([], TypeError, /requires more than 0 arguments/);
-assertInstantiateError([undefined], TypeError, /first argument must be a WebAssembly.Module, ArrayBuffer or typed array object/);
-assertInstantiateError([1], TypeError, /first argument must be a WebAssembly.Module, ArrayBuffer or typed array object/);
-assertInstantiateError([{}], TypeError, /first argument must be a WebAssembly.Module, ArrayBuffer or typed array object/);
-assertInstantiateError([new Uint8Array()], CompileError, /failed to match magic number/);
-assertInstantiateError([new ArrayBuffer()], CompileError, /failed to match magic number/);
-assertInstantiateError([importingModule], TypeError, /second argument must be an object/);
-assertInstantiateError([importingModule, null], TypeError, /second argument must be an object/);
-assertInstantiateError([importingModuleBinary, null], TypeError, /second argument must be an object/);
-function assertInstantiateSuccess(module, imports) {
-    var result = null;
-    instantiate(module, imports).then(r => result = r);
-    drainJobQueue();
-    if (module instanceof Module) {
-        assertEq(result instanceof Instance, true);
-    } else {
-        assertEq(result.module instanceof Module, true);
-        assertEq(result.instance instanceof Instance, true);
-    }
-}
-assertInstantiateSuccess(emptyModule);
-assertInstantiateSuccess(emptyModuleBinary);
-assertInstantiateSuccess(emptyModuleBinary.buffer);
-assertInstantiateSuccess(importingModule, {"":{f:()=>{}}});
-assertInstantiateSuccess(importingModuleBinary, {"":{f:()=>{}}});
-assertInstantiateSuccess(importingModuleBinary.buffer, {"":{f:()=>{}}});
--- a/js/src/jit-test/tests/wasm/memory-aliasing.js
+++ b/js/src/jit-test/tests/wasm/memory-aliasing.js
@@ -1,10 +1,8 @@
-load(libdir + "wasm.js");
-
 var i = wasmEvalText(
 `(module
    (memory 1) (data (i32.const 0) "\\01\\02\\03\\04\\05\\06\\07\\08")
    (func $off1 (param $base i32) (result i32)
      (i32.add
        (i32.load8_u (get_local $base))
        (i32.load8_u offset=1 (get_local $base)))
    )
--- a/js/src/jit-test/tests/wasm/memory.js
+++ b/js/src/jit-test/tests/wasm/memory.js
@@ -1,10 +1,9 @@
 // |jit-test| test-also-wasm-check-bce
-load(libdir + "wasm.js");
 
 const RuntimeError = WebAssembly.RuntimeError;
 
 function loadModule(type, ext, offset, align) {
     return wasmEvalText(
     `(module
        (memory 1)
        (data (i32.const 0) "\\00\\01\\02\\03\\04\\05\\06\\07\\08\\09\\0a\\0b\\0c\\0d\\0e\\0f")
@@ -271,17 +270,18 @@ for (var foldOffsets = 0; foldOffsets <=
 
     wasmFailValidateText('(module (memory 1) (func (f32.store offset=0 (i32.const 0) (i32.const 0))))', mismatchError("i32", "f32"));
     wasmFailValidateText('(module (memory 1) (func (f32.store offset=0 (i32.const 0) (f64.const 0))))', mismatchError("f64", "f32"));
 
     wasmFailValidateText('(module (memory 1) (func (i32.store offset=0 (i32.const 0) (f32.const 0))))', mismatchError("f32", "i32"));
     wasmFailValidateText('(module (memory 1) (func (i32.store offset=0 (i32.const 0) (f64.const 0))))', mismatchError("f64", "i32"));
 
     wasmEvalText('(module (memory 0 65535))')
-    wasmFailValidateText('(module (memory 0 65536))', /maximum memory size too big/);
+    wasmEvalText('(module (memory 0 65536))')
+    wasmFailValidateText('(module (memory 0 65537))', /maximum memory size too big/);
 
     // Test high charge of registers
     function testRegisters() {
         assertEq(wasmEvalText(
             `(module
               (memory 1)
               (data (i32.const 0) "\\00\\01\\02\\03\\04\\05\\06\\07\\08\\09\\0a\\0b\\0c\\0d\\0e\\0f")
               (data (i32.const 16) "\\f0\\f1\\f2\\f3\\f4\\f5\\f6\\f7\\f8\\f9\\fa\\fb\\fc\\fd\\fe\\ff")
--- a/js/src/jit-test/tests/wasm/nan-semantics.js
+++ b/js/src/jit-test/tests/wasm/nan-semantics.js
@@ -1,10 +1,8 @@
-load(libdir + "wasm.js");
-
 var f64 = new Float64Array(2);
 var f32 = new Float32Array(f64.buffer);
 var u8 = new Uint8Array(f64.buffer);
 
 function assertSameBitPattern(from, to, offset) {
     for (let i = from; i < to; i++)
         assertEq(u8[i], u8[i + offset], 'non equality in assertSameBitPattern');
 }
--- a/js/src/jit-test/tests/wasm/profiling.js
+++ b/js/src/jit-test/tests/wasm/profiling.js
@@ -1,10 +1,8 @@
-load(libdir + "wasm.js");
-
 // Single-step profiling currently only works in the ARM simulator
 if (!getBuildConfiguration()["arm-simulator"])
     quit();
 
 const Module = WebAssembly.Module;
 const Instance = WebAssembly.Instance;
 const Table = WebAssembly.Table;
 
--- a/js/src/jit-test/tests/wasm/regress/baseline-bytereg.js
+++ b/js/src/jit-test/tests/wasm/regress/baseline-bytereg.js
@@ -1,10 +1,8 @@
-load(libdir + "wasm.js");
-
 // Bug 1322450 is about the baseline compiler not properly handling a byte store
 // from a wider datum on 32-bit x86 because it does not move the value to be
 // stored to a valid byte register if it is in a 32-bit register that does not
 // have a byte part (EDI/ESI/EBP).
 //
 // This test is white-box because it knows about the register allocation order:
 // the two values pushed onto the stack occupy EAX and ECX, and the i64.store8
 // will use EDX for the index and (EDI or ESI or EBP) for the low register of
--- a/js/src/jit-test/tests/wasm/regress/baseline-joinreg.js
+++ b/js/src/jit-test/tests/wasm/regress/baseline-joinreg.js
@@ -1,10 +1,8 @@
-load(libdir + "wasm.js");
-
 // Bug 1322288 is about the floating join register not being reserved properly
 // in the presence of boolean evaluation for control.  The situation is that a
 // conditional branch passes a floating point value to the join point; the join register
 // must be available when it does that, but could have been allocated to the operands of
 // the conditional expression of the control flow.
 //
 // This test is white-box: it depends on the floating join reg being among the first
 // floating registers to be allocated.
--- a/js/src/jit-test/tests/wasm/regress/baseline-pop-along-edge.js
+++ b/js/src/jit-test/tests/wasm/regress/baseline-pop-along-edge.js
@@ -1,12 +1,10 @@
 // Bug 1316181
 
-load(libdir + "wasm.js");
-
 // There are locals with different values here to ensure that the
 // get_local at the end picks up the right one even if the stack might
 // have become unbalanced by a failure to adjust SP along the branch
 // edge.  The logic is that we use SP-relative addressing, and if the
 // actual SP is not what the compiler thinks it is we will read
 // something other than the expected value.
 
 var o = wasmEvalText(
--- a/js/src/jit-test/tests/wasm/regress/baseline-pop-before-capture.js
+++ b/js/src/jit-test/tests/wasm/regress/baseline-pop-before-capture.js
@@ -1,12 +1,10 @@
 // Bug 1319415
 
-load(libdir + "wasm.js");
-
 var src =
 `(module
   (func (result i32)
     i32.const 0
     i32.const 1
     br_if 0
     unreachable)
   (export "run" 0))`;
--- a/js/src/jit-test/tests/wasm/regress/brtable-conditionblock-folding.js
+++ b/js/src/jit-test/tests/wasm/regress/brtable-conditionblock-folding.js
@@ -1,10 +1,8 @@
-load(libdir + "wasm.js");
-
 assertEq(wasmEvalText(`
 (module
   (func $f (param $p i32)
     block $out
       i32.const 0
       if
         i32.const 1
         tee_local $p
--- a/js/src/jit-test/tests/wasm/regress/bug1300546.js
+++ b/js/src/jit-test/tests/wasm/regress/bug1300546.js
@@ -1,10 +1,8 @@
-load(libdir + "wasm.js");
-
 setJitCompilerOption('wasm.test-mode', 1);
 
 try {
     wasmEvalText(`
 
     (module
       (type $type0 (func))
       (func $func0
--- a/js/src/jit-test/tests/wasm/regress/bug1311019.js
+++ b/js/src/jit-test/tests/wasm/regress/bug1311019.js
@@ -1,10 +1,8 @@
-load(libdir + "wasm.js");
-
 new WebAssembly.Module(wasmTextToBinary(`(module
     (memory 1)
     (func
         (i64.trunc_s/f32 (f32.const 6.96875))
         (i32.load8_s (i32.const 0))
         (f32.const -7.66028056e-31)
         (unreachable)
     )
--- a/js/src/jit-test/tests/wasm/regress/current-memory-tls.js
+++ b/js/src/jit-test/tests/wasm/regress/current-memory-tls.js
@@ -1,10 +1,8 @@
-load(libdir + "wasm.js");
-
 // Bug 1341650:
 // - when compiled with Ion, pass the TLS register to current_memory;
 // - when compiled with Baseline, don't clobber the last stack slot when
 // calling into current_memory/grow_memory;
 
 // This toy module starts with an empty memory, then tries to set values at different
 // indexes, automatically growing memory when that would trigger an out of
 // bounds access, for the exact right amount of pages. Note it's not made for
--- a/js/src/jit-test/tests/wasm/regress/directives.txt
+++ b/js/src/jit-test/tests/wasm/regress/directives.txt
@@ -1,1 +1,1 @@
-|jit-test| test-also-wasm-baseline
+|jit-test| test-also-wasm-baseline; include:wasm.js
--- a/js/src/jit-test/tests/wasm/regress/gvn-unremovable-phi.js
+++ b/js/src/jit-test/tests/wasm/regress/gvn-unremovable-phi.js
@@ -1,10 +1,8 @@
-load(libdir + "wasm.js");
-
 wasmEvalText(`(module
   (type $type0 (func (param i32)))
   (func $f (param $p i32)
     (local $x i32) (local $y i32)
     loop $top
       get_local $x
       get_local $p
       get_local $x
--- a/js/src/jit-test/tests/wasm/regress/long-select.js
+++ b/js/src/jit-test/tests/wasm/regress/long-select.js
@@ -1,10 +1,8 @@
-load(libdir + "wasm.js");
-
 // Bug 1337060 causes too much register pressure on x86 by requiring four int64
 // values in registers at the same time.
 
 setJitCompilerOption('wasm.test-mode', 1);
 
 wasmFullPassI64(`
 (module
   (func (result i64)
--- a/js/src/jit-test/tests/wasm/regress/misc-control-flow.js
+++ b/js/src/jit-test/tests/wasm/regress/misc-control-flow.js
@@ -1,10 +1,8 @@
-load(libdir + "wasm.js");
-
 wasmFailValidateText(`(module
    (func (result i32) (param i32)
      (loop (if (i32.const 0) (br 0)) (get_local 0)))
    (export "" 0)
 )`, /unused values not explicitly dropped by end of block/);
 
 wasmFailValidateText(`(module
    (func (param i32)
--- a/js/src/jit-test/tests/wasm/regress/movable-traps.js
+++ b/js/src/jit-test/tests/wasm/regress/movable-traps.js
@@ -1,10 +1,8 @@
-load(libdir + "wasm.js");
-
 let bodies = [
     `
     i32.const 1
     i32.const 0
     i32.div_s
     `,
     `
     i32.const 1
--- a/js/src/jit-test/tests/wasm/regress/pass-stack-int64.js
+++ b/js/src/jit-test/tests/wasm/regress/pass-stack-int64.js
@@ -1,10 +1,8 @@
-load(libdir + "wasm.js");
-
 var params = '';
 var locals = '';
 for (let i = 0; i < 20; i++) {
     params += '(param i64) ';
     locals += `(get_local ${i}) `;
 }
 
 wasmEvalText(`
--- a/js/src/jit-test/tests/wasm/regres