merge mc to holly
authorJared Wein <jwein@mozilla.com>
Thu, 21 Nov 2013 19:58:35 -0500
changeset 172457 121ce5b3fc114a8f1437722a553b21885a0494ed
parent 172364 f760cffc3facf55f4d795ee955a5c699dd586208 (current diff)
parent 172456 7225e584d6c754a54e4787e312b0927b315cce99 (diff)
child 172507 beb188bd7767c82e113955f5eac2fb159166a76e
push id445
push userffxbld
push dateMon, 10 Mar 2014 22:05:19 +0000
treeherdermozilla-release@dc38b741b04e [default view] [failures only]
perfherder[talos] [build metrics] [platform microbench] (compared to previous push)
milestone28.0a1
merge mc to holly
CLOBBER
modules/libpref/src/init/all.js
--- a/CLOBBER
+++ b/CLOBBER
@@ -13,9 +13,9 @@
 #          |               |
 #          O <-- Clobber   O  <-- Clobber
 #
 # Note: The description below will be part of the error message shown to users.
 #
 # Modifying this file will now automatically clobber the buildbot machines \o/
 #
 
-Bug 928390 requires a clobber because of bug 939416.
+More Windows WebIDL changes. 
--- a/b2g/app/b2g.js
+++ b/b2g/app/b2g.js
@@ -37,16 +37,22 @@ pref("browser.offline-apps.notify", fals
 pref("browser.cache.offline.enable", true);
 pref("offline-apps.allow_by_default", true);
 
 /* protocol warning prefs */
 pref("network.protocol-handler.warn-external.tel", false);
 pref("network.protocol-handler.warn-external.mailto", false);
 pref("network.protocol-handler.warn-external.vnd.youtube", false);
 
+/* protocol expose prefs */
+// By default, all protocol handlers are exposed. This means that the browser
+// will response to openURL commands for all URL types. It will also try to open
+// link clicks inside the browser before failing over to the system handlers.
+pref("network.protocol-handler.expose.rtsp", false);
+
 /* http prefs */
 pref("network.http.pipelining", true);
 pref("network.http.pipelining.ssl", true);
 pref("network.http.proxy.pipelining", true);
 pref("network.http.pipelining.maxrequests" , 6);
 pref("network.http.keep-alive.timeout", 600);
 pref("network.http.max-connections", 20);
 pref("network.http.max-persistent-connections-per-server", 6);
--- a/b2g/config/gaia.json
+++ b/b2g/config/gaia.json
@@ -1,4 +1,4 @@
 {
-    "revision": "89c57a31cebe0d8d94cbce4bcb47788b18f4fe84", 
+    "revision": "94113691294813ec22930d07a5806921056dd856", 
     "repo_path": "/integration/gaia-central"
 }
--- a/browser/base/content/test/general/browser_save_private_link_perwindowpb.js
+++ b/browser/base/content/test/general/browser_save_private_link_perwindowpb.js
@@ -102,18 +102,16 @@ function test() {
         aWindow.document.addEventListener("popupshown",
                                           function(e) contextMenuOpened(aWindow, e), false);
         var img = aWindow.gBrowser.selectedBrowser.contentDocument.getElementById("img");
         EventUtils.synthesizeMouseAtCenter(img,
                                            { type: "contextmenu", button: 2 },
                                            aWindow.gBrowser.contentWindow);
       });
     });
-
-    aWindow.gBrowser.selectedBrowser.loadURI(testURI);
   }
 
   function testOnWindow(aOptions, aCallback) {
     whenNewWindowLoaded(aOptions, function(aWin) {
       windowsToClose.push(aWin);
       // execute should only be called when need, like when you are opening
       // web pages on the test. If calling executeSoon() is not necesary, then
       // call whenNewWindowLoaded() instead of testOnWindow() on your test.
--- a/browser/components/build/Makefile.in
+++ b/browser/components/build/Makefile.in
@@ -1,14 +1,12 @@
 # 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/.
 
-MODULE_NAME = nsBrowserCompsModule
-
 ifeq ($(OS_ARCH),WINNT)
 OS_LIBS	+= $(call EXPAND_LIBNAME,ole32 shell32 shlwapi)
 endif
 
 LOCAL_INCLUDES = \
 	-I$(srcdir)/../shell/src \
 	-I$(srcdir)/../feeds/src \
 	-I$(srcdir)/../about \
--- a/browser/devtools/debugger/test/head.js
+++ b/browser/devtools/debugger/test/head.js
@@ -30,16 +30,20 @@ const EXAMPLE_URL = "http://example.com/
 waitForExplicitFinish();
 
 registerCleanupFunction(function() {
   info("finish() was called, cleaning up...");
   Services.prefs.setBoolPref("devtools.debugger.log", gEnableLogging);
 
   // Properly shut down the server to avoid memory leaks.
   DebuggerServer.destroy();
+
+  // Debugger tests use a lot of memory, so force a GC to help fragmentation.
+  info("Forcing GC after debugger test.");
+  Cu.forceGC();
 });
 
 // Import the GCLI test helper
 let testDir = gTestPath.substr(0, gTestPath.lastIndexOf("/"));
 Services.scriptloader.loadSubScript(testDir + "../../../commandline/test/helpers.js", this);
 
 // Redeclare dbg_assert with a fatal behavior.
 function dbg_assert(cond, e) {
--- a/browser/devtools/netmonitor/test/browser_net_large-response.js
+++ b/browser/devtools/netmonitor/test/browser_net_large-response.js
@@ -39,9 +39,13 @@ function test() {
       EventUtils.sendMouseEvent({ type: "mousedown" },
         document.getElementById("details-pane-toggle"));
       EventUtils.sendMouseEvent({ type: "mousedown" },
         document.querySelectorAll("#details-pane tab")[3]);
     });
 
     aDebuggee.performRequests(1, CONTENT_TYPE_SJS + "?fmt=html-long");
   });
+
+  // This test uses a lot of memory, so force a GC to help fragmentation.
+  info("Forcing GC after netmonitor test.");
+  Cu.forceGC();
 }
--- a/browser/devtools/profiler/test/head.js
+++ b/browser/devtools/profiler/test/head.js
@@ -24,16 +24,21 @@ let testDir = gTestPath.substr(0, gTestP
 Services.scriptloader.loadSubScript(testDir + "../../../commandline/test/helpers.js", this);
 
 registerCleanupFunction(function () {
   helpers = null;
   Services.prefs.clearUserPref(PROFILER_ENABLED);
   Services.prefs.clearUserPref(REMOTE_ENABLED);
   Services.prefs.clearUserPref(SHOW_PLATFORM_DATA);
   DebuggerServer.destroy();
+
+  // These tests use a lot of memory due to GL contexts, so force a GC to help
+  // fragmentation.
+  info("Forcing GC after profiler test.");
+  Cu.forceGC();
 });
 
 function getProfileInternals(uid) {
   let profile = (uid != null) ? gPanel.profiles.get(uid) : gPanel.activeProfile;
   let win = profile.iframe.contentWindow;
   let doc = win.document;
 
   return [win, doc];
--- a/browser/devtools/shadereditor/test/head.js
+++ b/browser/devtools/shadereditor/test/head.js
@@ -33,16 +33,21 @@ const OVERLAPPING_GEOMETRY_CANVAS_URL = 
 waitForExplicitFinish();
 
 let gToolEnabled = Services.prefs.getBoolPref("devtools.shadereditor.enabled");
 
 registerCleanupFunction(() => {
   info("finish() was called, cleaning up...");
   Services.prefs.setBoolPref("devtools.debugger.log", gEnableLogging);
   Services.prefs.setBoolPref("devtools.shadereditor.enabled", gToolEnabled);
+
+  // These tests use a lot of memory due to GL contexts, so force a GC to help
+  // fragmentation.
+  info("Forcing GC after shadereditor test.");
+  Cu.forceGC();
 });
 
 function addTab(aUrl, aWindow) {
   info("Adding tab: " + aUrl);
 
   let deferred = promise.defer();
   let targetWindow = aWindow || window;
   let targetBrowser = targetWindow.gBrowser;
new file mode 100644
--- /dev/null
+++ b/build/sanitizers/tsan_suppressions.txt
@@ -0,0 +1,21 @@
+# Bug 931149
+race:DoImageDataComplete
+
+# Bug 939786
+race:_pt_root
+
+# Bug 939788
+# Tracked by http://code.google.com/p/thread-sanitizer/issues/detail?id=40
+race:ELMCreationDetector
+
+# Bug 939790
+race:xpcom/components/nsComponentManager.h
+
+# Bug 939807
+race:ComputeUTCTime
+
+# Bug 939805
+race:g_variant_type_info_get
+
+# Bug 844759
+race:js::gc::ArenaLists::allocateFromArenaInline
--- a/build/unix/elfhack/elfhack.cpp
+++ b/build/unix/elfhack/elfhack.cpp
@@ -763,17 +763,17 @@ void undo_file(const char *name, bool ba
         fprintf(stderr, elfhack_data " section not following " elfhack_text ". Skipping\n");
         return;
     }
 
     ElfSegment *first = elf.getSegmentByType(PT_LOAD);
     ElfSegment *second = elf.getSegmentByType(PT_LOAD, first);
     ElfSegment *filler = nullptr;
     // If the second PT_LOAD is a filler from elfhack --fill, check the third.
-    if (!second->isElfHackFillerSegment()) {
+    if (second->isElfHackFillerSegment()) {
         filler = second;
         second = elf.getSegmentByType(PT_LOAD, filler);
     }
     if (second->getFlags() != first->getFlags()) {
         fprintf(stderr, "Couldn't identify elfhacked PT_LOAD segments. Skipping\n");
         return;
     }
     // Move sections from the second PT_LOAD to the first, and remove the
--- a/caps/src/moz.build
+++ b/caps/src/moz.build
@@ -1,15 +1,15 @@
 # -*- Mode: python; c-basic-offset: 4; indent-tabs-mode: nil; tab-width: 40 -*-
 # vim: set filetype=python:
 # This Source Code Form is subject to the terms of the Mozilla Public
 # License, v. 2.0. If a copy of the MPL was not distributed with this
 # file, You can obtain one at http://mozilla.org/MPL/2.0/.
 
-SOURCES += [
+UNIFIED_SOURCES += [
     'DomainPolicy.cpp',
     'nsJSPrincipals.cpp',
     'nsNullPrincipal.cpp',
     'nsNullPrincipalURI.cpp',
     'nsPrincipal.cpp',
     'nsScriptSecurityManager.cpp',
     'nsSecurityManagerFactory.cpp',
     'nsSystemPrincipal.cpp',
--- a/config/config.mk
+++ b/config/config.mk
@@ -340,19 +340,16 @@ ifeq ($(FINAL_LIBRARY),xul)
   endif
   LIBXUL_LIBRARY := 1
 endif
 
 ifdef LIBXUL_LIBRARY
 ifdef IS_COMPONENT
 $(error IS_COMPONENT is set, but is not compatible with LIBXUL_LIBRARY)
 endif
-ifdef MODULE_NAME
-$(error MODULE_NAME is $(MODULE_NAME) but MODULE_NAME and LIBXUL_LIBRARY are not compatible)
-endif
 FORCE_STATIC_LIB=1
 endif
 
 # If we are building this component into an extension/xulapp, it cannot be
 # statically linked. In the future we may want to add a xulapp meta-component
 # build option.
 
 ifdef XPI_NAME
--- a/config/rules.mk
+++ b/config/rules.mk
@@ -452,30 +452,16 @@ endif
 # This will strip out symbols that the component should not be
 # exporting from the .dynsym section.
 #
 ifdef IS_COMPONENT
 EXTRA_DSO_LDOPTS += $(MOZ_COMPONENTS_VERSION_SCRIPT_LDFLAGS)
 endif # IS_COMPONENT
 
 #
-# Enforce the requirement that MODULE_NAME must be set
-# for components in static builds
-#
-ifdef IS_COMPONENT
-ifdef EXPORT_LIBRARY
-ifndef FORCE_SHARED_LIB
-ifndef MODULE_NAME
-$(error MODULE_NAME is required for components which may be used in static builds)
-endif
-endif
-endif
-endif
-
-#
 # MacOS X specific stuff
 #
 
 ifeq ($(OS_ARCH),Darwin)
 ifdef SHARED_LIBRARY
 ifdef IS_COMPONENT
 EXTRA_DSO_LDOPTS	+= -bundle
 else
--- a/configure.in
+++ b/configure.in
@@ -803,17 +803,16 @@ case "$target" in
 esac
 
 AC_SUBST(MACOSX_DEPLOYMENT_TARGET)
 
 dnl ========================================================
 dnl = Mac OS X SDK support
 dnl ========================================================
 MACOS_SDK_DIR=
-NEXT_ROOT=
 MOZ_ARG_WITH_STRING(macos-sdk,
 [  --with-macos-sdk=dir    Location of platform SDK to use (Mac OS X only)],
     MACOS_SDK_DIR=$withval)
 
 MACOS_PRIVATE_FRAMEWORKS_DIR_DEFAULTED=
 MOZ_ARG_WITH_STRING(macos-private-frameworks,
 [  --with-macos-private-frameworks=dir    Location of private frameworks to use (Mac OS X only)],
     MACOS_PRIVATE_FRAMEWORKS_DIR=$withval,
@@ -825,20 +824,18 @@ if test -z "${MACOS_PRIVATE_FRAMEWORKS_D
     AC_MSG_WARN([You should only be using --with-macos-private-frameworks when cross-compiling.])
   fi
   if test ! -d "$MACOS_PRIVATE_FRAMEWORKS_DIR"; then
     AC_MSG_ERROR([PrivateFrameworks directory not found.])
   fi
 fi
 
 dnl MACOS_SDK_DIR will be set to the SDK location whenever one is in use.
-dnl NEXT_ROOT will be set and exported only if it's needed.
 AC_SUBST(MACOS_SDK_DIR)
 AC_SUBST(MACOS_PRIVATE_FRAMEWORKS_DIR)
-AC_SUBST(NEXT_ROOT)
 
 if test "$MACOS_SDK_DIR"; then
   dnl Sync this section with the ones in NSPR and NSS.
   dnl Changes to the cross environment here need to be accounted for in
   dnl the libIDL checks (below) and xpidl build.
 
   if test ! -d "$MACOS_SDK_DIR"; then
     AC_MSG_ERROR([SDK not found.  When using --with-macos-sdk, you must
@@ -6793,19 +6790,21 @@ dnl ====================================
 dnl = Enable DMD
 dnl ========================================================
 
 MOZ_ARG_ENABLE_BOOL(dmd,
 [  --enable-dmd            Enable DMD; also enables jemalloc and replace-malloc],
     MOZ_DMD=1,
     MOZ_DMD= )
 
-if test "$NS_TRACE_MALLOC"; then        # trace-malloc disables DMD
-    MOZ_DMD=
-fi
+dnl The two options are conflicting. Fails the configure to alert the user.
+if test "$NS_TRACE_MALLOC" -a "$MOZ_DMD"; then
+    AC_MSG_ERROR([--enable-trace-malloc and --enable-dmd are conflicting options])
+fi
+
 if test "$MOZ_DMD"; then
     USE_ELF_DYNSTR_GC=
     AC_DEFINE(MOZ_DMD)
 
     if test "${CPU_ARCH}" = "arm"; then
         CFLAGS="$CFLAGS -funwind-tables"
         CXXFLAGS="$CXXFLAGS -funwind-tables"
     fi
@@ -6858,16 +6857,21 @@ fi
 dnl ========================================================
 dnl = Enable dynamic replacement of malloc implementation
 dnl ========================================================
 MOZ_ARG_ENABLE_BOOL(replace-malloc,
 [  --enable-replace-malloc   Enable ability to dynamically replace the malloc implementation],
     MOZ_REPLACE_MALLOC=1,
     MOZ_REPLACE_MALLOC= )
 
+dnl The two options are conflicting. Fails the configure to alert the user.
+if test "$NS_TRACE_MALLOC" -a "$MOZ_REPLACE_MALLOC"; then
+    AC_MSG_ERROR([--enable-trace-malloc and --enable-replace-malloc are conflicting options])
+fi
+
 if test -n "$MOZ_REPLACE_MALLOC" -a -z "$MOZ_MEMORY"; then
     dnl We don't want to enable jemalloc unconditionally because it may be a
     dnl deliberate choice not to enable it (bug 702250, for instance)
     AC_MSG_ERROR([--enable-replace-malloc requires --enable-jemalloc])
 elif test -n "$MOZ_REPLACE_MALLOC"; then
     MOZ_NATIVE_JEMALLOC=
 
     dnl Replace-malloc Mac linkage quirks
@@ -7335,17 +7339,17 @@ if test -n "$MOZ_B2G_BT"; then
 fi
 AC_SUBST(MOZ_B2G_BT)
 AC_SUBST(MOZ_B2G_BT_BLUEZ)
 AC_SUBST(MOZ_B2G_BT_BLUEDROID)
 
 dnl ========================================================
 dnl = Enable NFC Interface for B2G (Gonk usually)
 dnl ========================================================
-MOZ_ARG_ENABLE_BOOL(b2g-nfc,
+MOZ_ARG_ENABLE_BOOL(nfc,
 [  --enable-nfc         Set compile flags necessary for compiling NFC API ],
     MOZ_NFC=1,
     MOZ_NFC= )
 if test -n "$MOZ_NFC"; then
    AC_DEFINE(MOZ_NFC)
 fi
 AC_SUBST(MOZ_NFC)
 
--- a/content/base/src/nsGkAtomList.h
+++ b/content/base/src/nsGkAtomList.h
@@ -765,16 +765,17 @@ GK_ATOM(onpagehide, "onpagehide")
 GK_ATOM(onpageshow, "onpageshow")
 GK_ATOM(onpaint, "onpaint")
 GK_ATOM(onpairedstatuschanged, "onpairedstatuschanged")
 GK_ATOM(onpaste, "onpaste")
 GK_ATOM(onpopuphidden, "onpopuphidden")
 GK_ATOM(onpopuphiding, "onpopuphiding")
 GK_ATOM(onpopupshowing, "onpopupshowing")
 GK_ATOM(onpopupshown, "onpopupshown")
+GK_ATOM(onradiostatechange, "onradiostatechange")
 GK_ATOM(onreadystatechange, "onreadystatechange")
 GK_ATOM(onreceived, "onreceived")
 GK_ATOM(onremoteheld, "onremoteheld")
 GK_ATOM(onremoteresumed, "onremoteresumed")
 GK_ATOM(onretrieving, "onretrieving")
 GK_ATOM(onRequest, "onRequest")
 GK_ATOM(onrequestmediaplaystatus, "onrequestmediaplaystatus")
 GK_ATOM(onreset, "onreset")
--- a/content/canvas/src/CanvasRenderingContext2D.cpp
+++ b/content/canvas/src/CanvasRenderingContext2D.cpp
@@ -1077,30 +1077,30 @@ CanvasRenderingContext2D::GetImageBuffer
   *aFormat = imgIEncoder::INPUT_FORMAT_HOSTARGB;
 }
 
 NS_IMETHODIMP
 CanvasRenderingContext2D::GetInputStream(const char *aMimeType,
                                          const PRUnichar *aEncoderOptions,
                                          nsIInputStream **aStream)
 {
+  nsCString enccid("@mozilla.org/image/encoder;2?type=");
+  enccid += aMimeType;
+  nsCOMPtr<imgIEncoder> encoder = do_CreateInstance(enccid.get());
+  if (!encoder) {
+    return NS_ERROR_FAILURE;
+  }
+
   nsAutoArrayPtr<uint8_t> imageBuffer;
   int32_t format = 0;
   GetImageBuffer(getter_Transfers(imageBuffer), &format);
   if (!imageBuffer) {
     return NS_ERROR_FAILURE;
   }
 
-  nsCString enccid("@mozilla.org/image/encoder;2?type=");
-  enccid += aMimeType;
-  nsCOMPtr<imgIEncoder> encoder = do_CreateInstance(enccid.get());
-  if (!encoder) {
-    return NS_ERROR_FAILURE;
-  }
-
   return ImageEncoder::GetInputStream(mWidth, mHeight, imageBuffer, format,
                                       encoder, aEncoderOptions, aStream);
 }
 
 SurfaceFormat
 CanvasRenderingContext2D::GetSurfaceFormat() const
 {
   return mOpaque ? FORMAT_B8G8R8X8 : FORMAT_B8G8R8A8;
--- a/content/canvas/src/WebGLContext.cpp
+++ b/content/canvas/src/WebGLContext.cpp
@@ -789,30 +789,30 @@ NS_IMETHODIMP
 WebGLContext::GetInputStream(const char* aMimeType,
                              const PRUnichar* aEncoderOptions,
                              nsIInputStream **aStream)
 {
     NS_ASSERTION(gl, "GetInputStream on invalid context?");
     if (!gl)
         return NS_ERROR_FAILURE;
 
+    nsCString enccid("@mozilla.org/image/encoder;2?type=");
+    enccid += aMimeType;
+    nsCOMPtr<imgIEncoder> encoder = do_CreateInstance(enccid.get());
+    if (!encoder) {
+        return NS_ERROR_FAILURE;
+    }
+
     nsAutoArrayPtr<uint8_t> imageBuffer;
     int32_t format = 0;
     GetImageBuffer(getter_Transfers(imageBuffer), &format);
     if (!imageBuffer) {
         return NS_ERROR_FAILURE;
     }
 
-    nsCString enccid("@mozilla.org/image/encoder;2?type=");
-    enccid += aMimeType;
-    nsCOMPtr<imgIEncoder> encoder = do_CreateInstance(enccid.get());
-    if (!encoder) {
-        return NS_ERROR_FAILURE;
-    }
-
     return ImageEncoder::GetInputStream(mWidth, mHeight, imageBuffer, format,
                                         encoder, aEncoderOptions, aStream);
 }
 
 NS_IMETHODIMP
 WebGLContext::GetThebesSurface(gfxASurface **surface)
 {
     return NS_ERROR_NOT_AVAILABLE;
--- a/content/events/src/nsDOMMessageEvent.cpp
+++ b/content/events/src/nsDOMMessageEvent.cpp
@@ -151,17 +151,17 @@ nsDOMMessageEvent::Constructor(const moz
                                  getter_AddRefs(wrappedNative));
 
     if (wrappedNative) {
       event->mWindowSource = do_QueryWrappedNative(wrappedNative);
     }
 
     if (!event->mWindowSource) {
       MessagePortBase* port = nullptr;
-      nsresult rv = UNWRAP_OBJECT(MessagePort, aCx, aParam.mSource, port);
+      nsresult rv = UNWRAP_OBJECT(MessagePort, aParam.mSource, port);
       if (NS_FAILED(rv)) {
         aRv.Throw(NS_ERROR_INVALID_ARG);
         return nullptr;
       }
 
       event->mPortSource = port;
     }
   }
--- a/content/html/content/src/HTMLInputElement.cpp
+++ b/content/html/content/src/HTMLInputElement.cpp
@@ -3231,16 +3231,24 @@ HTMLInputElement::PreHandleEvent(nsEvent
 void
 HTMLInputElement::StartRangeThumbDrag(WidgetGUIEvent* aEvent)
 {
   mIsDraggingRange = true;
   mRangeThumbDragStartValue = GetValueAsDecimal();
   nsIPresShell::SetCapturingContent(this, CAPTURE_IGNOREALLOWED |
                                           CAPTURE_RETARGETTOELEMENT);
   nsRangeFrame* rangeFrame = do_QueryFrame(GetPrimaryFrame());
+
+  // Before we change the value, record the current value so that we'll
+  // correctly send a 'change' event if appropriate. We need to do this here
+  // because the 'focus' event is handled after the 'mousedown' event that
+  // we're being called for (i.e. too late to update mFocusedValue, since we'll
+  // have changed it by then).
+  GetValueInternal(mFocusedValue);
+
   SetValueOfRangeForUserEvent(rangeFrame->GetValueAtEventPoint(aEvent));
 }
 
 void
 HTMLInputElement::FinishRangeThumbDrag(WidgetGUIEvent* aEvent)
 {
   MOZ_ASSERT(mIsDraggingRange);
 
@@ -3378,17 +3386,18 @@ HTMLInputElement::PostHandleEvent(nsEven
     // Hack alert! In order to open file picker even in case the element isn't
     // in document, try to init picker even without PresContext.
     return MaybeInitPickers(aVisitor);
   }
 
   if (aVisitor.mEvent->message == NS_FOCUS_CONTENT ||
       aVisitor.mEvent->message == NS_BLUR_CONTENT) {
     if (aVisitor.mEvent->message == NS_FOCUS_CONTENT &&
-        MayFireChangeOnBlur()) {
+        MayFireChangeOnBlur() &&
+        !mIsDraggingRange) { // StartRangeThumbDrag already set mFocusedValue
       GetValueInternal(mFocusedValue);
     }
 
     if (mIsDraggingRange &&
         aVisitor.mEvent->message == NS_BLUR_CONTENT) {
       FinishRangeThumbDrag();
     }
 
--- a/content/html/content/test/forms/test_change_event.html
+++ b/content/html/content/test/forms/test_change_event.html
@@ -180,16 +180,20 @@ https://bugzilla.mozilla.org/show_bug.cg
     var centerOfRangeX = bcr.width / 2;
     var centerOfRangeY = bcr.height / 2;
     synthesizeMouse(range, centerOfRangeX - 10, centerOfRangeY, { type: "mousedown" });
     is(rangeChange, 1, "Change event shouldn't be dispatched on range input element for mousedown");
     synthesizeMouse(range, centerOfRangeX - 5, centerOfRangeY, { type: "mousemove" });
     is(rangeChange, 1, "Change event shouldn't be dispatched on range input element during drag of thumb");
     synthesizeMouse(range, centerOfRangeX, centerOfRangeY, { type: "mouseup" });
     is(rangeChange, 2, "Change event should be dispatched on range input element at end of drag");
+    range.blur();
+    is(rangeChange, 2, "Change event shouldn't be dispatched on range input element when range loses focus after a drag");
+    synthesizeMouse(range, centerOfRangeX - 10, centerOfRangeY, {});
+    is(rangeChange, 3, "Change event should be dispatched on range input element for a click that gives the range focus");
 
     //Input type change test.
     input = document.getElementById("input_checkbox");
     input.type = "text";
     input.focus();
     input.click();
     input.blur();
     is(NonTextInputChange[5], 1, "Change event shouldn't be dispatched for checkbox ---> text input type change");
--- a/content/html/content/test/forms/test_submit_invalid_file.html
+++ b/content/html/content/test/forms/test_submit_invalid_file.html
@@ -30,17 +30,18 @@ https://bugzilla.mozilla.org/show_bug.cg
    */
 
   SimpleTest.waitForExplicitFinish();
   addLoadEvent(function() {
     var FileUtils = SpecialPowers.Cu.import("resource://gre/modules/FileUtils.jsm").FileUtils;
 
     var i = document.getElementsByTagName('input')[0];
 
-    var file = FileUtils.getFile("TmpD", ["testfile"]);
+    var file = FileUtils.getDir("TmpD", [], false);
+    file.append("testfile");
     file.createUnique(SpecialPowers.Ci.nsIFile.NORMAL_FILE_TYPE, 0644);
 
     SpecialPowers.wrap(i).value = file.path;
     file.remove(/* recursive = */ false);
 
     document.getElementsByName('result')[0].addEventListener('load', function() {
       is(window.frames[0].document.body.textContent, "SUCCESS");
       SimpleTest.finish();
--- a/content/media/WebVTTListener.cpp
+++ b/content/media/WebVTTListener.cpp
@@ -157,17 +157,17 @@ WebVTTListener::OnDataAvailable(nsIReque
 NS_IMETHODIMP
 WebVTTListener::OnCue(const JS::Value &aCue, JSContext* aCx)
 {
   if (!aCue.isObject()) {
     return NS_ERROR_FAILURE;
   }
 
   TextTrackCue* cue;
-  nsresult rv = UNWRAP_OBJECT(VTTCue, aCx, &aCue.toObject(), cue);
+  nsresult rv = UNWRAP_OBJECT(VTTCue, &aCue.toObject(), cue);
   NS_ENSURE_SUCCESS(rv, rv);
 
   cue->SetTrackElement(mElement);
   mElement->mTrack->AddCue(*cue);
 
   return NS_OK;
 }
 
@@ -175,18 +175,17 @@ WebVTTListener::OnCue(const JS::Value &a
 NS_IMETHODIMP
 WebVTTListener::OnRegion(const JS::Value &aRegion, JSContext* aCx)
 {
   if (!aRegion.isObject()) {
     return NS_ERROR_FAILURE;
   }
 
   TextTrackRegion* region;
-  nsresult rv = UNWRAP_OBJECT(VTTRegion, aCx, &aRegion.toObject(),
-                              region);
+  nsresult rv = UNWRAP_OBJECT(VTTRegion, &aRegion.toObject(), region);
   NS_ENSURE_SUCCESS(rv, rv);
 
   mElement->mTrack->AddRegion(*region);
 
   return NS_OK;
 }
 
 } // namespace dom
--- a/dom/activities/src/ActivitiesServiceFilter.jsm
+++ b/dom/activities/src/ActivitiesServiceFilter.jsm
@@ -100,16 +100,20 @@ this.ActivitiesServiceFilter = {
 
     // For any incoming property.
     for (let prop in aValues) {
       // If this is unknown for the app, let's continue.
       if (!(prop in filtersMap)) {
         continue;
       }
 
+      if (Array.isArray(aValues[prop]) && aValues[prop].length == 0) {
+        continue;
+      }
+
       // Otherwise, let's check the value against the filter.
       if (!matchObject(aValues[prop], filtersMap[prop].filter)) {
         return false;
       }
 
       filtersMap[prop].found = true;
     }
 
--- a/dom/activities/tests/unit/test_activityFilters.js
+++ b/dom/activities/tests/unit/test_activityFilters.js
@@ -145,9 +145,13 @@ function run_test() {
   do_check_false(ActivitiesServiceFilter.match({a: 'aaFOOsdsad'},
                                                {a: { required: true, pattern: 'foo', patternFlags: 'i'}}));
   do_check_false(ActivitiesServiceFilter.match({a: 'aafoobarasdsad'},
                                                {a: { required: true, pattern: 'foo'}}));
   do_check_false(ActivitiesServiceFilter.match({a: 'aaFOOsdsad'},
                                                {a: { required: true, pattern: 'foobar'}}));
   do_check_true(ActivitiesServiceFilter.match({a: 'FoOBaR'},
                                               {a: { required: true, pattern: 'foobar', patternFlags: 'i'}}));
+
+  // Bug 923274
+  do_check_true(ActivitiesServiceFilter.match({a:[]}, {a:'a'}));
+  do_check_false(ActivitiesServiceFilter.match({a:[]}, {a: { required: true, value: 'a'}}));
 }
--- a/dom/base/MessagePort.cpp
+++ b/dom/base/MessagePort.cpp
@@ -186,17 +186,17 @@ PostMessageWriteStructuredClone(JSContex
     if (scTag) {
       return JS_WriteUint32Pair(writer, scTag, 0) &&
              JS_WriteBytes(writer, &supports, sizeof(supports)) &&
              scInfo->mEvent->StoreISupports(supports);
     }
   }
 
   MessagePortBase* port = nullptr;
-  nsresult rv = UNWRAP_OBJECT(MessagePort, cx, obj, port);
+  nsresult rv = UNWRAP_OBJECT(MessagePort, obj, port);
   if (NS_SUCCEEDED(rv)) {
     nsRefPtr<MessagePortBase> newPort = port->Clone();
 
     if (!newPort) {
       return false;
     }
 
     return JS_WriteUint32Pair(writer, SCTAG_DOM_MESSAGEPORT, 0) &&
--- a/dom/base/nsDOMClassInfo.cpp
+++ b/dom/base/nsDOMClassInfo.cpp
@@ -3998,17 +3998,17 @@ nsHTMLDocumentSH::GetDocumentAllNodeList
   nsresult rv = NS_OK;
 
   JS::Rooted<JS::Value> collection(cx, JS_GetReservedSlot(obj, 0));
 
   if (!JSVAL_IS_PRIMITIVE(collection)) {
     // We already have a node list in our reserved slot, use it.
     JS::Rooted<JSObject*> obj(cx, JSVAL_TO_OBJECT(collection));
     nsIHTMLCollection* htmlCollection;
-    rv = UNWRAP_OBJECT(HTMLCollection, cx, obj, htmlCollection);
+    rv = UNWRAP_OBJECT(HTMLCollection, obj, htmlCollection);
     if (NS_SUCCEEDED(rv)) {
       NS_ADDREF(*nodeList = static_cast<nsContentList*>(htmlCollection));
     }
     else {
       nsISupports *native = nsDOMClassInfo::XPConnect()->GetNativeOfWrapper(cx, obj);
       if (native) {
         NS_ADDREF(*nodeList = nsContentList::FromSupports(native));
         rv = NS_OK;
--- a/dom/base/nsGlobalWindow.cpp
+++ b/dom/base/nsGlobalWindow.cpp
@@ -7567,17 +7567,17 @@ PostMessageWriteStructuredClone(JSContex
     if (scTag)
       return JS_WriteUint32Pair(writer, scTag, 0) &&
              JS_WriteBytes(writer, &supports, sizeof(supports)) &&
              scInfo->event->StoreISupports(supports);
   }
 
   if (MessageChannel::PrefEnabled()) {
     MessagePortBase* port = nullptr;
-    nsresult rv = UNWRAP_OBJECT(MessagePort, cx, obj, port);
+    nsresult rv = UNWRAP_OBJECT(MessagePort, obj, port);
     if (NS_SUCCEEDED(rv) && scInfo->subsumes) {
       nsRefPtr<MessagePortBase> newPort = port->Clone();
 
       if (!newPort) {
         return false;
       }
 
       return JS_WriteUint32Pair(writer, SCTAG_DOM_MESSAGEPORT, 0) &&
--- a/dom/base/nsJSEnvironment.cpp
+++ b/dom/base/nsJSEnvironment.cpp
@@ -2800,17 +2800,17 @@ NS_DOMReadStructuredClone(JSContext* cx,
 
 bool
 NS_DOMWriteStructuredClone(JSContext* cx,
                            JSStructuredCloneWriter* writer,
                            JS::Handle<JSObject*> obj,
                            void *closure)
 {
   ImageData* imageData;
-  nsresult rv = UNWRAP_OBJECT(ImageData, cx, obj, imageData);
+  nsresult rv = UNWRAP_OBJECT(ImageData, obj, imageData);
   if (NS_FAILED(rv)) {
     // Don't know what this is. Bail.
     xpc::Throw(cx, NS_ERROR_DOM_DATA_CLONE_ERR);
     return false;
   }
 
   // Prepare the ImageData internals.
   uint32_t width = imageData->Width();
--- a/dom/bindings/BindingUtils.cpp
+++ b/dom/bindings/BindingUtils.cpp
@@ -194,18 +194,17 @@ ErrorResult::ReportJSException(JSContext
 
 void
 ErrorResult::ReportJSExceptionFromJSImplementation(JSContext* aCx)
 {
   MOZ_ASSERT(!mMightHaveUnreportedJSException,
              "Why didn't you tell us you planned to handle JS exceptions?");
 
   dom::DOMError* domError;
-  nsresult rv = UNWRAP_OBJECT(DOMError, aCx, &mJSException.toObject(),
-                              domError);
+  nsresult rv = UNWRAP_OBJECT(DOMError, &mJSException.toObject(), domError);
   if (NS_FAILED(rv)) {
     // Unwrapping really shouldn't fail here, if mExceptionHandling is set to
     // eRethrowContentExceptions then the CallSetup destructor only stores an
     // exception if it unwraps to DOMError. If we reach this then either
     // mExceptionHandling wasn't set to eRethrowContentExceptions and we
     // shouldn't be calling ReportJSExceptionFromJSImplementation or something
     // went really wrong.
     NS_RUNTIMEABORT("We stored a non-DOMError exception!");
@@ -1785,23 +1784,23 @@ ReparentWrapper(JSContext* aCx, JS::Hand
     }
 
     if (!copyTo || !JS_CopyPropertiesFrom(aCx, copyTo, propertyHolder)) {
       MOZ_CRASH();
     }
   }
 
   nsObjectLoadingContent* htmlobject;
-  nsresult rv = UNWRAP_OBJECT(HTMLObjectElement, aCx, aObj, htmlobject);
+  nsresult rv = UNWRAP_OBJECT(HTMLObjectElement, aObj, htmlobject);
   if (NS_FAILED(rv)) {
     rv = UnwrapObject<prototypes::id::HTMLEmbedElement,
-                      HTMLSharedObjectElement>(aCx, aObj, htmlobject);
+                      HTMLSharedObjectElement>(aObj, htmlobject);
     if (NS_FAILED(rv)) {
       rv = UnwrapObject<prototypes::id::HTMLAppletElement,
-                        HTMLSharedObjectElement>(aCx, aObj, htmlobject);
+                        HTMLSharedObjectElement>(aObj, htmlobject);
       if (NS_FAILED(rv)) {
         htmlobject = nullptr;
       }
     }
   }
   if (htmlobject) {
     htmlobject->SetupProtoChain(aCx, aObj);
   }
--- a/dom/bindings/BindingUtils.h
+++ b/dom/bindings/BindingUtils.h
@@ -188,27 +188,27 @@ UnwrapDOMObjectToISupports(JSObject* aOb
 
 inline bool
 IsDOMObject(JSObject* obj)
 {
   const js::Class* clasp = js::GetObjectClass(obj);
   return IsDOMClass(clasp) || IsDOMProxy(obj, clasp);
 }
 
-#define UNWRAP_OBJECT(Interface, cx, obj, value)                             \
+#define UNWRAP_OBJECT(Interface, obj, value)                                 \
   mozilla::dom::UnwrapObject<mozilla::dom::prototypes::id::Interface,        \
-    mozilla::dom::Interface##Binding::NativeType>(cx, obj, value)
+    mozilla::dom::Interface##Binding::NativeType>(obj, value)
 
 // Some callers don't want to set an exception when unwrapping fails
 // (for example, overload resolution uses unwrapping to tell what sort
 // of thing it's looking at).
 // U must be something that a T* can be assigned to (e.g. T* or an nsRefPtr<T>).
 template <prototypes::ID PrototypeID, class T, typename U>
 MOZ_ALWAYS_INLINE nsresult
-UnwrapObject(JSContext* cx, JSObject* obj, U& value)
+UnwrapObject(JSObject* obj, U& value)
 {
   /* First check to see whether we have a DOM object */
   const DOMClass* domClass = GetDOMClass(obj);
   if (!domClass) {
     /* Maybe we have a security wrapper or outer window? */
     if (!js::IsWrapper(obj)) {
       /* Not a DOM object, not a wrapper, just bail */
       return NS_ERROR_XPC_BAD_CONVERT_JS;
--- a/dom/bindings/CallbackObject.cpp
+++ b/dom/bindings/CallbackObject.cpp
@@ -152,17 +152,17 @@ CallbackObject::CallSetup::ShouldRethrow
 
   JS::Rooted<JSObject*> obj(mCx, &aException.toObject());
   obj = js::UncheckedUnwrap(obj, /* stopAtOuter = */ false);
   if (js::GetObjectCompartment(obj) != mCompartment) {
     return false;
   }
 
   DOMError* domError;
-  return NS_SUCCEEDED(UNWRAP_OBJECT(DOMError, mCx, obj, domError));
+  return NS_SUCCEEDED(UNWRAP_OBJECT(DOMError, obj, domError));
 }
 
 CallbackObject::CallSetup::~CallSetup()
 {
   // First things first: if we have a JSContext, report any pending
   // errors on it, unless we were told to re-throw them.
   if (mCx) {
     bool dealtWithPendingException = false;
--- a/dom/bindings/Codegen.py
+++ b/dom/bindings/Codegen.py
@@ -2531,17 +2531,17 @@ class CastableObjectUnwrapper():
         else:
             self.substitution["codeOnFailure"] = CGIndenter(
                 CGGeneric(self.substitution["codeOnFailure"])).define()
 
     def __str__(self):
         codeOnFailure = self.substitution["codeOnFailure"] % {'securityError': 'rv == NS_ERROR_XPC_SECURITY_MANAGER_VETO'}
         return string.Template(
 """{
-  nsresult rv = UnwrapObject<${protoID}, ${type}>(cx, ${source}, ${target});
+  nsresult rv = UnwrapObject<${protoID}, ${type}>(${source}, ${target});
   if (NS_FAILED(rv)) {
 ${codeOnFailure}
   }
 }""").substitute(self.substitution, codeOnFailure=codeOnFailure)
 
 class FailureFatalCastableObjectUnwrapper(CastableObjectUnwrapper):
     """
     As CastableObjectUnwrapper, but defaulting to throwing if unwrapping fails
--- a/dom/bluetooth/BluetoothRilListener.cpp
+++ b/dom/bluetooth/BluetoothRilListener.cpp
@@ -126,16 +126,22 @@ MobileConnectionListener::NotifyOtaStatu
 }
 
 NS_IMETHODIMP
 MobileConnectionListener::NotifyIccChanged()
 {
   return NS_OK;
 }
 
+NS_IMETHODIMP
+MobileConnectionListener::NotifyRadioStateChanged()
+{
+  return NS_OK;
+}
+
 /**
  *  TelephonyListener Implementation
  *
  *  TODO: Bug 921991 - B2G BT: support multiple sim cards
  */
 class TelephonyListener : public nsITelephonyListener
 {
 public:
--- a/dom/bluetooth/bluedroid/BluetoothHfpManager.cpp
+++ b/dom/bluetooth/bluedroid/BluetoothHfpManager.cpp
@@ -507,23 +507,23 @@ void
 BluetoothHfpManager::ProcessConnectionState(bthf_connection_state_t aState,
                                             bt_bdaddr_t* aBdAddress)
 {
   BT_LOGR("%s: state %d", __FUNCTION__, aState);
 
   mConnectionState = aState;
 
   if (aState == BTHF_CONNECTION_STATE_CONNECTED) {
+    BdAddressTypeToString(aBdAddress, mDeviceAddress);
     BT_HF_DISPATCH_MAIN(MainThreadTaskCmd::NOTIFY_CONN_STATE_CHANGED,
                         NS_LITERAL_STRING(BLUETOOTH_HFP_STATUS_CHANGED_ID));
   } else if (aState == BTHF_CONNECTION_STATE_DISCONNECTED) {
     DisconnectSco();
     BT_HF_DISPATCH_MAIN(MainThreadTaskCmd::NOTIFY_CONN_STATE_CHANGED,
                         NS_LITERAL_STRING(BLUETOOTH_HFP_STATUS_CHANGED_ID));
-    Reset();
   }
 }
 
 void
 BluetoothHfpManager::ProcessAudioState(bthf_audio_state_t aState,
                                        bt_bdaddr_t* aBdAddress)
 {
   BT_LOGR("%s: state %d", __FUNCTION__, aState);
@@ -736,16 +736,18 @@ BluetoothHfpManager::NotifyConnectionSta
 
       // Enumerate current calls
       mListener->EnumerateCalls();
 
       OnConnect(EmptyString());
     } else if (mConnectionState == BTHF_CONNECTION_STATE_DISCONNECTED) {
       mDeviceAddress.AssignLiteral(BLUETOOTH_ADDRESS_NONE);
       OnDisconnect(EmptyString());
+
+      Reset();
     }
   }
 }
 
 void
 BluetoothHfpManager::NotifyDialer(const nsAString& aCommand)
 {
   BluetoothValue v;
--- a/dom/bluetooth/bluedroid/gonk/BluetoothServiceBluedroid.cpp
+++ b/dom/bluetooth/bluedroid/gonk/BluetoothServiceBluedroid.cpp
@@ -70,17 +70,17 @@ static bool sIsBtEnabled = false;
 static nsString sAdapterBdAddress;
 static nsString sAdapterBdName;
 static uint32_t sAdapterDiscoverableTimeout;
 static InfallibleTArray<nsString> sAdapterBondedAddressArray;
 static InfallibleTArray<BluetoothNamedValue> sRemoteDevicesPack;
 static nsTArray<nsRefPtr<BluetoothProfileController> > sControllerArray;
 static nsTArray<nsRefPtr<BluetoothReplyRunnable> > sBondingRunnableArray;
 static nsTArray<nsRefPtr<BluetoothReplyRunnable> > sChangeDiscoveryRunnableArray;
-static nsTArray<nsRefPtr<BluetoothReplyRunnable> > sGetPairedDeviceRunnableArray;
+static nsTArray<nsRefPtr<BluetoothReplyRunnable> > sGetDeviceRunnableArray;
 static nsTArray<nsRefPtr<BluetoothReplyRunnable> > sSetPropertyRunnableArray;
 static nsTArray<nsRefPtr<BluetoothReplyRunnable> > sUnbondingRunnableArray;
 static nsTArray<int> sRequestedDeviceCountArray;
 static StaticAutoPtr<Monitor> sToggleBtMonitor;
 
 /**
  *  Static callback functions
  */
@@ -351,17 +351,17 @@ static void
 RemoteDevicePropertiesChangeCallback(bt_status_t aStatus,
                                      bt_bdaddr_t *aBdAddress,
                                      int aNumProperties,
                                      bt_property_t *aProperties)
 {
   MOZ_ASSERT(!NS_IsMainThread());
 
   if (sRequestedDeviceCountArray.IsEmpty()) {
-    MOZ_ASSERT(sGetPairedDeviceRunnableArray.IsEmpty());
+    MOZ_ASSERT(sGetDeviceRunnableArray.IsEmpty());
     return;
   }
 
   sRequestedDeviceCountArray[0]--;
 
   InfallibleTArray<BluetoothNamedValue> props;
 
   nsString remoteDeviceBdAddress;
@@ -390,31 +390,31 @@ RemoteDevicePropertiesChangeCallback(bt_
     }
   }
 
   // Use address as the index
   sRemoteDevicesPack.AppendElement(
     BluetoothNamedValue(remoteDeviceBdAddress, props));
 
   if (sRequestedDeviceCountArray[0] == 0) {
-    MOZ_ASSERT(!sGetPairedDeviceRunnableArray.IsEmpty());
+    MOZ_ASSERT(!sGetDeviceRunnableArray.IsEmpty());
 
-    if (sGetPairedDeviceRunnableArray.IsEmpty()) {
+    if (sGetDeviceRunnableArray.IsEmpty()) {
       BT_LOGR("No runnable to return");
       return;
     }
 
-    DispatchBluetoothReply(sGetPairedDeviceRunnableArray[0],
+    DispatchBluetoothReply(sGetDeviceRunnableArray[0],
                            sRemoteDevicesPack, EmptyString());
 
     // After firing it, clean up cache
     sRemoteDevicesPack.Clear();
 
     sRequestedDeviceCountArray.RemoveElementAt(0);
-    sGetPairedDeviceRunnableArray.RemoveElementAt(0);
+    sGetDeviceRunnableArray.RemoveElementAt(0);
   }
 }
 
 static void
 DeviceFoundCallback(int aNumProperties, bt_property_t *aProperties)
 {
   MOZ_ASSERT(!NS_IsMainThread());
 
@@ -783,22 +783,64 @@ BluetoothServiceBluedroid::GetDefaultAda
 
   runnable.forget();
 
   return NS_OK;
 }
 
 nsresult
 BluetoothServiceBluedroid::GetConnectedDevicePropertiesInternal(
-  uint16_t aProfileId, BluetoothReplyRunnable* aRunnable)
+  uint16_t aServiceUuid, BluetoothReplyRunnable* aRunnable)
 {
   MOZ_ASSERT(NS_IsMainThread());
 
-  //FIXME: This will be implemented in later patches
-  DispatchBluetoothReply(aRunnable, BluetoothValue(true), EmptyString());
+  if (!IsReady()) {
+    NS_NAMED_LITERAL_STRING(errorStr, "Bluetooth service is not ready yet!");
+    DispatchBluetoothReply(aRunnable, BluetoothValue(), errorStr);
+    return NS_OK;
+  }
+
+  BluetoothProfileManagerBase* profile =
+    BluetoothUuidHelper::GetBluetoothProfileManager(aServiceUuid);
+  if (!profile) {
+    InfallibleTArray<BluetoothNamedValue> emptyArr;
+    DispatchBluetoothReply(aRunnable, emptyArr,
+                           NS_LITERAL_STRING(ERR_UNKNOWN_PROFILE));
+    return NS_OK;
+  }
+
+  nsTArray<nsString> deviceAddresses;
+  if (profile->IsConnected()) {
+    nsString address;
+    profile->GetAddress(address);
+    deviceAddresses.AppendElement(address);
+  }
+
+  int requestedDeviceCount = deviceAddresses.Length();
+  if (requestedDeviceCount == 0) {
+    InfallibleTArray<BluetoothNamedValue> emptyArr;
+    DispatchBluetoothReply(aRunnable, emptyArr, EmptyString());
+    return NS_OK;
+  }
+
+  for (int i = 0; i < requestedDeviceCount; i++) {
+    // Retrieve all properties of devices
+    bt_bdaddr_t addressType;
+    StringToBdAddressType(deviceAddresses[i], &addressType);
+
+    int ret = sBtInterface->get_remote_device_properties(&addressType);
+    if (ret != BT_STATUS_SUCCESS) {
+      DispatchBluetoothReply(aRunnable, BluetoothValue(true),
+                             NS_LITERAL_STRING("GetConnectedDeviceFailed"));
+      return NS_OK;
+    }
+  }
+
+  sRequestedDeviceCountArray.AppendElement(requestedDeviceCount);
+  sGetDeviceRunnableArray.AppendElement(aRunnable);
 
   return NS_OK;
 }
 
 nsresult
 BluetoothServiceBluedroid::GetPairedDevicePropertiesInternal(
   const nsTArray<nsString>& aDeviceAddress, BluetoothReplyRunnable* aRunnable)
 {
@@ -825,17 +867,17 @@ BluetoothServiceBluedroid::GetPairedDevi
     if (ret != BT_STATUS_SUCCESS) {
       DispatchBluetoothReply(aRunnable, BluetoothValue(true),
                              NS_LITERAL_STRING("GetPairedDeviceFailed"));
       return NS_OK;
     }
   }
 
   sRequestedDeviceCountArray.AppendElement(requestedDeviceCount);
-  sGetPairedDeviceRunnableArray.AppendElement(aRunnable);
+  sGetDeviceRunnableArray.AppendElement(aRunnable);
 
   return NS_OK;
 }
 
 nsresult
 BluetoothServiceBluedroid::StartDiscoveryInternal(
   BluetoothReplyRunnable* aRunnable)
 {
@@ -864,23 +906,25 @@ BluetoothServiceBluedroid::StopDiscovery
 {
   MOZ_ASSERT(NS_IsMainThread());
 
   if (!IsReady()) {
     NS_NAMED_LITERAL_STRING(errorStr, "Bluetooth service is not ready yet!");
     DispatchBluetoothReply(aRunnable, BluetoothValue(), errorStr);
     return NS_OK;
   }
+
   int ret = sBtInterface->cancel_discovery();
   if (ret != BT_STATUS_SUCCESS) {
     ReplyStatusError(aRunnable, ret, NS_LITERAL_STRING("StopDiscovery"));
     return NS_OK;
   }
 
   sChangeDiscoveryRunnableArray.AppendElement(aRunnable);
+
   return NS_OK;
 }
 
 nsresult
 BluetoothServiceBluedroid::GetDevicePropertiesInternal(
   const BluetoothSignal& aSignal)
 {
   return NS_OK;
@@ -1143,22 +1187,24 @@ nsresult
 BluetoothServiceBluedroid::PrepareAdapterInternal()
 {
   return NS_OK;
 }
 
 static void
 NextBluetoothProfileController()
 {
-  sControllerArray[0] = nullptr;
-  sControllerArray.RemoveElementAt(0);
+  MOZ_ASSERT(NS_IsMainThread());
 
-  if (!sControllerArray.IsEmpty()) {
-    sControllerArray[0]->Start();
-  }
+  // First, remove the task at the front which has been already done.
+  NS_ENSURE_FALSE_VOID(sControllerArray.IsEmpty());
+  sControllerArray.RemoveElementAt(0);
+  // Re-check if the task array is empty, if it's not, the next task will begin.
+  NS_ENSURE_FALSE_VOID(sControllerArray.IsEmpty());
+  sControllerArray[0]->Start();
 }
 
 static void
 ConnectDisconnect(bool aConnect, const nsAString& aDeviceAddress,
                   BluetoothReplyRunnable* aRunnable,
                   uint16_t aServiceUuid, uint32_t aCod = 0)
 {
   MOZ_ASSERT(NS_IsMainThread());
--- a/dom/fmradio/FMRadio.cpp
+++ b/dom/fmradio/FMRadio.cpp
@@ -34,23 +34,36 @@ BEGIN_FMRADIO_NAMESPACE
 class FMRadioRequest MOZ_FINAL : public FMRadioReplyRunnable
                                , public DOMRequest
 {
 public:
   NS_DECL_ISUPPORTS_INHERITED
 
   FMRadioRequest(nsPIDOMWindow* aWindow, FMRadio* aFMRadio)
     : DOMRequest(aWindow)
+    , mType(FMRadioRequestArgs::T__None)
   {
     // |FMRadio| inherits from |nsIDOMEventTarget| and |nsISupportsWeakReference|
     // which both inherits from nsISupports, so |nsISupports| is an ambiguous
     // base of |FMRadio|, we have to cast |aFMRadio| to one of the base classes.
     mFMRadio = do_GetWeakReference(static_cast<nsIDOMEventTarget*>(aFMRadio));
   }
 
+  FMRadioRequest(nsPIDOMWindow* aWindow, FMRadio* aFMRadio,
+    FMRadioRequestArgs::Type aType)
+    : DOMRequest(aWindow)
+  {
+    MOZ_ASSERT(aType >= FMRadioRequestArgs::T__None &&
+               aType <= FMRadioRequestArgs::T__Last,
+               "Wrong FMRadioRequestArgs in FMRadioRequest");
+
+    mFMRadio = do_GetWeakReference(static_cast<nsIDOMEventTarget*>(aFMRadio));
+    mType = aType;
+  }
+
   ~FMRadioRequest() { }
 
   NS_IMETHODIMP
   Run()
   {
     MOZ_ASSERT(NS_IsMainThread(), "Wrong thread!");
 
     nsCOMPtr<nsIDOMEventTarget> target = do_QueryReferent(mFMRadio);
@@ -65,33 +78,39 @@ public:
       return NS_OK;
     }
 
     switch (mResponseType.type()) {
       case FMRadioResponseType::TErrorResponse:
         FireError(mResponseType.get_ErrorResponse().error());
         break;
       case FMRadioResponseType::TSuccessResponse:
+        if (mType == FMRadioRequestArgs::TEnableRequestArgs) {
+          fmRadio->EnableAudioChannelAgent();
+        }
+
         FireSuccess(JS::UndefinedHandleValue);
         break;
       default:
         MOZ_CRASH();
     }
 
     return NS_OK;
   }
 
 private:
+  FMRadioRequestArgs::Type mType;
   nsWeakPtr mFMRadio;
 };
 
 NS_IMPL_ISUPPORTS_INHERITED0(FMRadioRequest, DOMRequest)
 
 FMRadio::FMRadio()
   : mHeadphoneState(SWITCH_STATE_OFF)
+  , mAudioChannelAgentEnabled(false)
   , mHasInternalAntenna(false)
   , mIsShutdown(false)
 {
   LOG("FMRadio is initialized.");
 
   SetIsDOMBinding();
 }
 
@@ -116,30 +135,39 @@ FMRadio::Init(nsPIDOMWindow *aWindow)
   }
 
   nsCOMPtr<nsIDOMEventTarget> target = do_QueryInterface(GetOwner());
   NS_ENSURE_TRUE_VOID(target);
   target->AddSystemEventListener(NS_LITERAL_STRING("visibilitychange"), this,
                                  /* useCapture = */ true,
                                  /* wantsUntrusted = */ false);
 
-  mAudioChannelAgent = do_CreateInstance("@mozilla.org/audiochannelagent;1");
-  if (!mAudioChannelAgent) {
-    return;
-  }
+
+  // All of the codes below are for AudioChannel. We can directly return here
+  // if preferences doesn't enable AudioChannelService.
+  NS_ENSURE_TRUE_VOID(Preferences::GetBool("media.useAudioChannelService"));
 
-  mAudioChannelAgent->InitWithWeakCallback(nsIAudioChannelAgent::AUDIO_AGENT_CHANNEL_CONTENT,
-                                           this);
+  nsCOMPtr<nsIAudioChannelAgent> audioChannelAgent =
+    do_CreateInstance("@mozilla.org/audiochannelagent;1");
+  NS_ENSURE_TRUE_VOID(audioChannelAgent);
+
+  audioChannelAgent->InitWithWeakCallback(
+    nsIAudioChannelAgent::AUDIO_AGENT_CHANNEL_CONTENT,
+    this);
 
   nsCOMPtr<nsIDocShell> docshell = do_GetInterface(GetOwner());
-  if (docshell) {
-    bool isActive = false;
-    docshell->GetIsActive(&isActive);
-    mAudioChannelAgent->SetVisibilityState(isActive);
-  }
+  NS_ENSURE_TRUE_VOID(docshell);
+
+  bool isActive = false;
+  docshell->GetIsActive(&isActive);
+  audioChannelAgent->SetVisibilityState(isActive);
+
+  // Once all necessary resources are got successfully, we just enabled
+  // mAudioChannelAgent.
+  mAudioChannelAgent = audioChannelAgent;
 }
 
 void
 FMRadio::Shutdown()
 {
   IFMRadioService::Singleton()->RemoveObserver(this);
 
   if (!mHasInternalAntenna) {
@@ -176,23 +204,22 @@ void
 FMRadio::Notify(const FMRadioEventType& aType)
 {
   switch (aType) {
     case FrequencyChanged:
       DispatchTrustedEvent(NS_LITERAL_STRING("frequencychange"));
       break;
     case EnabledChanged:
       if (Enabled()) {
-        int32_t playingState = 0;
-        mAudioChannelAgent->StartPlaying(&playingState);
-        SetCanPlay(playingState == AudioChannelState::AUDIO_CHANNEL_STATE_NORMAL);
-
         DispatchTrustedEvent(NS_LITERAL_STRING("enabled"));
       } else {
-        mAudioChannelAgent->StopPlaying();
+        if (mAudioChannelAgentEnabled) {
+          mAudioChannelAgent->StopPlaying();
+          mAudioChannelAgentEnabled = false;
+        }
 
         DispatchTrustedEvent(NS_LITERAL_STRING("disabled"));
       }
       break;
     default:
       MOZ_CRASH();
   }
 }
@@ -239,17 +266,18 @@ FMRadio::ChannelWidth() const
 already_AddRefed<DOMRequest>
 FMRadio::Enable(double aFrequency)
 {
   nsCOMPtr<nsPIDOMWindow> win = GetOwner();
   if (!win) {
     return nullptr;
   }
 
-  nsRefPtr<FMRadioRequest> r = new FMRadioRequest(win, this);
+  nsRefPtr<FMRadioRequest> r =
+    new FMRadioRequest(win, this, FMRadioRequestArgs::TEnableRequestArgs);
   IFMRadioService::Singleton()->Enable(aFrequency, r);
 
   return r.forget();
 }
 
 already_AddRefed<DOMRequest>
 FMRadio::Disable()
 {
@@ -335,16 +363,28 @@ FMRadio::HandleEvent(nsIDOMEvent* aEvent
 
   bool isActive = false;
   docshell->GetIsActive(&isActive);
 
   mAudioChannelAgent->SetVisibilityState(isActive);
   return NS_OK;
 }
 
+void
+FMRadio::EnableAudioChannelAgent()
+{
+  NS_ENSURE_TRUE_VOID(mAudioChannelAgent);
+
+  int32_t playingState = 0;
+  mAudioChannelAgent->StartPlaying(&playingState);
+  SetCanPlay(playingState == AudioChannelState::AUDIO_CHANNEL_STATE_NORMAL);
+
+  mAudioChannelAgentEnabled = true;
+}
+
 NS_IMETHODIMP
 FMRadio::CanPlayChanged(int32_t aCanPlay)
 {
   SetCanPlay(aCanPlay == AudioChannelState::AUDIO_CHANNEL_STATE_NORMAL);
   return NS_OK;
 }
 
 void
--- a/dom/fmradio/FMRadio.h
+++ b/dom/fmradio/FMRadio.h
@@ -29,17 +29,16 @@ class FMRadio MOZ_FINAL : public nsDOMEv
 
 {
   friend class FMRadioRequest;
 
 public:
   FMRadio();
 
   NS_DECL_ISUPPORTS_INHERITED
-  NS_DECL_NSIAUDIOCHANNELAGENTCALLBACK
 
   NS_REALLY_FORWARD_NSIDOMEVENTTARGET(nsDOMEventTargetHelper)
 
   void Init(nsPIDOMWindow *aWindow);
   void Shutdown();
 
   /* hal::SwitchObserver */
   virtual void Notify(const hal::SwitchEvent& aEvent) MOZ_OVERRIDE;
@@ -78,25 +77,30 @@ public:
 
   already_AddRefed<DOMRequest> CancelSeek();
 
   IMPL_EVENT_HANDLER(enabled);
   IMPL_EVENT_HANDLER(disabled);
   IMPL_EVENT_HANDLER(antennaavailablechange);
   IMPL_EVENT_HANDLER(frequencychange);
 
+  // nsIAudioChannelAgentCallback
+  NS_IMETHOD CanPlayChanged(int32_t aCanPlay);
+
   // nsIDOMEventListener
   NS_IMETHOD HandleEvent(nsIDOMEvent* aEvent);
 
 private:
   ~FMRadio();
 
   void SetCanPlay(bool aCanPlay);
+  void EnableAudioChannelAgent();
 
   hal::SwitchState mHeadphoneState;
+  bool mAudioChannelAgentEnabled;
   bool mHasInternalAntenna;
   bool mIsShutdown;
 
   nsCOMPtr<nsIAudioChannelAgent> mAudioChannelAgent;
 };
 
 END_FMRADIO_NAMESPACE
 
--- a/dom/gamepad/moz.build
+++ b/dom/gamepad/moz.build
@@ -5,17 +5,17 @@
 # file, You can obtain one at http://mozilla.org/MPL/2.0/.
 
 EXPORTS.mozilla.dom += [
     'Gamepad.h',
     'GamepadButton.h',
     'GamepadService.h',
     ]
 
-SOURCES = [
+UNIFIED_SOURCES = [
     'Gamepad.cpp',
     'GamepadButton.cpp',
     'GamepadService.cpp',
     ]
 
 FAIL_ON_WARNINGS = True
 
 include('/ipc/chromium/chromium-config.mozbuild')
--- a/dom/icc/tests/marionette/test_icc_card_state.js
+++ b/dom/icc/tests/marionette/test_icc_card_state.js
@@ -1,34 +1,27 @@
 /* Any copyright is dedicated to the Public Domain.
    http://creativecommons.org/publicdomain/zero/1.0/ */
 
 MARIONETTE_TIMEOUT = 30000;
 MARIONETTE_HEAD_JS = "icc_header.js";
 
 function setRadioEnabled(enabled) {
-  SpecialPowers.addPermission("settings-write", true, document);
+  let connection = navigator.mozMobileConnections[0];
+  ok(connection);
 
-  // TODO: Bug 856553 - [B2G] RIL: need an API to enable/disable radio
-  let settings = navigator.mozSettings;
-  let setLock = settings.createLock();
-  let obj = {
-    "ril.radio.disabled": !enabled
-  };
-  let setReq = setLock.set(obj);
+  let request  = connection.setRadioEnabled(enabled);
 
-  setReq.addEventListener("success", function onSetSuccess() {
-    log("set 'ril.radio.disabled' to " + enabled);
-  });
+  request.onsuccess = function onsuccess() {
+    log('setRadioEnabled: ' + enabled);
+  };
 
-  setReq.addEventListener("error", function onSetError() {
-    ok(false, "cannot set 'ril.radio.disabled' to " + enabled);
-  });
-
-  SpecialPowers.removePermission("settings-write", document);
+  request.onerror = function onerror() {
+    ok(false, "setRadioEnabled should be ok");
+  };
 }
 
 /* Basic test */
 taskHelper.push(function basicTest() {
   is(icc.cardState, "ready", "card state is " + icc.cardState);
   taskHelper.runNext();
 });
 
--- a/dom/icc/tests/marionette/test_icc_info.js
+++ b/dom/icc/tests/marionette/test_icc_info.js
@@ -1,34 +1,27 @@
 /* Any copyright is dedicated to the Public Domain.
    http://creativecommons.org/publicdomain/zero/1.0/ */
 
 MARIONETTE_TIMEOUT = 30000;
 MARIONETTE_HEAD_JS = "icc_header.js";
 
 function setRadioEnabled(enabled) {
-  SpecialPowers.addPermission("settings-write", true, document);
+  let connection = navigator.mozMobileConnections[0];
+  ok(connection);
 
-  // TODO: Bug 856553 - [B2G] RIL: need an API to enable/disable radio
-  let settings = navigator.mozSettings;
-  let setLock = settings.createLock();
-  let obj = {
-    "ril.radio.disabled": !enabled
-  };
-  let setReq = setLock.set(obj);
+  let request  = connection.setRadioEnabled(enabled);
 
-  setReq.addEventListener("success", function onSetSuccess() {
-    log("set 'ril.radio.disabled' to " + enabled);
-  });
+  request.onsuccess = function onsuccess() {
+    log('setRadioEnabled: ' + enabled);
+  };
 
-  setReq.addEventListener("error", function onSetError() {
-    ok(false, "cannot set 'ril.radio.disabled' to " + enabled);
-  });
-
-  SpecialPowers.removePermission("settings-write", document);
+  request.onerror = function onerror() {
+    ok(false, "setRadioEnabled should be ok");
+  };
 }
 
 function setEmulatorMccMnc(mcc, mnc) {
   let cmd = "operator set 0 Android,Android," + mcc + mnc;
   emulatorHelper.sendCommand(cmd, function (result) {
     let re = new RegExp("" + mcc + mnc + "$");
     ok(result[0].match(re), "MCC/MNC should be changed.");
   });
--- a/dom/indexedDB/IDBKeyRange.cpp
+++ b/dom/indexedDB/IDBKeyRange.cpp
@@ -72,17 +72,17 @@ IDBKeyRange::FromJSVal(JSContext* aCx,
     nsresult rv = GetKeyFromJSVal(aCx, aVal, keyRange->Lower());
     if (NS_FAILED(rv)) {
       return rv;
     }
   }
   else {
     MOZ_ASSERT(aVal.isObject());
     // An object is not permitted unless it's another IDBKeyRange.
-    if (NS_FAILED(UNWRAP_OBJECT(IDBKeyRange, aCx, obj, keyRange))) {
+    if (NS_FAILED(UNWRAP_OBJECT(IDBKeyRange, obj, keyRange))) {
       return NS_ERROR_DOM_INDEXEDDB_DATA_ERR;
     }
   }
 
   keyRange.forget(aKeyRange);
   return NS_OK;
 }
 
--- a/dom/indexedDB/IDBObjectStore.cpp
+++ b/dom/indexedDB/IDBObjectStore.cpp
@@ -1587,17 +1587,17 @@ IDBObjectStore::StructuredCloneWriteCall
     uint64_t value = 0;
     return JS_WriteBytes(aWriter, &value, sizeof(value));
   }
 
   IDBTransaction* transaction = cloneWriteInfo->mTransaction;
   FileManager* fileManager = transaction->Database()->Manager();
 
   file::FileHandle* fileHandle = nullptr;
-  if (NS_SUCCEEDED(UNWRAP_OBJECT(FileHandle, aCx, aObj, fileHandle))) {
+  if (NS_SUCCEEDED(UNWRAP_OBJECT(FileHandle, aObj, fileHandle))) {
     nsRefPtr<FileInfo> fileInfo = fileHandle->GetFileInfo();
 
     // Throw when trying to store non IDB file handles or IDB file handles
     // across databases.
     if (!fileInfo || fileInfo->Manager() != fileManager) {
       return false;
     }
 
--- a/dom/indexedDB/OpenDatabaseHelper.cpp
+++ b/dom/indexedDB/OpenDatabaseHelper.cpp
@@ -58,21 +58,46 @@ MakeSchemaVersion(uint32_t aMajorSchemaV
                   uint32_t aMinorSchemaVersion)
 {
   return int32_t((aMajorSchemaVersion << 4) + aMinorSchemaVersion);
 }
 
 const int32_t kSQLiteSchemaVersion = int32_t((kMajorSchemaVersion << 4) +
                                              kMinorSchemaVersion);
 
+const uint32_t kGoldenRatioU32 = 0x9E3779B9U;
+
+inline
+uint32_t
+RotateBitsLeft32(uint32_t value, uint8_t bits)
+{
+  MOZ_ASSERT(bits < 32);
+  return (value << bits) | (value >> (32 - bits));
+}
+
+inline
+uint32_t
+HashName(const nsAString& aName)
+{
+  const char16_t* str = aName.BeginReading();
+  size_t length = aName.Length();
+
+  uint32_t hash = 0;
+  for (size_t i = 0; i < length; i++) {
+    hash = kGoldenRatioU32 * (RotateBitsLeft32(hash, 5) ^ str[i]);
+  }
+
+  return hash;
+}
+
 nsresult
 GetDatabaseFilename(const nsAString& aName,
                     nsAString& aDatabaseFilename)
 {
-  aDatabaseFilename.AppendInt(HashString(aName));
+  aDatabaseFilename.AppendInt(HashName(aName));
 
   nsCString escapedName;
   if (!NS_Escape(NS_ConvertUTF16toUTF8(aName), escapedName, url_XPAlphas)) {
     NS_WARNING("Can't escape database name!");
     return NS_ERROR_UNEXPECTED;
   }
 
   const char* forwardIter = escapedName.BeginReading();
--- a/dom/indexedDB/ipc/IndexedDBParent.cpp
+++ b/dom/indexedDB/ipc/IndexedDBParent.cpp
@@ -410,17 +410,17 @@ IndexedDBDatabaseParent::HandleRequestEv
 
   ErrorResult error;
   JS::Rooted<JS::Value> result(cx, mOpenRequest->GetResult(cx, error));
   ENSURE_SUCCESS(error, error.ErrorCode());
 
   MOZ_ASSERT(!JSVAL_IS_PRIMITIVE(result));
 
   IDBDatabase *database;
-  rv = UNWRAP_OBJECT(IDBDatabase, cx, &result.toObject(), database);
+  rv = UNWRAP_OBJECT(IDBDatabase, &result.toObject(), database);
   if (NS_FAILED(rv)) {
     NS_WARNING("Didn't get the object we expected!");
     return rv;
   }
 
   DatabaseInfo* dbInfo = database->Info();
   MOZ_ASSERT(dbInfo);
 
--- a/dom/inputmethod/forms.js
+++ b/dom/inputmethod/forms.js
@@ -757,18 +757,19 @@ function isContentEditable(element) {
   return element.ownerDocument && element.ownerDocument.designMode == "on";
 }
 
 function isPlainTextField(element) {
   if (!element) {
     return false;
   }
 
-  return element instanceof HTMLInputElement ||
-         element instanceof HTMLTextAreaElement;
+  return element instanceof HTMLTextAreaElement ||
+         (element instanceof HTMLInputElement &&
+          element.mozIsTextField(false));
 }
 
 function getJSON(element, focusCounter) {
   // <input type=number> has a nested anonymous <input type=text> element that
   // takes focus on behalf of the number control when someone tries to focus
   // the number control. If |element| is such an anonymous text control then we
   // need it's number control here in order to get the correct 'type' etc.:
   element = element.ownerNumberControl || element;
--- a/dom/messages/SystemMessagePermissionsChecker.jsm
+++ b/dom/messages/SystemMessagePermissionsChecker.jsm
@@ -98,17 +98,18 @@ this.SystemMessagePermissionsTable = {
   "nfc-manager-tech-discovered": {
     "nfc-manager": []
   },
   "nfc-manager-tech-lost": {
     "nfc-manager": []
   },
   "nfc-powerlevel-change": {
     "settings": ["read", "write"]
-  }
+  },
+  "rtsp-open-video": {},
 };
 
 this.SystemMessagePermissionsChecker = {
   /**
    * Return all the needed permission names for the given system message.
    * @param string aSysMsgName
    *        The system messsage name.
    * @returns object
--- a/dom/network/interfaces/nsIDOMMobileConnection.idl
+++ b/dom/network/interfaces/nsIDOMMobileConnection.idl
@@ -6,17 +6,17 @@
 
 interface nsIDOMEventListener;
 interface nsIDOMDOMRequest;
 interface nsIDOMMozMobileConnectionInfo;
 interface nsIDOMMozMobileNetworkInfo;
 interface nsIDOMMozMobileCellInfo;
 interface nsIDOMMozMobileCFInfo;
 
-[scriptable, builtinclass, uuid(052550e3-7466-4941-80d7-405c169652f9)]
+[scriptable, builtinclass, uuid(4c8331f9-45f3-479d-ac3f-acb60fcc0583)]
 interface nsIDOMMozMobileConnection : nsIDOMEventTarget
 {
   const long ICC_SERVICE_CLASS_VOICE = (1 << 0);
   const long ICC_SERVICE_CLASS_DATA = (1 << 1);
   const long ICC_SERVICE_CLASS_FAX = (1 << 2);
   const long ICC_SERVICE_CLASS_SMS = (1 << 3);
   const long ICC_SERVICE_CLASS_DATA_SYNC = (1 << 4);
   const long ICC_SERVICE_CLASS_DATA_ASYNC = (1 << 5);
@@ -78,16 +78,24 @@ interface nsIDOMMozMobileConnection : ns
   /**
    * The selection mode of the voice and data networks.
    *
    * Possible values: null (unknown), 'automatic', 'manual'
    */
   readonly attribute DOMString networkSelectionMode;
 
   /**
+   * The current radio state.
+   *
+   * Possible values: null (unknown), 'enabling', 'enabled', 'disabling',
+   * 'disabled'
+   */
+  readonly attribute DOMString radioState;
+
+  /**
    * Search for available networks.
    *
    * If successful, the request's onsuccess will be called, and the request's
    * result will be an array of nsIDOMMozMobileNetworkInfo.
    *
    * Otherwise, the request's onerror will be called, and the request's error
    * will be either 'RadioNotAvailable', 'RequestNotSupported',
    * or 'GenericFailure'.
@@ -344,16 +352,34 @@ interface nsIDOMMozMobileConnection : ns
    * If successful, the request's onsuccess will be called.
    *
    * Otherwise, the request's onerror will be called, and the request's error
    * will be either 'RequestNotSupported'  or 'GenericFailure'.
    */
   nsIDOMDOMRequest exitEmergencyCbMode();
 
   /**
+   * Set radio enabled/disabled.
+   *
+   * @param enabled
+   *        True to enable the radio.
+   *
+   * If successful, the request's onsuccess will be called.
+   *
+   * Otherwise, the request's onerror will be called, and the request's error
+   * will be either 'InvalidStateError', 'RadioNotAvailable', or
+   * 'GenericFailure'.
+   *
+   * Note: Request is not available when radioState is null, 'enabling', or
+   *       'disabling'. Calling the function in above conditions will receive
+   *       'InvalidStateError' error.
+   */
+  nsIDOMDOMRequest setRadioEnabled(in boolean enabled);
+
+  /**
    * The 'voicechange' event is notified whenever the voice connection object
    * changes.
    */
   [implicit_jscontext] attribute jsval onvoicechange;
 
   /**
    * The 'datachange' event is notified whenever the data connection object
    * changes values.
@@ -390,16 +416,22 @@ interface nsIDOMMozMobileConnection : ns
    */
   [implicit_jscontext] attribute jsval onotastatuschange;
 
   /**
    * The 'oniccchange' event is notified whenever the iccid value
    * changes.
    */
   [implicit_jscontext] attribute jsval oniccchange;
+
+  /**
+   * The 'onradiostatechange' event is notified whenever the radio state
+   * changes.
+   */
+  [implicit_jscontext] attribute jsval onradiostatechange;
 };
 
 [scriptable, uuid(49706beb-a160-40b7-b745-50f62e389a2c)]
 interface nsIDOMMozMobileConnectionInfo : nsISupports
 {
   /**
    * State of the connection.
    *
--- a/dom/network/interfaces/nsIMobileConnectionProvider.idl
+++ b/dom/network/interfaces/nsIMobileConnectionProvider.idl
@@ -5,17 +5,17 @@
 #include "nsISupports.idl"
 
 interface nsIDOMDOMRequest;
 interface nsIDOMMozMobileCFInfo;
 interface nsIDOMMozMobileConnectionInfo;
 interface nsIDOMMozMobileNetworkInfo;
 interface nsIDOMWindow;
 
-[scriptable, uuid(f02c50d5-9d34-4f24-80eb-527a280e31fa)]
+[scriptable, uuid(5013f5cc-24f9-45dc-ba03-f5dc031a3a6b)]
 interface nsIMobileConnectionListener : nsISupports
 {
   void notifyVoiceChanged();
   void notifyDataChanged();
   void notifyUssdReceived(in DOMString message,
                           in boolean sessionEnded);
   void notifyDataError(in DOMString message);
   void notifyCFStateChange(in boolean success,
@@ -23,39 +23,41 @@ interface nsIMobileConnectionListener : 
                            in unsigned short reason,
                            in DOMString number,
                            in unsigned short timeSeconds,
                            in unsigned short serviceClass);
   void notifyEmergencyCbModeChanged(in boolean active,
                                     in unsigned long timeoutMs);
   void notifyOtaStatusChanged(in DOMString status);
   void notifyIccChanged();
+  void notifyRadioStateChanged();
 };
 
 /**
  * XPCOM component (in the content process) that provides the mobile
  * network information.
  */
-[scriptable, uuid(84278a49-0f05-4585-b3f4-c74882ae5719)]
+[scriptable, uuid(9a804dc4-6900-46af-8c38-3d0f424672b5)]
 interface nsIMobileConnectionProvider : nsISupports
 {
   /**
    * Called when a content process registers receiving unsolicited messages from
    * RadioInterfaceLayer in the chrome process. Only a content process that has
    * the 'mobileconnection' permission is allowed to register.
    */
   void registerMobileConnectionMsg(in unsigned long clientId,
                                    in nsIMobileConnectionListener listener);
   void unregisterMobileConnectionMsg(in unsigned long clientId,
                                      in nsIMobileConnectionListener listener);
 
   nsIDOMMozMobileConnectionInfo getVoiceConnectionInfo(in unsigned long clientId);
   nsIDOMMozMobileConnectionInfo getDataConnectionInfo(in unsigned long clientId);
   DOMString getIccId(in unsigned long clientId);
   DOMString getNetworkSelectionMode(in unsigned long clientId);
+  DOMString getRadioState(in unsigned long clientId);
 
   nsIDOMDOMRequest getNetworks(in unsigned long clientId,
                                in nsIDOMWindow window);
   nsIDOMDOMRequest selectNetwork(in unsigned long clientId,
                                  in nsIDOMWindow window,
                                  in nsIDOMMozMobileNetworkInfo network);
   nsIDOMDOMRequest selectNetworkAutomatically(in unsigned long clientId,
                                               in nsIDOMWindow window);
@@ -104,9 +106,11 @@ interface nsIMobileConnectionProvider : 
   nsIDOMDOMRequest setCallingLineIdRestriction(in unsigned long clientId,
                                                in nsIDOMWindow window,
                                                in unsigned short clirMode);
   nsIDOMDOMRequest getCallingLineIdRestriction(in unsigned long clientId,
                                                in nsIDOMWindow window);
 
   nsIDOMDOMRequest exitEmergencyCbMode(in unsigned long clientId,
                                        in nsIDOMWindow window);
+
+  nsIDOMDOMRequest setRadioEnabled(in unsigned long clientId, in nsIDOMWindow window, in bool enabled);
 };
--- a/dom/network/src/MobileConnection.cpp
+++ b/dom/network/src/MobileConnection.cpp
@@ -73,16 +73,17 @@ NS_IMPL_RELEASE_INHERITED(MobileConnecti
 NS_IMPL_EVENT_HANDLER(MobileConnection, voicechange)
 NS_IMPL_EVENT_HANDLER(MobileConnection, datachange)
 NS_IMPL_EVENT_HANDLER(MobileConnection, ussdreceived)
 NS_IMPL_EVENT_HANDLER(MobileConnection, dataerror)
 NS_IMPL_EVENT_HANDLER(MobileConnection, cfstatechange)
 NS_IMPL_EVENT_HANDLER(MobileConnection, emergencycbmodechange)
 NS_IMPL_EVENT_HANDLER(MobileConnection, otastatuschange)
 NS_IMPL_EVENT_HANDLER(MobileConnection, iccchange)
+NS_IMPL_EVENT_HANDLER(MobileConnection, radiostatechange)
 
 MobileConnection::MobileConnection(uint32_t aClientId)
 : mClientId(aClientId)
 {
   mProvider = do_GetService(NS_RILCONTENTHELPER_CONTRACTID);
   mWindow = nullptr;
 
   // Not being able to acquire the provider isn't fatal since we check
@@ -207,16 +208,27 @@ MobileConnection::GetNetworkSelectionMod
 
   if (!mProvider || !CheckPermission("mobileconnection")) {
      return NS_OK;
   }
   return mProvider->GetNetworkSelectionMode(mClientId, aNetworkSelectionMode);
 }
 
 NS_IMETHODIMP
+MobileConnection::GetRadioState(nsAString& aRadioState)
+{
+  aRadioState.SetIsVoid(true);
+
+  if (!mProvider || !CheckPermission("mobileconnection")) {
+     return NS_OK;
+  }
+  return mProvider->GetRadioState(mClientId, aRadioState);
+}
+
+NS_IMETHODIMP
 MobileConnection::GetNetworks(nsIDOMDOMRequest** aRequest)
 {
   *aRequest = nullptr;
 
   if (!CheckPermission("mobileconnection")) {
     return NS_OK;
   }
 
@@ -514,16 +526,33 @@ MobileConnection::ExitEmergencyCbMode(ns
 
   if (!mProvider) {
     return NS_ERROR_FAILURE;
   }
 
   return mProvider->ExitEmergencyCbMode(mClientId, GetOwner(), aRequest);
 }
 
+NS_IMETHODIMP
+MobileConnection::SetRadioEnabled(bool aEnabled,
+                                  nsIDOMDOMRequest** aRequest)
+{
+  *aRequest = nullptr;
+
+  if (!CheckPermission("mobileconnection")) {
+    return NS_OK;
+  }
+
+  if (!mProvider) {
+    return NS_ERROR_FAILURE;
+  }
+
+  return mProvider->SetRadioEnabled(mClientId, GetOwner(), aEnabled, aRequest);
+}
+
 // nsIMobileConnectionListener
 
 NS_IMETHODIMP
 MobileConnection::NotifyVoiceChanged()
 {
   if (!CheckPermission("mobileconnection")) {
     return NS_OK;
   }
@@ -649,8 +678,18 @@ NS_IMETHODIMP
 MobileConnection::NotifyIccChanged()
 {
   if (!CheckPermission("mobileconnection")) {
     return NS_OK;
   }
 
   return DispatchTrustedEvent(NS_LITERAL_STRING("iccchange"));
 }
+
+NS_IMETHODIMP
+MobileConnection::NotifyRadioStateChanged()
+{
+  if (!CheckPermission("mobileconnection")) {
+    return NS_OK;
+  }
+
+  return DispatchTrustedEvent(NS_LITERAL_STRING("radiostatechange"));
+}
\ No newline at end of file
--- a/dom/network/tests/marionette/manifest.ini
+++ b/dom/network/tests/marionette/manifest.ini
@@ -13,8 +13,9 @@ disabled = Bug 808783
 [test_mobile_data_connection.js]
 [test_mobile_data_location.js]
 [test_mobile_data_state.js]
 [test_mobile_mmi.js]
 [test_mobile_roaming_preference.js]
 [test_call_barring_get_option.js]
 [test_call_barring_set_error.js]
 [test_call_barring_change_password.js]
+[test_mobile_set_radio.js]
new file mode 100644
--- /dev/null
+++ b/dom/network/tests/marionette/test_mobile_set_radio.js
@@ -0,0 +1,166 @@
+/* Any copyright is dedicated to the Public Domain.
+ * http://creativecommons.org/publicdomain/zero/1.0/ */
+
+MARIONETTE_TIMEOUT = 60000;
+
+const DATA_KEY  = "ril.data.enabled";
+const APN_KEY   = "ril.data.apnSettings";
+
+let Promise = SpecialPowers.Cu.import("resource://gre/modules/Promise.jsm").Promise;
+
+SpecialPowers.setBoolPref("dom.mozSettings.enabled", true);
+SpecialPowers.addPermission("mobileconnection", true, document);
+SpecialPowers.addPermission("settings-read", true, document);
+SpecialPowers.addPermission("settings-write", true, document);
+
+let settings = window.navigator.mozSettings;
+let connection = window.navigator.mozMobileConnections[0];
+ok(connection instanceof MozMobileConnection,
+   "connection is instanceof " + connection.constructor);
+
+function setSetting(key, value) {
+  let deferred = Promise.defer();
+
+  let setLock = settings.createLock();
+  let obj = {};
+  obj[key] = value;
+
+  let setReq = setLock.set(obj);
+  setReq.addEventListener("success", function onSetSuccess() {
+    ok(true, "set '" + key + "' to " + obj[key]);
+    deferred.resolve();
+  });
+  setReq.addEventListener("error", function onSetError() {
+    ok(false, "cannot set '" + key + "'");
+    deferred.reject();
+  });
+
+  return deferred.promise;
+}
+
+function setEmulatorAPN() {
+  let apn =
+    [
+      [
+        {"carrier":"T-Mobile US",
+         "apn":"epc.tmobile.com",
+         "mmsc":"http://mms.msg.eng.t-mobile.com/mms/wapenc",
+         "types":["default","supl","mms"]}
+      ]
+    ];
+  return setSetting(APN_KEY, apn);
+}
+
+function enableData() {
+  log("Turn data on.");
+
+  let deferred = Promise.defer();
+
+  connection.addEventListener("datachange", function ondatachange() {
+    if (connection.data.connected === true) {
+      connection.removeEventListener("datachange", ondatachange);
+      log("mobileConnection.data.connected is now '"
+          + connection.data.connected + "'.");
+      deferred.resolve();
+    }
+  });
+
+  setEmulatorAPN()
+    .then(() => setSetting(DATA_KEY, true));
+
+  return deferred.promise;
+}
+
+function receivedPending(received, pending, nextAction) {
+  let index = pending.indexOf(received);
+  if (index != -1) {
+    pending.splice(index, 1);
+  }
+  if (pending.length === 0) {
+    nextAction();
+  }
+}
+
+function waitRadioState(state) {
+  let deferred = Promise.defer();
+
+  waitFor(function() {
+    deferred.resolve();
+  }, function() {
+    return connection.radioState == state;
+  });
+
+  return deferred.promise;
+}
+
+function setRadioEnabled(enabled, transientState, finalState) {
+  log("setRadioEnabled to " + enabled);
+
+  let deferred = Promise.defer();
+  let done = function() {
+    deferred.resolve();
+  };
+
+  let pending = ["onradiostatechange", "onsuccess"];
+
+  let receivedTransient = false;
+  connection.onradiostatechange = function() {
+    let state = connection.radioState;
+    log("Received 'radiostatechange' event, radioState: " + state);
+
+    if (state == transientState) {
+      receivedTransient = true;
+    } else if (state == finalState) {
+      ok(receivedTransient);
+      receivedPending("onradiostatechange", pending, done);
+    }
+  };
+
+  let req = connection.setRadioEnabled(enabled);
+
+  req.onsuccess = function() {
+    log("setRadioEnabled success");
+    receivedPending("onsuccess", pending, done);
+  };
+
+  req.onerror = function() {
+    ok(false, "setRadioEnabled should not fail");
+    deferred.reject();
+  };
+
+  return deferred.promise;
+}
+
+function testSwitchRadio() {
+  log("= testSwitchRadio =");
+  return waitRadioState("enabled")
+    .then(setRadioEnabled.bind(null, false, "disabling", "disabled"))
+    .then(setRadioEnabled.bind(null, true, "enabling", "enabled"));
+}
+
+function testDisableRadioWhenDataConnected() {
+  log("= testDisableRadioWhenDataConnected =");
+  return waitRadioState("enabled")
+    .then(enableData)
+    .then(setRadioEnabled.bind(null, false, "disabling", "disabled"))
+    .then(() => {
+      // Data should be disconnected.
+      is(connection.data.connected, false);
+    })
+    .then(setRadioEnabled.bind(null, true, "enabling", "enabled"));
+}
+
+function cleanUp() {
+  SpecialPowers.removePermission("mobileconnection", document);
+  SpecialPowers.removePermission("settings-write", document);
+  SpecialPowers.removePermission("settings-read", document);
+  SpecialPowers.clearUserPref("dom.mozSettings.enabled");
+  finish();
+}
+
+testSwitchRadio()
+  .then(testDisableRadioWhenDataConnected)
+  .then(null, () => {
+    ok(false, "promise reject somewhere");
+  })
+  .then(cleanUp);
--- a/dom/plugins/test/testplugin/Makefile.in
+++ b/dom/plugins/test/testplugin/Makefile.in
@@ -1,10 +1,8 @@
 #
 # This Source Code Form is subject to the terms of the Mozilla Public
 # License, v. 2.0. If a copy of the MPL was not distributed with this
 # file, You can obtain one at http://mozilla.org/MPL/2.0/.
 
-MODULE_NAME  = TestPlugin
-
 RELATIVE_PATH=.
 COCOA_NAME=Test
 include @srcdir@/testplugin.mk
--- a/dom/plugins/test/testplugin/secondplugin/Makefile.in
+++ b/dom/plugins/test/testplugin/secondplugin/Makefile.in
@@ -1,10 +1,8 @@
 #
 # This Source Code Form is subject to the terms of the Mozilla Public
 # License, v. 2.0. If a copy of the MPL was not distributed with this file,
 # You can obtain one at http://mozilla.org/MPL/2.0/.
 
-MODULE_NAME  = SecondTestPlugin
-
 RELATIVE_PATH=..
 COCOA_NAME=SecondTest
 include @srcdir@/../testplugin.mk
--- a/dom/promise/Promise.cpp
+++ b/dom/promise/Promise.cpp
@@ -228,17 +228,17 @@ Promise::JSCallback(JSContext *aCx, unsi
   JS::CallArgs args = CallArgsFromVp(aArgc, aVp);
 
   JS::Rooted<JS::Value> v(aCx,
                           js::GetFunctionNativeReserved(&args.callee(),
                                                         SLOT_PROMISE));
   MOZ_ASSERT(v.isObject());
 
   Promise* promise;
-  if (NS_FAILED(UNWRAP_OBJECT(Promise, aCx, &v.toObject(), promise))) {
+  if (NS_FAILED(UNWRAP_OBJECT(Promise, &v.toObject(), promise))) {
     return Throw(aCx, NS_ERROR_UNEXPECTED);
   }
 
   v = js::GetFunctionNativeReserved(&args.callee(), SLOT_TASK);
   PromiseCallback::Task task = static_cast<PromiseCallback::Task>(v.toInt32());
 
   if (task == PromiseCallback::Resolve) {
     promise->MaybeResolveInternal(aCx, args.get(0));
@@ -496,17 +496,17 @@ Promise::ResolveInternal(JSContext* aCx,
                          PromiseTaskSync aAsynchronous)
 {
   mResolvePending = true;
 
   // TODO: Bug 879245 - Then-able objects
   if (aValue.isObject()) {
     JS::Rooted<JSObject*> valueObj(aCx, &aValue.toObject());
     Promise* nextPromise;
-    nsresult rv = UNWRAP_OBJECT(Promise, aCx, valueObj, nextPromise);
+    nsresult rv = UNWRAP_OBJECT(Promise, valueObj, nextPromise);
 
     if (NS_SUCCEEDED(rv)) {
       nsRefPtr<PromiseCallback> resolveCb = new ResolvePromiseCallback(this);
       nsRefPtr<PromiseCallback> rejectCb = new RejectPromiseCallback(this);
       nextPromise->AppendCallbacks(resolveCb, rejectCb);
       return;
     }
   }
--- a/dom/system/gonk/RILContentHelper.js
+++ b/dom/system/gonk/RILContentHelper.js
@@ -96,16 +96,18 @@ const RIL_IPC_MSG_NAMES = [
   "RIL:IccOpenChannel",
   "RIL:IccCloseChannel",
   "RIL:IccExchangeAPDU",
   "RIL:ReadIccContacts",
   "RIL:UpdateIccContact",
   "RIL:SetRoamingPreference",
   "RIL:GetRoamingPreference",
   "RIL:ExitEmergencyCbMode",
+  "RIL:SetRadioEnabled",
+  "RIL:RadioStateChanged",
   "RIL:SetVoicePrivacyMode",
   "RIL:GetVoicePrivacyMode",
   "RIL:OtaStatusChanged"
 ];
 
 XPCOMUtils.defineLazyServiceGetter(this, "cpmm",
                                    "@mozilla.org/childprocessmessagemanager;1",
                                    "nsISyncMessageSender");
@@ -454,16 +456,17 @@ function RILContentHelper() {
 
   this.rilContexts = [];
   this.voicemailInfos = [];
   this.voicemailStatuses = [];
   for (let clientId = 0; clientId < this.numClients; clientId++) {
     this.rilContexts[clientId] = {
       cardState:            RIL.GECKO_CARDSTATE_UNKNOWN,
       networkSelectionMode: RIL.GECKO_NETWORK_SELECTION_UNKNOWN,
+      radioState:           null,
       iccInfo:              null,
       voiceConnectionInfo:  new MobileConnectionInfo(),
       dataConnectionInfo:   new MobileConnectionInfo()
     };
 
     this.voicemailInfos[clientId] = new VoicemailInfo();
   }
 
@@ -606,16 +609,17 @@ RILContentHelper.prototype = {
       let rilContext =
         cpmm.sendSyncMessage("RIL:GetRilContext", {clientId: cId})[0];
       if (!rilContext) {
         if (DEBUG) debug("Received null rilContext from chrome process.");
         continue;
       }
       this.rilContexts[cId].cardState = rilContext.cardState;
       this.rilContexts[cId].networkSelectionMode = rilContext.networkSelectionMode;
+      this.rilContexts[cId].radioState = rilContext.detailedRadioState;
       this.updateIccInfo(cId, rilContext.iccInfo);
       this.updateConnectionInfo(rilContext.voice, this.rilContexts[cId].voiceConnectionInfo);
       this.updateConnectionInfo(rilContext.data, this.rilContexts[cId].dataConnectionInfo);
     }
 
     return this.rilContexts[clientId];
   },
 
@@ -652,16 +656,21 @@ RILContentHelper.prototype = {
     return context && context.iccInfo && context.iccInfo.iccid;
   },
 
   getNetworkSelectionMode: function getNetworkSelectionMode(clientId) {
     let context = this.getRilContext(clientId);
     return context && context.networkSelectionMode;
   },
 
+  getRadioState: function getRadioState(clientId) {
+    let context = this.getRilContext(clientId);
+    return context && context.radioState;
+  },
+
   /**
    * The networks that are currently trying to be selected (or "automatic").
    * This helps ensure that only one network per client is selected at a time.
    */
   _selectingNetworks: null,
 
   getNetworks: function getNetworks(clientId, window) {
     if (window == null) {
@@ -1357,16 +1366,35 @@ RILContentHelper.prototype = {
       data: {
         requestId: requestId,
       }
     });
 
     return request;
   },
 
+  setRadioEnabled: function setRadioEnabled(clientId, window, enabled) {
+    if (window == null) {
+      throw Components.Exception("Can't get window object",
+                                  Cr.NS_ERROR_UNEXPECTED);
+    }
+    let request = Services.DOMRequest.createRequest(window);
+    let requestId = this.getRequestId(request);
+
+    cpmm.sendAsyncMessage("RIL:SetRadioEnabled", {
+      clientId: clientId,
+      data: {
+        requestId: requestId,
+        enabled: enabled,
+      }
+    });
+
+    return request;
+  },
+
   _mobileConnectionListeners: null,
   _cellBroadcastListeners: null,
   _voicemailListeners: null,
   _iccListeners: null,
 
   voicemailInfos: null,
   voicemailStatuses: null,
 
@@ -1762,16 +1790,26 @@ RILContentHelper.prototype = {
         this.handleExitEmergencyCbMode(data);
         break;
       case "RIL:EmergencyCbModeChanged":
         this._deliverEvent(clientId,
                            "_mobileConnectionListeners",
                            "notifyEmergencyCbModeChanged",
                            [data.active, data.timeoutMs]);
         break;
+      case "RIL:SetRadioEnabled":
+        this.handleSimpleRequest(data.requestId, data.errorMsg, null);
+        break;
+      case "RIL:RadioStateChanged":
+        this.rilContexts[clientId].radioState = data;
+        this._deliverEvent(clientId,
+                           "_mobileConnectionListeners",
+                           "notifyRadioStateChanged",
+                           null);
+        break;
       case "RIL:SetVoicePrivacyMode":
         this.handleSimpleRequest(data.requestId, data.errorMsg, null);
         break;
       case "RIL:GetVoicePrivacyMode":
         this.handleSimpleRequest(data.requestId, data.errorMsg,
                                  data.enabled);
         break;
     }
@@ -2089,9 +2127,8 @@ RILContentHelper.prototype = {
 
     return true;
   }
 };
 
 this.NSGetFactory = XPCOMUtils.generateNSGetFactory([RILContentHelper,
                                                      DOMMMIError,
                                                      IccCardLockError]);
-
--- a/dom/system/gonk/RadioInterfaceLayer.js
+++ b/dom/system/gonk/RadioInterfaceLayer.js
@@ -16,16 +16,17 @@
 "use strict";
 
 const {classes: Cc, interfaces: Ci, utils: Cu, results: Cr} = Components;
 
 Cu.import("resource://gre/modules/XPCOMUtils.jsm");
 Cu.import("resource://gre/modules/Services.jsm");
 Cu.import("resource://gre/modules/Sntp.jsm");
 Cu.import("resource://gre/modules/systemlibs.js");
+Cu.import("resource://gre/modules/Promise.jsm");
 
 var RIL = {};
 Cu.import("resource://gre/modules/ril_consts.js", RIL);
 
 // set to true in ril_consts.js to see debug messages
 var DEBUG = RIL.DEBUG_RIL;
 
 // Read debug setting from pref
@@ -101,16 +102,17 @@ const RIL_IPC_MOBILECONNECTION_MSG_NAMES
   "RIL:ChangeCallBarringPassword",
   "RIL:SetCallWaitingOptions",
   "RIL:GetCallWaitingOptions",
   "RIL:SetCallingLineIdRestriction",
   "RIL:GetCallingLineIdRestriction",
   "RIL:SetRoamingPreference",
   "RIL:GetRoamingPreference",
   "RIL:ExitEmergencyCbMode",
+  "RIL:SetRadioEnabled",
   "RIL:SetVoicePrivacyMode",
   "RIL:GetVoicePrivacyMode"
 ];
 
 const RIL_IPC_ICCMANAGER_MSG_NAMES = [
   "RIL:SendStkResponse",
   "RIL:SendStkMenuSelection",
   "RIL:SendStkTimerExpiration",
@@ -412,16 +414,21 @@ XPCOMUtils.defineLazyGetter(this, "gMess
 
       let clientId = msg.json.clientId || 0;
       let radioInterface = this.ril.getRadioInterface(clientId);
       if (!radioInterface) {
         if (DEBUG) debug("No such radio interface: " + clientId);
         return null;
       }
 
+      if (msg.name === "RIL:SetRadioEnabled") {
+        // Special handler for SetRadioEnabled.
+        return gRadioEnabledController.receiveMessage(msg);
+      }
+
       return radioInterface.receiveMessage(msg);
     },
 
     /**
      * nsIObserver interface methods.
      */
 
     observe: function observe(subject, topic, data) {
@@ -461,17 +468,141 @@ XPCOMUtils.defineLazyGetter(this, "gMess
       this._sendTargetMessage("icc", message, {
         clientId: clientId,
         data: data
       });
     }
   };
 });
 
-// Initialize shared preference 'ril.numRadioInterfaces' according to system
+XPCOMUtils.defineLazyGetter(this, "gRadioEnabledController", function () {
+  return {
+    ril: null,
+    pendingMessages: [],  // For queueing "RIL:SetRadioEnabled" messages.
+    timer: null,
+    request: null,
+    deactivatingDeferred: {},
+
+    init: function init(ril) {
+      this.ril = ril;
+    },
+
+    receiveMessage: function(msg) {
+      if (DEBUG) debug("setRadioEnabled: receiveMessage: " + JSON.stringify(msg));
+      this.pendingMessages.push(msg);
+      if (this.pendingMessages.length === 1) {
+        this._processNextMessage();
+      }
+    },
+
+    isDeactivatingDataCalls: function() {
+      return this.request !== null;
+    },
+
+    finishDeactivatingDataCalls: function(clientId) {
+      if (DEBUG) debug("setRadioEnabled: finishDeactivatingDataCalls: " + clientId);
+      let deferred = this.deactivatingDeferred[clientId];
+      if (deferred) {
+        deferred.resolve();
+      }
+    },
+
+    _processNextMessage: function() {
+      if (this.pendingMessages.length === 0) {
+        return;
+      }
+
+      let msg = this.pendingMessages.shift();
+      this._handleMessage(msg);
+    },
+
+    _handleMessage: function(msg) {
+      if (DEBUG) debug("setRadioEnabled: handleMessage: " + JSON.stringify(msg));
+      let radioInterface = this.ril.getRadioInterface(msg.json.clientId || 0);
+
+      if (!radioInterface.isValidStateForSetRadioEnabled()) {
+        radioInterface.setRadioEnabledResponse(msg.target, msg.json.data,
+                                               "InvalidStateError");
+        this._processNextMessage();
+        return;
+      }
+
+      if (radioInterface.isDummyForSetRadioEnabled(msg.json.data)) {
+        radioInterface.setRadioEnabledResponse(msg.target, msg.json.data);
+        this._processNextMessage();
+        return;
+      }
+
+      if (msg.json.data.enabled) {
+        radioInterface.receiveMessage(msg);
+        this._processNextMessage();
+      } else {
+        this.request = (function() {
+          radioInterface.receiveMessage(msg);
+          this._processNextMessage();
+        }).bind(this);
+
+        // In some DSDS architecture with only one modem, toggling one radio may
+        // toggle both. Therefore, for safely turning off, we should first
+        // explicitly deactivate all data calls from all clients.
+        this._deactivateDataCalls().then(() => {
+          if (DEBUG) debug("setRadioEnabled: deactivation done");
+          this._executeRequest();
+        });
+
+        this._createTimer();
+      }
+    },
+
+    _deactivateDataCalls: function() {
+      if (DEBUG) debug("setRadioEnabled: deactivating data calls...");
+      this.deactivatingDeferred = {};
+
+      let promise = Promise.resolve();
+      for (let i = 0, N = this.ril.numRadioInterfaces; i < N; ++i) {
+        promise = promise.then(this._deactivateDataCallsForClient(i));
+      }
+
+      return promise;
+    },
+
+    _deactivateDataCallsForClient: function(clientId) {
+      return (function() {
+        let deferred = this.deactivatingDeferred[clientId] = Promise.defer();
+        this.ril.getRadioInterface(clientId).deactivateDataCalls();
+        return deferred.promise;
+      }).bind(this);
+    },
+
+    _createTimer: function() {
+      if (!this.timer) {
+        this.timer = Cc["@mozilla.org/timer;1"].createInstance(Ci.nsITimer);
+      }
+      this.timer.initWithCallback(this._executeRequest, RADIO_POWER_OFF_TIMEOUT,
+                                  Ci.nsITimer.TYPE_ONE_SHOT);
+    },
+
+    _cancelTimer: function() {
+      if (this.timer) {
+        this.timer.cancel();
+      }
+    },
+
+    _executeRequest: function() {
+      if (typeof this.request === "function") {
+        if (DEBUG) debug("setRadioEnabled: executeRequest");
+        this._cancelTimer();
+        this.request();
+        this.request = null;
+      }
+    }
+  };
+});
+
+// Initialize shared preference "ril.numRadioInterfaces" according to system
 // property.
 try {
   Services.prefs.setIntPref(kPrefRilNumRadioInterfaces, (function () {
     // When Gonk property "ro.moz.ril.numclients" is not set, return 1; if
     // explicitly set to any number larger-equal than 0, return num; else, return
     // 1 for compatibility.
     try {
       let numString = libcutils.property_get("ro.moz.ril.numclients", "1");
@@ -527,16 +658,17 @@ CdmaIccInfo.prototype = {
 
   // nsIDOMMozCdmaIccInfo
 
   mdn: null
 };
 
 function RadioInterfaceLayer() {
   gMessageManager.init(this);
+  gRadioEnabledController.init(this);
 
   let options = {
     debug: debugPref,
     cellBroadcastDisabled: false,
     clirMode: RIL.CLIR_DEFAULT
   };
 
   try {
@@ -680,17 +812,17 @@ WorkerMessenger.prototype = {
    * Send arbitrary message to worker.
    *
    * @param rilMessageType
    *        A text message type.
    * @param message [optional]
    *        An optional message object to send.
    * @param callback [optional]
    *        An optional callback function which is called when worker replies
-   *        with an message containing a 'rilMessageToken' attribute of the
+   *        with an message containing a "rilMessageToken" attribute of the
    *        same value we passed.  This callback function accepts only one
    *        parameter -- the reply from worker.  It also returns a boolean
    *        value true to keep current token-callback mapping and wait for
    *        another worker reply, or false to remove the mapping.
    */
   send: function send(rilMessageType, message, callback) {
     message = message || {};
 
@@ -715,17 +847,17 @@ WorkerMessenger.prototype = {
   /**
    * Send message to worker and return worker reply to RILContentHelper.
    *
    * @param msg
    *        A message object from ppmm.
    * @param rilMessageType
    *        A text string for worker message type.
    * @param ipcType [optinal]
-   *        A text string for ipc message type. 'msg.name' if omitted.
+   *        A text string for ipc message type. "msg.name" if omitted.
    *
    * @TODO: Bug 815526 - deprecate RILContentHelper.
    */
   sendWithIPCMessage: function sendWithIPCMessage(msg, rilMessageType, ipcType) {
     this.send(rilMessageType, msg.json.data, (function(reply) {
       ipcType = ipcType || msg.name;
       msg.target.sendAsyncMessage(ipcType, {
         clientId: this.radioInterface.clientId,
@@ -753,16 +885,17 @@ function RadioInterface(options) {
   //     via a given APN type.
   this.apnSettings = {
     byType: {},
     byApn: {}
   };
 
   this.rilContext = {
     radioState:     RIL.GECKO_RADIOSTATE_UNAVAILABLE,
+    detailedRadioState: null,
     cardState:      RIL.GECKO_CARDSTATE_UNKNOWN,
     networkSelectionMode: RIL.GECKO_NETWORK_SELECTION_UNKNOWN,
     iccInfo:        null,
     imsi:           null,
 
     // These objects implement the nsIDOMMozMobileConnectionInfo interface,
     // although the actual implementation lives in the content process. So are
     // the child attributes `network` and `cell`, which implement
@@ -787,34 +920,31 @@ function RadioInterface(options) {
 
   this.voicemailInfo = {
     number: null,
     displayName: null
   };
 
   this.operatorInfo = {};
 
-  // Read the 'ril.radio.disabled' setting in order to start with a known
-  // value at boot time.
   let lock = gSettingsService.createLock();
-  lock.get("ril.radio.disabled", this);
 
   // Read preferred network type from the setting DB.
   lock.get("ril.radio.preferredNetworkType", this);
 
   // Read the APN data from the settings DB.
   lock.get("ril.data.roaming_enabled", this);
   lock.get("ril.data.enabled", this);
   lock.get("ril.data.apnSettings", this);
 
-  // Read the 'time.clock.automatic-update.enabled' setting to see if
+  // Read the "time.clock.automatic-update.enabled" setting to see if
   // we need to adjust the system clock time by NITZ or SNTP.
   lock.get(kSettingsClockAutoUpdateEnabled, this);
 
-  // Read the 'time.timezone.automatic-update.enabled' setting to see if
+  // Read the "time.timezone.automatic-update.enabled" setting to see if
   // we need to adjust the system timezone by NITZ.
   lock.get(kSettingsTimezoneAutoUpdateEnabled, this);
 
   // Set "time.clock.automatic-update.available" to false when starting up.
   this.setClockAutoUpdateAvailable(false);
 
   // Set "time.timezone.automatic-update.available" to false when starting up.
   this.setTimezoneAutoUpdateAvailable(false);
@@ -831,21 +961,21 @@ function RadioInterface(options) {
 
   Services.obs.addObserver(this, kNetworkInterfaceStateChangedTopic, false);
   Services.prefs.addObserver(kPrefCellBroadcastDisabled, this, false);
 
   this.portAddressedSmsApps = {};
   this.portAddressedSmsApps[WAP.WDP_PORT_PUSH] = this.handleSmsWdpPortPush.bind(this);
 
   this._sntp = new Sntp(this.setClockBySntp.bind(this),
-                        Services.prefs.getIntPref('network.sntp.maxRetryCount'),
-                        Services.prefs.getIntPref('network.sntp.refreshPeriod'),
-                        Services.prefs.getIntPref('network.sntp.timeout'),
-                        Services.prefs.getCharPref('network.sntp.pools').split(';'),
-                        Services.prefs.getIntPref('network.sntp.port'));
+                        Services.prefs.getIntPref("network.sntp.maxRetryCount"),
+                        Services.prefs.getIntPref("network.sntp.refreshPeriod"),
+                        Services.prefs.getIntPref("network.sntp.timeout"),
+                        Services.prefs.getCharPref("network.sntp.pools").split(";"),
+                        Services.prefs.getIntPref("network.sntp.port"));
 }
 
 RadioInterface.prototype = {
 
   classID:   RADIOINTERFACE_CID,
   classInfo: XPCOMUtils.generateCI({classID: RADIOINTERFACE_CID,
                                     classDescription: "RadioInterface",
                                     interfaces: [Ci.nsIRadioInterface]}),
@@ -858,38 +988,38 @@ RadioInterface.prototype = {
   workerMessenger: null,
 
   debug: function debug(s) {
     dump("-*- RadioInterface[" + this.clientId + "]: " + s + "\n");
   },
 
   /**
    * A utility function to copy objects. The srcInfo may contain
-   * 'rilMessageType', should ignore it.
+   * "rilMessageType", should ignore it.
    */
   updateInfo: function updateInfo(srcInfo, destInfo) {
     for (let key in srcInfo) {
-      if (key === 'rilMessageType') {
+      if (key === "rilMessageType") {
         continue;
       }
       destInfo[key] = srcInfo[key];
     }
   },
 
   /**
    * A utility function to compare objects. The srcInfo may contain
-   * 'rilMessageType', should ignore it.
+   * "rilMessageType", should ignore it.
    */
   isInfoChanged: function isInfoChanged(srcInfo, destInfo) {
     if (!destInfo) {
       return true;
     }
 
     for (let key in srcInfo) {
-      if (key === 'rilMessageType') {
+      if (key === "rilMessageType") {
         continue;
       }
       if (srcInfo[key] !== destInfo[key]) {
         return true;
       }
     }
 
     return false;
@@ -986,16 +1116,19 @@ RadioInterface.prototype = {
         this.setCallingLineIdRestriction(msg.target, msg.json.data);
         break;
       case "RIL:GetCallingLineIdRestriction":
         this.workerMessenger.sendWithIPCMessage(msg, "getCLIR");
         break;
       case "RIL:ExitEmergencyCbMode":
         this.workerMessenger.sendWithIPCMessage(msg, "exitEmergencyCbMode");
         break;
+      case "RIL:SetRadioEnabled":
+        this.setRadioEnabled(msg.target, msg.json.data);
+        break;
       case "RIL:GetVoicemailInfo":
         // This message is sync.
         return this.voicemailInfo;
       case "RIL:SetRoamingPreference":
         this.workerMessenger.sendWithIPCMessage(msg, "setRoamingPreference");
         break;
       case "RIL:GetRoamingPreference":
         this.workerMessenger.sendWithIPCMessage(msg, "queryRoamingPreference");
@@ -1110,20 +1243,16 @@ RadioInterface.prototype = {
         this.handleUSSDReceived(message);
         break;
       case "stkcommand":
         this.handleStkProactiveCommand(message);
         break;
       case "stksessionend":
         gMessageManager.sendIccMessage("RIL:StkSessionEnd", this.clientId, null);
         break;
-      case "setRadioEnabled":
-        let lock = gSettingsService.createLock();
-        lock.set("ril.radio.disabled", !message.on, null, null);
-        break;
       case "exitEmergencyCbMode":
         this.handleExitEmergencyCbMode(message);
         break;
       case "cdma-info-rec-received":
         if (DEBUG) this.debug("cdma-info-rec-received: " + JSON.stringify(message));
         gSystemMessenger.broadcastMessage("cdma-info-rec-received", message);
         break;
       default:
@@ -1476,101 +1605,70 @@ RadioInterface.prototype = {
     }
 
     let status = RIL.CDMA_OTA_PROVISION_STATUS_TO_GECKO[message.status];
 
     gMessageManager.sendMobileConnectionMessage("RIL:OtaStatusChanged",
                                                 this.clientId, status);
   },
 
+  _isRadioChanging: function _isRadioChanging() {
+    let state = this.rilContext.detailedRadioState;
+    return state == RIL.GECKO_DETAILED_RADIOSTATE_ENABLING ||
+      state == RIL.GECKO_DETAILED_RADIOSTATE_DISABLING;
+  },
+
+  _convertRadioState: function _converRadioState(state) {
+    switch (state) {
+      case RIL.GECKO_RADIOSTATE_OFF:
+        return RIL.GECKO_DETAILED_RADIOSTATE_DISABLED;
+      case RIL.GECKO_RADIOSTATE_READY:
+        return RIL.GECKO_DETAILED_RADIOSTATE_ENABLED;
+      default:
+        return RIL.GECKO_DETAILED_RADIOSTATE_UNKNOWN;
+    }
+  },
+
   handleRadioStateChange: function handleRadioStateChange(message) {
-    this._changingRadioPower = false;
-
     let newState = message.radioState;
     if (this.rilContext.radioState == newState) {
       return;
     }
     this.rilContext.radioState = newState;
+    this.handleDetailedRadioStateChanged(this._convertRadioState(newState));
+
     //TODO Should we notify this change as a card state change?
-
-    this._ensureRadioState();
   },
 
-  _ensureRadioState: function _ensureRadioState() {
-    if (DEBUG) {
-      this.debug("Reported radio state is " + this.rilContext.radioState +
-                 ", desired radio enabled state is " + this._radioEnabled);
-    }
-    if (this._radioEnabled == null) {
-      // We haven't read the initial value from the settings DB yet.
-      // Wait for that.
-      return;
-    }
-    if (!this._sysMsgListenerReady) {
-      // The UI's system app isn't ready yet for us to receive any
-      // events (e.g. incoming SMS, etc.). Wait for that.
-      return;
-    }
-    if (this.rilContext.radioState == RIL.GECKO_RADIOSTATE_UNKNOWN) {
-      // We haven't received a radio state notification from the RIL
-      // yet. Wait for that.
-      return;
-    }
-    if (this._changingRadioPower) {
-      // We're changing the radio power currently, ignore any changes.
+  handleDetailedRadioStateChanged: function handleDetailedRadioStateChanged(state) {
+    if (this.rilContext.detailedRadioState == state) {
       return;
     }
-
-    if (this.rilContext.radioState == RIL.GECKO_RADIOSTATE_OFF &&
-        this._radioEnabled) {
-      this._changingRadioPower = true;
-      this.setRadioEnabled(true);
-    }
-    if (this.rilContext.radioState == RIL.GECKO_RADIOSTATE_READY &&
-        !this._radioEnabled) {
-      this._changingRadioPower = true;
-      this.powerOffRadioSafely();
-    }
+    this.rilContext.detailedRadioState = state;
+    gMessageManager.sendMobileConnectionMessage("RIL:RadioStateChanged",
+                                                this.clientId, state);
   },
 
-  _radioOffTimer: null,
-  _cancelRadioOffTimer: function _cancelRadioOffTimer() {
-    if (this._radioOffTimer) {
-      this._radioOffTimer.cancel();
-    }
-  },
-  _fireRadioOffTimer: function _fireRadioOffTimer() {
-    if (DEBUG) this.debug("Radio off timer expired, set radio power off right away.");
-    this.setRadioEnabled(false);
-  },
-
-  /**
-   * Clean up all existing data calls before turning radio off.
-   */
-  powerOffRadioSafely: function powerOffRadioSafely() {
+  deactivateDataCalls: function deactivateDataCalls() {
     let dataDisconnecting = false;
     for each (let apnSetting in this.apnSettings.byApn) {
       for each (let type in apnSetting.types) {
         if (this.getDataCallStateByType(type) ==
             RIL.GECKO_NETWORK_STATE_CONNECTED) {
           this.deactivateDataCallByType(type);
           dataDisconnecting = true;
         }
       }
     }
-    if (dataDisconnecting) {
-      if (this._radioOffTimer == null) {
-        this._radioOffTimer = Cc["@mozilla.org/timer;1"].createInstance(Ci.nsITimer);
-      }
-      this._radioOffTimer.initWithCallback(this._fireRadioOffTimer.bind(this),
-                                           RADIO_POWER_OFF_TIMEOUT, Ci.nsITimer.TYPE_ONE_SHOT);
-      this._radioOffAfterDataDisconnected = true;
-      return;
+
+    // No data calls exist. It's safe to proceed the pending radio power off
+    // request.
+    if (gRadioEnabledController.isDeactivatingDataCalls() && !dataDisconnecting) {
+      gRadioEnabledController.finishDeactivatingDataCalls(this.clientId);
     }
-    this.setRadioEnabled(false);
   },
 
   /**
    * This function will do the following steps:
    *   1. Clear the cached APN settings in the RIL.
    *   2. Combine APN, user name, and password as the key of |byApn| object to
    *      refer to the corresponding APN setting.
    *   3. Use APN type as the index of |byType| object to refer to the
@@ -1606,18 +1704,18 @@ RadioInterface.prototype = {
       let inputApnSetting = simApnSettings[i];
       if (!this.validateApnSetting(inputApnSetting)) {
         continue;
       }
 
       // Combine APN, user name, and password as the key of |byApn| object to
       // refer to the corresponding APN setting.
       let apnKey = inputApnSetting.apn +
-                   (inputApnSetting.user || '') +
-                   (inputApnSetting.password || '');
+                   (inputApnSetting.user || "") +
+                   (inputApnSetting.password || "");
 
       if (!this.apnSettings.byApn[apnKey]) {
         this.apnSettings.byApn[apnKey] = inputApnSetting;
       } else {
         this.apnSettings.byApn[apnKey].types =
           this.apnSettings.byApn[apnKey].types.concat(inputApnSetting.types);
       }
 
@@ -1724,17 +1822,17 @@ RadioInterface.prototype = {
     if (dataInfo.roaming && !this.dataCallSettings.roamingEnabled) {
       if (DEBUG) this.debug("We're roaming, but data roaming is disabled.");
       return;
     }
     if (wifi_active) {
       if (DEBUG) this.debug("Don't connect data call when Wifi is connected.");
       return;
     }
-    if (this._changingRadioPower) {
+    if (this._isRadioChanging()) {
       // We're changing the radio power currently, ignore any changes.
       return;
     }
 
     if (DEBUG) this.debug("Data call settings: connect data call.");
     this.setupDataCallByType("default");
   },
 
@@ -1931,28 +2029,28 @@ RadioInterface.prototype = {
         result: (success ? RIL.PDU_FCS_OK
                          : RIL.PDU_FCS_MEMORY_CAPACITY_EXCEEDED)
       });
 
       if (!success) {
         // At this point we could send a message to content to notify the user
         // that storing an incoming SMS failed, most likely due to a full disk.
         if (DEBUG) {
-          this.debug("Could not store SMS, error code " + rv);
+          this.debug("Could not store SMS " + message.id + ", error code " + rv);
         }
         return;
       }
 
       this.broadcastSmsSystemMessage(kSmsReceivedObserverTopic, domMessage);
       Services.obs.notifyObservers(domMessage, kSmsReceivedObserverTopic, null);
     }.bind(this);
 
     if (message.messageClass != RIL.GECKO_SMS_MESSAGE_CLASSES[RIL.PDU_DCS_MSG_CLASS_0]) {
-      gMobileMessageDatabaseService.saveReceivedMessage(message,
-                                                        notifyReceived);
+      message.id = gMobileMessageDatabaseService.saveReceivedMessage(message,
+                                                                     notifyReceived);
     } else {
       message.id = -1;
       message.threadId = 0;
       message.delivery = DOM_MOBILE_MESSAGE_DELIVERY_RECEIVED;
       message.deliveryStatus = RIL.GECKO_SMS_DELIVERY_STATUS_SUCCESS;
       message.read = false;
 
       let domMessage =
@@ -2000,34 +2098,32 @@ RadioInterface.prototype = {
     }
 
     this._deliverDataCallCallback("dataCallStateChanged",
                                   [datacall]);
 
     // Process pending radio power off request after all data calls
     // are disconnected.
     if (datacall.state == RIL.GECKO_NETWORK_STATE_UNKNOWN &&
-        this._radioOffAfterDataDisconnected) {
+        gRadioEnabledController.isDeactivatingDataCalls()) {
       let anyDataConnected = false;
       for each (let apnSetting in this.apnSettings.byApn) {
         for each (let type in apnSetting.types) {
           if (this.getDataCallStateByType(type) == RIL.GECKO_NETWORK_STATE_CONNECTED) {
             anyDataConnected = true;
             break;
           }
         }
         if (anyDataConnected) {
           break;
         }
       }
       if (!anyDataConnected) {
-        if (DEBUG) this.debug("All data connections are disconnected, set radio off.");
-        this._radioOffAfterDataDisconnected = false;
-        this._cancelRadioOffTimer();
-        this.setRadioEnabled(false);
+        if (DEBUG) this.debug("All data connections are disconnected.");
+        gRadioEnabledController.finishDeactivatingDataCalls(this.clientId);
       }
     }
   },
 
   /**
    * Handle data call list.
    */
   handleDataCallList: function handleDataCallList(message) {
@@ -2210,19 +2306,17 @@ RadioInterface.prototype = {
     gMessageManager.sendRequestResults("RIL:ExitEmergencyCbMode", message);
   },
 
   // nsIObserver
 
   observe: function observe(subject, topic, data) {
     switch (topic) {
       case kSysMsgListenerReadyObserverTopic:
-        Services.obs.removeObserver(this, kSysMsgListenerReadyObserverTopic);
-        this._sysMsgListenerReady = true;
-        this._ensureRadioState();
+        this.setRadioEnabledInternal({enabled: true}, null);
         break;
       case kMozSettingsChangedObserverTopic:
         let setting = JSON.parse(data);
         this.handleSettingsChange(setting.key, setting.value, setting.message);
         break;
       case NS_PREFBRANCH_PREFCHANGE_TOPIC_ID:
         if (data === kPrefCellBroadcastDisabled) {
           let value = false;
@@ -2267,43 +2361,27 @@ RadioInterface.prototype = {
         }
         break;
       case kScreenStateChangedTopic:
         this.workerMessenger.send("setScreenState", { on: (data === "on") });
         break;
     }
   },
 
-  // Flag to determine whether the UI's system app is ready to receive
-  // events yet.
-  _sysMsgListenerReady: false,
-
-  // Flag to determine the radio state to start with when we boot up. It
-  // corresponds to the 'ril.radio.disabled' setting from the UI.
-  _radioEnabled: null,
-
-  // Flag to ignore any radio power change requests during We're changing
-  // the radio power.
-  _changingRadioPower: false,
-
-  // Flag to determine if we need to set radio off when we are notified a data
-  // call has been disconnected.
-  _radioOffAfterDataDisconnected: false,
-
   // Data calls setting.
   dataCallSettings: null,
 
   apnSettings: null,
 
   // Flag to determine whether to update system clock automatically. It
-  // corresponds to the 'time.clock.automatic-update.enabled' setting.
+  // corresponds to the "time.clock.automatic-update.enabled" setting.
   _clockAutoUpdateEnabled: null,
 
   // Flag to determine whether to update system timezone automatically. It
-  // corresponds to the 'time.clock.automatic-update.enabled' setting.
+  // corresponds to the "time.clock.automatic-update.enabled" setting.
   _timezoneAutoUpdateEnabled: null,
 
   // Remember the last NITZ message so that we can set the time based on
   // the network immediately when users enable network-based time.
   _lastNitzMessage: null,
 
   // Object that handles SNTP.
   _sntp: null,
@@ -2341,21 +2419,16 @@ RadioInterface.prototype = {
     }
 
     this.handle(aName, aResult);
   },
 
   // nsISettingsServiceCallback
   handle: function handle(aName, aResult) {
     switch(aName) {
-      case "ril.radio.disabled":
-        if (DEBUG) this.debug("'ril.radio.disabled' is now " + aResult);
-        this._radioEnabled = !aResult;
-        this._ensureRadioState();
-        break;
       case "ril.radio.preferredNetworkType":
         if (DEBUG) this.debug("'ril.radio.preferredNetworkType' is now " + aResult);
         this.setPreferredNetworkType(aResult);
         break;
       case "ril.data.enabled":
         if (DEBUG) this.debug("'ril.data.enabled' is now " + aResult);
         let enabled;
         if (Array.isArray(aResult)) {
@@ -2417,37 +2490,28 @@ RadioInterface.prototype = {
         this.setCellBroadcastSearchList(aResult);
         break;
     }
   },
 
   handleError: function handleError(aErrorMessage) {
     if (DEBUG) this.debug("There was an error while reading RIL settings.");
 
-    // Default radio to on.
-    this._radioEnabled = true;
-    this._ensureRadioState();
-
     // Clean data call setting.
     this.dataCallSettings.oldEnabled = false;
     this.dataCallSettings.enabled = false;
     this.dataCallSettings.roamingEnabled = false;
     this.apnSettings = {
       byType: {},
       byApn: {},
     };
   },
 
   // nsIRadioInterface
 
-  setRadioEnabled: function setRadioEnabled(value) {
-    if (DEBUG) this.debug("Setting radio power to " + value);
-    this.workerMessenger.send("setRadioPower", { on: value });
-  },
-
   rilContext: null,
 
   // Handle phone functions of nsIRILContentHelper
 
   _sendCfStateChanged: function _sendCfStateChanged(message) {
     gMessageManager.sendMobileConnectionMessage("RIL:CfStateChanged",
                                                 this.clientId, message);
   },
@@ -2505,16 +2569,72 @@ RadioInterface.prototype = {
       target.sendAsyncMessage("RIL:SetCallingLineIdRestriction", {
         clientId: this.clientId,
         data: response
       });
       return false;
     }).bind(this));
   },
 
+  isValidStateForSetRadioEnabled: function() {
+    let state = this.rilContext.radioState;
+
+    return !this._isRadioChanging() &&
+        (state == RIL.GECKO_RADIOSTATE_READY ||
+         state == RIL.GECKO_RADIOSTATE_OFF);
+  },
+
+  isDummyForSetRadioEnabled: function(message) {
+    let state = this.rilContext.radioState;
+
+    return (state == RIL.GECKO_RADIOSTATE_READY && message.enabled) ||
+        (state == RIL.GECKO_RADIOSTATE_OFF && !message.enabled);
+  },
+
+  setRadioEnabledResponse: function(target, message, errorMsg) {
+    if (errorMsg) {
+      message.errorMsg = errorMsg;
+    }
+
+    target.sendAsyncMessage("RIL:SetRadioEnabled", {
+      clientId: this.clientId,
+      data: message
+    });
+  },
+
+  setRadioEnabled: function setRadioEnabled(target, message) {
+    if (DEBUG) {
+      this.debug("setRadioEnabled: " + JSON.stringify(message));
+    }
+
+    if (!this.isValidStateForSetRadioEnabled()) {
+      this.setRadioEnabledResponse(target, message, "InvalidStateError");
+      return;
+    }
+
+    if (this.isDummyForSetRadioEnabled(message)) {
+      this.setRadioEnabledResponse(target, message);
+      return;
+    }
+
+    let callback = (function(response) {
+      this.setRadioEnabledResponse(target, response);
+      return false;
+    }).bind(this);
+
+    this.setRadioEnabledInternal(message, callback);
+  },
+
+  setRadioEnabledInternal: function setRadioEnabledInternal(message, callback) {
+    let state = message.enabled ? RIL.GECKO_DETAILED_RADIOSTATE_ENABLING
+                                : RIL.GECKO_DETAILED_RADIOSTATE_DISABLING;
+    this.handleDetailedRadioStateChanged(state);
+    this.workerMessenger.send("setRadioEnabled", message, callback);
+  },
+
   /**
    * List of tuples of national language identifier pairs.
    *
    * TODO: Support static/runtime settings, see bug 733331.
    */
   enabledGsmTableTuples: [
     [RIL.PDU_NL_IDENTIFIER_DEFAULT, RIL.PDU_NL_IDENTIFIER_DEFAULT],
   ],
@@ -2581,17 +2701,17 @@ RadioInterface.prototype = {
       septet = langShiftTable.indexOf(c);
       if (septet < 0) {
         if (!strict7BitEncoding) {
           return -1;
         }
 
         // Bug 816082, when strict7BitEncoding is enabled, we should replace
         // characters that can't be encoded with GSM 7-Bit alphabets with '*'.
-        c = '*';
+        c = "*";
         if (langTable.indexOf(c) >= 0) {
           length++;
         } else if (langShiftTable.indexOf(c) >= 0) {
           length += 2;
         } else {
           // We can't even encode a '*' character with current configuration.
           return -1;
         }
@@ -2803,17 +2923,17 @@ RadioInterface.prototype = {
         inc = 2;
         if (septet < 0) {
           if (!strict7BitEncoding) {
             throw new Error("Given text cannot be encoded with GSM 7-bit Alphabet!");
           }
 
           // Bug 816082, when strict7BitEncoding is enabled, we should replace
           // characters that can't be encoded with GSM 7-Bit alphabets with '*'.
-          c = '*';
+          c = "*";
           if (langTable.indexOf(c) >= 0) {
             inc = 1;
           }
         }
       }
 
       if ((len + inc) > segmentSeptets) {
         ret.push({
@@ -2973,17 +3093,18 @@ RadioInterface.prototype = {
 
       // If the radio is disabled or the SIM card is not ready, just directly
       // return with the corresponding error code.
       let errorCode;
       if (!PhoneNumberUtils.isPlainPhoneNumber(options.number)) {
         if (DEBUG) this.debug("Error! Address is invalid when sending SMS: " +
                               options.number);
         errorCode = Ci.nsIMobileMessageCallback.INVALID_ADDRESS_ERROR;
-      } else if (!this._radioEnabled) {
+      } else if (this.rilContext.detailedRadioState ==
+                 RIL.GECKO_DETAILED_RADIOSTATE_DISABLED) {
         if (DEBUG) this.debug("Error! Radio is disabled when sending SMS.");
         errorCode = Ci.nsIMobileMessageCallback.RADIO_DISABLED_ERROR;
       } else if (this.rilContext.cardState != "ready") {
         if (DEBUG) this.debug("Error! SIM card is not ready when sending SMS.");
         errorCode = Ci.nsIMobileMessageCallback.NO_SIM_CARD_ERROR;
       }
       if (errorCode) {
         if (silent) {
@@ -3058,17 +3179,17 @@ RadioInterface.prototype = {
                                            (function notifyResult(rv, domMessage) {
             // TODO bug 832140 handle !Components.isSuccessCode(rv)
 
             let topic = (response.deliveryStatus ==
                          RIL.GECKO_SMS_DELIVERY_STATUS_SUCCESS)
                         ? kSmsDeliverySuccessObserverTopic
                         : kSmsDeliveryErrorObserverTopic;
 
-            // Broadcasting a 'sms-delivery-success' system message to open apps.
+            // Broadcasting a "sms-delivery-success" system message to open apps.
             if (topic == kSmsDeliverySuccessObserverTopic) {
               this.broadcastSmsSystemMessage(topic, domMessage);
             }
 
             // Notifying observers the delivery status is updated.
             Services.obs.notifyObservers(domMessage, topic, null);
           }).bind(this));
 
@@ -3147,18 +3268,18 @@ RadioInterface.prototype = {
                                                "normal", // message class
                                                sendingMessage.timestamp,
                                                0,
                                                false);
       notifyResult(Cr.NS_OK, domMessage);
       return;
     }
 
-    gMobileMessageDatabaseService.saveSendingMessage(sendingMessage,
-                                                     notifyResult);
+    let id = gMobileMessageDatabaseService.saveSendingMessage(
+      sendingMessage, notifyResult);
   },
 
   registerDataCallCallback: function registerDataCallCallback(callback) {
     if (this._datacall_callbacks) {
       if (this._datacall_callbacks.indexOf(callback) != -1) {
         throw new Error("Already registered this callback!");
       }
     } else {
@@ -3388,21 +3509,21 @@ RILNetworkInterface.prototype = {
 
   broadcast: null,
 
   dns1: null,
 
   dns2: null,
 
   get httpProxyHost() {
-    return this.apnSetting.proxy || '';
+    return this.apnSetting.proxy || "";
   },
 
   get httpProxyPort() {
-    return this.apnSetting.port || '';
+    return this.apnSetting.port || "";
   },
 
   /**
    * nsIRilNetworkInterface Implementation
    */
 
   get serviceId() {
     return this.radioInterface.clientId;
@@ -3520,17 +3641,17 @@ RILNetworkInterface.prototype = {
     // In current design, we don't update status of secondary APN if it shares
     // same APN name with the default APN.  In this condition, this.cid will
     // not be set and we don't want to update its status.
     if (this.cid == null) {
       return;
     }
 
     if (this.state == datacall.state) {
-      if (datacall.state != GECKO_NETWORK_STATE_CONNECTED) {
+      if (datacall.state != RIL.GECKO_NETWORK_STATE_CONNECTED) {
         return;
       }
       // State remains connected, check for minor changes.
       let changed = false;
       if (this.gateway != datacall.gw) {
         this.gateway = datacall.gw;
         changed = true;
       }
--- a/dom/system/gonk/ril_consts.js
+++ b/dom/system/gonk/ril_consts.js
@@ -2374,16 +2374,22 @@ this.CALL_FAIL_IMSI_UNKNOWN_IN_VLR = 242
 this.CALL_FAIL_IMEI_NOT_ACCEPTED = 243;
 this.CALL_FAIL_ERROR_UNSPECIFIED = 0xffff;
 
 // Other Gecko-specific constants
 this.GECKO_RADIOSTATE_UNAVAILABLE   = null;
 this.GECKO_RADIOSTATE_OFF           = "off";
 this.GECKO_RADIOSTATE_READY         = "ready";
 
+this.GECKO_DETAILED_RADIOSTATE_UNKNOWN    = null;
+this.GECKO_DETAILED_RADIOSTATE_ENABLING   = "enabling";
+this.GECKO_DETAILED_RADIOSTATE_ENABLED    = "enabled";
+this.GECKO_DETAILED_RADIOSTATE_DISABLING  = "disabling";
+this.GECKO_DETAILED_RADIOSTATE_DISABLED   = "disabled";
+
 this.GECKO_CARDSTATE_UNDETECTED                    = null;
 this.GECKO_CARDSTATE_ILLEGAL                       = "illegal";
 this.GECKO_CARDSTATE_UNKNOWN                       = "unknown";
 this.GECKO_CARDSTATE_PIN_REQUIRED                  = "pinRequired";
 this.GECKO_CARDSTATE_PUK_REQUIRED                  = "pukRequired";
 this.GECKO_CARDSTATE_PERSONALIZATION_IN_PROGRESS   = "personalizationInProgress";
 this.GECKO_CARDSTATE_PERSONALIZATION_READY         = "personalizationReady";
 this.GECKO_CARDSTATE_NETWORK_LOCKED                = "networkLocked";
--- a/dom/system/gonk/ril_worker.js
+++ b/dom/system/gonk/ril_worker.js
@@ -939,25 +939,25 @@ let RIL = {
         this.appType, options.contactType, contact, options.pin2, onsuccess, onerror);
     } else {
       ICCContactHelper.addICCContact(
         this.appType, options.contactType, contact, options.pin2, onsuccess, onerror);
     }
   },
 
   /**
-   * Request the phone's radio power to be switched on or off.
-   *
-   * @param on
-   *        Boolean indicating the desired power state.
-   */
-  setRadioPower: function setRadioPower(options) {
+   * Request the phone's radio to be enabled or disabled.
+   *
+   * @param enabled
+   *        Boolean indicating the desired state.
+   */
+  setRadioEnabled: function setRadioEnabled(options) {
     Buf.newParcel(REQUEST_RADIO_POWER, options);
     Buf.writeInt32(1);
-    Buf.writeInt32(options.on ? 1 : 0);
+    Buf.writeInt32(options.enabled ? 1 : 0);
     Buf.sendParcel();
   },
 
   /**
    * Query call waiting status via MMI.
    */
   _handleQueryMMICallWaiting: function _handleQueryMMICallWaiting(options) {
     function callback(options) {
@@ -1408,19 +1408,17 @@ let RIL = {
     if (this.radioState == GECKO_RADIOSTATE_OFF) {
       if (DEBUG) debug("Automatically enable radio for an emergency call.");
 
       if (!this.cachedDialRequest) {
         this.cachedDialRequest = {};
       }
       this.cachedDialRequest.onerror = onerror;
       this.cachedDialRequest.callback = this.sendDialRequest.bind(this, options);
-
-      // Change radio setting value in settings DB to enable radio.
-      this.sendChromeMessage({rilMessageType: "setRadioEnabled", on: true});
+      this.setRadioEnabled({enabled: true});
       return;
     }
 
     this.sendDialRequest(options);
   },
 
   sendDialRequest: function sendDialRequest(options) {
     Buf.newParcel(options.request);
@@ -5179,28 +5177,35 @@ RIL[REQUEST_OPERATOR] = function REQUEST
     return;
   }
 
   let operatorData = Buf.readStringList();
   if (DEBUG) debug("Operator: " + operatorData);
   this._processOperator(operatorData);
 };
 RIL[REQUEST_RADIO_POWER] = function REQUEST_RADIO_POWER(length, options) {
-  if (options.rilRequestError) {
-    if (this.cachedDialRequest && options.on) {
-      // Turning on radio fails. Notify the error of making an emergency call.
-      this.cachedDialRequest.onerror(GECKO_ERROR_RADIO_NOT_AVAILABLE);
-      this.cachedDialRequest = null;
-    }
+  if (options.rilMessageType == null) {
+    // The request was made by ril_worker itself.
+    if (options.rilRequestError) {
+      if (this.cachedDialRequest && options.enabled) {
+        // Turning on radio fails. Notify the error of making an emergency call.
+        this.cachedDialRequest.onerror(GECKO_ERROR_RADIO_NOT_AVAILABLE);
+        this.cachedDialRequest = null;
+      }
+      return;
+    }
+
+    if (this._isInitialRadioState) {
+      this._isInitialRadioState = false;
+    }
+
     return;
   }
 
-  if (this._isInitialRadioState) {
-    this._isInitialRadioState = false;
-  }
+  this.sendChromeMessage(options);
 };
 RIL[REQUEST_DTMF] = null;
 RIL[REQUEST_SEND_SMS] = function REQUEST_SEND_SMS(length, options) {
   this._processSmsSendResult(length, options);
 };
 RIL[REQUEST_SEND_SMS_EXPECT_MORE] = null;
 
 RIL.readSetupDataCall_v5 = function readSetupDataCall_v5(options) {
@@ -6015,17 +6020,17 @@ RIL[REQUEST_GET_UNLOCK_RETRY_COUNT] = fu
 };
 RIL[UNSOLICITED_RESPONSE_RADIO_STATE_CHANGED] = function UNSOLICITED_RESPONSE_RADIO_STATE_CHANGED() {
   let radioState = Buf.readInt32();
 
   // Ensure radio state at boot time.
   if (this._isInitialRadioState) {
     // Even radioState is RADIO_STATE_OFF, we still have to maually turn radio off,
     // otherwise REQUEST_GET_SIM_STATUS will still report CARD_STATE_PRESENT.
-    this.setRadioPower({on: false});
+    this.setRadioEnabled({enabled: false});
   }
 
   let newState;
   if (radioState == RADIO_STATE_UNAVAILABLE) {
     newState = GECKO_RADIOSTATE_UNAVAILABLE;
   } else if (radioState == RADIO_STATE_OFF) {
     newState = GECKO_RADIOSTATE_OFF;
   } else {
--- a/dom/telephony/test/marionette/test_outgoing_emergency_in_airplane_mode.js
+++ b/dom/telephony/test/marionette/test_outgoing_emergency_in_airplane_mode.js
@@ -1,42 +1,51 @@
 /* Any copyright is dedicated to the Public Domain.
  * http://creativecommons.org/publicdomain/zero/1.0/ */
 
 MARIONETTE_TIMEOUT = 60000;
 MARIONETTE_HEAD_JS = 'head.js';
 
-let Promise = SpecialPowers.Cu.import("resource://gre/modules/Promise.jsm").Promise;
-
-const KEY = "ril.radio.disabled";
-
-let settings;
+let connection;
 let number = "112";
 let outgoing;
 
-function setAirplaneMode() {
-  log("Turning on airplane mode");
+function receivedPending(received, pending, nextAction) {
+  let index = pending.indexOf(received);
+  if (index != -1) {
+    pending.splice(index, 1);
+  }
+  if (pending.length === 0) {
+    nextAction();
+  }
+}
 
-  let deferred = Promise.defer();
+function setRadioEnabled(enabled, callback) {
+  let request  = connection.setRadioEnabled(enabled);
+  let desiredRadioState = enabled ? 'enabled' : 'disabled';
 
-  let setLock = settings.createLock();
-  let obj = {};
-  obj[KEY] = false;
+  let pending = ['onradiostatechange', 'onsuccess'];
+  let done = callback;
 
-  let setReq = setLock.set(obj);
-  setReq.addEventListener("success", function onSetSuccess() {
-    ok(true, "set '" + KEY + "' to " + obj[KEY]);
-    deferred.resolve();
-  });
-  setReq.addEventListener("error", function onSetError() {
-    ok(false, "cannot set '" + KEY + "'");
-    deferred.reject();
-  });
+  connection.onradiostatechange = function() {
+    let state = connection.radioState;
+    log("Received 'radiostatechange' event, radioState: " + state);
 
-  return deferred.promise;
+    if (state == desiredRadioState) {
+      receivedPending('onradiostatechange', pending, done);
+    }
+  };
+
+  request.onsuccess = function onsuccess() {
+    receivedPending('onsuccess', pending, done);
+  };
+
+  request.onerror = function onerror() {
+    ok(false, "setRadioEnabled should be ok");
+  };
 }
 
 function dial() {
   log("Make an outgoing call.");
 
   outgoing = telephony.dial(number);
   ok(outgoing);
   is(outgoing.number, number);
@@ -103,15 +112,17 @@ function hangUp() {
   };
   emulator.run("gsm cancel " + number);
 }
 
 function cleanUp() {
   finish();
 }
 
-startTestWithPermissions(['settings-write'], function() {
-  settings = window.navigator.mozSettings;
-  ok(settings);
-  setAirplaneMode()
-    .then(dial)
-    .then(null, cleanUp);
+startTestWithPermissions(['mobileconnection'], function() {
+  connection = navigator.mozMobileConnections[0];
+  ok(connection instanceof MozMobileConnection,
+     "connection is instanceof " + connection.constructor);
+
+  setRadioEnabled(false, function() {
+    dial();
+  });
 });
--- a/dom/telephony/test/marionette/test_outgoing_radio_off.js
+++ b/dom/telephony/test/marionette/test_outgoing_radio_off.js
@@ -1,45 +1,50 @@
 /* Any copyright is dedicated to the Public Domain.
    http://creativecommons.org/publicdomain/zero/1.0/ */
 
 MARIONETTE_TIMEOUT = 60000;
 MARIONETTE_HEAD_JS = 'head.js';
 
-let icc;
 let connection;
 let outgoing;
 
-function changeSetting(key, value, callback) {
-  let obj = {};
-  obj[key] = value;
-
-  let setReq = navigator.mozSettings.createLock().set(obj);
-  setReq.addEventListener("success", function onSetSuccess() {
-    ok(true, "set '" + key + "' to " + obj[key]);
-    setReq.removeEventListener("success", onSetSuccess);
-    callback();
-  });
-  setReq.addEventListener("error", function onSetError() {
-    ok(false, "cannot set '" + key + "'");
-    cleanUp();
-  });
+function receivedPending(received, pending, nextAction) {
+  let index = pending.indexOf(received);
+  if (index != -1) {
+    pending.splice(index, 1);
+  }
+  if (pending.length === 0) {
+    nextAction();
+  }
 }
 
 function setRadioEnabled(enabled, callback) {
-  changeSetting("ril.radio.disabled", !enabled, function() {
-    // Wait for iccdetected event after turning on radio.
-    // Wait for iccundetected event after turning off radio.
-    let event = (enabled) ? "iccdetected" : "iccundetected";
-    icc.addEventListener(event, function handler(evt) {
-      log(event + ": " + evt.iccId);
-      icc.removeEventListener(event, handler);
-      callback();
-    });
-  });
+  let request  = connection.setRadioEnabled(enabled);
+  let desiredRadioState = enabled ? 'enabled' : 'disabled';
+
+  let pending = ['onradiostatechange', 'onsuccess'];
+  let done = callback;
+
+  connection.onradiostatechange = function() {
+    let state = connection.radioState;
+    log("Received 'radiostatechange' event, radioState: " + state);
+
+    if (state == desiredRadioState) {
+      receivedPending('onradiostatechange', pending, done);
+    }
+  };
+
+  request.onsuccess = function onsuccess() {
+    receivedPending('onsuccess', pending, done);
+  };
+
+  request.onerror = function onerror() {
+    ok(false, "setRadioEnabled should be ok");
+  };
 }
 
 function dial(number) {
   // Verify initial state before dial.
   ok(telephony);
   is(telephony.active, null);
   ok(telephony.calls);
   is(telephony.calls.length, 0);
@@ -69,25 +74,17 @@ function dial(number) {
     });
   };
 }
 
 function cleanUp() {
   finish();
 }
 
-let permissions = [
-  "mobileconnection",
-  "settings-write"
-];
-
-startTestWithPermissions(permissions, function() {
+startTestWithPermissions(['mobileconnection'], function() {
   connection = navigator.mozMobileConnections[0];
   ok(connection instanceof MozMobileConnection,
      "connection is instanceof " + connection.constructor);
 
-  icc = navigator.mozIccManager;
-  ok(icc instanceof MozIccManager, "icc is instanceof " + icc.constructor);
-
   setRadioEnabled(false, function() {
     dial("0912345678");
   });
 });
--- a/dom/tests/unit/test_geolocation_reset_accuracy.js
+++ b/dom/tests/unit/test_geolocation_reset_accuracy.js
@@ -27,16 +27,17 @@ var provider = {
   watch: function() {
   },
   shutdown: function() {
   },
   setHighAccuracy: function(enable) {
     this._isHigh = enable;
     if (enable) {
       this._seenHigh = true;
+      do_execute_soon(stop_high_accuracy_watch);
     }
   },
   _isHigh: false,
   _seenHigh: false
 };
 
 let runningInParent = true;
 try {
@@ -53,16 +54,19 @@ function successCallback()
 }
 
 function errorCallback()
 {
   do_check_true(false);
   do_test_finished();
 }
 
+var geolocation;
+var watchID2;
+
 function run_test()
 {
   if (runningInParent) {
     // XPCShell does not get a profile by default. The geolocation service
     // depends on the settings service which uses IndexedDB and IndexedDB
     // needs a place where it can store databases.
     do_get_profile();
 
@@ -73,28 +77,31 @@ function run_test()
     catMan.nsICategoryManager.addCategoryEntry(categoryName, "unit test",
                                                providerContract, false, true);
 
     var prefs = Cc["@mozilla.org/preferences-service;1"].getService(Ci.nsIPrefBranch);
     prefs.setBoolPref("geo.testing.ignore_ipc_principal", true);
     prefs.setBoolPref("geo.wifi.scan", false);
   }
 
-  let geolocation = Cc["@mozilla.org/geolocation;1"].createInstance(Ci.nsISupports);
-
   do_test_pending();
 
+  geolocation = Cc["@mozilla.org/geolocation;1"].createInstance(Ci.nsISupports);
   let watchID1 = geolocation.watchPosition(successCallback, errorCallback);
-  let watchID2 = geolocation.watchPosition(successCallback, errorCallback,
-                                           {enableHighAccuracy: true});
+  watchID2 = geolocation.watchPosition(successCallback, errorCallback,
+                                       {enableHighAccuracy: true});
 
-  do_timeout(5000, function() {
+  if (!runningInParent) {
+    do_await_remote_message('high_acc_enabled', stop_high_accuracy_watch);
+  }
+}
+
+function stop_high_accuracy_watch() {
     geolocation.clearWatch(watchID2);
-    do_timeout(1000, check_results);
-  });
+    check_results();
 }
 
 function check_results()
 {
   if (runningInParent) {
     // check the provider was set to high accuracy during the test
     do_check_true(provider._seenHigh);
     // check the provider is not currently set to high accuracy
--- a/dom/tests/unit/test_geolocation_reset_accuracy_wrap.js
+++ b/dom/tests/unit/test_geolocation_reset_accuracy_wrap.js
@@ -27,16 +27,17 @@ var provider = {
   watch: function() {
   },
   shutdown: function() {
   },
   setHighAccuracy: function(enable) {
     this._isHigh = enable;
     if (enable) {
       this._seenHigh = true;
+      do_send_remote_message('high_acc_enabled');
     }
   },
   _isHigh: false,
   _seenHigh: false
 };
 
 function run_test()
 {
--- a/dom/workers/WorkerPrivate.cpp
+++ b/dom/workers/WorkerPrivate.cpp
@@ -341,17 +341,17 @@ struct WorkerStructuredCloneCallbacks
           return true;
         }
       }
     }
 
     // See if this is an ImageData object.
     {
       ImageData* imageData = nullptr;
-      if (NS_SUCCEEDED(UNWRAP_OBJECT(ImageData, aCx, aObj, imageData))) {
+      if (NS_SUCCEEDED(UNWRAP_OBJECT(ImageData, aObj, imageData))) {
         // Prepare the ImageData internals.
         uint32_t width = imageData->Width();
         uint32_t height = imageData->Height();
         JS::Rooted<JSObject*> dataArray(aCx, imageData->GetDataObject());
 
         // Write the internals to the stream.
         JSAutoCompartment ac(aCx, dataArray);
         return JS_WriteUint32Pair(aWriter, SCTAG_DOM_IMAGEDATA, 0) &&
@@ -5402,17 +5402,17 @@ BEGIN_WORKERS_NAMESPACE
 WorkerCrossThreadDispatcher*
 GetWorkerCrossThreadDispatcher(JSContext* aCx, JS::Value aWorker)
 {
   if (!aWorker.isObject()) {
     return nullptr;
   }
 
   WorkerPrivate* w = nullptr;
-  UNWRAP_OBJECT(Worker, aCx, &aWorker.toObject(), w);
+  UNWRAP_OBJECT(Worker, &aWorker.toObject(), w);
   MOZ_ASSERT(w);
   return w->GetCrossThreadDispatcher();
 }
 
 // Can't use NS_IMPL_CYCLE_COLLECTION_CLASS(WorkerPrivateParent) because of the
 // templates.
 template <>
 WorkerPrivateParent<WorkerPrivate>::cycleCollection WorkerPrivateParent<WorkerPrivate>::_cycleCollectorGlobal = WorkerPrivateParent<WorkerPrivate>::cycleCollection();
--- a/dom/workers/WorkerScope.cpp
+++ b/dom/workers/WorkerScope.cpp
@@ -17,19 +17,19 @@
 #include "mozilla/dom/SharedWorkerGlobalScopeBinding.h"
 
 #ifdef ANDROID
 #include <android/log.h>
 #endif
 
 #include "RuntimeService.h" // For WorkersDumpEnabled().
 
-#define UNWRAP_WORKER_OBJECT(Interface, cx, obj, value)                       \
+#define UNWRAP_WORKER_OBJECT(Interface, obj, value)                           \
   UnwrapObject<prototypes::id::Interface##_workers,                           \
-    mozilla::dom::Interface##Binding_workers::NativeType>(cx, obj, value)
+    mozilla::dom::Interface##Binding_workers::NativeType>(obj, value)
 
 using namespace mozilla::dom;
 USING_WORKERS_NAMESPACE
 
 BEGIN_WORKERS_NAMESPACE
 
 WorkerGlobalScope::WorkerGlobalScope(WorkerPrivate* aWorkerPrivate)
 : mWorkerPrivate(aWorkerPrivate)
@@ -254,17 +254,17 @@ DedicatedWorkerGlobalScope::DedicatedWor
 : WorkerGlobalScope(aWorkerPrivate)
 {
 }
 
 /* static */ bool
 DedicatedWorkerGlobalScope::Visible(JSContext* aCx, JSObject* aObj)
 {
   DedicatedWorkerGlobalScope* self = nullptr;
-  nsresult rv = UNWRAP_WORKER_OBJECT(DedicatedWorkerGlobalScope, aCx, aObj, self);
+  nsresult rv = UNWRAP_WORKER_OBJECT(DedicatedWorkerGlobalScope, aObj, self);
   return NS_SUCCEEDED(rv) && self;
 }
 
 JSObject*
 DedicatedWorkerGlobalScope::WrapGlobalObject(JSContext* aCx,
                                              JS::CompartmentOptions& aOptions,
                                              JSPrincipals* aPrincipal)
 {
@@ -294,17 +294,17 @@ SharedWorkerGlobalScope::SharedWorkerGlo
 : WorkerGlobalScope(aWorkerPrivate), mName(aName)
 {
 }
 
 /* static */ bool
 SharedWorkerGlobalScope::Visible(JSContext* aCx, JSObject* aObj)
 {
   SharedWorkerGlobalScope* self = nullptr;
-  nsresult rv = UNWRAP_WORKER_OBJECT(SharedWorkerGlobalScope, aCx, aObj, self);
+  nsresult rv = UNWRAP_WORKER_OBJECT(SharedWorkerGlobalScope, aObj, self);
   return NS_SUCCEEDED(rv) && self;
 }
 
 JSObject*
 SharedWorkerGlobalScope::WrapGlobalObject(JSContext* aCx,
                                           JS::CompartmentOptions& aOptions,
                                           JSPrincipals* aPrincipal)
 {
--- a/gfx/2d/Blur.cpp
+++ b/gfx/2d/Blur.cpp
@@ -696,17 +696,17 @@ AlphaBoxBlur::BoxBlur_C(uint8_t* aData,
       int32_t topLeft = topLeftBase[x];
       int32_t topRight = topRightBase[x];
       int32_t bottomRight = bottomRightBase[x];
       int32_t bottomLeft = bottomLeftBase[x];
 
       uint32_t value = bottomRight - topRight - bottomLeft;
       value += topLeft;
 
-      data[stride * y + x] = (uint64_t(reciprocal) * value) >> 32;
+      data[stride * y + x] = (uint64_t(reciprocal) * value + (uint64_t(1) << 31)) >> 32;
     }
   }
 }
 
 /**
  * Compute the box blur size (which we're calling the blur radius) from
  * the standard deviation.
  *
--- a/gfx/2d/BlurSSE2.cpp
+++ b/gfx/2d/BlurSSE2.cpp
@@ -7,24 +7,42 @@
 #include "SSEHelpers.h"
 
 #include <string.h>
 
 namespace mozilla {
 namespace gfx {
 
 MOZ_ALWAYS_INLINE
-uint32_t DivideAndPack(__m128i aValues, __m128i aDivisor, __m128i aMask)
+__m128i Divide(__m128i aValues, __m128i aDivisor)
 {
-  __m128i multiplied = _mm_srli_epi64(_mm_mul_epu32(aValues, aDivisor), 32); // 00p300p1
-  multiplied = _mm_or_si128(multiplied, _mm_and_si128(_mm_mul_epu32(_mm_srli_epi64(aValues, 32), aDivisor),
-    aMask)); // p4p3p2p1
-  __m128i final = _mm_packus_epi16(_mm_packs_epi32(multiplied, _mm_setzero_si128()), _mm_setzero_si128());
+  const __m128i mask = _mm_setr_epi32(0x0, 0xffffffff, 0x0, 0xffffffff);
+  static const union {
+    int64_t i64[2];
+    __m128i m;
+  } roundingAddition = { { int64_t(1) << 31, int64_t(1) << 31 } };
+
+  __m128i multiplied31 = _mm_mul_epu32(aValues, aDivisor);
+  __m128i multiplied42 = _mm_mul_epu32(_mm_srli_epi64(aValues, 32), aDivisor);
 
-  return _mm_cvtsi128_si32(final);
+  // Add 1 << 31 before shifting or masking the lower 32 bits away, so that the
+  // result is rounded.
+  __m128i p_3_1 = _mm_srli_epi64(_mm_add_epi64(multiplied31, roundingAddition.m), 32);
+  __m128i p4_2_ = _mm_and_si128(_mm_add_epi64(multiplied42, roundingAddition.m), mask);
+  __m128i p4321 = _mm_or_si128(p_3_1, p4_2_);
+  return p4321;
+}
+
+MOZ_ALWAYS_INLINE
+__m128i BlurFourPixels(const __m128i& aTopLeft, const __m128i& aTopRight,
+                       const __m128i& aBottomRight, const __m128i& aBottomLeft,
+                       const __m128i& aDivisor)
+{
+  __m128i values = _mm_add_epi32(_mm_sub_epi32(_mm_sub_epi32(aBottomRight, aTopRight), aBottomLeft), aTopLeft);
+  return Divide(values, aDivisor);
 }
 
 MOZ_ALWAYS_INLINE
 void LoadIntegralRowFromRow(uint32_t *aDest, const uint8_t *aSource,
                             int32_t aSourceWidth, int32_t aLeftInflation,
                             int32_t aRightInflation)
 {
   int32_t currentRowSum = 0;
@@ -170,17 +188,17 @@ GenerateIntegralImage_SSE2(int32_t aLeft
   }
 }
 
 /**
  * Attempt to do an in-place box blur using an integral image.
  */
 void
 AlphaBoxBlur::BoxBlur_SSE2(uint8_t* aData,
-			   int32_t aLeftLobe,
+                           int32_t aLeftLobe,
                            int32_t aRightLobe,
                            int32_t aTopLobe,
                            int32_t aBottomLobe,
                            uint32_t *aIntegralImage,
                            size_t aIntegralImageStride)
 {
   IntSize size = GetSize();
 
@@ -204,48 +222,94 @@ AlphaBoxBlur::BoxBlur_SSE2(uint8_t* aDat
   uint32_t stride32bit = aIntegralImageStride / 4;
   int32_t leftInflation = RoundUpToMultipleOf4(aLeftLobe).value();
 
   GenerateIntegralImage_SSE2(leftInflation, aRightLobe, aTopLobe, aBottomLobe,
                              aIntegralImage, aIntegralImageStride, aData,
                              mStride, size);
 
   __m128i divisor = _mm_set1_epi32(reciprocal);
-  __m128i mask = _mm_setr_epi32(0x0, 0xffffffff, 0x0, 0xffffffff);
 
   // This points to the start of the rectangle within the IntegralImage that overlaps
   // the surface being blurred.
   uint32_t *innerIntegral = aIntegralImage + (aTopLobe * stride32bit) + leftInflation;
 
   IntRect skipRect = mSkipRect;
   int32_t stride = mStride;
   uint8_t *data = aData;
   for (int32_t y = 0; y < size.height; y++) {
     bool inSkipRectY = y > skipRect.y && y < skipRect.YMost();
 
     uint32_t *topLeftBase = innerIntegral + ((y - aTopLobe) * ptrdiff_t(stride32bit) - aLeftLobe);
     uint32_t *topRightBase = innerIntegral + ((y - aTopLobe) * ptrdiff_t(stride32bit) + aRightLobe);
     uint32_t *bottomRightBase = innerIntegral + ((y + aBottomLobe) * ptrdiff_t(stride32bit) + aRightLobe);
     uint32_t *bottomLeftBase = innerIntegral + ((y + aBottomLobe) * ptrdiff_t(stride32bit) - aLeftLobe);
 
-    for (int32_t x = 0; x < size.width; x += 4) {
+    int32_t x = 0;
+    // Process 16 pixels at a time for as long as possible.
+    for (; x <= size.width - 16; x += 16) {
+      if (inSkipRectY && x > skipRect.x && x < skipRect.XMost()) {
+        x = skipRect.XMost() - 16;
+        // Trigger early jump on coming loop iterations, this will be reset
+        // next line anyway.
+        inSkipRectY = false;
+        continue;
+      }
+
+      __m128i topLeft;
+      __m128i topRight;
+      __m128i bottomRight;
+      __m128i bottomLeft;
+
+      topLeft = loadUnaligned128((__m128i*)(topLeftBase + x));
+      topRight = loadUnaligned128((__m128i*)(topRightBase + x));
+      bottomRight = loadUnaligned128((__m128i*)(bottomRightBase + x));
+      bottomLeft = loadUnaligned128((__m128i*)(bottomLeftBase + x));
+      __m128i result1 = BlurFourPixels(topLeft, topRight, bottomRight, bottomLeft, divisor);
+
+      topLeft = loadUnaligned128((__m128i*)(topLeftBase + x + 4));
+      topRight = loadUnaligned128((__m128i*)(topRightBase + x + 4));
+      bottomRight = loadUnaligned128((__m128i*)(bottomRightBase + x + 4));
+      bottomLeft = loadUnaligned128((__m128i*)(bottomLeftBase + x + 4));
+      __m128i result2 = BlurFourPixels(topLeft, topRight, bottomRight, bottomLeft, divisor);
+
+      topLeft = loadUnaligned128((__m128i*)(topLeftBase + x + 8));
+      topRight = loadUnaligned128((__m128i*)(topRightBase + x + 8));
+      bottomRight = loadUnaligned128((__m128i*)(bottomRightBase + x + 8));
+      bottomLeft = loadUnaligned128((__m128i*)(bottomLeftBase + x + 8));
+      __m128i result3 = BlurFourPixels(topLeft, topRight, bottomRight, bottomLeft, divisor);
+
+      topLeft = loadUnaligned128((__m128i*)(topLeftBase + x + 12));
+      topRight = loadUnaligned128((__m128i*)(topRightBase + x + 12));
+      bottomRight = loadUnaligned128((__m128i*)(bottomRightBase + x + 12));
+      bottomLeft = loadUnaligned128((__m128i*)(bottomLeftBase + x + 12));
+      __m128i result4 = BlurFourPixels(topLeft, topRight, bottomRight, bottomLeft, divisor);
+
+      __m128i final = _mm_packus_epi16(_mm_packs_epi32(result1, result2), _mm_packs_epi32(result3, result4));
+
+      _mm_storeu_si128((__m128i*)(data + stride * y + x), final);
+    }
+
+    // Process the remaining pixels 4 bytes at a time.
+    for (; x < size.width; x += 4) {
       if (inSkipRectY && x > skipRect.x && x < skipRect.XMost()) {
         x = skipRect.XMost() - 4;
         // Trigger early jump on coming loop iterations, this will be reset
         // next line anyway.
         inSkipRectY = false;
         continue;
       }
       __m128i topLeft = loadUnaligned128((__m128i*)(topLeftBase + x));
       __m128i topRight = loadUnaligned128((__m128i*)(topRightBase + x));
       __m128i bottomRight = loadUnaligned128((__m128i*)(bottomRightBase + x));
       __m128i bottomLeft = loadUnaligned128((__m128i*)(bottomLeftBase + x));
 
-      __m128i values = _mm_add_epi32(_mm_sub_epi32(_mm_sub_epi32(bottomRight, topRight), bottomLeft), topLeft);
+      __m128i result = BlurFourPixels(topLeft, topRight, bottomRight, bottomLeft, divisor);
+      __m128i final = _mm_packus_epi16(_mm_packs_epi32(result, _mm_setzero_si128()), _mm_setzero_si128());
 
-      *(uint32_t*)(data + stride * y + x) = DivideAndPack(values, divisor, mask);
+      *(uint32_t*)(data + stride * y + x) = _mm_cvtsi128_si32(final);
     }
   }
 
 }
 
 }
 }
--- a/gfx/harfbuzz/src/moz.build
+++ b/gfx/harfbuzz/src/moz.build
@@ -18,40 +18,40 @@ EXPORTS.harfbuzz += [
     'hb-shape-plan.h',
     'hb-shape.h',
     'hb-unicode.h',
     'hb-version.h',
     'hb.h',
 ]
 
 SOURCES += [
+    'hb-blob.cc', # error: use of undeclared identifier 'snprintf' (FreeBSD)
     'hb-common.cc', # error: use of undeclared identifier 'strdup'
     'hb-ot-shape-complex-indic.cc', # error: redefinition of enumerator 'INIT'
     'hb-ot-shape-complex-sea.cc', # error: redefinition of 'basic_features'
     'hb-ot-shape.cc', # error: functions that differ only in their return type cannot be overloaded
+    'hb-shape-plan.cc', # error: redefinition of 'hb_ot_shaper_face_data_ensure'
 ]
 
 UNIFIED_SOURCES += [
-    'hb-blob.cc',
     'hb-buffer.cc',
     'hb-face.cc',
     'hb-fallback-shape.cc',
     'hb-font.cc',
     'hb-ot-layout.cc',
     'hb-ot-map.cc',
     'hb-ot-shape-complex-arabic.cc',
     'hb-ot-shape-complex-default.cc',
     'hb-ot-shape-complex-indic-table.cc',
     'hb-ot-shape-complex-myanmar.cc',
     'hb-ot-shape-complex-thai.cc',
     'hb-ot-shape-fallback.cc',
     'hb-ot-shape-normalize.cc',
     'hb-ot-tag.cc',
     'hb-set.cc',
-    'hb-shape-plan.cc',
     'hb-shape.cc',
     'hb-shaper.cc',
     'hb-unicode.cc',
     'hb-warning.cc',
 ]
 
 MSVC_ENABLE_PGO = True
 
--- a/gfx/layers/composite/APZCTreeManager.cpp
+++ b/gfx/layers/composite/APZCTreeManager.cpp
@@ -208,17 +208,19 @@ APZCTreeManager::UpdatePanZoomController
   if (apzc) {
     aTransform = gfx3DMatrix();
   } else {
     // Multiply child layer transforms on the left so they get applied first
     aTransform = aLayer->GetTransform() * aTransform;
   }
 
   uint64_t childLayersId = (aLayer->AsRefLayer() ? aLayer->AsRefLayer()->GetReferentId() : aLayersId);
-  AsyncPanZoomController* next = nullptr;
+  // If there's no APZC at this level, any APZCs for our child layers will
+  // have our siblings as siblings.
+  AsyncPanZoomController* next = apzc ? nullptr : aNextSibling;
   for (Layer* child = aLayer->GetLastChild(); child; child = child->GetPrevSibling()) {
     next = UpdatePanZoomControllerTree(aCompositor, child, childLayersId, aTransform, aParent, next,
                                        aIsFirstPaint, aFirstPaintLayersId, aApzcsToDestroy);
   }
 
   // Return the APZC that should be the sibling of other APZCs as we continue
   // moving towards the first child at this depth in the layer tree.
   // If this layer doesn't have an APZC, we promote any APZCs in the subtree
--- a/gfx/layers/d3d10/ImageLayerD3D10.cpp
+++ b/gfx/layers/d3d10/ImageLayerD3D10.cpp
@@ -352,20 +352,20 @@ void ImageLayerD3D10::AllocateTexturesYC
   nsAutoPtr<PlanarYCbCrD3D10BackendData> backendData(
     new PlanarYCbCrD3D10BackendData);
 
   const PlanarYCbCrData *data = aImage->GetData();
 
   D3D10_SUBRESOURCE_DATA dataY;
   D3D10_SUBRESOURCE_DATA dataCb;
   D3D10_SUBRESOURCE_DATA dataCr;
-  CD3D10_TEXTURE2D_DESC descY(DXGI_FORMAT_R8_UNORM,
+  CD3D10_TEXTURE2D_DESC descY(DXGI_FORMAT_A8_UNORM,
                               data->mYSize.width,
                               data->mYSize.height, 1, 1);
-  CD3D10_TEXTURE2D_DESC descCbCr(DXGI_FORMAT_R8_UNORM,
+  CD3D10_TEXTURE2D_DESC descCbCr(DXGI_FORMAT_A8_UNORM,
                                  data->mCbCrSize.width,
                                  data->mCbCrSize.height, 1, 1);
 
   descY.Usage = descCbCr.Usage = D3D10_USAGE_IMMUTABLE;
 
   dataY.pSysMem = data->mYChannel;
   dataY.SysMemPitch = data->mYStride;
   dataCb.pSysMem = data->mCbChannel;
--- a/gfx/layers/d3d10/LayerManagerD3D10.fx
+++ b/gfx/layers/d3d10/LayerManagerD3D10.fx
@@ -244,19 +244,19 @@ float4 RGBShaderMask(const VS_MASK_OUTPU
   return result * mask;
 }
 
 float4 CalculateYCbCrColor(const float2 aTexCoords)
 {
   float4 yuv;
   float4 color;
 
-  yuv.r = tCr.Sample(LayerTextureSamplerLinear, aTexCoords).r - 0.5;
-  yuv.g = tY.Sample(LayerTextureSamplerLinear, aTexCoords).r - 0.0625;
-  yuv.b = tCb.Sample(LayerTextureSamplerLinear, aTexCoords).r - 0.5;
+  yuv.r = tCr.Sample(LayerTextureSamplerLinear, aTexCoords).a - 0.5;
+  yuv.g = tY.Sample(LayerTextureSamplerLinear, aTexCoords).a - 0.0625;
+  yuv.b = tCb.Sample(LayerTextureSamplerLinear, aTexCoords).a - 0.5;
 
   color.r = yuv.g * 1.164 + yuv.r * 1.596;
   color.g = yuv.g * 1.164 - 0.813 * yuv.r - 0.391 * yuv.b;
   color.b = yuv.g * 1.164 + yuv.b * 2.018;
   color.a = 1.0f;
 
   return color;
 }
--- a/gfx/layers/d3d10/LayerManagerD3D10Effect.h
+++ b/gfx/layers/d3d10/LayerManagerD3D10Effect.h
@@ -1,12 +1,8 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
 #if 0
 //
 // FX Version: fx_4_0
 // Child effect (requires effect pool): false
 //
 // 3 local buffer(s)
 //
 cbuffer PerLayer
@@ -1602,49 +1598,49 @@ technique10 RenderYCbCrLayer
                 def c1, -0.5, -0.0625, 1.59599996, 0.813000023
                 def c2, 1.16400003, 2.01799989, 0.391000003, 1
                 dcl t0.xy
                 dcl_2d s0
                 dcl_2d s1
                 dcl_2d s2
                 texld r0, t0, s0
                 texld r1, t0, s2
-                add r0.y, r1.x, c1.x
-                mul r0.yz, r0.y, c1.xzww
-                add r0.x, r0.x, c1.y
-                mad r0.z, r0.x, c2.x, -r0.z
-                mad r1.x, r0.x, c2.x, r0.y
+                add r0.x, r1.w, c1.x
+                mul r0.xy, r0.x, c1.zwzw
+                add r0.z, r0.w, c1.y
+                mad r0.y, r0.z, c2.x, -r0.y
+                mad r1.x, r0.z, c2.x, r0.x
                 texld r2, t0, s1
-                add r0.y, r2.x, c1.x
-                mad r1.y, r0.y, -c2.z, r0.z
-                mul r0.y, r0.y, c2.y
-                mad r1.z, r0.x, c2.x, r0.y
+                add r0.x, r2.w, c1.x
+                mad r1.y, r0.x, -c2.z, r0.y
+                mul r0.x, r0.x, c2.y
+                mad r1.z, r0.z, c2.x, r0.x
                 mov r1.w, c2.w
                 mul r0, r1, c0.x
                 mov oC0, r0
             
             // approximately 15 instruction slots used (3 texture, 12 arithmetic)
             ps_4_0
             dcl_constantbuffer cb0[4], immediateIndexed
             dcl_sampler s0, mode_default
             dcl_resource_texture2d (float,float,float,float) t0
             dcl_resource_texture2d (float,float,float,float) t1
             dcl_resource_texture2d (float,float,float,float) t2
             dcl_input_ps linear v1.xy
             dcl_output o0.xyzw
             dcl_temps 3
             sample r0.xyzw, v1.xyxx, t2.xyzw, s0
-            add r0.x, r0.x, l(-0.500000)
+            add r0.x, r0.w, l(-0.500000)
             mul r0.xy, r0.xxxx, l(1.596000, 0.813000, 0.000000, 0.000000)
             sample r1.xyzw, v1.xyxx, t0.xyzw, s0
-            add r0.z, r1.x, l(-0.062500)
+            add r0.z, r1.w, l(-0.062500)
             mad r0.y, r0.z, l(1.164000), -r0.y
             mad r1.x, r0.z, l(1.164000), r0.x
             sample r2.xyzw, v1.xyxx, t1.xyzw, s0
-            add r0.x, r2.x, l(-0.500000)
+            add r0.x, r2.w, l(-0.500000)
             mad r1.y, -r0.x, l(0.391000), r0.y
             mul r0.x, r0.x, l(2.018000)
             mad r1.z, r0.z, l(1.164000), r0.x
             mov r1.w, l(1.000000)
             mul o0.xyzw, r1.xyzw, cb0[3].xxxx
             ret 
             // Approximately 15 instruction slots used
                     
@@ -4146,28 +4142,28 @@ technique10 RenderYCbCrLayerMask
                 def c2, 1.16400003, 2.01799989, 0.391000003, 1
                 dcl t0
                 dcl_2d s0
                 dcl_2d s1
                 dcl_2d s2
                 dcl_2d s3
                 texld r0, t0, s0
                 texld r1, t0, s2
-                add r0.y, r1.x, c1.x
-                mul r0.yz, r0.y, c1.xzww
-                add r0.x, r0.x, c1.y
-                mad r0.z, r0.x, c2.x, -r0.z
-                mad r1.x, r0.x, c2.x, r0.y
+                add r0.x, r1.w, c1.x
+                mul r0.xy, r0.x, c1.zwzw
+                add r0.z, r0.w, c1.y
+                mad r0.y, r0.z, c2.x, -r0.y
+                mad r1.x, r0.z, c2.x, r0.x
                 mov r2.xy, t0.wzzw
                 texld r3, t0, s1
                 texld r2, r2, s3
-                add r0.y, r3.x, c1.x
-                mad r1.y, r0.y, -c2.z, r0.z
-                mul r0.y, r0.y, c2.y
-                mad r1.z, r0.x, c2.x, r0.y
+                add r0.x, r3.w, c1.x
+                mad r1.y, r0.x, -c2.z, r0.y
+                mul r0.x, r0.x, c2.y
+                mad r1.z, r0.z, c2.x, r0.x
                 mov r1.w, c2.w
                 mul r0, r1, c0.x
                 mul r0, r2.w, r0
                 mov oC0, r0
             
             // approximately 18 instruction slots used (4 texture, 14 arithmetic)
             ps_4_0
             dcl_constantbuffer cb0[4], immediateIndexed
@@ -4176,24 +4172,24 @@ technique10 RenderYCbCrLayerMask
             dcl_resource_texture2d (float,float,float,float) t1
             dcl_resource_texture2d (float,float,float,float) t2
             dcl_resource_texture2d (float,float,float,float) t3
             dcl_input_ps linear v1.xy
             dcl_input_ps linear v1.zw
             dcl_output o0.xyzw
             dcl_temps 3
             sample r0.xyzw, v1.xyxx, t2.xyzw, s0
-            add r0.x, r0.x, l(-0.500000)
+            add r0.x, r0.w, l(-0.500000)
             mul r0.xy, r0.xxxx, l(1.596000, 0.813000, 0.000000, 0.000000)
             sample r1.xyzw, v1.xyxx, t0.xyzw, s0
-            add r0.z, r1.x, l(-0.062500)
+            add r0.z, r1.w, l(-0.062500)
             mad r0.y, r0.z, l(1.164000), -r0.y
             mad r1.x, r0.z, l(1.164000), r0.x
             sample r2.xyzw, v1.xyxx, t1.xyzw, s0
-            add r0.x, r2.x, l(-0.500000)
+            add r0.x, r2.w, l(-0.500000)
             mad r1.y, -r0.x, l(0.391000), r0.y
             mul r0.x, r0.x, l(2.018000)
             mad r1.z, r0.z, l(1.164000), r0.x
             mov r1.w, l(1.000000)
             mul r0.xyzw, r1.xyzw, cb0[3].xxxx
             sample r1.xyzw, v1.zwzz, t3.xyzw, s0
             mul o0.xyzw, r0.xyzw, r1.wwww
             ret 
@@ -4683,20 +4679,20 @@ technique10 RenderSolidColorLayerMask
     }
 
 }
 
 #endif
 
 const BYTE g_main[] =
 {
-     68,  88,  66,  67, 165,  47, 
-      2, 116, 253,  33,  81,  39, 
-     75,  42, 228, 176, 250, 109, 
-    200, 179,   1,   0,   0,   0, 
+     68,  88,  66,  67, 218, 142, 
+     35, 224, 179, 182, 169,  21, 
+     79, 128, 135,  14, 250, 174, 
+     44, 181,   1,   0,   0,   0, 
      30,  32,   1,   0,   1,   0, 
       0,   0,  36,   0,   0,   0, 
      70,  88,  49,  48, 242,  31, 
       1,   0,   1,  16, 255, 254, 
       3,   0,   0,   0,   8,   0, 
       0,   0,  13,   0,   0,   0, 
       0,   0,   0,   0,   0,   0, 
       0,   0,   0,   0,   0,   0, 
@@ -8368,20 +8364,20 @@ const BYTE g_main[] =
       0,  83,  86,  95,  80, 111, 
     115, 105, 116, 105, 111, 110, 
       0,  84,  69,  88,  67,  79, 
      79,  82,  68,   0, 171, 171, 
     171,  67,  78,   0,   0,   0, 
       0,   0,   0,   1,   0,   0, 
       0,   2,   0,   0,   0,   0, 
       0,   0,   0,  96,   7,   0, 
-      0,  68,  88,  66,  67, 240, 
-      1, 205, 211, 197,  17, 202, 
-     42,  30, 221, 209, 206, 174, 
-    135, 152, 163,   1,   0,   0, 
+      0,  68,  88,  66,  67, 248, 
+     27, 107, 126, 143, 194, 255, 
+     95, 146,  68,  72, 180, 162, 
+    134,  32,   4,   1,   0,   0, 
       0,  96,   7,   0,   0,   6, 
       0,   0,   0,  56,   0,   0, 
       0, 220,   1,   0,   0,  44, 
       4,   0,   0, 168,   4,   0, 
       0, 212,   6,   0,   0,  44, 
       7,   0,   0,  65, 111, 110, 
      57, 156,   1,   0,   0, 156, 
       1,   0,   0,   0,   2, 255, 
@@ -8411,45 +8407,45 @@ const BYTE g_main[] =
       8,  15, 160,  31,   0,   0, 
       2,   0,   0,   0, 144,   2, 
       8,  15, 160,  66,   0,   0, 
       3,   0,   0,  15, 128,   0, 
       0, 228, 176,   0,   8, 228, 
     160,  66,   0,   0,   3,   1, 
       0,  15, 128,   0,   0, 228, 
     176,   2,   8, 228, 160,   2, 
-      0,   0,   3,   0,   0,   2, 
-    128,   1,   0,   0, 128,   1, 
+      0,   0,   3,   0,   0,   1, 
+    128,   1,   0, 255, 128,   1, 
       0,   0, 160,   5,   0,   0, 
-      3,   0,   0,   6, 128,   0, 
-      0,  85, 128,   1,   0, 248, 
+      3,   0,   0,   3, 128,   0, 
+      0,   0, 128,   1,   0, 238, 
     160,   2,   0,   0,   3,   0, 
-      0,   1, 128,   0,   0,   0, 
+      0,   4, 128,   0,   0, 255, 
     128,   1,   0,  85, 160,   4, 
-      0,   0,   4,   0,   0,   4, 
-    128,   0,   0,   0, 128,   2, 
-      0,   0, 160,   0,   0, 170, 
+      0,   0,   4,   0,   0,   2, 
+    128,   0,   0, 170, 128,   2, 
+      0,   0, 160,   0,   0,  85, 
     129,   4,   0,   0,   4,   1, 
-      0,   1, 128,   0,   0,   0, 
+      0,   1, 128,   0,   0, 170, 
     128,   2,   0,   0, 160,   0, 
-      0,  85, 128,  66,   0,   0, 
+      0,   0, 128,  66,   0,   0, 
       3,   2,   0,  15, 128,   0, 
       0, 228, 176,   1,   8, 228, 
     160,   2,   0,   0,   3,   0, 
-      0,   2, 128,   2,   0,   0, 
+      0,   1, 128,   2,   0, 255, 
     128,   1,   0,   0, 160,   4, 
       0,   0,   4,   1,   0,   2, 
-    128,   0,   0,  85, 128,   2, 
-      0, 170, 161,   0,   0, 170, 
+    128,   0,   0,   0, 128,   2, 
+      0, 170, 161,   0,   0,  85, 
     128,   5,   0,   0,   3,   0, 
-      0,   2, 128,   0,   0,  85, 
+      0,   1, 128,   0,   0,   0, 
     128,   2,   0,  85, 160,   4, 
       0,   0,   4,   1,   0,   4, 
-    128,   0,   0,   0, 128,   2, 
-      0,   0, 160,   0,   0,  85, 
+    128,   0,   0, 170, 128,   2, 
+      0,   0, 160,   0,   0,   0, 
     128,   1,   0,   0,   2,   1, 
       0,   8, 128,   2,   0, 255, 
     160,   5,   0,   0,   3,   0, 
       0,  15, 128,   1,   0, 228, 
     128,   0,   0,   0, 160,   1, 
       0,   0,   2,   0,   8,  15, 
     128,   0,   0, 228, 128, 255, 
     255,   0,   0,  83,  72,  68, 
@@ -8476,34 +8472,34 @@ const BYTE g_main[] =
       0,  69,   0,   0,   9, 242, 
       0,  16,   0,   0,   0,   0, 
       0,  70,  16,  16,   0,   1, 
       0,   0,   0,  70, 126,  16, 
       0,   2,   0,   0,   0,   0, 
      96,  16,   0,   0,   0,   0, 
       0,   0,   0,   0,   7,  18, 
       0,  16,   0,   0,   0,   0, 
-      0,  10,   0,  16,   0,   0, 
+      0,  58,   0,  16,   0,   0, 
       0,   0,   0,   1,  64,   0, 
       0,   0,   0,   0, 191,  56, 
       0,   0,  10,  50,   0,  16, 
       0,   0,   0,   0,   0,   6, 
       0,  16,   0,   0,   0,   0, 
       0,   2,  64,   0,   0, 186, 
      73, 204,  63, 197,  32,  80, 
      63,   0,   0,   0,   0,   0, 
       0,   0,   0,  69,   0,   0, 
       9, 242,   0,  16,   0,   1, 
       0,   0,   0,  70,  16,  16, 
       0,   1,   0,   0,   0,  70, 
     126,  16,   0,   0,   0,   0, 
       0,   0,  96,  16,   0,   0, 
       0,   0,   0,   0,   0,   0, 
       7,  66,   0,  16,   0,   0, 
-      0,   0,   0,  10,   0,  16, 
+      0,   0,   0,  58,   0,  16, 
       0,   1,   0,   0,   0,   1, 
      64,   0,   0,   0,   0, 128, 
     189,  50,   0,   0,  10,  34, 
       0,  16,   0,   0,   0,   0, 
       0,  42,   0,  16,   0,   0, 
       0,   0,   0,   1,  64,   0, 
       0, 244, 253, 148,  63,  26, 
       0,  16, 128,  65,   0,   0, 
@@ -8516,17 +8512,17 @@ const BYTE g_main[] =
       0,   0,   0,   0,   0,  69, 
       0,   0,   9, 242,   0,  16, 
       0,   2,   0,   0,   0,  70, 
      16,  16,   0,   1,   0,   0, 
       0,  70, 126,  16,   0,   1, 
       0,   0,   0,   0,  96,  16, 
       0,   0,   0,   0,   0,   0, 
       0,   0,   7,  18,   0,  16, 
-      0,   0,   0,   0,   0,  10, 
+      0,   0,   0,   0,   0,  58, 
       0,  16,   0,   2,   0,   0, 
       0,   1,  64,   0,   0,   0, 
       0,   0, 191,  50,   0,   0, 
      10,  34,   0,  16,   0,   1, 
       0,   0,   0,  10,   0,  16, 
     128,  65,   0,   0,   0,   0, 
       0,   0,   0,   1,  64,   0, 
       0,  39,  49, 200,  62,  26, 
@@ -14771,19 +14767,19 @@ const BYTE g_main[] =
      95,  80, 111, 115, 105, 116, 
     105, 111, 110,   0,  84,  69, 
      88,  67,  79,  79,  82,  68, 
       0, 171, 171, 171, 142, 227, 
       0,   0,   0,   0,   0,   0, 
       1,   0,   0,   0,   2,   0, 
       0,   0,   0,   0,   0,   0, 
      52,   8,   0,   0,  68,  88, 
-     66,  67,  53, 130, 196, 222, 
-     55,   6,  85, 223,   2,  38, 
-     19,  66,  81, 203,  15,  85, 
+     66,  67, 202,  83,  22, 204, 
+    207, 151,  51, 179, 174, 132, 
+     82, 181, 125,  14, 145,  73, 
       1,   0,   0,   0,  52,   8, 
       0,   0,   6,   0,   0,   0, 
      56,   0,   0,   0,  24,   2, 
       0,   0, 196,   4,   0,   0, 
      64,   5,   0,   0, 144,   7, 
       0,   0,   0,   8,   0,   0, 
      65, 111, 110,  57, 216,   1, 
       0,   0, 216,   1,   0,   0, 
@@ -14817,49 +14813,49 @@ const BYTE g_main[] =
       0,   2,   0,   0,   0, 144, 
       3,   8,  15, 160,  66,   0, 
       0,   3,   0,   0,  15, 128, 
       0,   0, 228, 176,   0,   8, 
     228, 160,  66,   0,   0,   3, 
       1,   0,  15, 128,   0,   0, 
     228, 176,   2,   8, 228, 160, 
       2,   0,   0,   3,   0,   0, 
-      2, 128,   1,   0,   0, 128, 
+      1, 128,   1,   0, 255, 128, 
       1,   0,   0, 160,   5,   0, 
-      0,   3,   0,   0,   6, 128, 
-      0,   0,  85, 128,   1,   0, 
-    248, 160,   2,   0,   0,   3, 
-      0,   0,   1, 128,   0,   0, 
-      0, 128,   1,   0,  85, 160, 
+      0,   3,   0,   0,   3, 128, 
+      0,   0,   0, 128,   1,   0, 
+    238, 160,   2,   0,   0,   3, 
+      0,   0,   4, 128,   0,   0, 
+    255, 128,   1,   0,  85, 160, 
       4,   0,   0,   4,   0,   0, 
-      4, 128,   0,   0,   0, 128, 
+      2, 128,   0,   0, 170, 128, 
       2,   0,   0, 160,   0,   0, 
-    170, 129,   4,   0,   0,   4, 
+     85, 129,   4,   0,   0,   4, 
       1,   0,   1, 128,   0,   0, 
-      0, 128,   2,   0,   0, 160, 
-      0,   0,  85, 128,   1,   0, 
+    170, 128,   2,   0,   0, 160, 
+      0,   0,   0, 128,   1,   0, 
       0,   2,   2,   0,   3, 128, 
       0,   0, 235, 176,  66,   0, 
       0,   3,   3,   0,  15, 128, 
       0,   0, 228, 176,   1,   8, 
     228, 160,  66,   0,   0,   3, 
       2,   0,  15, 128,   2,   0, 
     228, 128,   3,   8, 228, 160, 
       2,   0,   0,   3,   0,   0, 
-      2, 128,   3,   0,   0, 128, 
+      1, 128,   3,   0, 255, 128, 
       1,   0,   0, 160,   4,   0, 
       0,   4,   1,   0,   2, 128, 
-      0,   0,  85, 128,   2,   0, 
-    170, 161,   0,   0, 170, 128, 
+      0,   0,   0, 128,   2,   0, 
+    170, 161,   0,   0,  85, 128, 
       5,   0,   0,   3,   0,   0, 
-      2, 128,   0,   0,  85, 128, 
+      1, 128,   0,   0,   0, 128, 
       2,   0,  85, 160,   4,   0, 
       0,   4,   1,   0,   4, 128, 
-      0,   0,   0, 128,   2,   0, 
-      0, 160,   0,   0,  85, 128, 
+      0,   0, 170, 128,   2,   0, 
+      0, 160,   0,   0,   0, 128, 
       1,   0,   0,   2,   1,   0, 
       8, 128,   2,   0, 255, 160, 
       5,   0,   0,   3,   0,   0, 
      15, 128,   1,   0, 228, 128, 
       0,   0,   0, 160,   5,   0, 
       0,   3,   0,   0,  15, 128, 
       2,   0, 255, 128,   0,   0, 
     228, 128,   1,   0,   0,   2, 
@@ -14893,34 +14889,34 @@ const BYTE g_main[] =
       0,   0,  69,   0,   0,   9, 
     242,   0,  16,   0,   0,   0, 
       0,   0,  70,  16,  16,   0, 
       1,   0,   0,   0,  70, 126, 
      16,   0,   2,   0,   0,   0, 
       0,  96,  16,   0,   0,   0, 
       0,   0,   0,   0,   0,   7, 
      18,   0,  16,   0,   0,   0, 
-      0,   0,  10,   0,  16,   0, 
+      0,   0,  58,   0,  16,   0, 
       0,   0,   0,   0,   1,  64, 
       0,   0,   0,   0,   0, 191, 
      56,   0,   0,  10,  50,   0, 
      16,   0,   0,   0,   0,   0, 
       6,   0,  16,   0,   0,   0, 
       0,   0,   2,  64,   0,   0, 
     186,  73, 204,  63, 197,  32, 
      80,  63,   0,   0,   0,   0, 
       0,   0,   0,   0,  69,   0, 
       0,   9, 242,   0,  16,   0, 
       1,   0,   0,   0,  70,  16, 
      16,   0,   1,   0,   0,   0, 
      70, 126,  16,   0,   0,   0, 
       0,   0,   0,  96,  16,   0, 
       0,   0,   0,   0,   0,   0, 
       0,   7,  66,   0,  16,   0, 
-      0,   0,   0,   0,  10,   0, 
+      0,   0,   0,   0,  58,   0, 
      16,   0,   1,   0,   0,   0, 
       1,  64,   0,   0,   0,   0, 
     128, 189,  50,   0,   0,  10, 
      34,   0,  16,   0,   0,   0, 
       0,   0,  42,   0,  16,   0, 
       0,   0,   0,   0,   1,  64, 
       0,   0, 244, 253, 148,  63, 
      26,   0,  16, 128,  65,   0, 
@@ -14934,17 +14930,17 @@ const BYTE g_main[] =
      69,   0,   0,   9, 242,   0, 
      16,   0,   2,   0,   0,   0, 
      70,  16,  16,   0,   1,   0, 
       0,   0,  70, 126,  16,   0, 
       1,   0,   0,   0,   0,  96, 
      16,   0,   0,   0,   0,   0, 
       0,   0,   0,   7,  18,   0, 
      16,   0,   0,   0,   0,   0, 
-     10,   0,  16,   0,   2,   0, 
+     58,   0,  16,   0,   2,   0, 
       0,   0,   1,  64,   0,   0, 
       0,   0,   0, 191,  50,   0, 
       0,  10,  34,   0,  16,   0, 
       1,   0,   0,   0,  10,   0, 
      16, 128,  65,   0,   0,   0, 
       0,   0,   0,   0,   1,  64, 
       0,   0,  39,  49, 200,  62, 
      26,   0,  16,   0,   0,   0, 
--- a/gfx/layers/d3d11/CompositorD3D11.fx
+++ b/gfx/layers/d3d11/CompositorD3D11.fx
@@ -180,19 +180,19 @@ float4 RGBShaderMask(const VS_MASK_OUTPU
   return result * mask;
 }
 
 float4 CalculateYCbCrColor(const float2 aTexCoords)
 {
   float4 yuv;
   float4 color;
 
-  yuv.r = tCr.Sample(sSampler, aTexCoords).r - 0.5;
-  yuv.g = tY.Sample(sSampler, aTexCoords).r - 0.0625;
-  yuv.b = tCb.Sample(sSampler, aTexCoords).r - 0.5;
+  yuv.r = tCr.Sample(sSampler, aTexCoords).a - 0.5;
+  yuv.g = tY.Sample(sSampler, aTexCoords).a - 0.0625;
+  yuv.b = tCb.Sample(sSampler, aTexCoords).a - 0.5;
 
   color.r = yuv.g * 1.164 + yuv.r * 1.596;
   color.g = yuv.g * 1.164 - 0.813 * yuv.r - 0.391 * yuv.b;
   color.b = yuv.g * 1.164 + yuv.b * 2.018;
   color.a = 1.0f;
 
   return color;
 }
--- a/gfx/layers/d3d11/CompositorD3D11Shaders.h
+++ b/gfx/layers/d3d11/CompositorD3D11Shaders.h
@@ -1,14 +1,17 @@
 #if 0
 //
-// Generated by Microsoft (R) HLSL Shader Compiler 9.30.9200.20499
-//
-//
-///
+// Generated by Microsoft (R) HLSL Shader Compiler 9.29.952.3111
+//
+//
+//   fxc CompositorD3D11.fx -ELayerQuadVS -nologo -Tvs_4_0_level_9_3
+//    -FhtmpShaderHeader -VnLayerQuadVS
+//
+//
 // Buffer Definitions: 
 //
 // cbuffer $Globals
 // {
 //
 //   float4x4 mLayerTransform;          // Offset:    0 Size:    64
 //   float4x4 mProjection;              // Offset:   64 Size:    64
 //   float4 vRenderTargetOffset;        // Offset:  128 Size:    16
@@ -26,27 +29,27 @@
 // Name                                 Type  Format         Dim Slot Elements
 // ------------------------------ ---------- ------- ----------- ---- --------
 // $Globals                          cbuffer      NA          NA    0        1
 //
 //
 //
 // Input signature:
 //
-// Name                 Index   Mask Register SysValue  Format   Used
-// -------------------- ----- ------ -------- -------- ------- ------
-// POSITION                 0   xy          0     NONE   float   xy  
+// Name                 Index   Mask Register SysValue Format   Used
+// -------------------- ----- ------ -------- -------- ------ ------
+// POSITION                 0   xy          0     NONE  float   xy  
 //
 //
 // Output signature:
 //
-// Name                 Index   Mask Register SysValue  Format   Used
-// -------------------- ----- ------ -------- -------- ------- ------
-// SV_Position              0   xyzw        0      POS   float   xyzw
-// TEXCOORD                 0   xy          1     NONE   float   xy  
+// Name                 Index   Mask Register SysValue Format   Used
+// -------------------- ----- ------ -------- -------- ------ ------
+// SV_Position              0   xyzw        0      POS  float   xyzw
+// TEXCOORD                 0   xy          1     NONE  float   xy  
 //
 //
 // Constant buffer to DX9 shader constant mappings:
 //
 // Target Reg Buffer  Start Reg # of Regs        Data Conversion
 // ---------- ------- --------- --------- ----------------------
 // c1         cb0             0         2  ( FLT, FLT, FLT, FLT)
 // c3         cb0             3         8  ( FLT, FLT, FLT, FLT)
@@ -99,20 +102,20 @@ mad r1.xyzw, cb0[6].xyzw, r0.zzzz, r1.xy
 mad o0.xyzw, cb0[7].xyzw, r0.wwww, r1.xyzw
 mad o1.xy, v0.xyxx, cb0[9].zwzz, cb0[9].xyxx
 ret 
 // Approximately 13 instruction slots used
 #endif
 
 const BYTE LayerQuadVS[] =
 {
-     68,  88,  66,  67,  47,  18, 
-    215, 102,  49, 131, 226,  28, 
-    246, 230, 114,  12,  64,  76, 
-    134,  41,   1,   0,   0,   0, 
+     68,  88,  66,  67,  26, 156, 
+     32, 249,  73, 220,  32,  91, 
+     64, 185, 136, 143, 133, 249, 
+    140, 206,   1,   0,   0,   0, 
     180,   6,   0,   0,   6,   0, 
       0,   0,  56,   0,   0,   0, 
     152,   1,   0,   0, 160,   3, 
       0,   0,  28,   4,   0,   0, 
      40,   6,   0,   0,  92,   6, 
       0,   0,  65, 111, 110,  57, 
      88,   1,   0,   0,  88,   1, 
       0,   0,   0,   2, 254, 255, 
@@ -267,17 +270,17 @@ const BYTE LayerQuadVS[] =
       0,   0,   0,   0,   1,   0, 
       0,   0,   0,   0,   0,   0, 
       0,   0,   0,   0,   0,   0, 
       0,   0,   0,   0,   0,   0, 
       0,   0,   0,   0,   0,   0, 
       0,   0,   0,   0,   0,   0, 
       0,   0,   0,   0,   0,   0, 
       0,   0,   0,   0,   0,   0, 
-      0,   0,   0,   0,   2,   0, 
+      0,   0,   0,   0,   1,   0, 
       0,   0,   0,   0,   0,   0, 
       0,   0,   0,   0,   0,   0, 
       0,   0,   0,   0,   0,   0, 
       0,   0,   0,   0,   0,   0, 
       0,   0,   0,   0,   0,   0, 
       0,   0,   0,   0,   0,   0, 
       0,   0,  82,  68,  69,  70, 
       4,   2,   0,   0,   1,   0, 
@@ -359,19 +362,19 @@ const BYTE LayerQuadVS[] =
       1,   0,   1,   0,   0,   0, 
       0,   0,   0,   0,   0,   0, 
      77, 105,  99, 114, 111, 115, 
     111, 102, 116,  32,  40,  82, 
      41,  32,  72,  76,  83,  76, 
      32,  83, 104,  97, 100, 101, 
     114,  32,  67, 111, 109, 112, 
     105, 108, 101, 114,  32,  57, 
-     46,  51,  48,  46,  57,  50, 
-     48,  48,  46,  50,  48,  52, 
-     57,  57,   0, 171,  73,  83, 
+     46,  50,  57,  46,  57,  53, 
+     50,  46,  51,  49,  49,  49, 
+      0, 171, 171, 171,  73,  83, 
      71,  78,  44,   0,   0,   0, 
       1,   0,   0,   0,   8,   0, 
       0,   0,  32,   0,   0,   0, 
       0,   0,   0,   0,   0,   0, 
       0,   0,   3,   0,   0,   0, 
       0,   0,   0,   0,   3,   3, 
       0,   0,  80,  79,  83,  73, 
      84,  73,  79,  78,   0, 171, 
@@ -388,20 +391,23 @@ const BYTE LayerQuadVS[] =
       0,   0,   3,  12,   0,   0, 
      83,  86,  95,  80, 111, 115, 
     105, 116, 105, 111, 110,   0, 
      84,  69,  88,  67,  79,  79, 
      82,  68,   0, 171, 171, 171
 };
 #if 0
 //
-// Generated by Microsoft (R) HLSL Shader Compiler 9.30.9200.20499
-//
-//
-///
+// Generated by Microsoft (R) HLSL Shader Compiler 9.29.952.3111
+//
+//
+//   fxc CompositorD3D11.fx -ESolidColorShader -Tps_4_0_level_9_3 -nologo
+//    -FhtmpShaderHeader -VnSolidColorShader
+//
+//
 // Buffer Definitions: 
 //
 // cbuffer $Globals
 // {
 //
 //   float4 fLayerColor;                // Offset:    0 Size:    16
 //   float fLayerOpacity;               // Offset:   16 Size:     4 [unused]
 //   float4x4 mLayerTransform;          // Offset:   32 Size:    64 [unused]
@@ -419,27 +425,27 @@ const BYTE LayerQuadVS[] =
 // Name                                 Type  Format         Dim Slot Elements
 // ------------------------------ ---------- ------- ----------- ---- --------
 // $Globals                          cbuffer      NA          NA    0        1
 //
 //
 //
 // Input signature:
 //
-// Name                 Index   Mask Register SysValue  Format   Used
-// -------------------- ----- ------ -------- -------- ------- ------
-// SV_Position              0   xyzw        0      POS   float       
-// TEXCOORD                 0   xy          1     NONE   float       
+// Name                 Index   Mask Register SysValue Format   Used
+// -------------------- ----- ------ -------- -------- ------ ------
+// SV_Position              0   xyzw        0      POS  float       
+// TEXCOORD                 0   xy          1     NONE  float       
 //
 //
 // Output signature:
 //
-// Name                 Index   Mask Register SysValue  Format   Used
-// -------------------- ----- ------ -------- -------- ------- ------
-// SV_Target                0   xyzw        0   TARGET   float   xyzw
+// Name                 Index   Mask Register SysValue Format   Used
+// -------------------- ----- ------ -------- -------- ------ ------
+// SV_Target                0   xyzw        0   TARGET  float   xyzw
 //
 //
 // Constant buffer to DX9 shader constant mappings:
 //
 // Target Reg Buffer  Start Reg # of Regs        Data Conversion
 // ---------- ------- --------- --------- ----------------------
 // c0         cb0             0         1  ( FLT, FLT, FLT, FLT)
 //
@@ -455,20 +461,20 @@ dcl_constantbuffer cb0[1], immediateInde
 dcl_output o0.xyzw
 mov o0.xyzw, cb0[0].xyzw
 ret 
 // Approximately 2 instruction slots used
 #endif
 
 const BYTE SolidColorShader[] =
 {
-     68,  88,  66,  67,  72,   6, 
-     38,  99, 159, 102, 163,  50, 
-    226,  48,  39, 199,  28, 105, 
-    245, 167,   1,   0,   0,   0, 
+     68,  88,  66,  67, 204,   8, 
+      5, 100,  51,  20, 107, 176, 
+    111, 165, 149, 245, 134, 187, 
+     83,  96,   1,   0,   0,   0, 
     224,   3,   0,   0,   6,   0, 
       0,   0,  56,   0,   0,   0, 
     132,   0,   0,   0, 204,   0, 
       0,   0,  72,   1,   0,   0, 
      84,   3,   0,   0, 172,   3, 
       0,   0,  65, 111, 110,  57, 
      68,   0,   0,   0,  68,   0, 
       0,   0,   0,   2, 255, 255, 
@@ -503,17 +509,17 @@ const BYTE SolidColorShader[] =
       1,   0,   0,   0,   0,   0, 
       0,   0,   0,   0,   0,   0, 
       0,   0,   0,   0,   0,   0, 
       0,   0,   0,   0,   0,   0, 
       0,   0,   0,   0,   0,   0, 
       0,   0,   0,   0,   0,   0, 
       0,   0,   0,   0,   0,   0, 
       0,   0,   0,   0,   0,   0, 
-      2,   0,   0,   0,   0,   0, 
+      1,   0,   0,   0,   0,   0, 
       0,   0,   0,   0,   0,   0, 
       0,   0,   0,   0,   0,   0, 
       0,   0,   0,   0,   0,   0, 
       0,   0,   0,   0,   0,   0, 
       0,   0,   0,   0,   0,   0, 
       0,   0,   0,   0,  82,  68, 
      69,  70,   4,   2,   0,   0, 
       1,   0,   0,   0,  72,   0, 
@@ -594,19 +600,19 @@ const BYTE SolidColorShader[] =
      81, 117,  97, 100,   0, 118, 
      77,  97, 115, 107,  81, 117, 
      97, 100,   0,  77, 105,  99, 
     114, 111, 115, 111, 102, 116, 
      32,  40,  82,  41,  32,  72, 
      76,  83,  76,  32,  83, 104, 
      97, 100, 101, 114,  32,  67, 
     111, 109, 112, 105, 108, 101, 
-    114,  32,  57,  46,  51,  48, 
-     46,  57,  50,  48,  48,  46, 
-     50,  48,  52,  57,  57,   0, 
+    114,  32,  57,  46,  50,  57, 
+     46,  57,  53,  50,  46,  51, 
+     49,  49,  49,   0, 171, 171, 
      73,  83,  71,  78,  80,   0, 
       0,   0,   2,   0,   0,   0, 
       8,   0,   0,   0,  56,   0, 
       0,   0,   0,   0,   0,   0, 
       1,   0,   0,   0,   3,   0, 
       0,   0,   0,   0,   0,   0, 
      15,   0,   0,   0,  68,   0, 
       0,   0,   0,   0,   0,   0, 
@@ -624,20 +630,23 @@ const BYTE SolidColorShader[] =
       0,   0,   3,   0,   0,   0, 
       0,   0,   0,   0,  15,   0, 
       0,   0,  83,  86,  95,  84, 
      97, 114, 103, 101, 116,   0, 
     171, 171
 };
 #if 0
 //
-// Generated by Microsoft (R) HLSL Shader Compiler 9.30.9200.20499
-//
-//
-///
+// Generated by Microsoft (R) HLSL Shader Compiler 9.29.952.3111
+//
+//
+//   fxc CompositorD3D11.fx -ERGBShader -Tps_4_0_level_9_3 -nologo
+//    -FhtmpShaderHeader -VnRGBShader
+//
+//
 // Buffer Definitions: 
 //
 // cbuffer $Globals
 // {
 //
 //   float4 fLayerColor;                // Offset:    0 Size:    16 [unused]
 //   float fLayerOpacity;               // Offset:   16 Size:     4
 //   float4x4 mLayerTransform;          // Offset:   32 Size:    64 [unused]
@@ -657,27 +666,27 @@ const BYTE SolidColorShader[] =
 // sSampler                          sampler      NA          NA    0        1
 // tRGB                              texture  float4          2d    0        1
 // $Globals                          cbuffer      NA          NA    0        1
 //
 //
 //
 // Input signature:
 //
-// Name                 Index   Mask Register SysValue  Format   Used
-// -------------------- ----- ------ -------- -------- ------- ------
-// SV_Position              0   xyzw        0      POS   float       
-// TEXCOORD                 0   xy          1     NONE   float   xy  
+// Name                 Index   Mask Register SysValue Format   Used
+// -------------------- ----- ------ -------- -------- ------ ------
+// SV_Position              0   xyzw        0      POS  float       
+// TEXCOORD                 0   xy          1     NONE  float   xy  
 //
 //
 // Output signature:
 //
-// Name                 Index   Mask Register SysValue  Format   Used
-// -------------------- ----- ------ -------- -------- ------- ------
-// SV_Target                0   xyzw        0   TARGET   float   xyzw
+// Name                 Index   Mask Register SysValue Format   Used
+// -------------------- ----- ------ -------- -------- ------ ------
+// SV_Target                0   xyzw        0   TARGET  float   xyzw
 //
 //
 // Constant buffer to DX9 shader constant mappings:
 //
 // Target Reg Buffer  Start Reg # of Regs        Data Conversion
 // ---------- ------- --------- --------- ----------------------
 // c0         cb0             1         1  ( FLT, FLT, FLT, FLT)
 //
@@ -711,20 +720,20 @@ sample r0.xyzw, v1.xyxx, t0.xyzw, s0
 mul o0.xyz, r0.xyzx, cb0[1].xxxx
 mov o0.w, cb0[1].x
 ret 
 // Approximately 4 instruction slots used
 #endif
 
 const BYTE RGBShader[] =
 {
-     68,  88,  66,  67,  48,  11, 
-     71, 110, 243, 129,  70,  47, 
-      7,  98, 199, 203, 128,  84, 
-    163,  90,   1,   0,   0,   0, 
+     68,  88,  66,  67,  20, 109, 
+    176, 198,  26, 112, 108, 185, 
+    246, 240, 143,  18,  57, 236, 
+    126,  68,   1,   0,   0,   0, 
     232,   4,   0,   0,   6,   0, 
       0,   0,  56,   0,   0,   0, 
     204,   0,   0,   0, 136,   1, 
       0,   0,   4,   2,   0,   0, 
      92,   4,   0,   0, 180,   4, 
       0,   0,  65, 111, 110,  57, 
     140,   0,   0,   0, 140,   0, 
       0,   0,   0,   2, 255, 255, 
@@ -790,308 +799,16 @@ const BYTE RGBShader[] =
       0,   0,   1,   0,   0,   0, 
       0,   0,   0,   0,   0,   0, 
       0,   0,   0,   0,   0,   0, 
       0,   0,   0,   0,   0,   0, 
       0,   0,   0,   0,   0,   0, 
       1,   0,   0,   0,   0,   0, 
       0,   0,   0,   0,   0,   0, 
       0,   0,   0,   0,   0,   0, 
-      0,   0,   2,   0,   0,   0, 
-      0,   0,   0,   0,   0,   0, 
-      0,   0,   0,   0,   0,   0, 
-      0,   0,   0,   0,   0,   0, 
-      0,   0,   0,   0,   0,   0, 
-      0,   0,   0,   0,   0,   0, 
-      0,   0,   0,   0,   0,   0, 
-     82,  68,  69,  70,  80,   2, 
-      0,   0,   1,   0,   0,   0, 
-    148,   0,   0,   0,   3,   0, 
-      0,   0,  28,   0,   0,   0, 
-      0,   4, 255, 255,   0,   1, 
-      0,   0,  29,   2,   0,   0, 
-    124,   0,   0,   0,   3,   0, 
-      0,   0,   0,   0,   0,   0, 
-      0,   0,   0,   0,   0,   0, 
-      0,   0,   0,   0,   0,   0, 
-      1,   0,   0,   0,   1,   0, 
-      0,   0, 133,   0,   0,   0, 
-      2,   0,   0,   0,   5,   0, 
-      0,   0,   4,   0,   0,   0, 
-    255, 255, 255, 255,   0,   0, 
-      0,   0,   1,   0,   0,   0, 
-     12,   0,   0,   0, 138,   0, 
-      0,   0,   0,   0,   0,   0, 
-      0,   0,   0,   0,   0,   0, 
-      0,   0,   0,   0,   0,   0, 
-      0,   0,   0,   0,   1,   0, 
-      0,   0,   0,   0,   0,   0, 
-    115,  83,  97, 109, 112, 108, 
-    101, 114,   0, 116,  82,  71, 
-     66,   0,  36,  71, 108, 111, 
-     98,  97, 108, 115,   0, 171, 
-    138,   0,   0,   0,   8,   0, 
-      0,   0, 172,   0,   0,   0, 
-    224,   0,   0,   0,   0,   0, 
-      0,   0,   0,   0,   0,   0, 
-    108,   1,   0,   0,   0,   0, 
-      0,   0,  16,   0,   0,   0, 
-      0,   0,   0,   0, 120,   1, 
-      0,   0,   0,   0,   0,   0, 
-    136,   1,   0,   0,  16,   0, 
-      0,   0,   4,   0,   0,   0, 
-      2,   0,   0,   0, 152,   1, 
-      0,   0,   0,   0,   0,   0, 
-    168,   1,   0,   0,  32,   0, 
-      0,   0,  64,   0,   0,   0, 
-      0,   0,   0,   0, 184,   1, 
-      0,   0,   0,   0,   0,   0, 
-    200,   1,   0,   0,  96,   0, 
-      0,   0,  64,   0,   0,   0, 
-      0,   0,   0,   0, 184,   1, 
-      0,   0,   0,   0,   0,   0, 
-    212,   1,   0,   0, 160,   0, 
-      0,   0,  16,   0,   0,   0, 
-      0,   0,   0,   0, 120,   1, 
-      0,   0,   0,   0,   0,   0, 
-    232,   1,   0,   0, 176,   0, 
-      0,   0,  16,   0,   0,   0, 
-      0,   0,   0,   0, 248,   1, 
-      0,   0,   0,   0,   0,   0, 
-      8,   2,   0,   0, 192,   0, 
-      0,   0,  16,   0,   0,   0, 
-      0,   0,   0,   0, 248,   1, 
-      0,   0,   0,   0,   0,   0, 
-     19,   2,   0,   0, 208,   0, 
-      0,   0,  16,   0,   0,   0, 
-      0,   0,   0,   0, 248,   1, 
-      0,   0,   0,   0,   0,   0, 
-    102,  76,  97, 121, 101, 114, 
-     67, 111, 108, 111, 114,   0, 
-      1,   0,   3,   0,   1,   0, 
-      4,   0,   0,   0,   0,   0, 
-      0,   0,   0,   0, 102,  76, 
-     97, 121, 101, 114,  79, 112, 
-     97,  99, 105, 116, 121,   0, 
-    171, 171,   0,   0,   3,   0, 
-      1,   0,   1,   0,   0,   0, 
-      0,   0,   0,   0,   0,   0, 
-    109,  76,  97, 121, 101, 114, 
-     84, 114,  97, 110, 115, 102, 
-    111, 114, 109,   0,   3,   0, 
-      3,   0,   4,   0,   4,   0, 
-      0,   0,   0,   0,   0,   0, 
-      0,   0, 109,  80, 114, 111, 
-    106, 101,  99, 116, 105, 111, 
-    110,   0, 118,  82, 101, 110, 
-    100, 101, 114,  84,  97, 114, 
-    103, 101, 116,  79, 102, 102, 
-    115, 101, 116,   0, 118,  84, 
-    101, 120, 116, 117, 114, 101, 
-     67, 111, 111, 114, 100, 115, 
-      0, 171,   1,   0,   3,   0, 
-      1,   0,   4,   0,   0,   0, 
-      0,   0,   0,   0,   0,   0, 
-    118,  76,  97, 121, 101, 114, 
-     81, 117,  97, 100,   0, 118, 
-     77,  97, 115, 107,  81, 117, 
-     97, 100,   0,  77, 105,  99, 
-    114, 111, 115, 111, 102, 116, 
-     32,  40,  82,  41,  32,  72, 
-     76,  83,  76,  32,  83, 104, 
-     97, 100, 101, 114,  32,  67, 
-    111, 109, 112, 105, 108, 101, 
-    114,  32,  57,  46,  51,  48, 
-     46,  57,  50,  48,  48,  46, 
-     50,  48,  52,  57,  57,   0, 
-     73,  83,  71,  78,  80,   0, 
-      0,   0,   2,   0,   0,   0, 
-      8,   0,   0,   0,  56,   0, 
-      0,   0,   0,   0,   0,   0, 
-      1,   0,   0,   0,   3,   0, 
-      0,   0,   0,   0,   0,   0, 
-     15,   0,   0,   0,  68,   0, 
-      0,   0,   0,   0,   0,   0, 
-      0,   0,   0,   0,   3,   0, 
-      0,   0,   1,   0,   0,   0, 
-      3,   3,   0,   0,  83,  86, 
-     95,  80, 111, 115, 105, 116, 
-    105, 111, 110,   0,  84,  69, 
-     88,  67,  79,  79,  82,  68, 
-      0, 171, 171, 171,  79,  83, 
-     71,  78,  44,   0,   0,   0, 
-      1,   0,   0,   0,   8,   0, 
-      0,   0,  32,   0,   0,   0, 
-      0,   0,   0,   0,   0,   0, 
-      0,   0,   3,   0,   0,   0, 
-      0,   0,   0,   0,  15,   0, 
-      0,   0,  83,  86,  95,  84, 
-     97, 114, 103, 101, 116,   0, 
-    171, 171
-};
-#if 0
-//
-// Generated by Microsoft (R) HLSL Shader Compiler 9.30.9200.20499
-//
-//
-///
-// Buffer Definitions: 
-//
-// cbuffer $Globals
-// {
-//
-//   float4 fLayerColor;                // Offset:    0 Size:    16 [unused]
-//   float fLayerOpacity;               // Offset:   16 Size:     4
-//   float4x4 mLayerTransform;          // Offset:   32 Size:    64 [unused]
-//   float4x4 mProjection;              // Offset:   96 Size:    64 [unused]
-//   float4 vRenderTargetOffset;        // Offset:  160 Size:    16 [unused]
-//   float4 vTextureCoords;             // Offset:  176 Size:    16 [unused]
-//   float4 vLayerQuad;                 // Offset:  192 Size:    16 [unused]
-//   float4 vMaskQuad;                  // Offset:  208 Size:    16 [unused]
-//
-// }
-//
-//
-// Resource Bindings:
-//
-// Name                                 Type  Format         Dim Slot Elements
-// ------------------------------ ---------- ------- ----------- ---- --------
-// sSampler                          sampler      NA          NA    0        1
-// tRGB                              texture  float4          2d    0        1
-// $Globals                          cbuffer      NA          NA    0        1
-//
-//
-//
-// Input signature:
-//
-// Name                 Index   Mask Register SysValue  Format   Used
-// -------------------- ----- ------ -------- -------- ------- ------
-// SV_Position              0   xyzw        0      POS   float       
-// TEXCOORD                 0   xy          1     NONE   float   xy  
-//
-//
-// Output signature:
-//
-// Name                 Index   Mask Register SysValue  Format   Used
-// -------------------- ----- ------ -------- -------- ------- ------
-// SV_Target                0   xyzw        0   TARGET   float   xyzw
-//
-//
-// Constant buffer to DX9 shader constant mappings:
-//
-// Target Reg Buffer  Start Reg # of Regs        Data Conversion
-// ---------- ------- --------- --------- ----------------------
-// c0         cb0             1         1  ( FLT, FLT, FLT, FLT)
-//
-//
-// Sampler/Resource to DX9 shader sampler mappings:
-//
-// Target Sampler Source Sampler  Source Resource
-// -------------- --------------- ----------------
-// s0             s0              t0               
-//
-//
-// Level9 shader bytecode:
-//
-    ps_2_x
-    dcl t0.xy
-    dcl_2d s0
-    texld r0, t0, s0
-    mul r0, r0, c0.x
-    mov oC0, r0
-
-// approximately 3 instruction slots used (1 texture, 2 arithmetic)
-ps_4_0
-dcl_constantbuffer cb0[2], immediateIndexed
-dcl_sampler s0, mode_default
-dcl_resource_texture2d (float,float,float,float) t0
-dcl_input_ps linear v1.xy
-dcl_output o0.xyzw
-dcl_temps 1
-sample r0.xyzw, v1.xyxx, t0.xyzw, s0
-mul o0.xyzw, r0.xyzw, cb0[1].xxxx
-ret 
-// Approximately 3 instruction slots used
-#endif
-
-const BYTE RGBAShader[] =
-{
-     68,  88,  66,  67, 128,  32, 
-     82,  55, 161,  84, 138, 165, 
-    193, 140,  13, 124, 203, 147, 
-    107, 158,   1,   0,   0,   0, 
-    196,   4,   0,   0,   6,   0, 
-      0,   0,  56,   0,   0,   0, 
-    192,   0,   0,   0, 100,   1, 
-      0,   0, 224,   1,   0,   0, 
-     56,   4,   0,   0, 144,   4, 
-      0,   0,  65, 111, 110,  57, 
-    128,   0,   0,   0, 128,   0, 
-      0,   0,   0,   2, 255, 255, 
-     76,   0,   0,   0,  52,   0, 
-      0,   0,   1,   0,  40,   0, 
-      0,   0,  52,   0,   0,   0, 
-     52,   0,   1,   0,  36,   0, 
-      0,   0,  52,   0,   0,   0, 
-      0,   0,   0,   0,   1,   0, 
-      1,   0,   0,   0,   0,   0, 
-      0,   0,   1,   2, 255, 255, 
-     31,   0,   0,   2,   0,   0, 
-      0, 128,   0,   0,   3, 176, 
-     31,   0,   0,   2,   0,   0, 
-      0, 144,   0,   8,  15, 160, 
-     66,   0,   0,   3,   0,   0, 
-     15, 128,   0,   0, 228, 176, 
-      0,   8, 228, 160,   5,   0, 
-      0,   3,   0,   0,  15, 128, 
-      0,   0, 228, 128,   0,   0, 
-      0, 160,   1,   0,   0,   2, 
-      0,   8,  15, 128,   0,   0, 
-    228, 128, 255, 255,   0,   0, 
-     83,  72,  68,  82, 156,   0, 
-      0,   0,  64,   0,   0,   0, 
-     39,   0,   0,   0,  89,   0, 
-      0,   4,  70, 142,  32,   0, 
-      0,   0,   0,   0,   2,   0, 
-      0,   0,  90,   0,   0,   3, 
-      0,  96,  16,   0,   0,   0, 
-      0,   0,  88,  24,   0,   4, 
-      0, 112,  16,   0,   0,   0, 
-      0,   0,  85,  85,   0,   0, 
-     98,  16,   0,   3,  50,  16, 
-     16,   0,   1,   0,   0,   0, 
-    101,   0,   0,   3, 242,  32, 
-     16,   0,   0,   0,   0,   0, 
-    104,   0,   0,   2,   1,   0, 
-      0,   0,  69,   0,   0,   9, 
-    242,   0,  16,   0,   0,   0, 
-      0,   0,  70,  16,  16,   0, 
-      1,   0,   0,   0,  70, 126, 
-     16,   0,   0,   0,   0,   0, 
-      0,  96,  16,   0,   0,   0, 
-      0,   0,  56,   0,   0,   8, 
-    242,  32,  16,   0,   0,   0, 
-      0,   0,  70,  14,  16,   0, 
-      0,   0,   0,   0,   6, 128, 
-     32,   0,   0,   0,   0,   0, 
-      1,   0,   0,   0,  62,   0, 
-      0,   1,  83,  84,  65,  84, 
-    116,   0,   0,   0,   3,   0, 
-      0,   0,   1,   0,   0,   0, 
-      0,   0,   0,   0,   2,   0, 
-      0,   0,   1,   0,   0,   0, 
-      0,   0,   0,   0,   0,   0, 
-      0,   0,   1,   0,   0,   0, 
-      0,   0,   0,   0,   0,   0, 
-      0,   0,   0,   0,   0,   0, 
-      0,   0,   0,   0,   0,   0, 
-      0,   0,   0,   0,   0,   0, 
-      1,   0,   0,   0,   0,   0, 
-      0,   0,   0,   0,   0,   0, 
-      0,   0,   0,   0,   0,   0, 
       0,   0,   1,   0,   0,   0, 
       0,   0,   0,   0,   0,   0, 
       0,   0,   0,   0,   0,   0, 
       0,   0,   0,   0,   0,   0, 
       0,   0,   0,   0,   0,   0, 
       0,   0,   0,   0,   0,   0, 
       0,   0,   0,   0,   0,   0, 
      82,  68,  69,  70,  80,   2, 
@@ -1186,19 +903,19 @@ const BYTE RGBAShader[] =
      81, 117,  97, 100,   0, 118, 
      77,  97, 115, 107,  81, 117, 
      97, 100,   0,  77, 105,  99, 
     114, 111, 115, 111, 102, 116, 
      32,  40,  82,  41,  32,  72, 
      76,  83,  76,  32,  83, 104, 
      97, 100, 101, 114,  32,  67, 
     111, 109, 112, 105, 108, 101, 
-    114,  32,  57,  46,  51,  48, 
-     46,  57,  50,  48,  48,  46, 
-     50,  48,  52,  57,  57,   0, 
+    114,  32,  57,  46,  50,  57, 
+     46,  57,  53,  50,  46,  51, 
+     49,  49,  49,   0, 171, 171, 
      73,  83,  71,  78,  80,   0, 
       0,   0,   2,   0,   0,   0, 
       8,   0,   0,   0,  56,   0, 
       0,   0,   0,   0,   0,   0, 
       1,   0,   0,   0,   3,   0, 
       0,   0,   0,   0,   0,   0, 
      15,   0,   0,   0,  68,   0, 
       0,   0,   0,   0,   0,   0, 
@@ -1216,20 +933,318 @@ const BYTE RGBAShader[] =
       0,   0,   3,   0,   0,   0, 
       0,   0,   0,   0,  15,   0, 
       0,   0,  83,  86,  95,  84, 
      97, 114, 103, 101, 116,   0, 
     171, 171
 };
 #if 0
 //
-// Generated by Microsoft (R) HLSL Shader Compiler 9.30.9200.20499
-//
-//
-///
+// Generated by Microsoft (R) HLSL Shader Compiler 9.29.952.3111
+//
+//
+//   fxc CompositorD3D11.fx -ERGBAShader -Tps_4_0_level_9_3 -nologo
+//    -FhtmpShaderHeader -VnRGBAShader
+//
+//
+// Buffer Definitions: 
+//
+// cbuffer $Globals
+// {
+//
+//   float4 fLayerColor;                // Offset:    0 Size:    16 [unused]
+//   float fLayerOpacity;               // Offset:   16 Size:     4
+//   float4x4 mLayerTransform;          // Offset:   32 Size:    64 [unused]
+//   float4x4 mProjection;              // Offset:   96 Size:    64 [unused]
+//   float4 vRenderTargetOffset;        // Offset:  160 Size:    16 [unused]
+//   float4 vTextureCoords;             // Offset:  176 Size:    16 [unused]
+//   float4 vLayerQuad;                 // Offset:  192 Size:    16 [unused]
+//   float4 vMaskQuad;                  // Offset:  208 Size:    16 [unused]
+//
+// }
+//
+//
+// Resource Bindings:
+//
+// Name                                 Type  Format         Dim Slot Elements
+// ------------------------------ ---------- ------- ----------- ---- --------
+// sSampler                          sampler      NA          NA    0        1
+// tRGB                              texture  float4          2d    0        1
+// $Globals                          cbuffer      NA          NA    0        1
+//
+//
+//
+// Input signature:
+//
+// Name                 Index   Mask Register SysValue Format   Used
+// -------------------- ----- ------ -------- -------- ------ ------
+// SV_Position              0   xyzw        0      POS  float       
+// TEXCOORD                 0   xy          1     NONE  float   xy  
+//
+//
+// Output signature:
+//
+// Name                 Index   Mask Register SysValue Format   Used
+// -------------------- ----- ------ -------- -------- ------ ------
+// SV_Target                0   xyzw        0   TARGET  float   xyzw
+//
+//
+// Constant buffer to DX9 shader constant mappings:
+//
+// Target Reg Buffer  Start Reg # of Regs        Data Conversion
+// ---------- ------- --------- --------- ----------------------
+// c0         cb0             1         1  ( FLT, FLT, FLT, FLT)
+//
+//
+// Sampler/Resource to DX9 shader sampler mappings:
+//
+// Target Sampler Source Sampler  Source Resource
+// -------------- --------------- ----------------
+// s0             s0              t0               
+//
+//
+// Level9 shader bytecode:
+//
+    ps_2_x
+    dcl t0.xy
+    dcl_2d s0
+    texld r0, t0, s0
+    mul r0, r0, c0.x
+    mov oC0, r0
+
+// approximately 3 instruction slots used (1 texture, 2 arithmetic)
+ps_4_0
+dcl_constantbuffer cb0[2], immediateIndexed
+dcl_sampler s0, mode_default
+dcl_resource_texture2d (float,float,float,float) t0
+dcl_input_ps linear v1.xy
+dcl_output o0.xyzw
+dcl_temps 1
+sample r0.xyzw, v1.xyxx, t0.xyzw, s0
+mul o0.xyzw, r0.xyzw, cb0[1].xxxx
+ret 
+// Approximately 3 instruction slots used
+#endif
+
+const BYTE RGBAShader[] =
+{
+     68,  88,  66,  67, 214,  26, 
+    168, 112,  65, 151,  75,  99, 
+    196,  63, 136, 104, 158, 202, 
+    217,   7,   1,   0,   0,   0, 
+    196,   4,   0,   0,   6,   0, 
+      0,   0,  56,   0,   0,   0, 
+    192,   0,   0,   0, 100,   1, 
+      0,   0, 224,   1,   0,   0, 
+     56,   4,   0,   0, 144,   4, 
+      0,   0,  65, 111, 110,  57, 
+    128,   0,   0,   0, 128,   0, 
+      0,   0,   0,   2, 255, 255, 
+     76,   0,   0,   0,  52,   0, 
+      0,   0,   1,   0,  40,   0, 
+      0,   0,  52,   0,   0,   0, 
+     52,   0,   1,   0,  36,   0, 
+      0,   0,  52,   0,   0,   0, 
+      0,   0,   0,   0,   1,   0, 
+      1,   0,   0,   0,   0,   0, 
+      0,   0,   1,   2, 255, 255, 
+     31,   0,   0,   2,   0,   0, 
+      0, 128,   0,   0,   3, 176, 
+     31,   0,   0,   2,   0,   0, 
+      0, 144,   0,   8,  15, 160, 
+     66,   0,   0,   3,   0,   0, 
+     15, 128,   0,   0, 228, 176, 
+      0,   8, 228, 160,   5,   0, 
+      0,   3,   0,   0,  15, 128, 
+      0,   0, 228, 128,   0,   0, 
+      0, 160,   1,   0,   0,   2, 
+      0,   8,  15, 128,   0,   0, 
+    228, 128, 255, 255,   0,   0, 
+     83,  72,  68,  82, 156,   0, 
+      0,   0,  64,   0,   0,   0, 
+     39,   0,   0,   0,  89,   0, 
+      0,   4,  70, 142,  32,   0, 
+      0,   0,   0,   0,   2,   0, 
+      0,   0,  90,   0,   0,   3, 
+      0,  96,  16,   0,   0,   0, 
+      0,   0,  88,  24,   0,   4, 
+      0, 112,  16,   0,   0,   0, 
+      0,   0,  85,  85,   0,   0, 
+     98,  16,   0,   3,  50,  16, 
+     16,   0,   1,   0,   0,   0, 
+    101,   0,   0,   3, 242,  32, 
+     16,   0,   0,   0,   0,   0, 
+    104,   0,   0,   2,   1,   0, 
+      0,   0,  69,   0,   0,   9, 
+    242,   0,  16,   0,   0,   0, 
+      0,   0,  70,  16,  16,   0, 
+      1,   0,   0,   0,  70, 126, 
+     16,   0,   0,   0,   0,   0, 
+      0,  96,  16,   0,   0,   0, 
+      0,   0,  56,   0,   0,   8, 
+    242,  32,  16,   0,   0,   0, 
+      0,   0,  70,  14,  16,   0, 
+      0,   0,   0,   0,   6, 128, 
+     32,   0,   0,   0,   0,   0, 
+      1,   0,   0,   0,  62,   0, 
+      0,   1,  83,  84,  65,  84, 
+    116,   0,   0,   0,   3,   0, 
+      0,   0,   1,   0,   0,   0, 
+      0,   0,   0,   0,   2,   0, 
+      0,   0,   1,   0,   0,   0, 
+      0,   0,   0,   0,   0,   0, 
+      0,   0,   1,   0,   0,   0, 
+      0,   0,   0,   0,   0,   0, 
+      0,   0,   0,   0,   0,   0, 
+      0,   0,   0,   0,   0,   0, 
+      0,   0,   0,   0,   0,   0, 
+      1,   0,   0,   0,   0,   0, 
+      0,   0,   0,   0,   0,   0, 
+      0,   0,   0,   0,   0,   0, 
+      0,   0,   0,   0,   0,   0, 
+      0,   0,   0,   0,   0,   0, 
+      0,   0,   0,   0,   0,   0, 
+      0,   0,   0,   0,   0,   0, 
+      0,   0,   0,   0,   0,   0, 
+      0,   0,   0,   0,   0,   0, 
+      0,   0,   0,   0,   0,   0, 
+     82,  68,  69,  70,  80,   2, 
+      0,   0,   1,   0,   0,   0, 
+    148,   0,   0,   0,   3,   0, 
+      0,   0,  28,   0,   0,   0, 
+      0,   4, 255, 255,   0,   1, 
+      0,   0,  29,   2,   0,   0, 
+    124,   0,   0,   0,   3,   0, 
+      0,   0,   0,   0,   0,   0, 
+      0,   0,   0,   0,   0,   0, 
+      0,   0,   0,   0,   0,   0, 
+      1,   0,   0,   0,   1,   0, 
+      0,   0, 133,   0,   0,   0, 
+      2,   0,   0,   0,   5,   0, 
+      0,   0,   4,   0,   0,   0, 
+    255, 255, 255, 255,   0,   0, 
+      0,   0,   1,   0,   0,   0, 
+     12,   0,   0,   0, 138,   0, 
+      0,   0,   0,   0,   0,   0, 
+      0,   0,   0,   0,   0,   0, 
+      0,   0,   0,   0,   0,   0, 
+      0,   0,   0,   0,   1,   0, 
+      0,   0,   0,   0,   0,   0, 
+    115,  83,  97, 109, 112, 108, 
+    101, 114,   0, 116,  82,  71, 
+     66,   0,  36,  71, 108, 111, 
+     98,  97, 108, 115,   0, 171, 
+    138,   0,   0,   0,   8,   0, 
+      0,   0, 172,   0,   0,   0, 
+    224,   0,   0,   0,   0,   0, 
+      0,   0,   0,   0,   0,   0, 
+    108,   1,   0,   0,   0,   0, 
+      0,   0,  16,   0,   0,   0, 
+      0,   0,   0,   0, 120,   1, 
+      0,   0,   0,   0,   0,   0, 
+    136,   1,   0,   0,  16,   0, 
+      0,   0,   4,   0,   0,   0, 
+      2,   0,   0,   0, 152,   1, 
+      0,   0,   0,   0,   0,   0, 
+    168,   1,   0,   0,  32,   0, 
+      0,   0,  64,   0,   0,   0, 
+      0,   0,   0,   0, 184,   1, 
+      0,   0,   0,   0,   0,   0, 
+    200,   1,   0,   0,  96,   0, 
+      0,   0,  64,   0,   0,   0, 
+      0,   0,   0,   0, 184,   1, 
+      0,   0,   0,   0,   0,   0, 
+    212,   1,   0,   0, 160,   0, 
+      0,   0,  16,   0,   0,   0, 
+      0,   0,   0,   0, 120,   1, 
+      0,   0,   0,   0,   0,   0, 
+    232,   1,   0,   0, 176,   0, 
+      0,   0,  16,   0,   0,   0, 
+      0,   0,   0,   0, 248,   1, 
+      0,   0,   0,   0,   0,   0, 
+      8,   2,   0,   0, 192,   0, 
+      0,   0,  16,   0,   0,   0, 
+      0,   0,   0,   0, 248,   1, 
+      0,   0,   0,   0,   0,   0, 
+     19,   2,   0,   0, 208,   0, 
+      0,   0,  16,   0,   0,   0, 
+      0,   0,   0,   0, 248,   1, 
+      0,   0,   0,   0,   0,   0, 
+    102,  76,  97, 121, 101, 114, 
+     67, 111, 108, 111, 114,   0, 
+      1,   0,   3,   0,   1,   0, 
+      4,   0,   0,   0,   0,   0, 
+      0,   0,   0,   0, 102,  76, 
+     97, 121, 101, 114,  79, 112, 
+     97,  99, 105, 116, 121,   0, 
+    171, 171,   0,   0,   3,   0, 
+      1,   0,   1,   0,   0,   0, 
+      0,   0,   0,   0,   0,   0, 
+    109,  76,  97, 121, 101, 114, 
+     84, 114,  97, 110, 115, 102, 
+    111, 114, 109,   0,   3,   0, 
+      3,   0,   4,   0,   4,   0, 
+      0,   0,   0,   0,   0,   0, 
+      0,   0, 109,  80, 114, 111, 
+    106, 101,  99, 116, 105, 111, 
+    110,   0, 118,  82, 101, 110, 
+    100, 101, 114,  84,  97, 114, 
+    103, 101, 116,  79, 102, 102, 
+    115, 101, 116,   0, 118,  84, 
+    101, 120, 116, 117, 114, 101, 
+     67, 111, 111, 114, 100, 115, 
+      0, 171,   1,   0,   3,   0, 
+      1,   0,   4,   0,   0,   0, 
+      0,   0,   0,   0,   0,   0, 
+    118,  76,  97, 121, 101, 114, 
+     81, 117,  97, 100,   0, 118, 
+     77,  97, 115, 107,  81, 117, 
+     97, 100,   0,  77, 105,  99, 
+    114, 111, 115, 111, 102, 116, 
+     32,  40,  82,  41,  32,  72, 
+     76,  83,  76,  32,  83, 104, 
+     97, 100, 101, 114,  32,  67, 
+    111, 109, 112, 105, 108, 101, 
+    114,  32,  57,  46,  50,  57, 
+     46,  57,  53,  50,  46,  51, 
+     49,  49,  49,   0, 171, 171, 
+     73,  83,  71,  78,  80,   0, 
+      0,   0,   2,   0,   0,   0, 
+      8,   0,   0,   0,  56,   0, 
+      0,   0,   0,   0,   0,   0, 
+      1,   0,   0,   0,   3,   0, 
+      0,   0,   0,   0,   0,   0, 
+     15,   0,   0,   0,  68,   0, 
+      0,   0,   0,   0,   0,   0, 
+      0,   0,   0,   0,   3,   0, 
+      0,   0,   1,   0,   0,   0, 
+      3,   3,   0,   0,  83,  86, 
+     95,  80, 111, 115, 105, 116, 
+    105, 111, 110,   0,  84,  69, 
+     88,  67,  79,  79,  82,  68, 
+      0, 171, 171, 171,  79,  83, 
+     71,  78,  44,   0,   0,   0, 
+      1,   0,   0,   0,   8,   0, 
+      0,   0,  32,   0,   0,   0, 
+      0,   0,   0,   0,   0,   0, 
+      0,   0,   3,   0,   0,   0, 
+      0,   0,   0,   0,  15,   0, 
+      0,   0,  83,  86,  95,  84, 
+     97, 114, 103, 101, 116,   0, 
+    171, 171
+};
+#if 0
+//
+// Generated by Microsoft (R) HLSL Shader Compiler 9.29.952.3111
+//
+//
+//   fxc CompositorD3D11.fx -EComponentAlphaShader -Tps_4_0_level_9_3 -nologo
+//    -FhtmpShaderHeader -VnComponentAlphaShader
+//
+//
 // Buffer Definitions: 
 //
 // cbuffer $Globals
 // {
 //
 //   float4 fLayerColor;                // Offset:    0 Size:    16 [unused]
 //   float fLayerOpacity;               // Offset:   16 Size:     4
 //   float4x4 mLayerTransform;          // Offset:   32 Size:    64 [unused]
@@ -1250,28 +1265,28 @@ const BYTE RGBAShader[] =
 // tRGB                              texture  float4          2d    0        1
 // tRGBWhite                         texture  float4          2d    1        1
 // $Globals                          cbuffer      NA          NA    0        1
 //
 //
 //
 // Input signature:
 //
-// Name                 Index   Mask Register SysValue  Format   Used
-// -------------------- ----- ------ -------- -------- ------- ------
-// SV_Position              0   xyzw        0      POS   float       
-// TEXCOORD                 0   xy          1     NONE   float   xy  
+// Name                 Index   Mask Register SysValue Format   Used
+// -------------------- ----- ------ -------- -------- ------ ------
+// SV_Position              0   xyzw        0      POS  float       
+// TEXCOORD                 0   xy          1     NONE  float   xy  
 //
 //
 // Output signature:
 //
-// Name                 Index   Mask Register SysValue  Format   Used
-// -------------------- ----- ------ -------- -------- ------- ------
-// SV_Target                0   xyzw        0   TARGET   float   xyzw
-// SV_Target                1   xyzw        1   TARGET   float   xyzw
+// Name                 Index   Mask Register SysValue Format   Used
+// -------------------- ----- ------ -------- -------- ------ ------
+// SV_Target                0   xyzw        0   TARGET  float   xyzw
+// SV_Target                1   xyzw        1   TARGET  float   xyzw
 //
 //
 // Constant buffer to DX9 shader constant mappings:
 //
 // Target Reg Buffer  Start Reg # of Regs        Data Conversion
 // ---------- ------- --------- --------- ----------------------
 // c0         cb0             1         1  ( FLT, FLT, FLT, FLT)
 //
@@ -1319,20 +1334,20 @@ mov r1.w, r0.y
 mul o1.xyzw, r0.xyzw, cb0[1].xxxx
 mul o0.xyzw, r1.xyzw, cb0[1].xxxx
 ret 
 // Approximately 8 instruction slots used
 #endif
 
 const BYTE ComponentAlphaShader[] =
 {
-     68,  88,  66,  67, 190, 185, 
-     77,  23, 211, 233,   5, 234, 
-     37, 188,  49, 201, 108, 250, 
-    125, 123,   1,   0,   0,   0, 
+     68,  88,  66,  67, 207, 238, 
+    180, 151, 111,  52, 137,   3, 
+     45, 243, 229, 223,  99, 172, 
+     89,   3,   1,   0,   0,   0, 
      68,   6,   0,   0,   6,   0, 
       0,   0,  56,   0,   0,   0, 
      64,   1,   0,   0, 160,   2, 
       0,   0,  28,   3,   0,   0, 
     160,   5,   0,   0, 248,   5, 
       0,   0,  65, 111, 110,  57, 
       0,   1,   0,   0,   0,   1, 
       0,   0,   0,   2, 255, 255, 
@@ -1445,17 +1460,17 @@ const BYTE ComponentAlphaShader[] =
       1,   0,   0,   0,   0,   0, 
       0,   0,   0,   0,   0,   0, 
       0,   0,   0,   0,   0,   0, 
       0,   0,   0,   0,   0,   0, 
       0,   0,   0,   0,   2,   0, 
       0,   0,   0,   0,   0,   0, 
       0,   0,   0,   0,   0,   0, 
       0,   0,   0,   0,   0,   0, 
-      3,   0,   0,   0,   0,   0, 
+      2,   0,   0,   0,   0,   0, 
       0,   0,   0,   0,   0,   0, 
       0,   0,   0,   0,   0,   0, 
       0,   0,   0,   0,   0,   0, 
       0,   0,   0,   0,   0,   0, 
       0,   0,   0,   0,   0,   0, 
       0,   0,   0,   0,  82,  68, 
      69,  70, 124,   2,   0,   0, 
       1,   0,   0,   0, 192,   0, 
@@ -1556,19 +1571,19 @@ const BYTE ComponentAlphaShader[] =
      81, 117,  97, 100,   0, 118, 
      77,  97, 115, 107,  81, 117, 
      97, 100,   0,  77, 105,  99, 
     114, 111, 115, 111, 102, 116, 
      32,  40,  82,  41,  32,  72, 
      76,  83,  76,  32,  83, 104, 
      97, 100, 101, 114,  32,  67, 
     111, 109, 112, 105, 108, 101, 
-    114,  32,  57,  46,  51,  48, 
-     46,  57,  50,  48,  48,  46, 
-     50,  48,  52,  57,  57,   0, 
+    114,  32,  57,  46,  50,  57, 
+     46,  57,  53,  50,  46,  51, 
+     49,  49,  49,   0, 171, 171, 
      73,  83,  71,  78,  80,   0, 
       0,   0,   2,   0,   0,   0, 
       8,   0,   0,   0,  56,   0, 
       0,   0,   0,   0,   0,   0, 
       1,   0,   0,   0,   3,   0, 
       0,   0,   0,   0,   0,   0, 
      15,   0,   0,   0,  68,   0, 
       0,   0,   0,   0,   0,   0, 
@@ -1590,20 +1605,23 @@ const BYTE ComponentAlphaShader[] =
       0,   0,   3,   0,   0,   0, 
       1,   0,   0,   0,  15,   0, 
       0,   0,  83,  86,  95,  84, 
      97, 114, 103, 101, 116,   0, 
     171, 171
 };
 #if 0
 //
-// Generated by Microsoft (R) HLSL Shader Compiler 9.30.9200.20499
-//
-//
-///
+// Generated by Microsoft (R) HLSL Shader Compiler 9.29.952.3111
+//
+//
+//   fxc CompositorD3D11.fx -EYCbCrShader -Tps_4_0_level_9_3 -nologo
+//    -FhtmpShaderHeader -VnYCbCrShader
+//
+//
 // Buffer Definitions: 
 //
 // cbuffer $Globals
 // {
 //
 //   float4 fLayerColor;                // Offset:    0 Size:    16 [unused]
 //   float fLayerOpacity;               // Offset:   16 Size:     4
 //   float4x4 mLayerTransform;          // Offset:   32 Size:    64 [unused]
@@ -1625,27 +1643,27 @@ const BYTE ComponentAlphaShader[] =
 // tCb                               texture  float4          2d    1        1
 // tCr                               texture  float4          2d    2        1
 // $Globals                          cbuffer      NA          NA    0        1
 //
 //
 //
 // Input signature:
 //
-// Name                 Index   Mask Register SysValue  Format   Used
-// -------------------- ----- ------ -------- -------- ------- ------
-// SV_Position              0   xyzw        0      POS   float       
-// TEXCOORD                 0   xy          1     NONE   float   xy  
+// Name                 Index   Mask Register SysValue Format   Used
+// -------------------- ----- ------ -------- -------- ------ ------
+// SV_Position              0   xyzw        0      POS  float       
+// TEXCOORD                 0   xy          1     NONE  float   xy  
 //
 //
 // Output signature:
 //
-// Name                 Index   Mask Register SysValue  Format   Used
-// -------------------- ----- ------ -------- -------- ------- ------
-// SV_Target                0   xyzw        0   TARGET   float   xyzw
+// Name                 Index   Mask Register SysValue Format   Used
+// -------------------- ----- ------ -------- -------- ------ ------
+// SV_Target                0   xyzw        0   TARGET  float   xyzw
 //
 //
 // Constant buffer to DX9 shader constant mappings:
 //
 // Target Reg Buffer  Start Reg # of Regs        Data Conversion
 // ---------- ------- --------- --------- ----------------------
 // c0         cb0             1         1  ( FLT, FLT, FLT, FLT)
 //
@@ -1665,64 +1683,64 @@ const BYTE ComponentAlphaShader[] =
     def c1, -0.5, -0.0625, 1.59599996, 0.813000023
     def c2, 1.16400003, 2.01799989, 0.391000003, 1
     dcl t0.xy
     dcl_2d s0
     dcl_2d s1
     dcl_2d s2
     texld r0, t0, s0
     texld r1, t0, s2
-    add r0.y, r1.x, c1.x
-    mul r0.yz, r0.y, c1.xzww
-    add r0.x, r0.x, c1.y
-    mad r0.z, r0.x, c2.x, -r0.z
-    mad r1.x, r0.x, c2.x, r0.y
+    add r0.x, r1.w, c1.x
+    mul r0.xy, r0.x, c1.zwzw
+    add r0.z, r0.w, c1.y
+    mad r0.y, r0.z, c2.x, -r0.y
+    mad r1.x, r0.z, c2.x, r0.x
     texld r2, t0, s1
-    add r0.y, r2.x, c1.x
-    mad r1.y, r0.y, -c2.z, r0.z
-    mul r0.y, r0.y, c2.y
-    mad r1.z, r0.x, c2.x, r0.y
+    add r0.x, r2.w, c1.x
+    mad r1.y, r0.x, -c2.z, r0.y
+    mul r0.x, r0.x, c2.y
+    mad r1.z, r0.z, c2.x, r0.x
     mov r1.w, c2.w
     mul r0, r1, c0.x
     mov oC0, r0
 
 // approximately 15 instruction slots used (3 texture, 12 arithmetic)
 ps_4_0
 dcl_constantbuffer cb0[2], immediateIndexed
 dcl_sampler s0, mode_default
 dcl_resource_texture2d (float,float,float,float) t0
 dcl_resource_texture2d (float,float,float,float) t1
 dcl_resource_texture2d (float,float,float,float) t2
 dcl_input_ps linear v1.xy
 dcl_output o0.xyzw
 dcl_temps 3
 sample r0.xyzw, v1.xyxx, t2.xyzw, s0
-add r0.x, r0.x, l(-0.500000)
+add r0.x, r0.w, l(-0.500000)
 mul r0.xy, r0.xxxx, l(1.596000, 0.813000, 0.000000, 0.000000)
 sample r1.xyzw, v1.xyxx, t0.xyzw, s0
-add r0.z, r1.x, l(-0.062500)
+add r0.z, r1.w, l(-0.062500)
 mad r0.y, r0.z, l(1.164000), -r0.y
 mad r1.x, r0.z, l(1.164000), r0.x
 sample r2.xyzw, v1.xyxx, t1.xyzw, s0
-add r0.x, r2.x, l(-0.500000)
+add r0.x, r2.w, l(-0.500000)
 mad r1.y, -r0.x, l(0.391000), r0.y
 mul r0.x, r0.x, l(2.018000)
 mad r1.z, r0.z, l(1.164000), r0.x
 mov r1.w, l(1.000000)
 mul o0.xyzw, r1.xyzw, cb0[1].xxxx
 ret 
 // Approximately 15 instruction slots used
 #endif
 
 const BYTE YCbCrShader[] =
 {
-     68,  88,  66,  67,  91, 247, 
-     39, 217, 176, 190,  84, 226, 
-     80, 249,  99, 249, 169, 218, 
-     66, 246,   1,   0,   0,   0, 
+     68,  88,  66,  67, 235,  16, 
+    121, 249, 238, 190, 171,  40, 
+    106,   5,  31,  27, 153,  48, 
+    114,  96,   1,   0,   0,   0, 
     212,   7,   0,   0,   6,   0, 
       0,   0,  56,   0,   0,   0, 
     220,   1,   0,   0,  44,   4, 
       0,   0, 168,   4,   0,   0, 
      72,   7,   0,   0, 160,   7, 
       0,   0,  65, 111, 110,  57, 
     156,   1,   0,   0, 156,   1, 
       0,   0,   0,   2, 255, 255, 
@@ -1752,45 +1770,45 @@ const BYTE YCbCrShader[] =
      15, 160,  31,   0,   0,   2, 
       0,   0,   0, 144,   2,   8, 
      15, 160,  66,   0,   0,   3, 
       0,   0,  15, 128,   0,   0, 
     228, 176,   0,   8, 228, 160, 
      66,   0,   0,   3,   1,   0, 
      15, 128,   0,   0, 228, 176, 
       2,   8, 228, 160,   2,   0, 
-      0,   3,   0,   0,   2, 128, 
-      1,   0,   0, 128,   1,   0, 
+      0,   3,   0,   0,   1, 128, 
+      1,   0, 255, 128,   1,   0, 
       0, 160,   5,   0,   0,   3, 
-      0,   0,   6, 128,   0,   0, 
-     85, 128,   1,   0, 248, 160, 
+      0,   0,   3, 128,   0,   0, 
+      0, 128,   1,   0, 238, 160, 
       2,   0,   0,   3,   0,   0, 
-      1, 128,   0,   0,   0, 128, 
+      4, 128,   0,   0, 255, 128, 
       1,   0,  85, 160,   4,   0, 
-      0,   4,   0,   0,   4, 128, 
-      0,   0,   0, 128,   2,   0, 
-      0, 160,   0,   0, 170, 129, 
+      0,   4,   0,   0,   2, 128, 
+      0,   0, 170, 128,   2,   0, 
+      0, 160,   0,   0,  85, 129, 
       4,   0,   0,   4,   1,   0, 
-      1, 128,   0,   0,   0, 128, 
+      1, 128,   0,   0, 170, 128, 
       2,   0,   0, 160,   0,   0, 
-     85, 128,  66,   0,   0,   3, 
+      0, 128,  66,   0,   0,   3, 
       2,   0,  15, 128,   0,   0, 
     228, 176,   1,   8, 228, 160, 
       2,   0,   0,   3,   0,   0, 
-      2, 128,   2,   0,   0, 128, 
+      1, 128,   2,   0, 255, 128, 
       1,   0,   0, 160,   4,   0, 
       0,   4,   1,   0,   2, 128, 
-      0,   0,  85, 128,   2,   0, 
-    170, 161,   0,   0, 170, 128, 
+      0,   0,   0, 128,   2,   0, 
+    170, 161,   0,   0,  85, 128, 
       5,   0,   0,   3,   0,   0, 
-      2, 128,   0,   0,  85, 128, 
+      1, 128,   0,   0,   0, 128, 
       2,   0,  85, 160,   4,   0, 
       0,   4,   1,   0,   4, 128, 
-      0,   0,   0, 128,   2,   0, 
-      0, 160,   0,   0,  85, 128, 
+      0,   0, 170, 128,   2,   0, 
+      0, 160,   0,   0,   0, 128, 
       1,   0,   0,   2,   1,   0, 
       8, 128,   2,   0, 255, 160, 
       5,   0,   0,   3,   0,   0, 
      15, 128,   1,   0, 228, 128, 
       0,   0,   0, 160,   1,   0, 
       0,   2,   0,   8,  15, 128, 
       0,   0, 228, 128, 255, 255, 
       0,   0,  83,  72,  68,  82, 
@@ -1817,34 +1835,34 @@ const BYTE YCbCrShader[] =
      69,   0,   0,   9, 242,   0, 
      16,   0,   0,   0,   0,   0, 
      70,  16,  16,   0,   1,   0, 
       0,   0,  70, 126,  16,   0, 
       2,   0,   0,   0,   0,  96, 
      16,   0,   0,   0,   0,   0, 
       0,   0,   0,   7,  18,   0, 
      16,   0,   0,   0,   0,   0, 
-     10,   0,  16,   0,   0,   0, 
+     58,   0,  16,   0,   0,   0, 
       0,   0,   1,  64,   0,   0, 
       0,   0,   0, 191,  56,   0, 
       0,  10,  50,   0,  16,   0, 
       0,   0,   0,   0,   6,   0, 
      16,   0,   0,   0,   0,   0, 
       2,  64,   0,   0, 186,  73, 
     204,  63, 197,  32,  80,  63, 
       0,   0,   0,   0,   0,   0, 
       0,   0,  69,   0,   0,   9, 
     242,   0,  16,   0,   1,   0, 
       0,   0,  70,  16,  16,   0, 
       1,   0,   0,   0,  70, 126, 
      16,   0,   0,   0,   0,   0, 
       0,  96,  16,   0,   0,   0, 
       0,   0,   0,   0,   0,   7, 
      66,   0,  16,   0,   0,   0, 
-      0,   0,  10,   0,  16,   0, 
+      0,   0,  58,   0,  16,   0, 
       1,   0,   0,   0,   1,  64, 
       0,   0,   0,   0, 128, 189, 
      50,   0,   0,  10,  34,   0, 
      16,   0,   0,   0,   0,   0, 
      42,   0,  16,   0,   0,   0, 
       0,   0,   1,  64,   0,   0, 
     244, 253, 148,  63,  26,   0, 
      16, 128,  65,   0,   0,   0, 
@@ -1857,17 +1875,17 @@ const BYTE YCbCrShader[] =
       0,   0,   0,   0,  69,   0, 
       0,   9, 242,   0,  16,   0, 
       2,   0,   0,   0,  70,  16, 
      16,   0,   1,   0,   0,   0, 
      70, 126,  16,   0,   1,   0, 
       0,   0,   0,  96,  16,   0, 
       0,   0,   0,   0,   0,   0, 
       0,   7,  18,   0,  16,   0, 
-      0,   0,   0,   0,  10,   0, 
+      0,   0,   0,   0,  58,   0, 
      16,   0,   2,   0,   0,   0, 
       1,  64,   0,   0,   0,   0, 
       0, 191,  50,   0,   0,  10, 
      34,   0,  16,   0,   1,   0, 
       0,   0,  10,   0,  16, 128, 
      65,   0,   0,   0,   0,   0, 
       0,   0,   1,  64,   0,   0, 
      39,  49, 200,  62,  26,   0, 
@@ -1901,17 +1919,17 @@ const BYTE YCbCrShader[] =
       1,   0,   0,   0,   0,   0, 
       0,   0,   0,   0,   0,   0, 
       0,   0,   0,   0,   0,   0, 
       0,   0,   0,   0,   0,   0, 
       0,   0,   0,   0,   3,   0, 
       0,   0,   0,   0,   0,   0, 
       0,   0,   0,   0,   0,   0, 
       0,   0,   0,   0,   0,   0, 
-      2,   0,   0,   0,   0,   0, 
+      1,   0,   0,   0,   0,   0, 
       0,   0,   0,   0,   0,   0, 
       0,   0,   0,   0,   0,   0, 
       0,   0,   0,   0,   0,   0, 
       0,   0,   0,   0,   0,   0, 
       0,   0,   0,   0,   0,   0, 
       0,   0,   0,   0,  82,  68, 
      69,  70, 152,   2,   0,   0, 
       1,   0,   0,   0, 220,   0, 
@@ -2017,19 +2035,19 @@ const BYTE YCbCrShader[] =
      97, 100,   0, 118,  77,  97, 
     115, 107,  81, 117,  97, 100, 
       0,  77, 105,  99, 114, 111, 
     115, 111, 102, 116,  32,  40, 
      82,  41,  32,  72,  76,  83, 
      76,  32,  83, 104,  97, 100, 
     101, 114,  32,  67, 111, 109, 
     112, 105, 108, 101, 114,  32, 
-     57,  46,  51,  48,  46,  57, 
-     50,  48,  48,  46,  50,  48, 
-     52,  57,  57,   0,  73,  83, 
+     57,  46,  50,  57,  46,  57, 
+     53,  50,  46,  51,  49,  49, 
+     49,   0, 171, 171,  73,  83, 
      71,  78,  80,   0,   0,   0, 
       2,   0,   0,   0,   8,   0, 
       0,   0,  56,   0,   0,   0, 
       0,   0,   0,   0,   1,   0, 
       0,   0,   3,   0,   0,   0, 
       0,   0,   0,   0,  15,   0, 
       0,   0,  68,   0,   0,   0, 
       0,   0,   0,   0,   0,   0, 
@@ -2046,20 +2064,23 @@ const BYTE YCbCrShader[] =
       0,   0,   0,   0,   0,   0, 
       3,   0,   0,   0,   0,   0, 
       0,   0,  15,   0,   0,   0, 
      83,  86,  95,  84,  97, 114, 
     103, 101, 116,   0, 171, 171
 };
 #if 0
 //
-// Generated by Microsoft (R) HLSL Shader Compiler 9.30.9200.20499
-//
-//
-///
+// Generated by Microsoft (R) HLSL Shader Compiler 9.29.952.3111
+//
+//
+//   fxc CompositorD3D11.fx -ELayerQuadMaskVS -nologo -Tvs_4_0_level_9_3
+//    -FhtmpShaderHeader -VnLayerQuadMaskVS
+//
+//
 // Buffer Definitions: 
 //
 // cbuffer $Globals
 // {
 //
 //   float4x4 mLayerTransform;          // Offset:    0 Size:    64
 //   float4x4 mProjection;              // Offset:   64 Size:    64
 //   float4 vRenderTargetOffset;        // Offset:  128 Size:    16
@@ -2077,28 +2098,28 @@ const BYTE YCbCrShader[] =
 // Name                                 Type  Format         Dim Slot Elements
 // ------------------------------ ---------- ------- ----------- ---- --------
 // $Globals                          cbuffer      NA          NA    0        1
 //
 //
 //
 // Input signature:
 //
-// Name                 Index   Mask Register SysValue  Format   Used
-// -------------------- ----- ------ -------- -------- ------- ------
-// POSITION                 0   xy          0     NONE   float   xy  
+// Name                 Index   Mask Register SysValue Format   Used
+// -------------------- ----- ------ -------- -------- ------ ------
+// POSITION                 0   xy          0     NONE  float   xy  
 //
 //
 // Output signature:
 //
-// Name                 Index   Mask Register SysValue  Format   Used
-// -------------------- ----- ------ -------- -------- ------- ------
-// SV_Position              0   xyzw        0      POS   float   xyzw
-// TEXCOORD                 0   xy          1     NONE   float   xy  
-// TEXCOORD                 1     zw        1     NONE   float     zw
+// Name                 Index   Mask Register SysValue Format   Used
+// -------------------- ----- ------ -------- -------- ------ ------
+// SV_Position              0   xyzw        0      POS  float   xyzw
+// TEXCOORD                 0   xy          1     NONE  float   xy  
+// TEXCOORD                 1     zw        1     NONE  float     zw
 //
 //
 // Constant buffer to DX9 shader constant mappings:
 //
 // Target Reg Buffer  Start Reg # of Regs        Data Conversion
 // ---------- ------- --------- --------- ----------------------
 // c1         cb0             0         2  ( FLT, FLT, FLT, FLT)
 // c3         cb0             3         9  ( FLT, FLT, FLT, FLT)
@@ -2160,20 +2181,20 @@ mad r1.xyzw, cb0[6].xyzw, r0.zzzz, r1.xy
 mad o0.xyzw, cb0[7].xyzw, r0.wwww, r1.xyzw
 mad o1.xy, v0.xyxx, cb0[9].zwzz, cb0[9].xyxx
 ret 
 // Approximately 16 instruction slots used
 #endif
 
 const BYTE LayerQuadMaskVS[] =
 {
-     68,  88,  66,  67,  40, 251, 
-    200, 161,  89, 188,  29, 161, 
-    182, 221,  52,  28,  31, 141, 
-    174, 202,   1,   0,   0,   0, 
+     68,  88,  66,  67,  15, 196, 
+    252, 199, 211, 188,  92,  26, 
+     46, 113, 249,  29, 135, 110, 
+     83, 119,   1,   0,   0,   0, 
     120,   7,   0,   0,   6,   0, 
       0,   0,  56,   0,   0,   0, 
     224,   1,   0,   0,  76,   4, 
       0,   0, 200,   4,   0,   0, 
     212,   6,   0,   0,   8,   7, 
       0,   0,  65, 111, 110,  57, 
     160,   1,   0,   0, 160,   1, 
       0,   0,   0,   2, 254, 255, 
@@ -2357,17 +2378,17 @@ const BYTE LayerQuadMaskVS[] =
       0,   0,   1,   0,   0,   0, 
       0,   0,   0,   0,   0,   0, 
       0,   0,   0,   0,   0,   0, 
       0,   0,   0,   0,   0,   0, 
       0,   0,   0,   0,   0,   0, 
       0,   0,   0,   0,   0,   0, 
       0,   0,   0,   0,   0,   0, 
       0,   0,   0,   0,   0,   0, 
-      0,   0,   2,   0,   0,   0, 
+      0,   0,   1,   0,   0,   0, 
       0,   0,   0,   0,   0,   0, 
       0,   0,   0,   0,   0,   0, 
       0,   0,   0,   0,   0,   0, 
       0,   0,   0,   0,   0,   0, 
       0,   0,   0,   0,   0,   0, 
       0,   0,   0,   0,   0,   0, 
      82,  68,  69,  70,   4,   2, 
       0,   0,   1,   0,   0,   0, 
@@ -2448,20 +2469,20 @@ const BYTE LayerQuadMaskVS[] =
       0,   0,   3,   0,   1,   0, 
       1,   0,   0,   0,   0,   0, 
       0,   0,   0,   0,  77, 105, 
      99, 114, 111, 115, 111, 102, 
     116,  32,  40,  82,  41,  32, 
      72,  76,  83,  76,  32,  83, 
     104,  97, 100, 101, 114,  32, 
      67, 111, 109, 112, 105, 108, 
-    101, 114,  32,  57,  46,  51, 
-     48,  46,  57,  50,  48,  48, 
-     46,  50,  48,  52,  57,  57, 
-      0, 171,  73,  83,  71,  78, 
+    101, 114,  32,  57,  46,  50, 
+     57,  46,  57,  53,  50,  46, 
+     51,  49,  49,  49,   0, 171, 
+    171, 171,  73,  83,  71,  78, 
      44,   0,   0,   0,   1,   0, 
       0,   0,   8,   0,   0,   0, 
      32,   0,   0,   0,   0,   0, 
       0,   0,   0,   0,   0,   0, 
       3,   0,   0,   0,   0,   0, 
       0,   0,   3,   3,   0,   0, 
      80,  79,  83,  73,  84,  73, 
      79,  78,   0, 171, 171, 171, 
@@ -2482,20 +2503,23 @@ const BYTE LayerQuadMaskVS[] =
      12,   3,   0,   0,  83,  86, 
      95,  80, 111, 115, 105, 116, 
     105, 111, 110,   0,  84,  69, 
      88,  67,  79,  79,  82,  68, 
       0, 171, 171, 171
 };
 #if 0
 //
-// Generated by Microsoft (R) HLSL Shader Compiler 9.30.9200.20499
-//
-//
-///
+// Generated by Microsoft (R) HLSL Shader Compiler 9.29.952.3111
+//
+//
+//   fxc CompositorD3D11.fx -ELayerQuadMask3DVS -nologo -Tvs_4_0_level_9_3
+//    -FhtmpShaderHeader -VnLayerQuadMask3DVS
+//
+//
 // Buffer Definitions: 
 //
 // cbuffer $Globals
 // {
 //
 //   float4x4 mLayerTransform;          // Offset:    0 Size:    64
 //   float4x4 mProjection;              // Offset:   64 Size:    64
 //   float4 vRenderTargetOffset;        // Offset:  128 Size:    16
@@ -2513,28 +2537,28 @@ const BYTE LayerQuadMaskVS[] =
 // Name                                 Type  Format         Dim Slot Elements
 // ------------------------------ ---------- ------- ----------- ---- --------
 // $Globals                          cbuffer      NA          NA    0        1
 //
 //
 //
 // Input signature:
 //
-// Name                 Index   Mask Register SysValue  Format   Used
-// -------------------- ----- ------ -------- -------- ------- ------
-// POSITION                 0   xy          0     NONE   float   xy  
+// Name                 Index   Mask Register SysValue Format   Used
+// -------------------- ----- ------ -------- -------- ------ ------
+// POSITION                 0   xy          0     NONE  float   xy  
 //
 //
 // Output signature:
 //
-// Name                 Index   Mask Register SysValue  Format   Used
-// -------------------- ----- ------ -------- -------- ------- ------
-// SV_Position              0   xyzw        0      POS   float   xyzw
-// TEXCOORD                 0   xy          1     NONE   float   xy  
-// TEXCOORD                 1   xyz         2     NONE   float   xyz 
+// Name                 Index   Mask Register SysValue Format   Used
+// -------------------- ----- ------ -------- -------- ------ ------
+// SV_Position              0   xyzw        0      POS  float   xyzw
+// TEXCOORD                 0   xy          1     NONE  float   xy  
+// TEXCOORD                 1   xyz         2     NONE  float   xyz 
 //
 //
 // Constant buffer to DX9 shader constant mappings:
 //
 // Target Reg Buffer  Start Reg # of Regs        Data Conversion
 // ---------- ------- --------- --------- ----------------------
 // c1         cb0             0         2  ( FLT, FLT, FLT, FLT)
 // c3         cb0             3         9  ( FLT, FLT, FLT, FLT)
@@ -2600,20 +2624,20 @@ mad o1.xy, v0.xyxx, cb0[9].zwzz, cb0[9].
 mov r0.z, l(1.000000)
 mul o2.xyz, r0.wwww, r0.xyzx
 ret 
 // Approximately 17 instruction slots used
 #endif
 
 const BYTE LayerQuadMask3DVS[] =
 {
-     68,  88,  66,  67, 111,  70, 
-    229, 103,  94, 104, 158, 115, 
-     72,  63, 234, 127,  49,  42, 
-    210,  99,   1,   0,   0,   0, 
+     68,  88,  66,  67, 100,  40, 
+     55,  29, 238,  71, 107,  78, 
+    214, 182,  73, 149, 138,  22, 
+    163, 187,   1,   0,   0,   0, 
     204,   7,   0,   0,   6,   0, 
       0,   0,  56,   0,   0,   0, 
      24,   2,   0,   0, 160,   4, 
       0,   0,  28,   5,   0,   0, 
      40,   7,   0,   0,  92,   7, 
       0,   0,  65, 111, 110,  57, 
     216,   1,   0,   0, 216,   1, 
       0,   0,   0,   2, 254, 255, 
@@ -2811,17 +2835,17 @@ const BYTE LayerQuadMask3DVS[] =
       0,   0,   1,   0,   0,   0, 
       0,   0,   0,   0,   0,   0, 
       0,   0,   0,   0,   0,   0, 
       0,   0,   0,   0,   0,   0, 
       0,   0,   0,   0,   0,   0, 
       0,   0,   0,   0,   0,   0, 
       0,   0,   0,   0,   0,   0, 
       0,   0,   0,   0,   0,   0, 
-      0,   0,   3,   0,   0,   0, 
+      0,   0,   2,   0,   0,   0, 
       0,   0,   0,   0,   0,   0, 
       0,   0,   0,   0,   0,   0, 
       0,   0,   0,   0,   0,   0, 
       0,   0,   0,   0,   0,   0, 
       0,   0,   0,   0,   0,   0, 
       0,   0,   0,   0,   0,   0, 
      82,  68,  69,  70,   4,   2, 
       0,   0,   1,   0,   0,   0, 
@@ -2902,20 +2926,20 @@ const BYTE LayerQuadMask3DVS[] =
       0,   0,   3,   0,   1,   0, 
       1,   0,   0,   0,   0,   0, 
       0,   0,   0,   0,  77, 105, 
      99, 114, 111, 115, 111, 102, 
     116,  32,  40,  82,  41,  32, 
      72,  76,  83,  76,  32,  83, 
     104,  97, 100, 101, 114,  32, 
      67, 111, 109, 112, 105, 108, 
-    101, 114,  32,  57,  46,  51, 
-     48,  46,  57,  50,  48,  48, 
-     46,  50,  48,  52,  57,  57, 
-      0, 171,  73,  83,  71,  78, 
+    101, 114,  32,  57,  46,  50, 
+     57,  46,  57,  53,  50,  46, 
+     51,  49,  49,  49,   0, 171, 
+    171, 171,  73,  83,  71,  78, 
      44,   0,   0,   0,   1,   0, 
       0,   0,   8,   0,   0,   0, 
      32,   0,   0,   0,   0,   0, 
       0,   0,   0,   0,   0,   0, 
       3,   0,   0,   0,   0,   0, 
       0,   0,   3,   3,   0,   0, 
      80,  79,  83,  73,  84,  73, 
      79,  78,   0, 171, 171, 171, 
@@ -2936,20 +2960,23 @@ const BYTE LayerQuadMask3DVS[] =
       7,   8,   0,   0,  83,  86, 
      95,  80, 111, 115, 105, 116, 
     105, 111, 110,   0,  84,  69, 
      88,  67,  79,  79,  82,  68, 
       0, 171, 171, 171
 };
 #if 0
 //
-// Generated by Microsoft (R) HLSL Shader Compiler 9.30.9200.20499
-//
-//
-///
+// Generated by Microsoft (R) HLSL Shader Compiler 9.29.952.3111
+//
+//
+//   fxc CompositorD3D11.fx -ESolidColorShaderMask -Tps_4_0_level_9_3 -nologo
+//    -FhtmpShaderHeader -VnSolidColorShaderMask
+//
+//
 // Buffer Definitions: 
 //
 // cbuffer $Globals
 // {
 //
 //   float4 fLayerColor;                // Offset:    0 Size:    16
 //   float fLayerOpacity;               // Offset:   16 Size:     4 [unused]
 //   float4x4 mLayerTransform;          // Offset:   32 Size:    64 [unused]
@@ -2969,28 +2996,28 @@ const BYTE LayerQuadMask3DVS[] =
 // sSampler                          sampler      NA          NA    0        1
 // tMask                             texture  float4          2d    3        1
 // $Globals                          cbuffer      NA          NA    0        1
 //
 //
 //
 // Input signature:
 //
-// Name                 Index   Mask Register SysValue  Format   Used
-// -------------------- ----- ------ -------- -------- ------- ------
-// SV_Position              0   xyzw        0      POS   float       
-// TEXCOORD                 0   xy          1     NONE   float       
-// TEXCOORD                 1     zw        1     NONE   float     zw
+// Name                 Index   Mask Register SysValue Format   Used
+// -------------------- ----- ------ -------- -------- ------ ------
+// SV_Position              0   xyzw        0      POS  float       
+// TEXCOORD                 0   xy          1     NONE  float       
+// TEXCOORD                 1     zw        1     NONE  float     zw
 //
 //
 // Output signature:
 //
-// Name                 Index   Mask Register SysValue  Format   Used
-// -------------------- ----- ------ -------- -------- ------- ------
-// SV_Target                0   xyzw        0   TARGET   float   xyzw
+// Name                 Index   Mask Register SysValue Format   Used
+// -------------------- ----- ------ -------- -------- ------ ------
+// SV_Target                0   xyzw        0   TARGET  float   xyzw
 //
 //
 // Constant buffer to DX9 shader constant mappings:
 //
 // Target Reg Buffer  Start Reg # of Regs        Data Conversion
 // ---------- ------- --------- --------- ----------------------
 // c0         cb0             0         1  ( FLT, FLT, FLT, FLT)
 //
@@ -3023,20 +3050,20 @@ dcl_temps 1
 sample r0.xyzw, v1.zwzz, t3.xyzw, s0
 mul o0.xyzw, r0.wwww, cb0[0].xyzw
 ret 
 // Approximately 3 instruction slots used
 #endif
 
 const BYTE SolidColorShaderMask[] =
 {
-     68,  88,  66,  67, 197,   5, 
-     14,  11, 127,  94,  25,  20, 
-    204, 148, 179,  59,  49,  64, 
-    217, 226,   1,   0,   0,   0, 
+     68,  88,  66,  67,  92, 193, 
+    158, 159, 177, 150, 196, 208, 
+    237,  57,  66,  98,  44, 248, 
+    148, 128,   1,   0,   0,   0, 
     232,   4,   0,   0,   6,   0, 
       0,   0,  56,   0,   0,   0, 
     204,   0,   0,   0, 112,   1, 
       0,   0, 236,   1,   0,   0, 
      68,   4,   0,   0, 180,   4, 
       0,   0,  65, 111, 110,  57, 
     140,   0,   0,   0, 140,   0, 
       0,   0,   0,   2, 255, 255, 
@@ -3098,17 +3125,17 @@ const BYTE SolidColorShaderMask[] =
       0,   0,   1,   0,   0,   0, 
       0,   0,   0,   0,   0,   0, 
       0,   0,   0,   0,   0,   0, 
       0,   0,   0,   0,   0,   0, 
       0,   0,   0,   0,   0,   0, 
       1,   0,   0,   0,   0,   0, 
       0,   0,   0,   0,   0,   0, 
       0,   0,   0,   0,   0,   0, 
-      0,   0,   1,   0,   0,   0, 
+      0,   0,   0,   0,   0,   0, 
       0,   0,   0,   0,   0,   0, 
       0,   0,   0,   0,   0,   0, 
       0,   0,   0,   0,   0,   0, 
       0,   0,   0,   0,   0,   0, 
       0,   0,   0,   0,   0,   0, 
       0,   0,   0,   0,   0,   0, 
      82,  68,  69,  70,  80,   2, 
       0,   0,   1,   0,   0,   0, 
@@ -3202,19 +3229,19 @@ const BYTE SolidColorShaderMask[] =
      81, 117,  97, 100,   0, 118, 
      77,  97, 115, 107,  81, 117, 
      97, 100,   0,  77, 105,  99, 
     114, 111, 115, 111, 102, 116, 
      32,  40,  82,  41,  32,  72, 
      76,  83,  76,  32,  83, 104, 
      97, 100, 101, 114,  32,  67, 
     111, 109, 112, 105, 108, 101, 
-    114,  32,  57,  46,  51,  48, 
-     46,  57,  50,  48,  48,  46, 
-     50,  48,  52,  57,  57,   0, 
+    114,  32,  57,  46,  50,  57, 
+     46,  57,  53,  50,  46,  51, 
+     49,  49,  49,   0, 171, 171, 
      73,  83,  71,  78, 104,   0, 
       0,   0,   3,   0,   0,   0, 
       8,   0,   0,   0,  80,   0, 
       0,   0,   0,   0,   0,   0, 
       1,   0,   0,   0,   3,   0, 
       0,   0,   0,   0,   0,   0, 
      15,   0,   0,   0,  92,   0, 
       0,   0,   0,   0,   0,   0, 
@@ -3236,20 +3263,23 @@ const BYTE SolidColorShaderMask[] =
       0,   0,   3,   0,   0,   0, 
       0,   0,   0,   0,  15,   0, 
       0,   0,  83,  86,  95,  84, 
      97, 114, 103, 101, 116,   0, 
     171, 171
 };
 #if 0
 //
-// Generated by Microsoft (R) HLSL Shader Compiler 9.30.9200.20499
-//
-//
-///
+// Generated by Microsoft (R) HLSL Shader Compiler 9.29.952.3111
+//
+//
+//   fxc CompositorD3D11.fx -ERGBShaderMask -Tps_4_0_level_9_3 -nologo
+//    -FhtmpShaderHeader -VnRGBShaderMask
+//
+//
 // Buffer Definitions: 
 //
 // cbuffer $Globals
 // {
 //
 //   float4 fLayerColor;                // Offset:    0 Size:    16 [unused]
 //   float fLayerOpacity;               // Offset:   16 Size:     4
 //   float4x4 mLayerTransform;          // Offset:   32 Size:    64 [unused]
@@ -3270,28 +3300,28 @@ const BYTE SolidColorShaderMask[] =
 // tRGB                              texture  float4          2d    0        1
 // tMask                             texture  float4          2d    3        1
 // $Globals                          cbuffer      NA          NA    0        1
 //
 //
 //
 // Input signature:
 //
-// Name                 Index   Mask Register SysValue  Format   Used
-// -------------------- ----- ------ -------- -------- ------- ------
-// SV_Position              0   xyzw        0      POS   float       
-// TEXCOORD                 0   xy          1     NONE   float   xy  
-// TEXCOORD                 1     zw        1     NONE   float     zw
+// Name                 Index   Mask Register SysValue Format   Used
+// -------------------- ----- ------ -------- -------- ------ ------
+// SV_Position              0   xyzw        0      POS  float       
+// TEXCOORD                 0   xy          1     NONE  float   xy  
+// TEXCOORD                 1     zw        1     NONE  float     zw
 //
 //
 // Output signature:
 //
-// Name                 Index   Mask Register SysValue  Format   Used
-// -------------------- ----- ------ -------- -------- ------- ------
-// SV_Target                0   xyzw        0   TARGET   float   xyzw
+// Name                 Index   Mask Register SysValue Format   Used
+// -------------------- ----- ------ -------- -------- ------ ------
+// SV_Target                0   xyzw        0   TARGET  float   xyzw
 //
 //
 // Constant buffer to DX9 shader constant mappings:
 //
 // Target Reg Buffer  Start Reg # of Regs        Data Conversion
 // ---------- ------- --------- --------- ----------------------
 // c0         cb0             1         1  ( FLT, FLT, FLT, FLT)
 //
@@ -3334,20 +3364,20 @@ sample r1.xyzw, v1.zwzz, t3.xyzw, s0
 mov r0.w, cb0[1].x
 mul o0.xyzw, r0.xyzw, r1.wwww
 ret 
 // Approximately 6 instruction slots used
 #endif
 
 const BYTE RGBShaderMask[] =
 {
-     68,  88,  66,  67,   4, 194, 
-    232, 177, 243,  31,   1, 121, 
-    250, 122, 178, 255, 171,  23, 
-    244, 226,   1,   0,   0,   0, 
+     68,  88,  66,  67, 211,  41, 
+    177, 153, 133,  94, 180, 137, 
+    188,  24,  43, 126, 122,  18, 
+    165, 144,   1,   0,   0,   0, 
     192,   5,   0,   0,   6,   0, 
       0,   0,  56,   0,   0,   0, 
       8,   1,   0,   0,  32,   2, 
       0,   0, 156,   2,   0,   0, 
      28,   5,   0,   0, 140,   5, 
       0,   0,  65, 111, 110,  57, 
     200,   0,   0,   0, 200,   0, 
       0,   0,   0,   2, 255, 255, 
@@ -3438,355 +3468,16 @@ const BYTE RGBShaderMask[] =
       0,   0,   0,   0,   1,   0, 
       0,   0,   0,   0,   0,   0, 
       0,   0,   0,   0,   0,   0, 
       0,   0,   0,   0,   0,   0, 
       0,   0,   0,   0,   0,   0, 
       0,   0,   2,   0,   0,   0, 
       0,   0,   0,   0,   0,   0, 
       0,   0,   0,   0,   0,   0, 
-      0,   0,   0,   0,   2,   0, 
-      0,   0,   0,   0,   0,   0, 
-      0,   0,   0,   0,   0,   0, 
-      0,   0,   0,   0,   0,   0, 
-      0,   0,   0,   0,   0,   0, 
-      0,   0,   0,   0,   0,   0, 
-      0,   0,   0,   0,   0,   0, 
-      0,   0,  82,  68,  69,  70, 
-    120,   2,   0,   0,   1,   0, 
-      0,   0, 188,   0,   0,   0, 
-      4,   0,   0,   0,  28,   0, 
-      0,   0,   0,   4, 255, 255, 
-      0,   1,   0,   0,  69,   2, 
-      0,   0, 156,   0,   0,   0, 
-      3,   0,   0,   0,   0,   0, 
-      0,   0,   0,   0,   0,   0, 
-      0,   0,   0,   0,   0,   0, 
-      0,   0,   1,   0,   0,   0, 
-      1,   0,   0,   0, 165,   0, 
-      0,   0,   2,   0,   0,   0, 
-      5,   0,   0,   0,   4,   0, 
-      0,   0, 255, 255, 255, 255, 
-      0,   0,   0,   0,   1,   0, 
-      0,   0,  12,   0,   0,   0, 
-    170,   0,   0,   0,   2,   0, 
-      0,   0,   5,   0,   0,   0, 
-      4,   0,   0,   0, 255, 255, 
-    255, 255,   3,   0,   0,   0, 
-      1,   0,   0,   0,  13,   0, 
-      0,   0, 176,   0,   0,   0, 
-      0,   0,   0,   0,   0,   0, 
-      0,   0,   0,   0,   0,   0, 
-      0,   0,   0,   0,   0,   0, 
-      0,   0,   1,   0,   0,   0, 
-      0,   0,   0,   0, 115,  83, 
-     97, 109, 112, 108, 101, 114, 
-      0, 116,  82,  71,  66,   0, 
-    116,  77,  97, 115, 107,   0, 
-     36,  71, 108, 111,  98,  97, 
-    108, 115,   0, 171, 171, 171, 
-    176,   0,   0,   0,   8,   0, 
-      0,   0, 212,   0,   0,   0, 
-    224,   0,   0,   0,   0,   0, 
-      0,   0,   0,   0,   0,   0, 
-    148,   1,   0,   0,   0,   0, 
-      0,   0,  16,   0,   0,   0, 
-      0,   0,   0,   0, 160,   1, 
-      0,   0,   0,   0,   0,   0, 
-    176,   1,   0,   0,  16,   0, 
-      0,   0,   4,   0,   0,   0, 
-      2,   0,   0,   0, 192,   1, 
-      0,   0,   0,   0,   0,   0, 
-    208,   1,   0,   0,  32,   0, 
-      0,   0,  64,   0,   0,   0, 
-      0,   0,   0,   0, 224,   1, 
-      0,   0,   0,   0,   0,   0, 
-    240,   1,   0,   0,  96,   0, 
-      0,   0,  64,   0,   0,   0, 
-      0,   0,   0,   0, 224,   1, 
-      0,   0,   0,   0,   0,   0, 
-    252,   1,   0,   0, 160,   0, 
-      0,   0,  16,   0,   0,   0, 
-      0,   0,   0,   0, 160,   1, 
-      0,   0,   0,   0,   0,   0, 
-     16,   2,   0,   0, 176,   0, 
-      0,   0,  16,   0,   0,   0, 
-      0,   0,   0,   0,  32,   2, 
-      0,   0,   0,   0,   0,   0, 
-     48,   2,   0,   0, 192,   0, 
-      0,   0,  16,   0,   0,   0, 
-      0,   0,   0,   0,  32,   2, 
-      0,   0,   0,   0,   0,   0, 
-     59,   2,   0,   0, 208,   0, 
-      0,   0,  16,   0,   0,   0, 
-      0,   0,   0,   0,  32,   2, 
-      0,   0,   0,   0,   0,   0, 
-    102,  76,  97, 121, 101, 114, 
-     67, 111, 108, 111, 114,   0, 
-      1,   0,   3,   0,   1,   0, 
-      4,   0,   0,   0,   0,   0, 
-      0,   0,   0,   0, 102,  76, 
-     97, 121, 101, 114,  79, 112, 
-     97,  99, 105, 116, 121,   0, 
-    171, 171,   0,   0,   3,   0, 
-      1,   0,   1,   0,   0,   0, 
-      0,   0,   0,   0,   0,   0, 
-    109,  76,  97, 121, 101, 114, 
-     84, 114,  97, 110, 115, 102, 
-    111, 114, 109,   0,   3,   0, 
-      3,   0,   4,   0,   4,   0, 
-      0,   0,   0,   0,   0,   0, 
-      0,   0, 109,  80, 114, 111, 
-    106, 101,  99, 116, 105, 111, 
-    110,   0, 118,  82, 101, 110, 
-    100, 101, 114,  84,  97, 114, 
-    103, 101, 116,  79, 102, 102, 
-    115, 101, 116,   0, 118,  84, 
-    101, 120, 116, 117, 114, 101, 
-     67, 111, 111, 114, 100, 115, 
-      0, 171,   1,   0,   3,   0, 
-      1,   0,   4,   0,   0,   0, 
-      0,   0,   0,   0,   0,   0, 
-    118,  76,  97, 121, 101, 114, 
-     81, 117,  97, 100,   0, 118, 
-     77,  97, 115, 107,  81, 117, 
-     97, 100,   0,  77, 105,  99, 
-    114, 111, 115, 111, 102, 116, 
-     32,  40,  82,  41,  32,  72, 
-     76,  83,  76,  32,  83, 104, 
-     97, 100, 101, 114,  32,  67, 
-    111, 109, 112, 105, 108, 101, 
-    114,  32,  57,  46,  51,  48, 
-     46,  57,  50,  48,  48,  46, 
-     50,  48,  52,  57,  57,   0, 
-     73,  83,  71,  78, 104,   0, 
-      0,   0,   3,   0,   0,   0, 
-      8,   0,   0,   0,  80,   0, 
-      0,   0,   0,   0,   0,   0, 
-      1,   0,   0,   0,   3,   0, 
-      0,   0,   0,   0,   0,   0, 
-     15,   0,   0,   0,  92,   0, 
-      0,   0,   0,   0,   0,   0, 
-      0,   0,   0,   0,   3,   0, 
-      0,   0,   1,   0,   0,   0, 
-      3,   3,   0,   0,  92,   0, 
-      0,   0,   1,   0,   0,   0, 
-      0,   0,   0,   0,   3,   0, 
-      0,   0,   1,   0,   0,   0, 
-     12,  12,   0,   0,  83,  86, 
-     95,  80, 111, 115, 105, 116, 
-    105, 111, 110,   0,  84,  69, 
-     88,  67,  79,  79,  82,  68, 
-      0, 171, 171, 171,  79,  83, 
-     71,  78,  44,   0,   0,   0, 
-      1,   0,   0,   0,   8,   0, 
-      0,   0,  32,   0,   0,   0, 
-      0,   0,   0,   0,   0,   0, 
-      0,   0,   3,   0,   0,   0, 
-      0,   0,   0,   0,  15,   0, 
-      0,   0,  83,  86,  95,  84, 
-     97, 114, 103, 101, 116,   0, 
-    171, 171
-};
-#if 0
-//
-// Generated by Microsoft (R) HLSL Shader Compiler 9.30.9200.20499
-//
-//
-///
-// Buffer Definitions: 
-//
-// cbuffer $Globals
-// {
-//
-//   float4 fLayerColor;                // Offset:    0 Size:    16 [unused]
-//   float fLayerOpacity;               // Offset:   16 Size:     4
-//   float4x4 mLayerTransform;          // Offset:   32 Size:    64 [unused]
-//   float4x4 mProjection;              // Offset:   96 Size:    64 [unused]
-//   float4 vRenderTargetOffset;        // Offset:  160 Size:    16 [unused]
-//   float4 vTextureCoords;             // Offset:  176 Size:    16 [unused]
-//   float4 vLayerQuad;                 // Offset:  192 Size:    16 [unused]
-//   float4 vMaskQuad;                  // Offset:  208 Size:    16 [unused]
-//
-// }
-//
-//
-// Resource Bindings:
-//
-// Name                                 Type  Format         Dim Slot Elements
-// ------------------------------ ---------- ------- ----------- ---- --------
-// sSampler                          sampler      NA          NA    0        1
-// tRGB                              texture  float4          2d    0        1
-// tMask                             texture  float4          2d    3        1
-// $Globals                          cbuffer      NA          NA    0        1
-//
-//
-//
-// Input signature:
-//
-// Name                 Index   Mask Register SysValue  Format   Used
-// -------------------- ----- ------ -------- -------- ------- ------
-// SV_Position              0   xyzw        0      POS   float       
-// TEXCOORD                 0   xy          1     NONE   float   xy  
-// TEXCOORD                 1     zw        1     NONE   float     zw
-//
-//
-// Output signature:
-//
-// Name                 Index   Mask Register SysValue  Format   Used
-// -------------------- ----- ------ -------- -------- ------- ------
-// SV_Target                0   xyzw        0   TARGET   float   xyzw
-//
-//
-// Constant buffer to DX9 shader constant mappings:
-//
-// Target Reg Buffer  Start Reg # of Regs        Data Conversion
-// ---------- ------- --------- --------- ----------------------
-// c0         cb0             1         1  ( FLT, FLT, FLT, FLT)
-//
-//
-// Sampler/Resource to DX9 shader sampler mappings:
-//
-// Target Sampler Source Sampler  Source Resource
-// -------------- --------------- ----------------
-// s0             s0              t3               
-// s1             s0              t0               
-//
-//
-// Level9 shader bytecode:
-//
-    ps_2_x
-    dcl t0
-    dcl_2d s0
-    dcl_2d s1
-    mov r0.xy, t0.wzzw
-    texld r1, t0, s1
-    texld r0, r0, s0
-    mul r1, r1, c0.x
-    mul r0, r0.w, r1
-    mov oC0, r0
-
-// approximately 6 instruction slots used (2 texture, 4 arithmetic)
-ps_4_0
-dcl_constantbuffer cb0[2], immediateIndexed
-dcl_sampler s0, mode_default
-dcl_resource_texture2d (float,float,float,float) t0
-dcl_resource_texture2d (float,float,float,float) t3
-dcl_input_ps linear v1.xy
-dcl_input_ps linear v1.zw
-dcl_output o0.xyzw
-dcl_temps 2
-sample r0.xyzw, v1.xyxx, t0.xyzw, s0
-mul r0.xyzw, r0.xyzw, cb0[1].xxxx
-sample r1.xyzw, v1.zwzz, t3.xyzw, s0
-mul o0.xyzw, r0.xyzw, r1.wwww
-ret 
-// Approximately 5 instruction slots used
-#endif
-
-const BYTE RGBAShaderMask[] =
-{
-     68,  88,  66,  67,  36, 250, 
-     10,  70, 114, 153, 149, 249, 
-     19, 167, 212, 168, 179,  28, 
-    106, 163,   1,   0,   0,   0, 
-    156,   5,   0,   0,   6,   0, 
-      0,   0,  56,   0,   0,   0, 
-    252,   0,   0,   0, 252,   1, 
-      0,   0, 120,   2,   0,   0, 
-    248,   4,   0,   0, 104,   5, 
-      0,   0,  65, 111, 110,  57, 
-    188,   0,   0,   0, 188,   0, 
-      0,   0,   0,   2, 255, 255, 
-    132,   0,   0,   0,  56,   0, 
-      0,   0,   1,   0,  44,   0, 
-      0,   0,  56,   0,   0,   0, 
-     56,   0,   2,   0,  36,   0, 
-      0,   0,  56,   0,   3,   0, 
-      0,   0,   0,   0,   1,   0, 
-      0,   0,   1,   0,   1,   0, 
-      0,   0,   0,   0,   0,   0, 
-      1,   2, 255, 255,  31,   0, 
-      0,   2,   0,   0,   0, 128, 
-      0,   0,  15, 176,  31,   0, 
-      0,   2,   0,   0,   0, 144, 
-      0,   8,  15, 160,  31,   0, 
-      0,   2,   0,   0,   0, 144, 
-      1,   8,  15, 160,   1,   0, 
-      0,   2,   0,   0,   3, 128, 
-      0,   0, 235, 176,  66,   0, 
-      0,   3,   1,   0,  15, 128, 
-      0,   0, 228, 176,   1,   8, 
-    228, 160,  66,   0,   0,   3, 
-      0,   0,  15, 128,   0,   0, 
-    228, 128,   0,   8, 228, 160, 
-      5,   0,   0,   3,   1,   0, 
-     15, 128,   1,   0, 228, 128, 
-      0,   0,   0, 160,   5,   0, 
-      0,   3,   0,   0,  15, 128, 
-      0,   0, 255, 128,   1,   0, 
-    228, 128,   1,   0,   0,   2, 
-      0,   8,  15, 128,   0,   0, 
-    228, 128, 255, 255,   0,   0, 
-     83,  72,  68,  82, 248,   0, 
-      0,   0,  64,   0,   0,   0, 
-     62,   0,   0,   0,  89,   0, 
-      0,   4,  70, 142,  32,   0, 
-      0,   0,   0,   0,   2,   0, 
-      0,   0,  90,   0,   0,   3, 
-      0,  96,  16,   0,   0,   0, 
-      0,   0,  88,  24,   0,   4, 
-      0, 112,  16,   0,   0,   0, 
-      0,   0,  85,  85,   0,   0, 
-     88,  24,   0,   4,   0, 112, 
-     16,   0,   3,   0,   0,   0, 
-     85,  85,   0,   0,  98,  16, 
-      0,   3,  50,  16,  16,   0, 
-      1,   0,   0,   0,  98,  16, 
-      0,   3, 194,  16,  16,   0, 
-      1,   0,   0,   0, 101,   0, 
-      0,   3, 242,  32,  16,   0, 
-      0,   0,   0,   0, 104,   0, 
-      0,   2,   2,   0,   0,   0, 
-     69,   0,   0,   9, 242,   0, 
-     16,   0,   0,   0,   0,   0, 
-     70,  16,  16,   0,   1,   0, 
-      0,   0,  70, 126,  16,   0, 
-      0,   0,   0,   0,   0,  96, 
-     16,   0,   0,   0,   0,   0, 
-     56,   0,   0,   8, 242,   0, 
-     16,   0,   0,   0,   0,   0, 
-     70,  14,  16,   0,   0,   0, 
-      0,   0,   6, 128,  32,   0, 
-      0,   0,   0,   0,   1,   0, 
-      0,   0,  69,   0,   0,   9, 
-    242,   0,  16,   0,   1,   0, 
-      0,   0, 230,  26,  16,   0, 
-      1,   0,   0,   0,  70, 126, 
-     16,   0,   3,   0,   0,   0, 
-      0,  96,  16,   0,   0,   0, 
-      0,   0,  56,   0,   0,   7, 
-    242,  32,  16,   0,   0,   0, 
-      0,   0,  70,  14,  16,   0, 
-      0,   0,   0,   0, 246,  15, 
-     16,   0,   1,   0,   0,   0, 
-     62,   0,   0,   1,  83,  84, 
-     65,  84, 116,   0,   0,   0, 
-      5,   0,   0,   0,   2,   0, 
-      0,   0,   0,   0,   0,   0, 
-      3,   0,   0,   0,   2,   0, 
-      0,   0,   0,   0,   0,   0, 
-      0,   0,   0,   0,   1,   0, 
-      0,   0,   0,   0,   0,   0, 
-      0,   0,   0,   0,   0,   0, 
-      0,   0,   0,   0,   0,   0, 
-      0,   0,   0,   0,   0,   0, 
-      0,   0,   2,   0,   0,   0, 
-      0,   0,   0,   0,   0,   0, 
-      0,   0,   0,   0,   0,   0, 
       0,   0,   0,   0,   1,   0, 
       0,   0,   0,   0,   0,   0, 
       0,   0,   0,   0,   0,   0, 
       0,   0,   0,   0,   0,   0, 
       0,   0,   0,   0,   0,   0, 
       0,   0,   0,   0,   0,   0, 
       0,   0,   0,   0,   0,   0, 
       0,   0,  82,  68,  69,  70, 
@@ -3888,19 +3579,19 @@ const BYTE RGBAShaderMask[] =
      81, 117,  97, 100,   0, 118, 
      77,  97, 115, 107,  81, 117, 
      97, 100,   0,  77, 105,  99, 
     114, 111, 115, 111, 102, 116, 
      32,  40,  82,  41,  32,  72, 
      76,  83,  76,  32,  83, 104, 
      97, 100, 101, 114,  32,  67, 
     111, 109, 112, 105, 108, 101, 
-    114,  32,  57,  46,  51,  48, 
-     46,  57,  50,  48,  48,  46, 
-     50,  48,  52,  57,  57,   0, 
+    114,  32,  57,  46,  50,  57, 
+     46,  57,  53,  50,  46,  51, 
+     49,  49,  49,   0, 171, 171, 
      73,  83,  71,  78, 104,   0, 
       0,   0,   3,   0,   0,   0, 
       8,   0,   0,   0,  80,   0, 
       0,   0,   0,   0,   0,   0, 
       1,   0,   0,   0,   3,   0, 
       0,   0,   0,   0,   0,   0, 
      15,   0,   0,   0,  92,   0, 
       0,   0,   0,   0,   0,   0, 
@@ -3922,20 +3613,365 @@ const BYTE RGBAShaderMask[] =
       0,   0,   3,   0,   0,   0, 
       0,   0,   0,   0,  15,   0, 
       0,   0,  83,  86,  95,  84, 
      97, 114, 103, 101, 116,   0, 
     171, 171
 };
 #if 0
 //
-// Generated by Microsoft (R) HLSL Shader Compiler 9.30.9200.20499
-//
-//
-///
+// Generated by Microsoft (R) HLSL Shader Compiler 9.29.952.3111
+//
+//
+//   fxc CompositorD3D11.fx -ERGBAShaderMask -Tps_4_0_level_9_3 -nologo
+//    -FhtmpShaderHeader -VnRGBAShaderMask
+//
+//
+// Buffer Definitions: 
+//
+// cbuffer $Globals
+// {
+//
+//   float4 fLayerColor;                // Offset:    0 Size:    16 [unused]
+//   float fLayerOpacity;               // Offset:   16 Size:     4
+//   float4x4 mLayerTransform;          // Offset:   32 Size:    64 [unused]
+//   float4x4 mProjection;              // Offset:   96 Size:    64 [unused]
+//   float4 vRenderTargetOffset;        // Offset:  160 Size:    16 [unused]
+//   float4 vTextureCoords;             // Offset:  176 Size:    16 [unused]
+//   float4 vLayerQuad;                 // Offset:  192 Size:    16 [unused]
+//   float4 vMaskQuad;                  // Offset:  208 Size:    16 [unused]
+//
+// }
+//
+//
+// Resource Bindings:
+//
+// Name                                 Type  Format         Dim Slot Elements
+// ------------------------------ ---------- ------- ----------- ---- --------
+// sSampler                          sampler      NA          NA    0        1
+// tRGB                              texture  float4          2d    0        1
+// tMask                             texture  float4          2d    3        1
+// $Globals                          cbuffer      NA          NA    0        1
+//
+//
+//
+// Input signature:
+//
+// Name                 Index   Mask Register SysValue Format   Used
+// -------------------- ----- ------ -------- -------- ------ ------
+// SV_Position              0   xyzw        0      POS  float       
+// TEXCOORD                 0   xy          1     NONE  float   xy  
+// TEXCOORD                 1     zw        1     NONE  float     zw
+//
+//
+// Output signature:
+//
+// Name                 Index   Mask Register SysValue Format   Used
+// -------------------- ----- ------ -------- -------- ------ ------
+// SV_Target                0   xyzw        0   TARGET  float   xyzw
+//
+//
+// Constant buffer to DX9 shader constant mappings:
+//
+// Target Reg Buffer  Start Reg # of Regs        Data Conversion
+// ---------- ------- --------- --------- ----------------------
+// c0         cb0             1         1  ( FLT, FLT, FLT, FLT)
+//
+//
+// Sampler/Resource to DX9 shader sampler mappings:
+//
+// Target Sampler Source Sampler  Source Resource
+// -------------- --------------- ----------------
+// s0             s0              t3               
+// s1             s0              t0               
+//
+//
+// Level9 shader bytecode:
+//
+    ps_2_x
+    dcl t0
+    dcl_2d s0
+    dcl_2d s1
+    mov r0.xy, t0.wzzw
+    texld r1, t0, s1
+    texld r0, r0, s0
+    mul r1, r1, c0.x
+    mul r0, r0.w, r1
+    mov oC0, r0
+
+// approximately 6 instruction slots used (2 texture, 4 arithmetic)
+ps_4_0
+dcl_constantbuffer cb0[2], immediateIndexed
+dcl_sampler s0, mode_default
+dcl_resource_texture2d (float,float,float,float) t0
+dcl_resource_texture2d (float,float,float,float) t3
+dcl_input_ps linear v1.xy
+dcl_input_ps linear v1.zw
+dcl_output o0.xyzw
+dcl_temps 2
+sample r0.xyzw, v1.xyxx, t0.xyzw, s0
+mul r0.xyzw, r0.xyzw, cb0[1].xxxx
+sample r1.xyzw, v1.zwzz, t3.xyzw, s0
+mul o0.xyzw, r0.xyzw, r1.wwww
+ret 
+// Approximately 5 instruction slots used
+#endif
+
+const BYTE RGBAShaderMask[] =
+{
+     68,  88,  66,  67, 234,  65, 
+    122,  94, 147, 106,  10, 149, 
+     54, 131, 161,  84,  79,  89, 
+    113, 104,   1,   0,   0,   0, 
+    156,   5,   0,   0,   6,   0, 
+      0,   0,  56,   0,   0,   0, 
+    252,   0,   0,   0, 252,   1, 
+      0,   0, 120,   2,   0,   0, 
+    248,   4,   0,   0, 104,   5, 
+      0,   0,  65, 111, 110,  57, 
+    188,   0,   0,   0, 188,   0, 
+      0,   0,   0,   2, 255, 255, 
+    132,   0,   0,   0,  56,   0, 
+      0,   0,   1,   0,  44,   0, 
+      0,   0,  56,   0,   0,   0, 
+     56,   0,   2,   0,  36,   0, 
+      0,   0,  56,   0,   3,   0, 
+      0,   0,   0,   0,   1,   0, 
+      0,   0,   1,   0,   1,   0, 
+      0,   0,   0,   0,   0,   0, 
+      1,   2, 255, 255,  31,   0, 
+      0,   2,   0,   0,   0, 128, 
+      0,   0,  15, 176,  31,   0, 
+      0,   2,   0,   0,   0, 144, 
+      0,   8,  15, 160,  31,   0, 
+      0,   2,   0,   0,   0, 144, 
+      1,   8,  15, 160,   1,   0, 
+      0,   2,   0,   0,   3, 128, 
+      0,   0, 235, 176,  66,   0, 
+      0,   3,   1,   0,  15, 128, 
+      0,   0, 228, 176,   1,   8, 
+    228, 160,  66,   0,   0,   3, 
+      0,   0,  15, 128,   0,   0, 
+    228, 128,   0,   8, 228, 160, 
+      5,   0,   0,   3,   1,   0, 
+     15, 128,   1,   0, 228, 128, 
+      0,   0,   0, 160,   5,   0, 
+      0,   3,   0,   0,  15, 128, 
+      0,   0, 255, 128,   1,   0, 
+    228, 128,   1,   0,   0,   2, 
+      0,   8,  15, 128,   0,   0, 
+    228, 128, 255, 255,   0,   0, 
+     83,  72,  68,  82, 248,   0, 
+      0,   0,  64,   0,   0,   0, 
+     62,   0,   0,   0,  89,   0, 
+      0,   4,  70, 142,  32,   0, 
+      0,   0,   0,   0,   2,   0, 
+      0,   0,  90,   0,   0,   3, 
+      0,  96,  16,   0,   0,   0, 
+      0,   0,  88,  24,   0,   4, 
+      0, 112,  16,   0,   0,   0, 
+      0,   0,  85,  85,   0,   0, 
+     88,  24,   0,   4,   0, 112, 
+     16,   0,   3,   0,   0,   0, 
+     85,  85,   0,   0,  98,  16, 
+      0,   3,  50,  16,  16,   0, 
+      1,   0,   0,   0,  98,  16, 
+      0,   3, 194,  16,  16,   0, 
+      1,   0,   0,   0, 101,   0, 
+      0,   3, 242,  32,  16,   0, 
+      0,   0,   0,   0, 104,   0, 
+      0,   2,   2,   0,   0,   0, 
+     69,   0,   0,   9, 242,   0, 
+     16,   0,   0,   0,   0,   0, 
+     70,  16,  16,   0,   1,   0, 
+      0,   0,  70, 126,  16,   0, 
+      0,   0,   0,   0,   0,  96, 
+     16,   0,   0,   0,   0,   0, 
+     56,   0,   0,   8, 242,   0, 
+     16,   0,   0,   0,   0,   0, 
+     70,  14,  16,   0,   0,   0, 
+      0,   0,   6, 128,  32,   0, 
+      0,   0,   0,   0,   1,   0, 
+      0,   0,  69,   0,   0,   9, 
+    242,   0,  16,   0,   1,   0, 
+      0,   0, 230,  26,  16,   0, 
+      1,   0,   0,   0,  70, 126, 
+     16,   0,   3,   0,   0,   0, 
+      0,  96,  16,   0,   0,   0, 
+      0,   0,  56,   0,   0,   7, 
+    242,  32,  16,   0,   0,   0, 
+      0,   0,  70,  14,  16,   0, 
+      0,   0,   0,   0, 246,  15, 
+     16,   0,   1,   0,   0,   0, 
+     62,   0,   0,   1,  83,  84, 
+     65,  84, 116,   0,   0,   0, 
+      5,   0,   0,   0,   2,   0, 
+      0,   0,   0,   0,   0,   0, 
+      3,   0,   0,   0,   2,   0, 
+      0,   0,   0,   0,   0,   0, 
+      0,   0,   0,   0,   1,   0, 
+      0,   0,   0,   0,   0,   0, 
+      0,   0,   0,   0,   0,   0, 
+      0,   0,   0,   0,   0,   0, 
+      0,   0,   0,   0,   0,   0, 
+      0,   0,   2,   0,   0,   0, 
+      0,   0,   0,   0,   0,   0, 
+      0,   0,   0,   0,   0,   0, 
+      0,   0,   0,   0,   0,   0, 
+      0,   0,   0,   0,   0,   0, 
+      0,   0,   0,   0,   0,   0, 
+      0,   0,   0,   0,   0,   0, 
+      0,   0,   0,   0,   0,   0, 
+      0,   0,   0,   0,   0,   0, 
+      0,   0,   0,   0,   0,   0, 
+      0,   0,  82,  68,  69,  70, 
+    120,   2,   0,   0,   1,   0, 
+      0,   0, 188,   0,   0,   0, 
+      4,   0,   0,   0,  28,   0, 
+      0,   0,   0,   4, 255, 255, 
+      0,   1,   0,   0,  69,   2, 
+      0,   0, 156,   0,   0,   0, 
+      3,   0,   0,   0,   0,   0, 
+      0,   0,   0,   0,   0,   0, 
+      0,   0,   0,   0,   0,   0, 
+      0,   0,   1,   0,   0,   0, 
+      1,   0,   0,   0, 165,   0, 
+      0,   0,   2,   0,   0,   0, 
+      5,   0,   0,   0,   4,   0, 
+      0,   0, 255, 255, 255, 255, 
+      0,   0,   0,   0,   1,   0, 
+      0,   0,  12,   0,   0,   0, 
+    170,   0,   0,   0,   2,   0, 
+      0,   0,   5,   0,   0,   0, 
+      4,   0,   0,   0, 255, 255, 
+    255, 255,   3,   0,   0,   0, 
+      1,   0,   0,   0,  13,   0, 
+      0,   0, 176,   0,   0,   0, 
+      0,   0,   0,   0,   0,   0, 
+      0,   0,   0,   0,   0,   0, 
+      0,   0,   0,   0,   0,   0, 
+      0,   0,   1,   0,   0,   0, 
+      0,   0,   0,   0, 115,  83, 
+     97, 109, 112, 108, 101, 114, 
+      0, 116,  82,  71,  66,   0, 
+    116,  77,  97, 115, 107,   0, 
+     36,  71, 108, 111,  98,  97, 
+    108, 115,   0, 171, 171, 171, 
+    176,   0,   0,   0,   8,   0, 
+      0,   0, 212,   0,   0,   0, 
+    224,   0,   0,   0,   0,   0, 
+      0,   0,   0,   0,   0,   0, 
+    148,   1,   0,   0,   0,   0, 
+      0,   0,  16,   0,   0,   0, 
+      0,   0,   0,   0, 160,   1, 
+      0,   0,   0,   0,   0,   0, 
+    176,   1,   0,   0,  16,   0, 
+      0,   0,   4,   0,   0,   0, 
+      2,   0,   0,   0, 192,   1, 
+      0,   0,   0,   0,   0,   0, 
+    208,   1,   0,   0,  32,   0, 
+      0,   0,  64,   0,   0,   0, 
+      0,   0,   0,   0, 224,   1, 
+      0,   0,   0,   0,   0,   0, 
+    240,   1,   0,   0,  96,   0, 
+      0,   0,  64,   0,   0,   0, 
+      0,   0,   0,   0, 224,   1, 
+      0,   0,   0,   0,   0,   0, 
+    252,   1,   0,   0, 160,   0, 
+      0,   0,  16,   0,   0,   0, 
+      0,   0,   0,   0, 160,   1, 
+      0,   0,   0,   0,   0,   0, 
+     16,   2,   0,   0, 176,   0, 
+      0,   0,  16,   0,   0,   0, 
+      0,   0,   0,   0,  32,   2, 
+      0,   0,   0,   0,   0,   0, 
+     48,   2,   0,   0, 192,   0, 
+      0,   0,  16,   0,   0,   0, 
+      0,   0,   0,   0,  32,   2, 
+      0,   0,   0,   0,   0,   0, 
+     59,   2,   0,   0, 208,   0, 
+      0,   0,  16,   0,   0,   0, 
+      0,   0,   0,   0,  32,   2, 
+      0,   0,   0,   0,   0,   0, 
+    102,  76,  97, 121, 101, 114, 
+     67, 111, 108, 111, 114,   0, 
+      1,   0,   3,   0,   1,   0, 
+      4,   0,   0,   0,   0,   0, 
+      0,   0,   0,   0, 102,  76, 
+     97, 121, 101, 114,  79, 112, 
+     97,  99, 105, 116, 121,   0, 
+    171, 171,   0,   0,   3,   0, 
+      1,   0,   1,   0,   0,   0, 
+      0,   0,   0,   0,   0,   0, 
+    109,  76,  97, 121, 101, 114, 
+     84, 114,  97, 110, 115, 102, 
+    111, 114, 109,   0,   3,   0, 
+      3,   0,   4,   0,   4,   0, 
+      0,   0,   0,   0,   0,   0, 
+      0,   0, 109,  80, 114, 111, 
+    106, 101,  99, 116, 105, 111, 
+    110,   0, 118,  82, 101, 110, 
+    100, 101, 114,  84,  97, 114, 
+    103, 101, 116,  79, 102, 102, 
+    115, 101, 116,   0, 118,  84, 
+    101, 120, 116, 117, 114, 101, 
+     67, 111, 111, 114, 100, 115, 
+      0, 171,   1,   0,   3,   0, 
+      1,   0,   4,   0,   0,   0, 
+      0,   0,   0,   0,   0,   0, 
+    118,  76,  97, 121, 101, 114, 
+     81, 117,  97, 100,   0, 118, 
+     77,  97, 115, 107,  81, 117, 
+     97, 100,   0,  77, 105,  99, 
+    114, 111, 115, 111, 102, 116, 
+     32,  40,  82,  41,  32,  72, 
+     76,  83,  76,  32,  83, 104, 
+     97, 100, 101, 114,  32,  67, 
+    111, 109, 112, 105, 108, 101, 
+    114,  32,  57,  46,  50,  57, 
+     46,  57,  53,  50,  46,  51, 
+     49,  49,  49,   0, 171, 171, 
+     73,  83,  71,  78, 104,   0, 
+      0,   0,   3,   0,   0,   0, 
+      8,   0,   0,   0,  80,   0, 
+      0,   0,   0,   0,   0,   0, 
+      1,   0,   0,   0,   3,   0, 
+      0,   0,   0,   0,   0,   0, 
+     15,   0,   0,   0,  92,   0, 
+      0,   0,   0,   0,   0,   0, 
+      0,   0,   0,   0,   3,   0, 
+      0,   0,   1,   0,   0,   0, 
+      3,   3,   0,   0,  92,   0, 
+      0,   0,   1,   0,   0,   0, 
+      0,   0,   0,   0,   3,   0, 
+      0,   0,   1,   0,   0,   0, 
+     12,  12,   0,   0,  83,  86, 
+     95,  80, 111, 115, 105, 116, 
+    105, 111, 110,   0,  84,  69, 
+     88,  67,  79,  79,  82,  68, 
+      0, 171, 171, 171,  79,  83, 
+     71,  78,  44,   0,   0,   0, 
+      1,   0,   0,   0,   8,   0, 
+      0,   0,  32,   0,   0,   0, 
+      0,   0,   0,   0,   0,   0, 
+      0,   0,   3,   0,   0,   0, 
+      0,   0,   0,   0,  15,   0, 
+      0,   0,  83,  86,  95,  84, 
+     97, 114, 103, 101, 116,   0, 
+    171, 171
+};
+#if 0
+//
+// Generated by Microsoft (R) HLSL Shader Compiler 9.29.952.3111
+//
+//
+//   fxc CompositorD3D11.fx -ERGBAShaderMask3D -Tps_4_0_level_9_3 -nologo
+//    -FhtmpShaderHeader -VnRGBAShaderMask3D
+//
+//
 // Buffer Definitions: 
 //
 // cbuffer $Globals
 // {
 //
 //   float4 fLayerColor;                // Offset:    0 Size:    16 [unused]
 //   float fLayerOpacity;               // Offset:   16 Size:     4
 //   float4x4 mLayerTransform;          // Offset:   32 Size:    64 [unused]
@@ -3957,28 +3993,28 @@ const BYTE RGBAShaderMask[] =
 // tRGB                              texture  float4          2d    0        1
 // tMask                             texture  float4          2d    3        1
 // $Globals                          cbuffer      NA          NA    0        1
 //
 //
 //
 // Input signature:
 //
-// Name                 Index   Mask Register SysValue  Format   Used
-// -------------------- ----- ------ -------- -------- ------- ------
-// SV_Position              0   xyzw        0      POS   float       
-// TEXCOORD                 0   xy          1     NONE   float   xy  
-// TEXCOORD                 1   xyz         2     NONE   float   xyz 
+// Name                 Index   Mask Register SysValue Format   Used
+// -------------------- ----- ------ -------- -------- ------ ------
+// SV_Position              0   xyzw        0      POS  float       
+// TEXCOORD                 0   xy          1     NONE  float   xy  
+// TEXCOORD                 1   xyz         2     NONE  float   xyz 
 //
 //
 // Output signature:
 //
-// Name                 Index   Mask Register SysValue  Format   Used
-// -------------------- ----- ------ -------- -------- ------- ------
-// SV_Target                0   xyzw        0   TARGET   float   xyzw
+// Name                 Index   Mask Register SysValue Format   Used
+// -------------------- ----- ------ -------- -------- ------ ------
+// SV_Target                0   xyzw        0   TARGET  float   xyzw
 //
 //
 // Constant buffer to DX9 shader constant mappings:
 //
 // Target Reg Buffer  Start Reg # of Regs        Data Conversion
 // ---------- ------- --------- --------- ----------------------
 // c0         cb0             1         1  ( FLT, FLT, FLT, FLT)
 //
@@ -4023,20 +4059,20 @@ sample r1.xyzw, v1.xyxx, t0.xyzw, s0
 mul r1.xyzw, r1.xyzw, cb0[1].xxxx
 mul o0.xyzw, r0.wwww, r1.xyzw
 ret 
 // Approximately 6 instruction slots used
 #endif
 
 const BYTE RGBAShaderMask3D[] =
 {
-     68,  88,  66,  67,  51, 245, 
-    244, 214, 206, 248,  79, 212, 
-     44,  24, 163, 203, 134,  21, 
-    209, 199,   1,   0,   0,   0, 
+     68,  88,  66,  67,  44,  91, 
+    221, 241,  68, 147, 240, 210, 
+    227, 186, 152,  41,  63, 147, 
+    120,  30,   1,   0,   0,   0, 
      24,   6,   0,   0,   6,   0, 
       0,   0,  56,   0,   0,   0, 
      24,   1,   0,   0,  64,   2, 
       0,   0, 188,   2,   0,   0, 
     116,   5,   0,   0, 228,   5, 
       0,   0,  65, 111, 110,  57, 
     216,   0,   0,   0, 216,   0, 
       0,   0,   0,   2, 255, 255, 
@@ -4133,17 +4169,17 @@ const BYTE RGBAShaderMask3D[] =
       1,   0,   0,   0,   0,   0, 
       0,   0,   0,   0,   0,   0, 
       0,   0,   0,   0,   0,   0, 
       0,   0,   0,   0,   0,   0, 
       0,   0,   0,   0,   2,   0, 
       0,   0,   0,   0,   0,   0, 
       0,   0,   0,   0,   0,   0, 
       0,   0,   0,   0,   0,   0, 
-      1,   0,   0,   0,   0,   0, 
+      0,   0,   0,   0,   0,   0, 
       0,   0,   0,   0,   0,   0, 
       0,   0,   0,   0,   0,   0, 
       0,   0,   0,   0,   0,   0, 
       0,   0,   0,   0,   0,   0, 
       0,   0,   0,   0,   0,   0, 
       0,   0,   0,   0,  82,  68, 
      69,  70, 176,   2,   0,   0, 
       1,   0,   0,   0, 244,   0, 
@@ -4253,19 +4289,19 @@ const BYTE RGBAShaderMask3D[] =
      97, 100,   0, 118,  77,  97, 
     115, 107,  81, 117,  97, 100, 
       0,  77, 105,  99, 114, 111, 
     115, 111, 102, 116,  32,  40, 
      82,  41,  32,  72,  76,  83, 
      76,  32,  83, 104,  97, 100, 
     101, 114,  32,  67, 111, 109, 
     112, 105, 108, 101, 114,  32, 
-     57,  46,  51,  48,  46,  57, 
-     50,  48,  48,  46,  50,  48, 
-     52,  57,  57,   0,  73,  83, 
+     57,  46,  50,  57,  46,  57, 
+     53,  50,  46,  51,  49,  49, 
+     49,   0, 171, 171,  73,  83, 
      71,  78, 104,   0,   0,   0, 
       3,   0,   0,   0,   8,   0, 
       0,   0,  80,   0,   0,   0, 
       0,   0,   0,   0,   1,   0, 
       0,   0,   3,   0,   0,   0, 
       0,   0,   0,   0,  15,   0, 
       0,   0,  92,   0,   0,   0, 
       0,   0,   0,   0,   0,   0, 
@@ -4286,20 +4322,23 @@ const BYTE RGBAShaderMask3D[] =
       0,   0,   0,   0,   0,   0, 
       3,   0,   0,   0,   0,   0, 
       0,   0,  15,   0,   0,   0, 
      83,  86,  95,  84,  97, 114, 
     103, 101, 116,   0, 171, 171
 };
 #if 0
 //
-// Generated by Microsoft (R) HLSL Shader Compiler 9.30.9200.20499
-//
-//
-///
+// Generated by Microsoft (R) HLSL Shader Compiler 9.29.952.3111
+//
+//
+//   fxc CompositorD3D11.fx -EYCbCrShaderMask -Tps_4_0_level_9_3 -nologo
+//    -FhtmpShaderHeader -VnYCbCrShaderMask
+//
+//
 // Buffer Definitions: 
 //
 // cbuffer $Globals
 // {
 //
 //   float4 fLayerColor;                // Offset:    0 Size:    16 [unused]
 //   float fLayerOpacity;               // Offset:   16 Size:     4
 //   float4x4 mLayerTransform;          // Offset:   32 Size:    64 [unused]
@@ -4322,28 +4361,28 @@ const BYTE RGBAShaderMask3D[] =
 // tCr                               texture  float4          2d    2        1
 // tMask                             texture  float4          2d    3        1
 // $Globals                          cbuffer      NA          NA    0        1
 //
 //
 //
 // Input signature:
 //
-// Name                 Index   Mask Register SysValue  Format   Used
-// -------------------- ----- ------ -------- -------- ------- ------
-// SV_Position              0   xyzw        0      POS   float       
-// TEXCOORD                 0   xy          1     NONE   float   xy  
-// TEXCOORD                 1     zw        1     NONE   float     zw
+// Name                 Index   Mask Register SysValue Format   Used
+// -------------------- ----- ------ -------- -------- ------ ------
+// SV_Position              0   xyzw        0      POS  float       
+// TEXCOORD                 0   xy          1     NONE  float   xy  
+// TEXCOORD                 1     zw        1     NONE  float     zw
 //
 //
 // Output signature:
 //
-// Name                 Index   Mask Register SysValue  Format   Used
-// -------------------- ----- ------ -------- -------- ------- ------
-// SV_Target                0   xyzw        0   TARGET   float   xyzw
+// Name                 Index   Mask Register SysValue Format   Used
+// -------------------- ----- ------ -------- -------- ------ ------
+// SV_Target                0   xyzw        0   TARGET  float   xyzw
 //
 //
 // Constant buffer to DX9 shader constant mappings:
 //
 // Target Reg Buffer  Start Reg # of Regs        Data Conversion
 // ---------- ------- --------- --------- ----------------------
 // c0         cb0             1         1  ( FLT, FLT, FLT, FLT)
 //
@@ -4365,28 +4404,28 @@ const BYTE RGBAShaderMask3D[] =
     def c2, 1.16400003, 2.01799989, 0.391000003, 1
     dcl t0
     dcl_2d s0
     dcl_2d s1
     dcl_2d s2
     dcl_2d s3
     texld r0, t0, s1
     texld r1, t0, s3
-    add r0.y, r1.x, c1.x
-    mul r0.yz, r0.y, c1.xzww
-    add r0.x, r0.x, c1.y
-    mad r0.z, r0.x, c2.x, -r0.z
-    mad r1.x, r0.x, c2.x, r0.y
+    add r0.x, r1.w, c1.x
+    mul r0.xy, r0.x, c1.zwzw
+    add r0.z, r0.w, c1.y
+    mad r0.y, r0.z, c2.x, -r0.y
+    mad r1.x, r0.z, c2.x, r0.x
     mov r2.xy, t0.wzzw
     texld r3, t0, s2
     texld r2, r2, s0
-    add r0.y, r3.x, c1.x
-    mad r1.y, r0.y, -c2.z, r0.z
-    mul r0.y, r0.y, c2.y
-    mad r1.z, r0.x, c2.x, r0.y
+    add r0.x, r3.w, c1.x
+    mad r1.y, r0.x, -c2.z, r0.y
+    mul r0.x, r0.x, c2.y
+    mad r1.z, r0.z, c2.x, r0.x
     mov r1.w, c2.w
     mul r0, r1, c0.x
     mul r0, r2.w, r0
     mov oC0, r0
 
 // approximately 18 instruction slots used (4 texture, 14 arithmetic)
 ps_4_0
 dcl_constantbuffer cb0[2], immediateIndexed
@@ -4395,41 +4434,41 @@ dcl_resource_texture2d (float,float,floa
 dcl_resource_texture2d (float,float,float,float) t1
 dcl_resource_texture2d (float,float,float,float) t2
 dcl_resource_texture2d (float,float,float,float) t3
 dcl_input_ps linear v1.xy
 dcl_input_ps linear v1.zw
 dcl_output o0.xyzw
 dcl_temps 3
 sample r0.xyzw, v1.xyxx, t2.xyzw, s0
-add r0.x, r0.x, l(-0.500000)
+add r0.x, r0.w, l(-0.500000)
 mul r0.xy, r0.xxxx, l(1.596000, 0.813000, 0.000000, 0.000000)
 sample r1.xyzw, v1.xyxx, t0.xyzw, s0
-add r0.z, r1.x, l(-0.062500)
+add r0.z, r1.w, l(-0.062500)
 mad r0.y, r0.z, l(1.164000), -r0.y
 mad r1.x, r0.z, l(1.164000), r0.x
 sample r2.xyzw, v1.xyxx, t1.xyzw, s0
-add r0.x, r2.x, l(-0.500000)
+add r0.x, r2.w, l(-0.500000)
 mad r1.y, -r0.x, l(0.391000), r0.y
 mul r0.x, r0.x, l(2.018000)
 mad r1.z, r0.z, l(1.164000), r0.x
 mov r1.w, l(1.000000)
 mul r0.xyzw, r1.xyzw, cb0[1].xxxx
 sample r1.xyzw, v1.zwzz, t3.xyzw, s0
 mul o0.xyzw, r0.xyzw, r1.wwww
 ret 
 // Approximately 17 instruction slots used
 #endif
 
 const BYTE YCbCrShaderMask[] =
 {
-     68,  88,  66,  67, 248,  68, 
-    121,  34,  27,  10,  35, 131, 
-     87, 186, 229, 112, 219,  20, 
-    149,  92,   1,   0,   0,   0, 
+     68,  88,  66,  67, 129,  98, 
+     44, 194,  35,  91, 102,  10, 
+    204, 216, 255, 140,  38, 205, 
+     76,  26,   1,   0,   0,   0, 
     168,   8,   0,   0,   6,   0, 
       0,   0,  56,   0,   0,   0, 
      24,   2,   0,   0, 196,   4, 
       0,   0,  64,   5,   0,   0, 
       4,   8,   0,   0, 116,   8, 
       0,   0,  65, 111, 110,  57, 
     216,   1,   0,   0, 216,   1, 
       0,   0,   0,   2, 255, 255, 
@@ -4462,50 +4501,50 @@ const BYTE YCbCrShaderMask[] =
      31,   0,   0,   2,   0,   0, 
       0, 144,   3,   8,  15, 160, 
      66,   0,   0,   3,   0,   0, 
      15, 128,   0,   0, 228, 176, 
       1,   8, 228, 160,  66,   0, 
       0,   3,   1,   0,  15, 128, 
       0,   0, 228, 176,   3,   8, 
     228, 160,   2,   0,   0,   3, 
-      0,   0,   2, 128,   1,   0, 
-      0, 128,   1,   0,   0, 160, 
+      0,   0,   1, 128,   1,   0, 
+    255, 128,   1,   0,   0, 160, 
       5,   0,   0,   3,   0,   0, 
-      6, 128,   0,   0,  85, 128, 
-      1,   0, 248, 160,   2,   0, 
-      0,   3,   0,   0,   1, 128, 
-      0,   0,   0, 128,   1,   0, 
+      3, 128,   0,   0,   0, 128, 
+      1,   0, 238, 160,   2,   0, 
+      0,   3,   0,   0,   4, 128, 
+      0,   0, 255, 128,   1,   0, 
      85, 160,   4,   0,   0,   4, 
-      0,   0,   4, 128,   0,   0, 
-      0, 128,   2,   0,   0, 160, 
-      0,   0, 170, 129,   4,   0, 
+      0,   0,   2, 128,   0,   0, 
+    170, 128,   2,   0,   0, 160, 
+      0,   0,  85, 129,   4,   0, 
       0,   4,   1,   0,   1, 128, 
-      0,   0,   0, 128,   2,   0, 
-      0, 160,   0,   0,  85, 128, 
+      0,   0, 170, 128,   2,   0, 
+      0, 160,   0,   0,   0, 128, 
       1,   0,   0,   2,   2,   0, 
       3, 128,   0,   0, 235, 176, 
      66,   0,   0,   3,   3,   0, 
      15, 128,   0,   0, 228, 176, 
       2,   8, 228, 160,  66,   0, 
       0,   3,   2,   0,  15, 128, 
       2,   0, 228, 128,   0,   8, 
     228, 160,   2,   0,   0,   3, 
-      0,   0,   2, 128,   3,   0, 
-      0, 128,   1,   0,   0, 160, 
+      0,   0,   1, 128,   3,   0, 
+    255, 128,   1,   0,   0, 160, 
       4,   0,   0,   4,   1,   0, 
-      2, 128,   0,   0,  85, 128, 
+      2, 128,   0,   0,   0, 128, 
       2,   0, 170, 161,   0,   0, 
-    170, 128,   5,   0,   0,   3, 
-      0,   0,   2, 128,   0,   0, 
-     85, 128,   2,   0,  85, 160, 
+     85, 128,   5,   0,   0,   3, 
+      0,   0,   1, 128,   0,   0, 
+      0, 128,   2,   0,  85, 160, 
       4,   0,   0,   4,   1,   0, 
-      4, 128,   0,   0,   0, 128, 
+      4, 128,   0,   0, 170, 128, 
       2,   0,   0, 160,   0,   0, 
-     85, 128,   1,   0,   0,   2, 
+      0, 128,   1,   0,   0,   2, 
       1,   0,   8, 128,   2,   0, 
     255, 160,   5,   0,   0,   3, 
       0,   0,  15, 128,   1,   0, 
     228, 128,   0,   0,   0, 160, 
       5,   0,   0,   3,   0,   0, 
      15, 128,   2,   0, 255, 128, 
       0,   0, 228, 128,   1,   0, 
       0,   2,   0,   8,  15, 128, 
@@ -4538,17 +4577,17 @@ const BYTE YCbCrShaderMask[] =
       3,   0,   0,   0,  69,   0, 
       0,   9, 242,   0,  16,   0, 
       0,   0,   0,   0,  70,  16, 
      16,   0,   1,   0,   0,   0, 
      70, 126,  16,   0,   2,   0, 
       0,   0,   0,  96,  16,   0, 
       0,   0,   0,   0,   0,   0, 
       0,   7,  18,   0,  16,   0, 
-      0,   0,   0,   0,  10,   0, 
+      0,   0,   0,   0,  58,   0, 
      16,   0,   0,   0,   0,   0, 
       1,  64,   0,   0,   0,   0, 
       0, 191,  56,   0,   0,  10, 
      50,   0,  16,   0,   0,   0, 
       0,   0,   6,   0,  16,   0, 
       0,   0,   0,   0,   2,  64, 
       0,   0, 186,  73, 204,  63, 
     197,  32,  80,  63,   0,   0, 
@@ -4556,17 +4595,17 @@ const BYTE YCbCrShaderMask[] =
      69,   0,   0,   9, 242,   0, 
      16,   0,   1,   0,   0,   0, 
      70,  16,  16,   0,   1,   0, 
       0,   0,  70, 126,  16,   0, 
       0,   0,   0,   0,   0,  96, 
      16,   0,   0,   0,   0,   0, 
       0,   0,   0,   7,  66,   0, 
      16,   0,   0,   0,   0,   0, 
-     10,   0,  16,   0,   1,   0, 
+     58,   0,  16,   0,   1,   0, 
       0,   0,   1,  64,   0,   0, 
       0,   0, 128, 189,  50,   0, 
       0,  10,  34,   0,  16,   0, 
       0,   0,   0,   0,  42,   0, 
      16,   0,   0,   0,   0,   0, 
       1,  64,   0,   0, 244, 253, 
     148,  63,  26,   0,  16, 128, 
      65,   0,   0,   0,   0,   0, 
@@ -4579,17 +4618,17 @@ const BYTE YCbCrShaderMask[] =
       0,   0,  69,   0,   0,   9, 
     242,   0,  16,   0,   2,   0, 
       0,   0,  70,  16,  16,   0, 
       1,   0,   0,   0,  70, 126, 
      16,   0,   1,   0,   0,   0, 
       0,  96,  16,   0,   0,   0, 
       0,   0,   0,   0,   0,   7, 
      18,   0,  16,   0,   0,   0, 
-      0,   0,  10,   0,  16,   0, 
+      0,   0,  58,   0,  16,   0, 
       2,   0,   0,   0,   1,  64, 
       0,   0,   0,   0,   0, 191, 
      50,   0,   0,  10,  34,   0, 
      16,   0,   1,   0,   0,   0, 
      10,   0,  16, 128,  65,   0, 
       0,   0,   0,   0,   0,   0, 
       1,  64,   0,   0,  39,  49, 
     200,  62,  26,   0,  16,   0, 
@@ -4633,17 +4672,17 @@ const BYTE YCbCrShaderMask[] =
       0,   0,   1,   0,   0,   0, 
       0,   0,   0,   0,   0,   0, 
       0,   0,   0,   0,   0,   0, 
       0,   0,   0,   0,   0,   0, 
       0,   0,   0,   0,   0,   0, 
       4,   0,   0,   0,   0,   0, 
       0,   0,   0,   0,   0,   0, 
       0,   0,   0,   0,   0,   0, 
-      0,   0,   2,   0,   0,   0, 
+      0,   0,   1,   0,   0,   0, 
       0,   0,   0,   0,   0,   0, 
       0,   0,   0,   0,   0,   0, 
       0,   0,   0,   0,   0,   0, 
       0,   0,   0,   0,   0,   0, 
       0,   0,   0,   0,   0,   0, 
       0,   0,   0,   0,   0,   0, 
      82,  68,  69,  70, 188,   2, 
       0,   0,   1,   0,   0,   0, 
@@ -4755,19 +4794,19 @@ const BYTE YCbCrShaderMask[] =
      81, 117,  97, 100,   0, 118, 
      77,  97, 115, 107,  81, 117, 
      97, 100,   0,  77, 105,  99, 
     114, 111, 115, 111, 102, 116, 
      32,  40,  82,  41,  32,  72, 
      76,  83,  76,  32,  83, 104, 
      97, 100, 101, 114,  32,  67, 
     111, 109, 112, 105, 108, 101, 
-    114,  32,  57,  46,  51,  48, 
-     46,  57,  50,  48,  48,  46, 
-     50,  48,  52,  57,  57,   0, 
+    114,  32,  57,  46,  50,  57, 
+     46,  57,  53,  50,  46,  51, 
+     49,  49,  49,   0, 171, 171, 
      73,  83,  71,  78, 104,   0, 
       0,   0,   3,   0,   0,   0, 
       8,   0,   0,   0,  80,   0, 
       0,   0,   0,   0,   0,   0, 
       1,   0,   0,   0,   3,   0, 
       0,   0,   0,   0,   0,   0, 
      15,   0,   0,   0,  92,   0, 
       0,   0,   0,   0,   0,   0, 
@@ -4789,20 +4828,23 @@ const BYTE YCbCrShaderMask[] =
       0,   0,   3,   0,   0,   0, 
       0,   0,   0,   0,  15,   0, 
       0,   0,  83,  86,  95,  84, 
      97, 114, 103, 101, 116,   0, 
     171, 171
 };
 #if 0
 //
-// Generated by Microsoft (R) HLSL Shader Compiler 9.30.9200.20499
-//
-//
-///
+// Generated by Microsoft (R) HLSL Shader Compiler 9.29.952.3111
+//
+//
+//   fxc CompositorD3D11.fx -EComponentAlphaShaderMask -Tps_4_0_level_9_3
+//    -nologo -FhtmpShaderHeader -VnComponentAlphaShaderMask
+//
+//
 // Buffer Definitions: 
 //
 // cbuffer $Globals
 // {
 //
 //   float4 fLayerColor;                // Offset:    0 Size:    16 [unused]
 //   float fLayerOpacity;               // Offset:   16 Size:     4
 //   float4x4 mLayerTransform;          // Offset:   32 Size:    64 [unused]
@@ -4824,29 +4866,29 @@ const BYTE YCbCrShaderMask[] =
 // tRGBWhite                         texture  float4          2d    1        1
 // tMask                             texture  float4          2d    3        1
 // $Globals                          cbuffer      NA          NA    0        1
 //
 //
 //
 // Input signature:
 //
-// Name                 Index   Mask Register SysValue  Format   Used
-// -------------------- ----- ------ -------- -------- ------- ------
-// SV_Position              0   xyzw        0      POS   float       
-// TEXCOORD                 0   xy          1     NONE   float   xy  
-// TEXCOORD                 1     zw        1     NONE   float     zw
+// Name                 Index   Mask Register SysValue Format   Used
+// -------------------- ----- ------ -------- -------- ------ ------
+// SV_Position              0   xyzw        0      POS  float       
+// TEXCOORD                 0   xy          1     NONE  float   xy  
+// TEXCOORD                 1     zw        1     NONE  float     zw
 //
 //
 // Output signature:
 //
-// Name                 Index   Mask Register SysValue  Format   Used
-// -------------------- ----- ------ -------- -------- ------- ------
-// SV_Target                0   xyzw        0   TARGET   float   xyzw
-// SV_Target                1   xyzw        1   TARGET   float   xyzw
+// Name                 Index   Mask Register SysValue Format   Used
+// -------------------- ----- ------ -------- -------- ------ ------
+// SV_Target                0   xyzw        0   TARGET  float   xyzw
+// SV_Target                1   xyzw        1   TARGET  float   xyzw
 //
 //
 // Constant buffer to DX9 shader constant mappings:
 //
 // Target Reg Buffer  Start Reg # of Regs        Data Conversion
 // ---------- ------- --------- --------- ----------------------
 // c0         cb0             1         1  ( FLT, FLT, FLT, FLT)
 //
@@ -4903,20 +4945,20 @@ mul r2.x, r2.w, cb0[1].x
 mul o0.xyzw, r1.xyzw, r2.xxxx
 mul o1.xyzw, r0.xyzw, r2.xxxx
 ret 
 // Approximately 10 instruction slots used
 #endif
 
 const BYTE ComponentAlphaShaderMask[] =
 {
-     68,  88,  66,  67, 150, 158, 
-    242, 249, 229,  57, 247, 147, 
-     10,   1,  42,  77,  39,  42, 
-    220, 133,   1,   0,   0,   0, 
+     68,  88,  66,  67, 136,  77, 
+     10,  16, 135, 130, 127, 127, 
+     44,  35, 233, 219,  89, 184, 
+    173, 170,   1,   0,   0,   0, 
      20,   7,   0,   0,   6,   0, 
       0,   0,  56,   0,   0,   0, 
     124,   1,   0,   0,  52,   3, 
       0,   0, 176,   3,   0,   0, 
      88,   6,   0,   0, 200,   6, 
       0,   0,  65, 111, 110,  57, 
      60,   1,   0,   0,  60,   1, 
       0,   0,   0,   2, 255, 255, 
@@ -5053,17 +5095,17 @@ const BYTE ComponentAlphaShaderMask[] =
       0,   0,   0,   0,   1,   0, 
       0,   0,   0,   0,   0,   0, 
       0,   0,   0,   0,   0,   0, 
       0,   0,   0,   0,   0,   0, 
       0,   0,   0,   0,   0,   0, 
       0,   0,   3,   0,   0,   0, 
       0,   0,   0,   0,   0,   0, 
       0,   0,   0,   0,   0,   0, 
-      0,   0,   0,   0,   3,   0, 
+      0,   0,   0,   0,   2,   0, 
       0,   0,   0,   0,   0,   0, 
       0,   0,   0,   0,   0,   0, 
       0,   0,   0,   0,   0,   0, 
       0,   0,   0,   0,   0,   0, 
       0,   0,   0,   0,   0,   0, 
       0,   0,   0,   0,   0,   0, 
       0,   0,  82,  68,  69,  70, 
     160,   2,   0,   0,   1,   0, 
@@ -5171,19 +5213,19 @@ const BYTE ComponentAlphaShaderMask[] =
      97, 100,   0, 118,  77,  97, 
     115, 107,  81, 117,  97, 100, 
       0,  77, 105,  99, 114, 111, 
     115, 111, 102, 116,  32,  40, 
      82,  41,  32,  72,  76,  83, 
      76,  32,  83, 104,  97, 100, 
     101, 114,  32,  67, 111, 109, 
     112, 105, 108, 101, 114,  32, 
-     57,  46,  51,  48,  46,  57, 
-     50,  48,  48,  46,  50,  48, 
-     52,  57,  57,   0,  73,  83, 
+     57,  46,  50,  57,  46,  57, 
+     53,  50,  46,  51,  49,  49, 
+     49,   0, 171, 171,  73,  83, 
      71,  78, 104,   0,   0,   0, 
       3,   0,   0,   0,   8,   0, 
       0,   0,  80,   0,   0,   0, 
       0,   0,   0,   0,   1,   0, 
       0,   0,   3,   0,   0,   0, 
       0,   0,   0,   0,  15,   0, 
       0,   0,  92,   0,   0,   0, 
       0,   0,   0,   0,   0,   0, 
--- a/gfx/layers/d3d11/TextureD3D11.cpp
+++ b/gfx/layers/d3d11/TextureD3D11.cpp
@@ -491,17 +491,17 @@ DeprecatedTextureHostYCbCrD3D11::UpdateI
   gfxIntSize gfxCbCrSize = yuvDeserializer.GetCbCrSize();
 
   gfxIntSize size = yuvDeserializer.GetYSize();
 
   D3D11_SUBRESOURCE_DATA initData;
   initData.pSysMem = yuvDeserializer.GetYData();
   initData.SysMemPitch = yuvDeserializer.GetYStride();
 
-  CD3D11_TEXTURE2D_DESC desc(DXGI_FORMAT_R8_UNORM, size.width, size.height,
+  CD3D11_TEXTURE2D_DESC desc(DXGI_FORMAT_A8_UNORM, size.width, size.height,
                              1, 1, D3D11_BIND_SHADER_RESOURCE,
                              D3D11_USAGE_IMMUTABLE);
 
   mDevice->CreateTexture2D(&desc, &initData, byRef(mTextures[0]));
 
   initData.pSysMem = yuvDeserializer.GetCbData();
   initData.SysMemPitch = yuvDeserializer.GetCbCrStride();
   desc.Width = yuvDeserializer.GetCbCrSize().width;
--- a/gfx/layers/d3d9/ImageLayerD3D9.cpp
+++ b/gfx/layers/d3d9/ImageLayerD3D9.cpp
@@ -179,41 +179,41 @@ static void AllocateTexturesYCbCr(Planar
     nsRefPtr<IDirect3DTexture9> tmpCbTexture;
     nsRefPtr<IDirect3DTexture9> tmpCrTexture;
     // D3D9Ex does not support the managed pool, could use dynamic textures
     // here. But since an Image is immutable static textures are probably a
     // better idea.
 
     HRESULT hr;
     hr = aDevice->CreateTexture(data->mYSize.width, data->mYSize.height,
-                                1, 0, D3DFMT_L8, D3DPOOL_DEFAULT,
+                                1, 0, D3DFMT_A8, D3DPOOL_DEFAULT,
                                 getter_AddRefs(backendData->mYTexture), nullptr);
     if (!FAILED(hr)) {
       hr = aDevice->CreateTexture(data->mCbCrSize.width, data->mCbCrSize.height,
-                                  1, 0, D3DFMT_L8, D3DPOOL_DEFAULT,
+                                  1, 0, D3DFMT_A8, D3DPOOL_DEFAULT,
                                   getter_AddRefs(backendData->mCbTexture), nullptr);
     }
     if (!FAILED(hr)) {
       hr = aDevice->CreateTexture(data->mCbCrSize.width, data->mCbCrSize.height,
-                                  1, 0, D3DFMT_L8, D3DPOOL_DEFAULT,
+                                  1, 0, D3DFMT_A8, D3DPOOL_DEFAULT,
                                   getter_AddRefs(backendData->mCrTexture), nullptr);
     }
     if (!FAILED(hr)) {
       hr = aDevice->CreateTexture(data->mYSize.width, data->mYSize.height,
-                                  1, 0, D3DFMT_L8, D3DPOOL_SYSTEMMEM,
+                                  1, 0, D3DFMT_A8, D3DPOOL_SYSTEMMEM,
                                   getter_AddRefs(tmpYTexture), nullptr);
     }
     if (!FAILED(hr)) {
       hr = aDevice->CreateTexture(data->mCbCrSize.width, data->mCbCrSize.height,
-                                  1, 0, D3DFMT_L8, D3DPOOL_SYSTEMMEM,
+                                  1, 0, D3DFMT_A8, D3DPOOL_SYSTEMMEM,
                                   getter_AddRefs(tmpCbTexture), nullptr);
     }
     if (!FAILED(hr)) {
       hr = aDevice->CreateTexture(data->mCbCrSize.width, data->mCbCrSize.height,
-                                  1, 0, D3DFMT_L8, D3DPOOL_SYSTEMMEM,
+                                  1, 0, D3DFMT_A8, D3DPOOL_SYSTEMMEM,
                                   getter_AddRefs(tmpCrTexture), nullptr);
     }
 
     if (FAILED(hr)) {
       aManager->ReportFailure(NS_LITERAL_CSTRING("PlanarYCbCrImageD3D9::AllocateTextures(): Failed to create texture (isD3D9Ex)"),
                               hr);
       return;
     }
@@ -222,26 +222,26 @@ static void AllocateTexturesYCbCr(Planar
     tmpCbTexture->GetSurfaceLevel(0, getter_AddRefs(tmpSurfaceCb));
     tmpCrTexture->GetSurfaceLevel(0, getter_AddRefs(tmpSurfaceCr));
     tmpSurfaceY->LockRect(&lockrectY, nullptr, 0);
     tmpSurfaceCb->LockRect(&lockrectCb, nullptr, 0);
     tmpSurfaceCr->LockRect(&lockrectCr, nullptr, 0);
   } else {
     HRESULT hr;
     hr = aDevice->CreateTexture(data->mYSize.width, data->mYSize.height,
-                                1, 0, D3DFMT_L8, D3DPOOL_MANAGED,
+                                1, 0, D3DFMT_A8, D3DPOOL_MANAGED,
                                 getter_AddRefs(backendData->mYTexture), nullptr);
     if (!FAILED(hr)) {
       aDevice->CreateTexture(data->mCbCrSize.width, data->mCbCrSize.height,
-                             1, 0, D3DFMT_L8, D3DPOOL_MANAGED,
+                             1, 0, D3DFMT_A8, D3DPOOL_MANAGED,
                              getter_AddRefs(backendData->mCbTexture), nullptr);
     }
     if (!FAILED(hr)) {
       aDevice->CreateTexture(data->mCbCrSize.width, data->mCbCrSize.height,
-                             1, 0, D3DFMT_L8, D3DPOOL_MANAGED,
+                             1, 0, D3DFMT_A8, D3DPOOL_MANAGED,
                              getter_AddRefs(backendData->mCrTexture), nullptr);
     }
 
     if (FAILED(hr)) {
       aManager->ReportFailure(NS_LITERAL_CSTRING("PlanarYCbCrImageD3D9::AllocateTextures(): Failed to create texture (!isD3D9Ex)"),
                               hr);
       return;
     }
--- a/gfx/layers/d3d9/LayerManagerD3D9Shaders.h
+++ b/gfx/layers/d3d9/LayerManagerD3D9Shaders.h
@@ -1,12 +1,8 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
 #if 0
 //
 // Generated by Microsoft (R) HLSL Shader Compiler 9.29.952.3111
 //
 //   fxc LayerManagerD3D9Shaders.hlsl -ELayerQuadVS -nologo -FhtmpShaderHeader
 //    -VnLayerQuadVS
 //
 //
@@ -580,22 +576,22 @@ const BYTE RGBShaderPS[] =
     def c2, 0.813000023, 0.391000003, 2.01799989, 1
     dcl t0.xy
     dcl_2d s0
     dcl_2d s1
     dcl_2d s2
     texld r0, t0, s2
     texld r1, t0, s0
     texld r2, t0, s1
-    add r0.x, r0.x, c1.x
-    add r0.y, r1.x, c1.y
+    add r0.x, r0.w, c1.x
+    add r0.y, r1.w, c1.y
     mul r0.y, r0.y, c1.z
     mad r0.z, r0.x, -c2.x, r0.y
     mad r1.x, r0.x, c1.w, r0.y
-    add r0.x, r2.x, c1.x
+    add r0.x, r2.w, c1.x
     mad r1.y, r0.x, -c2.y, r0.z
     mad r1.z, r0.x, c2.z, r0.y
     mov r1.w, c2.w
     mul r0, r1, c0.x
     mov oC0, r0
 
 // approximately 14 instruction slots used (3 texture, 11 arithmetic)
 #endif
@@ -669,32 +665,32 @@ const BYTE YCbCrShaderPS[] =
       0,   0, 228, 176,   2,   8, 
     228, 160,  66,   0,   0,   3, 
       1,   0,  15, 128,   0,   0, 
     228, 176,   0,   8, 228, 160, 
      66,   0,   0,   3,   2,   0, 
      15, 128,   0,   0, 228, 176, 
       1,   8, 228, 160,   2,   0, 
       0,   3,   0,   0,   1, 128, 
-      0,   0,   0, 128,   1,   0, 
+      0,   0, 255, 128,   1,   0, 
       0, 160,   2,   0,   0,   3, 
       0,   0,   2, 128,   1,   0, 
-      0, 128,   1,   0,  85, 160, 
+    255, 128,   1,   0,  85, 160, 
       5,   0,   0,   3,   0,   0, 
       2, 128,   0,   0,  85, 128, 
       1,   0, 170, 160,   4,   0, 
       0,   4,   0,   0,   4, 128, 
       0,   0,   0, 128,   2,   0, 
       0, 161,   0,   0,  85, 128, 
       4,   0,   0,   4,   1,   0, 
       1, 128,   0,   0,   0, 128, 
       1,   0, 255, 160,   0,   0, 
      85, 128,   2,   0,   0,   3, 
       0,   0,   1, 128,   2,   0, 
-      0, 128,   1,   0,   0, 160, 
+    255, 128,   1,   0,   0, 160, 
       4,   0,   0,   4,   1,   0, 
       2, 128,   0,   0,   0, 128, 
       2,   0,  85, 161,   0,   0, 
     170, 128,   4,   0,   0,   4, 
       1,   0,   4, 128,   0,   0, 
       0, 128,   2,   0, 170, 160, 
       0,   0,  85, 128,   1,   0, 
       0,   2,   1,   0,   8, 128, 
@@ -1750,22 +1746,22 @@ const BYTE RGBShaderPSMask[] =
     dcl_2d s0
     dcl_2d s1
     dcl_2d s2
     dcl_2d s3
     texld r0, t0, s2
     texld r1, t0, s0
     texld r2, t0, s1
     texld r3, t1, s3
-    add r0.x, r0.x, c1.x
-    add r0.y, r1.x, c1.y
+    add r0.x, r0.w, c1.x
+    add r0.y, r1.w, c1.y
     mul r0.y, r0.y, c1.z
     mad r0.z, r0.x, -c2.x, r0.y
     mad r1.x, r0.x, c1.w, r0.y
-    add r0.x, r2.x, c1.x
+    add r0.x, r2.w, c1.x
     mad r1.y, r0.x, -c2.y, r0.z
     mad r1.z, r0.x, c2.z, r0.y
     mov r1.w, c2.w
     mul r0, r1, c0.x
     mul r0, r3.w, r0
     mov oC0, r0
 
 // approximately 16 instruction slots used (4 texture, 12 arithmetic)
@@ -1854,32 +1850,32 @@ const BYTE YCbCrShaderPSMask[] =
       0,   0, 228, 176,   0,   8, 
     228, 160,  66,   0,   0,   3, 
       2,   0,  15, 128,   0,   0, 
     228, 176,   1,   8, 228, 160, 
      66,   0,   0,   3,   3,   0, 
      15, 128,   1,   0, 228, 176, 
       3,   8, 228, 160,   2,   0, 
       0,   3,   0,   0,   1, 128, 
-      0,   0,   0, 128,   1,   0, 
+      0,   0, 255, 128,   1,   0, 
       0, 160,   2,   0,   0,   3, 
       0,   0,   2, 128,   1,   0, 
-      0, 128,   1,   0,  85, 160, 
+    255, 128,   1,   0,  85, 160, 
       5,   0,   0,   3,   0,   0, 
       2, 128,   0,   0,  85, 128, 
       1,   0, 170, 160,   4,   0, 
       0,   4,   0,   0,   4, 128, 
       0,   0,   0, 128,   2,   0, 
       0, 161,   0,   0,  85, 128, 
       4,   0,   0,   4,   1,   0, 
       1, 128,   0,   0,   0, 128, 
       1,   0, 255, 160,   0,   0, 
      85, 128,   2,   0,   0,   3, 
       0,   0,   1, 128,   2,   0, 
-      0, 128,   1,   0,   0, 160, 
+    255, 128,   1,   0,   0, 160, 
       4,   0,   0,   4,   1,   0, 
       2, 128,   0,   0,   0, 128, 
       2,   0,  85, 161,   0,   0, 
     170, 128,   4,   0,   0,   4, 
       1,   0,   4, 128,   0,   0, 
       0, 128,   2,   0, 170, 160, 
       0,   0,  85, 128,   1,   0, 
       0,   2,   1,   0,   8, 128, 
--- a/gfx/layers/d3d9/LayerManagerD3D9Shaders.hlsl
+++ b/gfx/layers/d3d9/LayerManagerD3D9Shaders.hlsl
@@ -184,19 +184,19 @@ float4 RGBShader(const VS_OUTPUT aVertex
   return result * fLayerOpacity;
 }
 
 float4 YCbCrShader(const VS_OUTPUT aVertex) : COLOR
 {
   float4 yuv;
   float4 color;
 
-  yuv.r = tex2D(s2DCr, aVertex.vTexCoords).r - 0.5;
-  yuv.g = tex2D(s2DY, aVertex.vTexCoords).r - 0.0625;
-  yuv.b = tex2D(s2DCb, aVertex.vTexCoords).r - 0.5;
+  yuv.r = tex2D(s2DCr, aVertex.vTexCoords).a - 0.5;
+  yuv.g = tex2D(s2DY, aVertex.vTexCoords).a - 0.0625;
+  yuv.b = tex2D(s2DCb, aVertex.vTexCoords).a - 0.5;
 
   color.r = yuv.g * 1.164 + yuv.r * 1.596;
   color.g = yuv.g * 1.164 - 0.813 * yuv.r - 0.391 * yuv.b;
   color.b = yuv.g * 1.164 + yuv.b * 2.018;
   color.a = 1.0f;
  
   return color * fLayerOpacity;
 }
@@ -250,19 +250,19 @@ float4 RGBShaderMask(const VS_OUTPUT_MAS
   return result * fLayerOpacity * mask;
 }
 
 float4 YCbCrShaderMask(const VS_OUTPUT_MASK aVertex) : COLOR
 {
   float4 yuv;
   float4 color;
 
-  yuv.r = tex2D(s2DCr, aVertex.vTexCoords).r - 0.5;
-  yuv.g = tex2D(s2DY, aVertex.vTexCoords).r - 0.0625;
-  yuv.b = tex2D(s2DCb, aVertex.vTexCoords).r - 0.5;
+  yuv.r = tex2D(s2DCr, aVertex.vTexCoords).a - 0.5;
+  yuv.g = tex2D(s2DY, aVertex.vTexCoords).a - 0.0625;
+  yuv.b = tex2D(s2DCb, aVertex.vTexCoords).a - 0.5;
 
   color.r = yuv.g * 1.164 + yuv.r * 1.596;
   color.g = yuv.g * 1.164 - 0.813 * yuv.r - 0.391 * yuv.b;
   color.b = yuv.g * 1.164 + yuv.b * 2.018;
   color.a = 1.0f;
  
   float2 maskCoords = aVertex.vMaskCoords;
   float mask = tex2D(s2DMask, maskCoords).a;
--- a/gfx/layers/d3d9/TextureD3D9.cpp
+++ b/gfx/layers/d3d9/TextureD3D9.cpp
@@ -353,27 +353,27 @@ DeprecatedTextureHostYCbCrD3D9::UpdateIm
   gfxIntSize size = yuvDeserializer.GetYSize();
   mSize = IntSize(size.width, size.height);
   mStereoMode = yuvDeserializer.GetStereoMode();
 
   mTextures[0] = DataToTexture(mDevice,
                                yuvDeserializer.GetYData(),
                                yuvDeserializer.GetYStride(),
                                size,
-                               D3DFMT_L8, 1);
+                               D3DFMT_A8, 1);
   mTextures[1] = DataToTexture(mDevice,
                                yuvDeserializer.GetCbData(),
                                yuvDeserializer.GetCbCrStride(),
                                gfxCbCrSize,
-                               D3DFMT_L8, 1);
+                               D3DFMT_A8, 1);
   mTextures[2] = DataToTexture(mDevice,
                                yuvDeserializer.GetCrData(),
                                yuvDeserializer.GetCbCrStride(),
                                gfxCbCrSize,
-                               D3DFMT_L8, 1);
+                               D3DFMT_A8, 1);
 }
 
 // aTexture should be in SYSTEMMEM, returns a texture in the default
 // pool (that is, in video memory).
 static TemporaryRef<IDirect3DTexture9>
 TextureToTexture(IDirect3DDevice9* aDevice,
                  IDirect3DTexture9* aTexture,
                  const IntSize& aSize,
--- a/gfx/layers/ipc/CompositableTransactionParent.cpp
+++ b/gfx/layers/ipc/CompositableTransactionParent.cpp
@@ -31,16 +31,27 @@ class BasicTiledLayerBuffer;
 class Compositor;
 
 template<typename T>
 CompositableHost* AsCompositable(const T& op)
 {
   return static_cast<CompositableParent*>(op.compositableParent())->GetCompositableHost();
 }
 
+// This function can in some cases fail and return false without it being a bug.
+// This can theoretically happen if the ImageBridge sends frames before
+// we created the layer tree. Since we can't enforce that the layer
+// tree is already created before ImageBridge operates, there isn't much
+// we can do about it, but in practice it is very rare.
+// Typically when a tab with a video is dragged from a window to another,
+// there can be a short time when the video is still sending frames
+// asynchonously while the layer tree is not reconstructed. It's not a
+// big deal.
+// Note that Layers transactions do not need to call this because they always
+// schedule the composition, in LayerManagerComposite::EndTransaction.
 template<typename T>
 bool ScheduleComposition(const T& op)
 {
   CompositableParent* comp = static_cast<CompositableParent*>(op.compositableParent());
   if (!comp || !comp->GetCompositorID()) {
     return false;
   }
   CompositorParent* cp
@@ -128,17 +139,17 @@ CompositableParentManager::ReceiveCompos
 
         SurfaceDescriptor newBack;
         bool shouldRecomposite = compositable->Update(descriptor, &newBack);
         if (IsSurfaceDescriptorValid(newBack)) {
           replyv.push_back(OpTextureSwap(compositableParent, nullptr,
                                          op.textureId(), newBack));
         }
 
-        if (shouldRecomposite) {
+        if (IsAsync() && shouldRecomposite) {
           ScheduleComposition(op);
         }
       }
 
       if (layer) {
         RenderTraceInvalidateEnd(layer, "FF00FF");
       }
 
@@ -216,18 +227,18 @@ CompositableParentManager::ReceiveCompos
         break;
       }
       CompositableHost* compositable = AsCompositable(op);
       RefPtr<TextureHost> tex = compositable->GetTextureHost(op.textureID());
 
       MOZ_ASSERT(tex.get());
       compositable->UseTextureHost(tex);
 
-      if (!ScheduleComposition(op)) {
-        NS_WARNING("could not find a compositor to schedule composition");
+      if (IsAsync()) {
+        ScheduleComposition(op);
       }
       break;
     }
     case CompositableOperation::TOpAddTexture: {
       const OpAddTexture& op = aEdit.get_OpAddTexture();
       if (op.textureID() == 0) {
         NS_WARNING("Invalid texture ID");
         break;
--- a/gfx/layers/ipc/CompositableTransactionParent.h
+++ b/gfx/layers/ipc/CompositableTransactionParent.h
@@ -26,14 +26,20 @@ class CompositableParentManager : public
 {
 protected:
   /**
    * Handle the IPDL messages that affect PCompositable actors.
    */
   bool ReceiveCompositableUpdate(const CompositableOperation& aEdit,
                                  EditReplyVector& replyv);
   bool IsOnCompositorSide() const MOZ_OVERRIDE { return true; }
+
+  /**
+   * Return true if this protocol is asynchronous with respect to the content
+   * thread (ImageBridge for instance).
+   */
+  virtual bool IsAsync() const { return false; }
 };
 
 } // namespace
 } // namespace
 
 #endif
--- a/gfx/layers/ipc/ImageBridgeParent.h
+++ b/gfx/layers/ipc/ImageBridgeParent.h
@@ -56,16 +56,18 @@ public:
 
   virtual bool
   DeallocPGrallocBufferParent(PGrallocBufferParent* actor) MOZ_OVERRIDE;
 
   // PImageBridge
   virtual bool RecvUpdate(const EditArray& aEdits, EditReplyArray* aReply);
   virtual bool RecvUpdateNoSwap(const EditArray& aEdits);
 
+  virtual bool IsAsync() const MOZ_OVERRIDE { return true; }
+
   PCompositableParent* AllocPCompositableParent(const TextureInfo& aInfo,
                                                 uint64_t*) MOZ_OVERRIDE;
   bool DeallocPCompositableParent(PCompositableParent* aActor) MOZ_OVERRIDE;
 
   bool RecvStop() MOZ_OVERRIDE;
 
   MessageLoop * GetMessageLoop();
 
--- a/gfx/ycbcr/moz.build
+++ b/gfx/ycbcr/moz.build
@@ -6,17 +6,17 @@
 
 EXPORTS += [
     'chromium_types.h',
     'ycbcr_to_rgb565.h',
     'yuv_convert.h',
     'yuv_row.h',
 ]
 
-SOURCES += [
+UNIFIED_SOURCES += [
     'ycbcr_to_rgb565.cpp',
     'yuv_convert.cpp',
     'yuv_row_c.cpp',
     'yuv_row_table.cpp',
 ]
 
 if CONFIG['INTEL_ARCHITECTURE']:
     SOURCES += [
--- a/image/decoders/icon/moz.build
+++ b/image/decoders/icon/moz.build
@@ -5,17 +5,17 @@
 # file, You can obtain one at http://mozilla.org/MPL/2.0/.
 
 XPIDL_SOURCES += [
     'nsIIconURI.idl',
 ]
 
 XPIDL_MODULE = 'imgicon'
 
-SOURCES += [
+UNIFIED_SOURCES += [
     'nsIconModule.cpp',
     'nsIconProtocolHandler.cpp',
     'nsIconURI.cpp',
 ]
 
 LIBRARY_NAME = 'imgicon'
 
 FAIL_ON_WARNINGS = True
--- a/ipc/nfc/Nfc.cpp
+++ b/ipc/nfc/Nfc.cpp
@@ -8,21 +8,21 @@
 
 #include "mozilla/ipc/Nfc.h"
 
 #include <fcntl.h>
 #include <sys/socket.h>
 #include <sys/un.h>
 
 #undef LOG
-#if defined(MOZ_WIDGET_GONK)
+#if (defined(MOZ_WIDGET_GONK) && defined(DEBUG))
 #include <android/log.h>
 #define LOG(args...)  __android_log_print(ANDROID_LOG_INFO, "Gonk", args)
 #else
-#define LOG(args...)  printf(args);
+#define LOG(args...)
 #endif
 
 #include "jsfriendapi.h"
 #include "nsThreadUtils.h" // For NS_IsMainThread.
 
 USING_WORKERS_NAMESPACE
 using namespace mozilla::ipc;
 
--- a/js/public/GCAPI.h
+++ b/js/public/GCAPI.h
@@ -20,17 +20,16 @@ namespace JS {
     D(API)                                      \
     D(MAYBEGC)                                  \
     D(DESTROY_RUNTIME)                          \
     D(DESTROY_CONTEXT)                          \
     D(LAST_DITCH)                               \
     D(TOO_MUCH_MALLOC)                          \
     D(ALLOC_TRIGGER)                            \
     D(DEBUG_GC)                                 \
-    D(DEBUG_MODE_GC)                            \
     D(TRANSPLANT)                               \
     D(RESET)                                    \
     D(OUT_OF_NURSERY)                           \
     D(EVICT_NURSERY)                            \
     D(FULL_STORE_BUFFER)                        \
                                                 \
     /* These are reserved for future use. */    \
     D(RESERVED0)                                \
--- a/js/src/builtin/Eval.cpp
+++ b/js/src/builtin/Eval.cpp
@@ -427,16 +427,22 @@ js::DirectEval(JSContext *cx, const Call
 
 bool
 js::IsBuiltinEvalForScope(JSObject *scopeChain, const Value &v)
 {
     return scopeChain->global().getOriginalEval() == v;
 }
 
 bool
+js::IsBuiltinEvalForScope(GlobalObject *global, const Value &v)
+{
+    return global->getOriginalEval() == v;
+}
+
+bool
 js::IsAnyBuiltinEval(JSFunction *fun)
 {
     return fun->maybeNative() == IndirectEval;
 }
 
 JSPrincipals *
 js::PrincipalsForCompiledCode(const CallReceiver &call, JSContext *cx)
 {
--- a/js/src/builtin/Eval.h
+++ b/js/src/builtin/Eval.h
@@ -33,16 +33,21 @@ DirectEvalFromIon(JSContext *cx,
                   HandleValue thisValue, HandleString str,
                   jsbytecode * pc, MutableHandleValue vp);
 
 // True iff 'v' is the built-in eval function for the global object that
 // corresponds to 'scopeChain'.
 extern bool
 IsBuiltinEvalForScope(JSObject *scopeChain, const Value &v);
 
+class GlobalObject;
+
+extern bool
+IsBuiltinEvalForScope(GlobalObject *global, const Value &v);
+
 // True iff fun is a built-in eval function.
 extern bool
 IsAnyBuiltinEval(JSFunction *fun);
 
 // Return the principals to assign to code compiled for a call to
 // eval or the Function constructor.
 extern JSPrincipals *
 PrincipalsForCompiledCode(const CallReceiver &call, JSContext *cx);
--- a/js/src/config/config.mk
+++ b/js/src/config/config.mk
@@ -340,19 +340,16 @@ ifeq ($(FINAL_LIBRARY),xul)
   endif
   LIBXUL_LIBRARY := 1
 endif
 
 ifdef LIBXUL_LIBRARY
 ifdef IS_COMPONENT
 $(error IS_COMPONENT is set, but is not compatible with LIBXUL_LIBRARY)
 endif
-ifdef MODULE_NAME
-$(error MODULE_NAME is $(MODULE_NAME) but MODULE_NAME and LIBXUL_LIBRARY are not compatible)
-endif
 FORCE_STATIC_LIB=1
 endif
 
 # If we are building this component into an extension/xulapp, it cannot be
 # statically linked. In the future we may want to add a xulapp meta-component
 # build option.
 
 ifdef XPI_NAME
--- a/js/src/config/rules.mk
+++ b/js/src/config/rules.mk
@@ -452,30 +452,16 @@ endif
 # This will strip out symbols that the component should not be
 # exporting from the .dynsym section.
 #
 ifdef IS_COMPONENT
 EXTRA_DSO_LDOPTS += $(MOZ_COMPONENTS_VERSION_SCRIPT_LDFLAGS)
 endif # IS_COMPONENT
 
 #
-# Enforce the requirement that MODULE_NAME must be set
-# for components in static builds
-#
-ifdef IS_COMPONENT
-ifdef EXPORT_LIBRARY
-ifndef FORCE_SHARED_LIB
-ifndef MODULE_NAME
-$(error MODULE_NAME is required for components which may be used in static builds)
-endif
-endif
-endif
-endif
-
-#
 # MacOS X specific stuff
 #
 
 ifeq ($(OS_ARCH),Darwin)
 ifdef SHARED_LIBRARY
 ifdef IS_COMPONENT
 EXTRA_DSO_LDOPTS	+= -bundle
 else
--- a/js/src/configure.in
+++ b/js/src/configure.in
@@ -667,25 +667,22 @@ esac
 fi
 
 AC_SUBST(MACOSX_DEPLOYMENT_TARGET)
 
 dnl ========================================================
 dnl = Mac OS X SDK support
 dnl ========================================================
 MACOS_SDK_DIR=
-NEXT_ROOT=
 MOZ_ARG_WITH_STRING(macos-sdk,
 [  --with-macos-sdk=dir    Location of platform SDK to use (Mac OS X only)],
     MACOS_SDK_DIR=$withval)
 
 dnl MACOS_SDK_DIR will be set to the SDK location whenever one is in use.
-dnl NEXT_ROOT will be set and exported only if it's needed.
 AC_SUBST(MACOS_SDK_DIR)
-AC_SUBST(NEXT_ROOT)
 
 if test "$MACOS_SDK_DIR"; then
   dnl Sync this section with the ones in NSPR and NSS.
   dnl Changes to the cross environment here need to be accounted for in
   dnl the libIDL checks (below) and xpidl build.
 
   if test ! -d "$MACOS_SDK_DIR"; then
     AC_MSG_ERROR([SDK not found.  When using --with-macos-sdk, you must
--- a/js/src/frontend/Parser.cpp
+++ b/js/src/frontend/Parser.cpp
@@ -2122,16 +2122,19 @@ Parser<FullParseHandler>::functionArgsAn
                 return false;
             }
 
             outerpc->blockidGen = funpc.blockidGen;
 
             // Advance this parser over tokens processed by the syntax parser.
             parser->tokenStream.tell(&position);
             tokenStream.seek(position, parser->tokenStream);
+
+            // Update the end position of the parse node.
+            pn->pn_pos.end = tokenStream.currentToken().pos.end;
         }
 
         if (!addFreeVariablesFromLazyFunction(fun, pc))
             return false;
 
         pn->pn_blockid = outerpc->blockid();
         PropagateTransitiveParseFlags(funbox, outerpc->sc);
         return true;
--- a/js/src/gc/Zone.cpp
+++ b/js/src/gc/Zone.cpp
@@ -221,23 +221,18 @@ Zone::discardJitCode(FreeOp *fop)
             /*
              * Use counts for scripts are reset on GC. After discarding code we
              * need to let it warm back up to get information such as which
              * opcodes are setting array holes or accessing getter properties.
              */
             script->resetUseCount();
         }
 
-        for (CompartmentsInZoneIter comp(this); !comp.done(); comp.next()) {
-            /* Free optimized baseline stubs. */
-            if (comp->jitCompartment())
-                comp->jitCompartment()->optimizedStubSpace()->free();
-
-            comp->types.clearCompilerOutputs(fop);
-        }
+        for (CompartmentsInZoneIter comp(this); !comp.done(); comp.next())
+            jit::FinishDiscardJitCode(fop, comp);
     }
 #endif
 }
 
 uint64_t
 Zone::gcNumber()
 {
     // Zones in use by exclusive threads are not collected, and threads using
new file mode 100644
--- /dev/null
+++ b/js/src/jit-test/tests/debug/Script-getLineOffsets-07.js
@@ -0,0 +1,19 @@
+// Lazy scripts should correctly report line offsets
+
+var g = newGlobal();
+var dbg = new Debugger();
+
+g.eval("// Header comment\n" +   // <- line 6 in this file
+       "\n" +
+       "\n" +
+       "function f(n) {\n" +     // <- line 9 in this file
+       "    var foo = '!';\n" +
+       "}");
+
+dbg.addDebuggee(g);
+var scripts = dbg.findScripts();
+for (var i = 0; i < scripts.length; i++) {
+  // Nothing should have offsets for the deffun on line 9 if lazy scripts
+  // correctly update the position.
+  assertEq(scripts[i].getLineOffsets(9).length, 0);
+}
--- a/js/src/jit/BaselineIC.cpp
+++ b/js/src/jit/BaselineIC.cpp
@@ -3876,28 +3876,31 @@ TryAttachGetElemStub(JSContext *cx, Hand
         // Check for NativeObject[id] shape-optimizable accesses.
         if (rhs.isString()) {
             if (!TryAttachNativeGetElemStub(cx, script, pc, stub, obj, rhs))
                 return false;
         }
     }
 
     // Check for TypedArray[int] => Number accesses.
-    if (obj->is<TypedArrayObject>() && rhs.isInt32() && res.isNumber() &&
+    if (obj->is<TypedArrayObject>() && rhs.isNumber() && res.isNumber() &&
         !TypedArrayGetElemStubExists(stub, obj))
     {
         // Don't attach CALLELEM stubs for accesses on typed array expected to yield numbers.
 #if JS_HAS_NO_SUCH_METHOD
         if (isCallElem)
             return true;
 #endif
 
         Rooted<TypedArrayObject*> tarr(cx, &obj->as<TypedArrayObject>());
-        if (!cx->runtime()->jitSupportsFloatingPoint && TypedArrayRequiresFloatingPoint(tarr))
+        if (!cx->runtime()->jitSupportsFloatingPoint &&
+            (TypedArrayRequiresFloatingPoint(tarr) || rhs.isDouble()))
+        {
             return true;
+        }
 
         IonSpew(IonSpew_BaselineIC, "  Generating GetElem(TypedArray[Int32]) stub");
         ICGetElem_TypedArray::Compiler compiler(cx, tarr->lastProperty(), tarr->type());
         ICStub *typedArrayStub = compiler.getStub(compiler.getStubSpace(script));
         if (!typedArrayStub)
             return false;
 
         stub->addNewStub(typedArrayStub);
@@ -4497,26 +4500,43 @@ ICGetElem_Dense::Compiler::generateStubC
 // GetElem_TypedArray
 //
 
 bool
 ICGetElem_TypedArray::Compiler::generateStubCode(MacroAssembler &masm)
 {
     Label failure;
     masm.branchTestObject(Assembler::NotEqual, R0, &failure);
-    masm.branchTestInt32(Assembler::NotEqual, R1, &failure);
 
     GeneralRegisterSet regs(availableGeneralRegs(2));
     Register scratchReg = regs.takeAny();
 
     // Unbox R0 and shape guard.
     Register obj = masm.extractObject(R0, ExtractTemp0);
     masm.loadPtr(Address(BaselineStubReg, ICGetElem_TypedArray::offsetOfShape()), scratchReg);
     masm.branchTestObjShape(Assembler::NotEqual, obj, scratchReg, &failure);
 
+    // Ensure the index is an integer.
+    if (cx->runtime()->jitSupportsFloatingPoint) {
+        Label isInt32;
+        masm.branchTestInt32(Assembler::Equal, R1, &isInt32);
+        {
+            // If the index is a double, try to convert it to int32. It's okay
+            // to convert -0 to 0: the shape check ensures the object is a typed
+            // array so the difference is not observable.
+            masm.branchTestDouble(Assembler::NotEqual, R1, &failure);
+            masm.unboxDouble(R1, FloatReg0);
+            masm.convertDoubleToInt32(FloatReg0, scratchReg, &failure, /* negZeroCheck = */false);
+            masm.tagValue(JSVAL_TYPE_INT32, scratchReg, R1);
+        }
+        masm.bind(&isInt32);
+    } else {
+        masm.branchTestInt32(Assembler::NotEqual, R1, &failure);
+    }
+
     // Unbox key.
     Register key = masm.extractInt32(R1, ExtractTemp1);
 
     // Bounds check.
     masm.unboxInt32(Address(obj, TypedArrayObject::lengthOffset()), scratchReg);
     masm.branch32(Assembler::BelowOrEqual, scratchReg, key, &failure);
 
     // Load the elements vector.
@@ -4935,24 +4955,27 @@ DoSetElemFallback(JSContext *cx, Baselin
 
                 stub->addNewStub(denseStub);
             }
         }
 
         return true;
     }
 
-    if (obj->is<TypedArrayObject>() && index.isInt32() && rhs.isNumber()) {
+    if (obj->is<TypedArrayObject>() && index.isNumber() && rhs.isNumber()) {
         Rooted<TypedArrayObject*> tarr(cx, &obj->as<TypedArrayObject>());
-        if (!cx->runtime()->jitSupportsFloatingPoint && TypedArrayRequiresFloatingPoint(tarr))
+        if (!cx->runtime()->jitSupportsFloatingPoint &&
+            (TypedArrayRequiresFloatingPoint(tarr) || index.isDouble()))
+        {
             return true;
+        }
 
         uint32_t len = tarr->length();
-        int32_t idx = index.toInt32();
-        bool expectOutOfBounds = (idx < 0) || (static_cast<uint32_t>(idx) >= len);
+        double idx = index.toNumber();
+        bool expectOutOfBounds = (idx < 0 || idx >= double(len));
 
         if (!TypedArraySetElemStubExists(stub, tarr, expectOutOfBounds)) {
             // Remove any existing TypedArraySetElemStub that doesn't handle out-of-bounds
             if (expectOutOfBounds)
                 RemoveExistingTypedArraySetElemStub(cx, stub, tarr);
 
             IonSpew(IonSpew_BaselineIC,
                     "  Generating SetElem_TypedArray stub (shape=%p, type=%u, oob=%s)",
@@ -5335,26 +5358,43 @@ ICSetElemDenseAddCompiler::generateStubC
 // SetElem_TypedArray
 //
 
 bool
 ICSetElem_TypedArray::Compiler::generateStubCode(MacroAssembler &masm)
 {
     Label failure;
     masm.branchTestObject(Assembler::NotEqual, R0, &failure);
-    masm.branchTestInt32(Assembler::NotEqual, R1, &failure);
 
     GeneralRegisterSet regs(availableGeneralRegs(2));
     Register scratchReg = regs.takeAny();
 
     // Unbox R0 and shape guard.
     Register obj = masm.extractObject(R0, ExtractTemp0);
     masm.loadPtr(Address(BaselineStubReg, ICSetElem_TypedArray::offsetOfShape()), scratchReg);
     masm.branchTestObjShape(Assembler::NotEqual, obj, scratchReg, &failure);
 
+    // Ensure the index is an integer.
+    if (cx->runtime()->jitSupportsFloatingPoint) {
+        Label isInt32;
+        masm.branchTestInt32(Assembler::Equal, R1, &isInt32);
+        {
+            // If the index is a double, try to convert it to int32. It's okay
+            // to convert -0 to 0: the shape check ensures the object is a typed
+            // array so the difference is not observable.
+            masm.branchTestDouble(Assembler::NotEqual, R1, &failure);
+            masm.unboxDouble(R1, FloatReg0);
+            masm.convertDoubleToInt32(FloatReg0, scratchReg, &failure, /* negZeroCheck = */false);
+            masm.tagValue(JSVAL_TYPE_INT32, scratchReg, R1);
+        }
+        masm.bind(&isInt32);
+    } else {
+        masm.branchTestInt32(Assembler::NotEqual, R1, &failure);
+    }
+
     // Unbox key.
     Register key = masm.extractInt32(R1, ExtractTemp1);
 
     // Bounds check.
     Label oobWrite;
     masm.unboxInt32(Address(obj, TypedArrayObject::lengthOffset()), scratchReg);
     masm.branch32(Assembler::BelowOrEqual, scratchReg, key,
                   expectOutOfBounds_ ? &oobWrite : &failure);
--- a/js/src/jit/CompileInfo.h
+++ b/js/src/jit/CompileInfo.h
@@ -10,17 +10,17 @@
 #include "jsfun.h"
 
 #include "jit/Registers.h"
 
 namespace js {
 namespace jit {
 
 inline unsigned
-StartArgSlot(JSScript *script, JSFunction *fun)
+StartArgSlot(JSScript *script)
 {
     // Reserved slots:
     // Slot 0: Scope chain.
     // Slot 1: Return value.
 
     // When needed:
     // Slot 2: Argumentsobject.
 
@@ -32,17 +32,17 @@ inline unsigned
 CountArgSlots(JSScript *script, JSFunction *fun)
 {
     // Slot x + 0: This value.
     // Slot x + 1: Argument 1.
     // ...
     // Slot x + n: Argument n.
 
     // Note: when updating this, please also update the assert in SnapshotWriter::startFrame
-    return StartArgSlot(script, fun) + (fun ? fun->nargs + 1 : 0);
+    return StartArgSlot(script) + (fun ? fun->nargs + 1 : 0);
 }
 
 // Contains information about the compilation source for IR being generated.
 class CompileInfo
 {
   public:
     CompileInfo(JSScript *script, JSFunction *fun, jsbytecode *osrPc, bool constructing,
                 ExecutionMode executionMode)
@@ -53,17 +53,17 @@ class CompileInfo
 
         // The function here can flow in from anywhere so look up the canonical function to ensure that
         // we do not try to embed a nursery pointer in jit-code.
         if (fun_) {
             fun_ = fun_->nonLazyScript()->function();
             JS_ASSERT(fun_->isTenured());
         }
 
-        nimplicit_ = StartArgSlot(script, fun)              /* scope chain and argument obj */
+        nimplicit_ = StartArgSlot(script)                   /* scope chain and argument obj */
                    + (fun ? 1 : 0);                         /* this */
         nargs_ = fun ? fun->nargs : 0;
         nlocals_ = script->nfixed;
         nstack_ = script->nslots - script->nfixed;
         nslots_ = nimplicit_ + nargs_ + nlocals_ + nstack_;
     }
 
     CompileInfo(unsigned nlocals, ExecutionMode executionMode)
@@ -204,17 +204,17 @@ class CompileInfo
         return firstLocalSlot() + nlocals();
     }
     uint32_t stackSlot(uint32_t i) const {
         return firstStackSlot() + i;
     }
 
     uint32_t startArgSlot() const {
         JS_ASSERT(script());
-        return StartArgSlot(script(), fun());
+        return StartArgSlot(script());
     }
     uint32_t endArgSlot() const {
         JS_ASSERT(script());
         return CountArgSlots(script(), fun());
     }
 
     uint32_t totalSlots() const {
         JS_ASSERT(script() && fun());
--- a/js/src/jit/Ion.cpp
+++ b/js/src/jit/Ion.cpp
@@ -2371,25 +2371,30 @@ InvalidateActivation(FreeOp *fop, uint8_
         IonSpew(IonSpew_Invalidate, "   ! Invalidate ionScript %p (ref %u) -> patching osipoint %p",
                 ionScript, ionScript->refcount(), (void *) osiPatchPoint.raw());
         Assembler::patchWrite_NearCall(osiPatchPoint, invalidateEpilogue);
     }
 
     IonSpew(IonSpew_Invalidate, "END invalidating activation");
 }
 
+static void
+StopOffThreadCompilation(JSCompartment *comp)
+{
+    if (!comp->jitCompartment())
+        return;
+    CancelOffThreadIonCompile(comp, nullptr);
+    FinishAllOffThreadCompilations(comp->jitCompartment());
+}
+
 void
 jit::InvalidateAll(FreeOp *fop, Zone *zone)
 {
-    for (CompartmentsInZoneIter comp(zone); !comp.done(); comp.next()) {
-        if (!comp->jitCompartment())
-            continue;
-        CancelOffThreadIonCompile(comp, nullptr);
-        FinishAllOffThreadCompilations(comp->jitCompartment());
-    }
+    for (CompartmentsInZoneIter comp(zone); !comp.done(); comp.next())
+        StopOffThreadCompilation(comp);
 
     for (JitActivationIterator iter(fop->runtime()); !iter.done(); ++iter) {
         if (iter.activation()->compartment()->zone() == zone) {
             IonContext ictx(CompileRuntime::get(fop->runtime()));
             AutoFlushCache afc("InvalidateAll", fop->runtime()->jitRuntime());
             IonSpew(IonSpew_Invalidate, "Invalidating all frames for GC");
             InvalidateActivation(fop, iter.jitTop(), true);
         }
@@ -2539,16 +2544,26 @@ jit::FinishInvalidation(FreeOp *fop, JSS
     if (script->hasIonScript())
         FinishInvalidationOf(fop, script, script->ionScript(), false);
 
     if (script->hasParallelIonScript())
         FinishInvalidationOf(fop, script, script->parallelIonScript(), true);
 }
 
 void
+jit::FinishDiscardJitCode(FreeOp *fop, JSCompartment *comp)
+{
+    // Free optimized baseline stubs.
+    if (comp->jitCompartment())
+        comp->jitCompartment()->optimizedStubSpace()->free();
+
+    comp->types.clearCompilerOutputs(fop);
+}
+
+void
 jit::MarkValueFromIon(JSRuntime *rt, Value *vp)
 {
     gc::MarkValueUnbarriered(&rt->gcMarker, vp, "write barrier");
 }
 
 void
 jit::MarkShapeFromIon(JSRuntime *rt, Shape **shapep)
 {
@@ -2726,8 +2741,67 @@ jit::TraceIonScripts(JSTracer* trc, JSSc
         jit::IonScript::Trace(trc, script->ionScript());
 
     if (script->hasParallelIonScript())
         jit::IonScript::Trace(trc, script->parallelIonScript());
 
     if (script->hasBaselineScript())
         jit::BaselineScript::Trace(trc, script->baselineScript());
 }
+
+AutoDebugModeInvalidation::~AutoDebugModeInvalidation()
+{
+    MOZ_ASSERT(!!comp_ != !!zone_);
+
+    if (needInvalidation_ == NoNeed)
+        return;
+
+    // Invalidate the stack if any compartments toggled from on->off, because
+    // we allow scripts to be on stack when turning off debug mode.
+    bool invalidateStack = needInvalidation_ == ToggledOff;
+    Zone *zone = zone_ ? zone_ : comp_->zone();
+    JSRuntime *rt = zone->runtimeFromMainThread();
+    FreeOp *fop = rt->defaultFreeOp();
+
+    if (comp_) {
+        StopOffThreadCompilation(comp_);
+    } else {
+        for (CompartmentsInZoneIter comp(zone_); !comp.done(); comp.next())
+            StopOffThreadCompilation(comp);
+    }
+
+    if (invalidateStack) {
+        jit::MarkActiveBaselineScripts(zone);
+
+        for (JitActivationIterator iter(rt); !iter.done(); ++iter) {
+            JSCompartment *comp = iter.activation()->compartment();
+            if ((comp_ && comp_ == comp) ||
+                (zone_ && zone_ == comp->zone() && comp->principals))
+            {
+                IonContext ictx(CompileRuntime::get(rt));
+                AutoFlushCache afc("AutoDebugModeInvalidation", rt->jitRuntime());
+                IonSpew(IonSpew_Invalidate, "Invalidating frames for debug mode toggle");
+                InvalidateActivation(fop, iter.jitTop(), true);
+            }
+        }
+    }
+
+    for (gc::CellIter i(zone, gc::FINALIZE_SCRIPT); !i.done(); i.next()) {
+        JSScript *script = i.get<JSScript>();
+        if ((comp_ && script->compartment() == comp_) ||
+            (zone_ && script->compartment()->principals))
+        {
+            FinishInvalidation(fop, script);
+            FinishDiscardBaselineScript(fop, script);
+            // script->clearAnalysis();
+            script->resetUseCount();
+        } else if (script->hasBaselineScript()) {
+            script->baselineScript()->resetActive();
+        }
+    }
+
+    if (comp_) {
+        FinishDiscardJitCode(fop, comp_);
+    } else {
+        for (CompartmentsInZoneIter comp(zone_); !comp.done(); comp.next())
+            FinishDiscardJitCode(fop, comp);
+    }
+}
--- a/js/src/jit/IonBuilder.cpp
+++ b/js/src/jit/IonBuilder.cpp
@@ -276,21 +276,16 @@ IonBuilder::canEnterInlinedFunction(JSFu
 bool
 IonBuilder::canInlineTarget(JSFunction *target, CallInfo &callInfo)
 {
     if (!target->isInterpreted()) {
         IonSpew(IonSpew_Inlining, "Cannot inline due to non-interpreted");
         return false;
     }
 
-    if (target->getParent() != &script()->global()) {
-        IonSpew(IonSpew_Inlining, "Cannot inline due to scope mismatch");
-        return false;
-    }
-
     // Allow constructing lazy scripts when performing the definite properties
     // analysis, as baseline has not been used to warm the caller up yet.
     if (target->isInterpreted() && info().executionMode() == DefinitePropertiesAnalysis) {
         if (!target->getOrCreateScript(analysisContext))
             return false;
 
         RootedScript script(analysisContext, target->nonLazyScript());
         if (!script->hasBaselineScript() && script->canBaselineCompile()) {
@@ -4557,18 +4552,18 @@ IonBuilder::createCallObject(MDefinition
 {
     // Get a template CallObject that we'll use to generate inline object
     // creation.
     CallObject *templateObj = inspector->templateCallObject();
 
     // If the CallObject needs dynamic slots, allocate those now.
     MInstruction *slots;
     if (templateObj->hasDynamicSlots()) {
-        size_t nslots = JSObject::dynamicSlotsCount(templateObj->numFixedSlots(),
-                                                    templateObj->slotSpan());
+        size_t nslots = JSObject::dynamicSlotsCount(templateObj->numFixedSlotsForCompilation(),
+                                                    templateObj->lastProperty()->slotSpan(templateObj->getClass()));
         slots = MNewSlots::New(alloc(), nslots);
     } else {
         slots = MConstant::New(alloc(), NullValue());
     }
     current->add(slots);
 
     // Allocate the actual object. It is important that no intervening
     // instructions could potentially bailout, thus leaking the dynamic slots
@@ -4587,18 +4582,18 @@ IonBuilder::createCallObject(MDefinition
     current->add(MStoreFixedSlot::New(alloc(), callObj, CallObject::enclosingScopeSlot(), scope));
     current->add(MStoreFixedSlot::New(alloc(), callObj, CallObject::calleeSlot(), callee));
 
     // Initialize argument slots.
     for (AliasedFormalIter i(script()); i; i++) {
         unsigned slot = i.scopeSlot();
         unsigned formal = i.frameIndex();
         MDefinition *param = current->getSlot(info().argSlotUnchecked(formal));
-        if (slot >= templateObj->numFixedSlots())
-            current->add(MStoreSlot::New(alloc(), slots, slot - templateObj->numFixedSlots(), param));
+        if (slot >= templateObj->numFixedSlotsForCompilation())
+            current->add(MStoreSlot::New(alloc(), slots, slot - templateObj->numFixedSlotsForCompilation(), param));
         else
             current->add(MStoreFixedSlot::New(alloc(), callObj, slot, param));
     }
 
     return callObj;
 }
 
 MDefinition *
@@ -4653,25 +4648,24 @@ IonBuilder::getSingletonPrototype(JSFunc
 MDefinition *
 IonBuilder::createThisScriptedSingleton(JSFunction *target, MDefinition *callee)
 {
     // Get the singleton prototype (if exists)
     JSObject *proto = getSingletonPrototype(target);
     if (!proto)
         return nullptr;
 
-    if (!target->nonLazyScript()->types)
-        return nullptr;
-
     JSObject *templateObject = inspector->getTemplateObject(pc);
     if (!templateObject || !templateObject->is<JSObject>())
         return nullptr;
     if (templateObject->getProto() != proto)
         return nullptr;
 
+    if (!target->nonLazyScript()->types)
+        return nullptr;
     if (!types::TypeScript::ThisTypes(target->nonLazyScript())->hasType(types::Type::ObjectType(templateObject)))
         return nullptr;
 
     // For template objects with NewScript info, the appropriate allocation
     // kind to use may change due to dynamic property adds. In these cases
     // calling Ion code will be invalidated, but any baseline template object
     // may be stale. Update to the correct template object in this case.
     types::TypeObject *templateType = templateObject->type();
@@ -5302,19 +5296,19 @@ IonBuilder::jsop_eval(uint32_t argc)
 
         // Try to pattern match 'eval(v + "()")'. In this case v is likely a
         // name on the scope chain and the eval is performing a call on that
         // value. Use a dynamic scope chain lookup rather than a full eval.
         if (string->isConcat() &&
             string->getOperand(1)->isConstant() &&
             string->getOperand(1)->toConstant()->value().isString())
         {
-            JSString *str = string->getOperand(1)->toConstant()->value().toString();
-
-            if (str->isLinear() && StringEqualsAscii(&str->asLinear(), "()")) {
+            JSAtom *atom = &string->getOperand(1)->toConstant()->value().toString()->asAtom();
+
+            if (StringEqualsAscii(atom, "()")) {
                 MDefinition *name = string->getOperand(0);
                 MInstruction *dynamicName = MGetDynamicName::New(alloc(), scopeChain, name);
                 current->add(dynamicName);
 
                 MInstruction *thisv = MPassArg::New(alloc(), thisValue);
                 current->add(thisv);
 
                 current->push(dynamicName);
@@ -5482,17 +5476,17 @@ IonBuilder::jsop_initelem_array()
 bool
 IonBuilder::jsop_initprop(PropertyName *name)
 {
     MDefinition *value = current->pop();
     MDefinition *obj = current->peek(-1);
 
     JSObject *templateObject = obj->toNewObject()->templateObject();
 
-    Shape *shape = templateObject->nativeLookupPure(name);
+    Shape *shape = templateObject->lastProperty()->searchLinear(NameToId(name));
 
     if (!shape) {
         // JSOP_NEWINIT becomes an MNewObject without preconfigured properties.
         MInitProp *init = MInitProp::New(alloc(), obj, name, value);
         current->add(init);
         return resumeAfter(init);
     }
 
@@ -6322,19 +6316,16 @@ bool
 IonBuilder::setStaticName(JSObject *staticObject, PropertyName *name)
 {
     jsid id = NameToId(name);
 
     JS_ASSERT(staticObject->is<GlobalObject>() || staticObject->is<CallObject>());
 
     MDefinition *value = current->peek(-1);
 
-    if (staticObject->watched())
-        return jsop_setprop(name);
-
     types::TypeObjectKey *staticType = types::TypeObjectKey::get(staticObject);
     if (staticType->unknownProperties())
         return jsop_setprop(name);
 
     types::HeapTypeSetKey property = staticType->property(id);
     if (!property.maybeTypes() ||
         !property.maybeTypes()->definiteProperty() ||
         property.configured(constraints(), staticType))
@@ -6729,17 +6720,17 @@ IonBuilder::getElemTryTypedStatic(bool *
     if (!obj->resultTypeSet())
         return true;
 
     JSObject *tarrObj = obj->resultTypeSet()->getSingleton();
     if (!tarrObj)
         return true;
 
     TypedArrayObject *tarr = &tarrObj->as<TypedArrayObject>();
-    ArrayBufferView::ViewType viewType = JS_GetArrayBufferViewType(tarr);
+    ArrayBufferView::ViewType viewType = (ArrayBufferView::ViewType) tarr->type();
 
     // LoadTypedArrayElementStatic currently treats uint32 arrays as int32.
     if (viewType == ArrayBufferView::TYPE_UINT32)
         return true;
 
     MDefinition *ptr = convertShiftToMaskForStaticTypedArray(index, viewType);
     if (!ptr)
         return true;
@@ -7286,17 +7277,17 @@ IonBuilder::setElemTryTypedStatic(bool *
 
     if (!object->resultTypeSet())
         return true;
     JSObject *tarrObj = object->resultTypeSet()->getSingleton();
     if (!tarrObj)
         return true;
 
     TypedArrayObject *tarr = &tarrObj->as<TypedArrayObject>();
-    ArrayBufferView::ViewType viewType = JS_GetArrayBufferViewType(tarr);
+    ArrayBufferView::ViewType viewType = (ArrayBufferView::ViewType) tarr->type();
 
     MDefinition *ptr = convertShiftToMaskForStaticTypedArray(index, viewType);
     if (!ptr)
         return true;
 
     // Emit StoreTypedArrayElementStatic.
     object->setFoldedUnchecked();
     index->setFoldedUnchecked();
@@ -8026,19 +8017,16 @@ IonBuilder::loadSlot(MDefinition *obj, s
     load->setResultType(rvalType);
     return pushTypeBarrier(load, types, barrier);
 }
 
 bool
 IonBuilder::loadSlot(MDefinition *obj, Shape *shape, MIRType rvalType,
                      bool barrier, types::TemporaryTypeSet *types)
 {
-    JS_ASSERT(shape->hasDefaultGetter());
-    JS_ASSERT(shape->hasSlot());
-
     return loadSlot(obj, shape->slot(), shape->numFixedSlots(), rvalType, barrier, types);
 }
 
 bool
 IonBuilder::storeSlot(MDefinition *obj, size_t slot, size_t nfixed,
                       MDefinition *value, bool needsBarrier,
                       MIRType slotType /* = MIRType_None */)
 {
@@ -8063,20 +8051,17 @@ IonBuilder::storeSlot(MDefinition *obj, 
         store->setSlotType(slotType);
     return resumeAfter(store);
 }
 
 bool
 IonBuilder::storeSlot(MDefinition *obj, Shape *shape, MDefinition *value, bool needsBarrier,
                       MIRType slotType /* = MIRType_None */)
 {
-    JS_ASSERT(shape->hasDefaultSetter());
     JS_ASSERT(shape->writable());
-    JS_ASSERT(shape->hasSlot());
-
     return storeSlot(obj, shape->slot(), shape->numFixedSlots(), value, needsBarrier, slotType);
 }
 
 bool
 IonBuilder::jsop_getprop(PropertyName *name)
 {
     bool emitted = false;
 
@@ -8930,21 +8915,16 @@ IonBuilder::jsop_delelem()
     current->push(ins);
 
     return resumeAfter(ins);
 }
 
 bool
 IonBuilder::jsop_regexp(RegExpObject *reobj)
 {
-    JSObject *prototype = reobj->getProto();
-    JS_ASSERT(prototype == script()->global().maybeGetRegExpPrototype());
-
-    JS_ASSERT(&reobj->JSObject::global() == &script()->global());
-
     // JS semantics require regular expression literals to create different
     // objects every time they execute. We only need to do this cloning if the
     // script could actually observe the effect of such cloning, for instance
     // by getting or setting properties on it.
     //
     // First, make sure the regex is one we can safely optimize. Lowering can
     // then check if this regex object only flows into known natives and can
     // avoid cloning in this case.
@@ -8957,16 +8937,18 @@ IonBuilder::jsop_regexp(RegExpObject *re
         DebugOnly<uint32_t> origFlags = reobj->getFlags();
         DebugOnly<uint32_t> staticsFlags = res->getFlags();
         JS_ASSERT((origFlags & staticsFlags) == staticsFlags);
 
         if (!reobj->global() && !reobj->sticky())
             mustClone = false;
     }
 
+    JSObject *prototype = reobj->getProto();
+
     MRegExp *regexp = MRegExp::New(alloc(), reobj, prototype, mustClone);
     current->add(regexp);
     current->push(regexp);
 
     regexp->setMovable();
 
     // The MRegExp is set to be movable.
     // That would be incorrect for global/sticky, because lastIndex could be wrong.
--- a/js/src/jit/IonMacroAssembler.cpp
+++ b/js/src/jit/IonMacroAssembler.cpp
@@ -680,17 +680,16 @@ MacroAssembler::newGCThing(const Registe
     subPtr(Imm32(thingSize), result);
 }
 
 void
 MacroAssembler::newGCThing(const Register &result, JSObject *templateObject, Label *fail)
 {
     gc::AllocKind allocKind = templateObject->tenuredGetAllocKind();
     JS_ASSERT(allocKind >= gc::FINALIZE_OBJECT0 && allocKind <= gc::FINALIZE_OBJECT_LAST);
-    JS_ASSERT(!templateObject->hasDynamicElements());
 
     gc::InitialHeap initialHeap = templateObject->type()->initialHeapForJITAlloc();
     newGCThing(result, allocKind, fail, initialHeap);
 }
 
 void
 MacroAssembler::newGCString(const Register &result, Label *fail)
 {
@@ -753,17 +752,16 @@ MacroAssembler::newGCThingPar(const Regi
 
 void
 MacroAssembler::newGCThingPar(const Register &result, const Register &slice,
                               const Register &tempReg1, const Register &tempReg2,
                               JSObject *templateObject, Label *fail)
 {
     gc::AllocKind allocKind = templateObject->tenuredGetAllocKind();
     JS_ASSERT(allocKind >= gc::FINALIZE_OBJECT0 && allocKind <= gc::FINALIZE_OBJECT_LAST);
-    JS_ASSERT(!templateObject->hasDynamicElements());
 
     newGCThingPar(result, slice, tempReg1, tempReg2, allocKind, fail);
 }
 
 void
 MacroAssembler::newGCStringPar(const Register &result, const Register &slice,
                                const Register &tempReg1, const Register &tempReg2,
                                Label *fail)
@@ -779,16 +777,18 @@ MacroAssembler::newGCShortStringPar(cons
     newGCThingPar(result, slice, tempReg1, tempReg2, js::gc::FINALIZE_SHORT_STRING, fail);
 }
 
 void
 MacroAssembler::initGCThing(const Register &obj, JSObject *templateObject)
 {
     // Fast initialization of an empty object returned by NewGCThing().
 
+    JS_ASSERT(!templateObject->hasDynamicElements());
+
     storePtr(ImmGCPtr(templateObject->lastProperty()), Address(obj, JSObject::offsetOfShape()));
     storePtr(ImmGCPtr(templateObject->type()), Address(obj, JSObject::offsetOfType()));
     storePtr(ImmPtr(nullptr), Address(obj, JSObject::offsetOfSlots()));
 
     if (templateObject->is<ArrayObject>()) {
         JS_ASSERT(!templateObject->getDenseInitializedLength());
 
         int elementsOffset = JSObject::offsetOfFixedElements();
@@ -808,17 +808,18 @@ MacroAssembler::initGCThing(const Regist
                       ? ObjectElements::CONVERT_DOUBLE_ELEMENTS
                       : 0),
                 Address(obj, elementsOffset + ObjectElements::offsetOfFlags()));
     } else {
         storePtr(ImmPtr(emptyObjectElements), Address(obj, JSObject::offsetOfElements()));
 
         // Fixed slots of non-array objects are required to be initialized.
         // Use the values currently in the template object.
-        size_t nslots = Min(templateObject->numFixedSlots(), templateObject->slotSpan());
+        size_t nslots = Min(templateObject->numFixedSlotsForCompilation(),
+                            templateObject->lastProperty()->slotSpan(templateObject->getClass()));
         for (unsigned i = 0; i < nslots; i++) {
             storeValue(templateObject->getFixedSlot(i),
                        Address(obj, JSObject::getFixedSlotOffset(i)));
         }
     }
 
     if (templateObject->hasPrivate()) {
         uint32_t nfixed = templateObject->numFixedSlots();
--- a/js/src/jit/JitCompartment.h
+++ b/js/src/jit/JitCompartment.h
@@ -435,16 +435,17 @@ class JitCompartment
     OptimizedICStubSpace *optimizedStubSpace() {
         return &optimizedStubSpace_;
     }
 };
 
 // Called from JSCompartment::discardJitCode().
 void InvalidateAll(FreeOp *fop, JS::Zone *zone);
 void FinishInvalidation(FreeOp *fop, JSScript *script);
+void FinishDiscardJitCode(FreeOp *fop, JSCompartment *comp);
 
 // On windows systems, really large frames need to be incrementally touched.
 // The following constant defines the minimum increment of the touch.
 #ifdef XP_WIN
 const unsigned WINDOWS_BIG_FRAME_TOUCH_INCREMENT = 4096 - 1;
 #endif
 
 } // namespace jit
--- a/js/src/jit/MCallOptimize.cpp
+++ b/js/src/jit/MCallOptimize.cpp
@@ -452,21 +452,18 @@ IonBuilder::inlineArrayConcat(CallInfo &
     // global, so we can create the result object inline.
     if (thisTypes->getObjectCount() != 1)
         return InliningStatus_NotInlined;
 
     types::TypeObject *baseThisType = thisTypes->getTypeObject(0);
     if (!baseThisType)
         return InliningStatus_NotInlined;
     types::TypeObjectKey *thisType = types::TypeObjectKey::get(baseThisType);
-    if (thisType->unknownProperties() ||
-        &thisType->proto().toObject()->global() != &script()->global())
-    {
+    if (thisType->unknownProperties())
         return InliningStatus_NotInlined;
-    }
 
     // Don't inline if 'this' is packed and the argument may not be packed
     // (the result array will reuse the 'this' type).
     if (!thisTypes->hasObjectFlags(constraints(), types::OBJECT_FLAG_NON_PACKED) &&
         argTypes->hasObjectFlags(constraints(), types::OBJECT_FLAG_NON_PACKED))
     {
         return InliningStatus_NotInlined;
     }
--- a/js/src/jit/MIR.cpp
+++ b/js/src/jit/MIR.cpp
@@ -2314,20 +2314,18 @@ MCompare::evaluateConstantOperands(bool 
         return false;
 
     Value lhs = left->toConstant()->value();
     Value rhs = right->toConstant()->value();
 
     // Fold away some String equality comparisons.
     if (lhs.isString() && rhs.isString()) {
         int32_t comp = 0; // Default to equal.
-        if (left != right) {
-            if (!CompareStrings(GetIonContext()->cx, lhs.toString(), rhs.toString(), &comp))
-                return false;
-        }
+        if (left != right)
+            comp = CompareAtoms(&lhs.toString()->asAtom(), &rhs.toString()->asAtom());
         
         switch (jsop_) {
           case JSOP_LT:
             *result = (comp < 0);
             break;
           case JSOP_LE:
             *result = (comp <= 0);
             break;
@@ -2923,17 +2921,17 @@ jit::PropertyReadNeedsTypeBarrier(JSCont
                                   types::TemporaryTypeSet *observed, bool updateObserved)
 {
     // If this access has never executed, try to add types to the observed set
     // according to any property which exists on the object or its prototype.
     if (updateObserved && observed->empty() && name) {
         JSObject *obj = object->singleton() ? object->singleton() : object->proto().toObjectOrNull();
 
         while (obj) {
-            if (!obj->isNative())
+            if (!obj->getClass()->isNative())
                 break;
 
             types::TypeObjectKey *typeObj = types::TypeObjectKey::get(obj);
             if (propertycx)
                 typeObj->ensureTrackedProperty(propertycx, NameToId(name));
 
             if (!typeObj->unknownProperties()) {
                 types::HeapTypeSetKey property = typeObj->property(NameToId(name));
--- a/js/src/jit/MIR.h
+++ b/js/src/jit/MIR.h
@@ -5959,17 +5959,19 @@ class MLoadTypedArrayElementStatic
     INSTRUCTION_HEADER(LoadTypedArrayElementStatic);
 
     static MLoadTypedArrayElementStatic *New(TempAllocator &alloc, TypedArrayObject *typedArray,
                                              MDefinition *ptr)
     {
         return new(alloc) MLoadTypedArrayElementStatic(typedArray, ptr);
     }
 
-    ArrayBufferView::ViewType viewType() const { return JS_GetArrayBufferViewType(typedArray_); }
+    ArrayBufferView::ViewType viewType() const {
+        return (ArrayBufferView::ViewType) typedArray_->type();
+    }
     void *base() const;
     size_t length() const;
 
     MDefinition *ptr() const { return getOperand(0); }
     AliasSet getAliasSet() const {
         return AliasSet::Load(AliasSet::TypedArrayElement);
     }
 
@@ -6141,17 +6143,19 @@ class MStoreTypedArrayElementStatic :
     {
         return new(alloc) MStoreTypedArrayElementStatic(typedArray, ptr, v);
     }
 
     TypePolicy *typePolicy() {
         return this;
     }
 
-    ArrayBufferView::ViewType viewType() const { return JS_GetArrayBufferViewType(typedArray_); }
+    ArrayBufferView::ViewType viewType() const {
+        return (ArrayBufferView::ViewType) typedArray_->type();
+    }
     bool isFloatArray() const {
         return (viewType() == ArrayBufferView::TYPE_FLOAT32 ||
                 viewType() == ArrayBufferView::TYPE_FLOAT64);
     }
 
     void *base() const;
     size_t length() const;
 
--- a/js/src/jit/ParallelFunctions.cpp
+++ b/js/src/jit/ParallelFunctions.cpp
@@ -253,19 +253,19 @@ do {                                    
 static bool
 CompareStringsPar(ForkJoinSlice *slice, JSString *left, JSString *right, int32_t *res)
 {
     ScopedThreadSafeStringInspector leftInspector(left);
     ScopedThreadSafeStringInspector rightInspector(right);
     if (!leftInspector.ensureChars(slice) || !rightInspector.ensureChars(slice))
         return false;
 
-    return CompareChars(leftInspector.chars(), left->length(),
-                        rightInspector.chars(), right->length(),
-                        res);
+    *res = CompareChars(leftInspector.chars(), left->length(),
+                        rightInspector.chars(), right->length());
+    return true;
 }
 
 static bool
 CompareMaybeStringsPar(ForkJoinSlice *slice, HandleValue v1, HandleValue v2, int32_t *res)
 {
     if (!v1.isString())
         return false;
     if (!v2.isString())
--- a/js/src/jit/Snapshots.cpp
+++ b/js/src/jit/Snapshots.cpp
@@ -301,17 +301,17 @@ SnapshotWriter::startSnapshot(uint32_t f
 void
 SnapshotWriter::startFrame(JSFunction *fun, JSScript *script, jsbytecode *pc, uint32_t exprStack)
 {
     // Test if we honor the maximum of arguments at all times.
     // This is a sanity check and not an algorithm limit. So check might be a bit too loose.
     // +4 to account for scope chain, return value, this value and maybe arguments_object.
     JS_ASSERT(CountArgSlots(script, fun) < SNAPSHOT_MAX_NARGS + 4);
 
-    uint32_t implicit = StartArgSlot(script, fun);
+    uint32_t implicit = StartArgSlot(script);
     uint32_t formalArgs = CountArgSlots(script, fun);
 
     nslots_ = formalArgs + script->nfixed + exprStack;
     slotsWritten_ = 0;
 
     IonSpew(IonSpew_Snapshots, "Starting frame; implicit %u, formals %u, fixed %u, exprs %u",
             implicit, formalArgs - implicit, script->nfixed, exprStack);
 
--- a/js/src/jsapi-tests/moz.build
+++ b/js/src/jsapi-tests/moz.build
@@ -1,17 +1,17 @@
 # -*- Mode: python; c-basic-offset: 4; indent-tabs-mode: nil; tab-width: 40 -*-
 # vim: set filetype=python:
 # This Source Code Form is subject to the terms of the Mozilla Public
 # License, v. 2.0. If a copy of the MPL was not distributed with this
 # file, You can obtain one at http://mozilla.org/MPL/2.0/.
 
 PROGRAM = 'jsapi-tests'
 
-SOURCES += [
+UNIFIED_SOURCES += [
     'selfTest.cpp',
     'testAddPropertyPropcache.cpp',
     'testArgumentsObject.cpp',
     'testArrayBuffer.cpp',
     'testBindCallable.cpp',
     'testBug604087.cpp',
     'testCallNonGenericMethodOnProxy.cpp',
     'testChromeBuffer.cpp',
--- a/js/src/jsapi-tests/testAddPropertyPropcache.cpp
+++ b/js/src/jsapi-tests/testAddPropertyPropcache.cpp
@@ -2,71 +2,74 @@
  * vim: set ts=8 sts=4 et sw=4 tw=99:
  */
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #include "jsapi-tests/tests.h"
 
-/* Do the test a bunch of times, because sometimes we seem to randomly
-   miss the propcache */
-static const int expectedCount = 100;
 static int callCount = 0;
 
 static bool
-addProperty(JSContext *cx, JS::HandleObject obj, JS::HandleId id, JS::MutableHandleValue vp)
+AddProperty(JSContext *cx, JS::HandleObject obj, JS::HandleId id, JS::MutableHandleValue vp)
 {
-  callCount++;
-  return true;
+    callCount++;
+    return true;
 }
 
-const JSClass addPropertyClass = {
+static const JSClass AddPropertyClass = {
     "AddPropertyTester",
     0,
-    addProperty,
+    AddProperty,
     JS_DeletePropertyStub,   /* delProperty */
     JS_PropertyStub,         /* getProperty */
     JS_StrictPropertyStub,   /* setProperty */
     JS_EnumerateStub,
     JS_ResolveStub,
     JS_ConvertStub
 };
 
 BEGIN_TEST(testAddPropertyHook)
 {
+    /*
+     * Do the test a bunch of times, because sometimes we seem to randomly
+     * miss the propcache.
+     */
+    static const int ExpectedCount = 100;
+
     JS::RootedObject obj(cx, JS_NewObject(cx, nullptr, nullptr, nullptr));
     CHECK(obj);
     JS::RootedValue proto(cx, OBJECT_TO_JSVAL(obj));
-    JS_InitClass(cx, global, obj, &addPropertyClass, nullptr, 0, nullptr, nullptr, nullptr,
+    JS_InitClass(cx, global, obj, &AddPropertyClass, nullptr, 0, nullptr, nullptr, nullptr,
                  nullptr);
 
     obj = JS_NewArrayObject(cx, 0, nullptr);
     CHECK(obj);
     JS::RootedValue arr(cx, OBJECT_TO_JSVAL(obj));
 
     CHECK(JS_DefineProperty(cx, global, "arr", arr,
                             JS_PropertyStub, JS_StrictPropertyStub,
                             JSPROP_ENUMERATE));
 
-    for (int i = 0; i < expectedCount; ++i) {
-        obj = JS_NewObject(cx, &addPropertyClass, nullptr, nullptr);
+    for (int i = 0; i < ExpectedCount; ++i) {
+        obj = JS_NewObject(cx, &AddPropertyClass, nullptr, nullptr);
         CHECK(obj);
         JS::RootedValue vobj(cx, OBJECT_TO_JSVAL(obj));
         JS::RootedObject arrObj(cx, JSVAL_TO_OBJECT(arr));
         CHECK(JS_DefineElement(cx, arrObj, i, vobj,
                                JS_PropertyStub, JS_StrictPropertyStub,
                                JSPROP_ENUMERATE));
     }
 
     // Now add a prop to each of the objects, but make sure to do
     // so at the same bytecode location so we can hit the propcache.
     EXEC("'use strict';                                     \n"
          "for (var i = 0; i < arr.length; ++i)              \n"
          "  arr[i].prop = 42;                               \n"
          );
 
-    CHECK(callCount == expectedCount);
+    CHECK(callCount == ExpectedCount);
 
     return true;
 }
 END_TEST(testAddPropertyHook)
 
--- a/js/src/jsapi-tests/testArgumentsObject.cpp
+++ b/js/src/jsapi-tests/testArgumentsObject.cpp
@@ -29,26 +29,16 @@ static const char STRICT_ONE[] =
 static const char STRICT_TWO[] =
     "function f() { 'use strict'; return arguments; }";
 static const char STRICT_THREE[] =
     "function f() { 'use strict'; return arguments; }";
 
 static const char * const CALL_CODES[] =
     { "f()", "f(0)", "f(0, 1)", "f(0, 1, 2)", "f(0, 1, 2, 3)", "f(0, 1, 2, 3, 4)" };
 
-static const size_t MAX_ELEMS = 6;
-
-static void
-ClearElements(Value elems[MAX_ELEMS])
-{
-    for (size_t i = 0; i < MAX_ELEMS - 1; i++)
-        elems[i] = NullValue();
-    elems[MAX_ELEMS - 1] = Int32Value(42);
-}
-
 BEGIN_TEST(testArgumentsObject)
 {
     return ExhaustiveTest<0>(NORMAL_ZERO) &&
            ExhaustiveTest<1>(NORMAL_ZERO) &&
            ExhaustiveTest<2>(NORMAL_ZERO) &&
            ExhaustiveTest<0>(NORMAL_ONE) &&
            ExhaustiveTest<1>(NORMAL_ONE) &&
            ExhaustiveTest<2>(NORMAL_ONE) &&
@@ -79,16 +69,18 @@ BEGIN_TEST(testArgumentsObject)
            ExhaustiveTest<0>(STRICT_THREE) &&
            ExhaustiveTest<1>(STRICT_THREE) &&
            ExhaustiveTest<2>(STRICT_THREE) &&
            ExhaustiveTest<3>(STRICT_THREE) &&
            ExhaustiveTest<4>(STRICT_THREE) &&
            ExhaustiveTest<5>(STRICT_THREE);
 }
 
+static const size_t MAX_ELEMS = 6;
+
 template<size_t ArgCount> bool
 ExhaustiveTest(const char funcode[])
 {
     RootedValue v(cx);
     EVAL(funcode, v.address());
 
     EVAL(CALL_CODES[ArgCount], v.address());
     Rooted<ArgumentsObject*> argsobj(cx, &JSVAL_TO_OBJECT(v)->as<ArgumentsObject>());
@@ -104,9 +96,17 @@ ExhaustiveTest(const char funcode[])
             for (size_t k = j; k < MAX_ELEMS - 1; k++)
                 CHECK_SAME(elems[k], JSVAL_NULL);
             CHECK_SAME(elems[MAX_ELEMS - 1], INT_TO_JSVAL(42));
         }
     }
 
     return true;
 }
+
+static void
+ClearElements(Value elems[MAX_ELEMS])
+{
+    for (size_t i = 0; i < MAX_ELEMS - 1; i++)
+        elems[i] = NullValue();
+    elems[MAX_ELEMS - 1] = Int32Value(42);
+}
 END_TEST(testArgumentsObject)
--- a/js/src/jsapi-tests/testArrayBuffer.cpp
+++ b/js/src/jsapi-tests/testArrayBuffer.cpp
@@ -1,22 +1,22 @@
 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*-
  * vim: set ts=8 sts=4 et sw=4 tw=99:
  */
 
 #include "jsfriendapi.h"
 
 #include "jsapi-tests/tests.h"
 
-#define NUM_TEST_BUFFERS 2
-#define MAGIC_VALUE_1 3
-#define MAGIC_VALUE_2 17
-
 BEGIN_TEST(testArrayBuffer_bug720949_steal)
 {
+    static const unsigned NUM_TEST_BUFFERS  = 2;
+    static const unsigned MAGIC_VALUE_1 = 3;
+    static const unsigned MAGIC_VALUE_2 = 17;
+
     JS::RootedObject buf_len1(cx), buf_len200(cx);
     JS::RootedObject tarray_len1(cx), tarray_len200(cx);
 
     uint32_t sizes[NUM_TEST_BUFFERS] = { sizeof(uint32_t), 200 * sizeof(uint32_t) };
     JS::HandleObject testBuf[NUM_TEST_BUFFERS] = { buf_len1, buf_len200 };
     JS::HandleObject testArray[NUM_TEST_BUFFERS] = { tarray_len1, tarray_len200 };
 
     // Single-element ArrayBuffer (uses fixed slots for storage)
@@ -87,22 +87,16 @@ BEGIN_TEST(testArrayBuffer_bug720949_ste
         CHECK(JS_GetElement(cx, dstview, 0, &v));
         CHECK_SAME(v, INT_TO_JSVAL(MAGIC_VALUE_2));
     }
 
     return true;
 }
 END_TEST(testArrayBuffer_bug720949_steal)
 
-static void GC(JSContext *cx)
-{
-    JS_GC(JS_GetRuntime(cx));
-    JS_GC(JS_GetRuntime(cx)); // Trigger another to wait for background finalization to end
-}
-
 // Varying number of views of a buffer, to test the neutering weak pointers
 BEGIN_TEST(testArrayBuffer_bug720949_viewList)
 {
     JS::RootedObject buffer(cx);
 
     // No views
     buffer = JS_NewArrayBuffer(cx, 2000);
     buffer = nullptr;
@@ -157,14 +151,20 @@ BEGIN_TEST(testArrayBuffer_bug720949_vie
         GC(cx);
         buffer = nullptr;
         GC(cx);
     }
 
     return true;
 }
 
+static void GC(JSContext *cx)
+{
+    JS_GC(JS_GetRuntime(cx));
+    JS_GC(JS_GetRuntime(cx)); // Trigger another to wait for background finalization to end
+}
+
 bool isNeutered(JS::HandleObject obj) {
     JS::RootedValue v(cx);
     return JS_GetProperty(cx, obj, "byteLength", &v) && v.toInt32() == 0;
 }
 
 END_TEST(testArrayBuffer_bug720949_viewList)
--- a/js/src/jsapi-tests/testChromeBuffer.cpp
+++ b/js/src/jsapi-tests/testChromeBuffer.cpp
@@ -1,36 +1,36 @@
 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*-
  * vim: set ts=8 sts=4 et sw=4 tw=99:
  * This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #include "jsapi-tests/tests.h"
 
-JSPrincipals system_principals = {
+static JSPrincipals system_principals = {
     1
 };
 
-const JSClass global_class = {
+static const JSClass global_class = {
     "global",
     JSCLASS_IS_GLOBAL | JSCLASS_GLOBAL_FLAGS,
     JS_PropertyStub,
     JS_DeletePropertyStub,
     JS_PropertyStub,
     JS_StrictPropertyStub,
     JS_EnumerateStub,
     JS_ResolveStub,
     JS_ConvertStub
 };
 
-JSObject *trusted_glob = nullptr;
-JSObject *trusted_fun = nullptr;
+static JSObject *trusted_glob = nullptr;
+static JSObject *trusted_fun = nullptr;
 
-bool
+static bool
 CallTrusted(JSContext *cx, unsigned argc, jsval *vp)
 {
     if (!JS_SaveFrameChain(cx))
         return false;
 
     bool ok = false;
     {
         JSAutoCompartment ac(cx, trusted_glob);
--- a/js/src/jsapi-tests/testClassGetter.cpp
+++ b/js/src/jsapi-tests/testClassGetter.cpp
@@ -4,18 +4,18 @@
  * Tests the JSClass::getProperty hook
  */
 /* 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 "jsapi-tests/tests.h"
 
-int called_test_fn;
-int called_test_prop_get;
+static int called_test_fn;
+static int called_test_prop_get;
 
 static bool test_prop_get( JSContext *cx, JS::HandleObject obj, JS::HandleId id, JS::MutableHandleValue vp )
 {
     called_test_prop_get++;
     return true;
 }
 
 static bool
--- a/js/src/jsapi-tests/testCloneScript.cpp
+++ b/js/src/jsapi-tests/testCloneScript.cpp
@@ -45,17 +45,17 @@ BEGIN_TEST(test_cloneScript)
         JSAutoCompartment b(cx, B);
         CHECK(JS_CloneFunctionObject(cx, obj, B));
     }
 
     return true;
 }
 END_TEST(test_cloneScript)
 
-void
+static void
 DestroyPrincipals(JSPrincipals *principals)
 {
     delete principals;
 }
 
 struct Principals : public JSPrincipals
 {
   public:
--- a/js/src/jsapi-tests/testConservativeGC.cpp
+++ b/js/src/jsapi-tests/testConservativeGC.cpp
@@ -55,17 +55,16 @@ BEGIN_TEST(testConservativeGC)
 
     return true;
 }
 
 bool checkObjectFields(JSObject *savedCopy, JSObject *obj)
 {
     /* Ignore fields which are unstable across GCs. */
     CHECK(savedCopy->lastProperty() == obj->lastProperty());
-    CHECK(savedCopy->getProto() == obj->getProto());
     return true;
 }
 
 END_TEST(testConservativeGC)
 
 BEGIN_TEST(testDerivedValues)
 {
   JSString *str = JS_NewStringCopyZ(cx, "once upon a midnight dreary");
--- a/js/src/jsapi-tests/testCustomIterator.cpp
+++ b/js/src/jsapi-tests/testCustomIterator.cpp
@@ -1,23 +1,23 @@
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #include "js/Class.h"
 #include "jsapi-tests/tests.h"
 
-int count = 0;
+static int iterCount = 0;
 
 static bool
 IterNext(JSContext *cx, unsigned argc, jsval *vp)
 {
-    if (count++ == 100)
+    if (iterCount++ == 100)
         return JS_ThrowStopIteration(cx);
-    JS_SET_RVAL(cx, vp, INT_TO_JSVAL(count));
+    JS_SET_RVAL(cx, vp, INT_TO_JSVAL(iterCount));
     return true;
 }
 
 static JSObject *
 IterHook(JSContext *cx, JS::HandleObject obj, bool keysonly)
 {
     JS::RootedObject iterObj(cx, JS_NewObject(cx, nullptr, nullptr, nullptr));
     if (!iterObj)
@@ -46,17 +46,17 @@ const js::Class HasCustomIterClass = {
     {
         nullptr,     /* outerObject */
         nullptr,     /* innerObject */
         IterHook,
         false        /* isWrappedNative */
     }
 };
 
-bool
+static bool
 IterClassConstructor(JSContext *cx, unsigned argc, jsval *vp)
 {
     JSObject *obj = JS_NewObjectForConstructor(cx, Jsvalify(&HasCustomIterClass), vp);
     if (!obj)
         return false;
     JS_SET_RVAL(cx, vp, OBJECT_TO_JSVAL(obj));
     return true;
 }
@@ -69,13 +69,13 @@ BEGIN_TEST(testCustomIterator_bug612523)
     JS::RootedValue result(cx);
     EVAL("var o = new HasCustomIter(); \n"
          "var j = 0; \n"
          "for (var i in o) { ++j; }; \n"
          "j;", result.address());
 
     CHECK(JSVAL_IS_INT(result));
     CHECK_EQUAL(JSVAL_TO_INT(result), 100);
-    CHECK_EQUAL(count, 101);
+    CHECK_EQUAL(iterCount, 101);
 
     return true;
 }
 END_TEST(testCustomIterator_bug612523)
--- a/js/src/jsapi-tests/testDebugger.cpp
+++ b/js/src/jsapi-tests/testDebugger.cpp
@@ -5,40 +5,40 @@
  * 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 "jscntxt.h"
 
 #include "js/OldDebugAPI.h"
 #include "jsapi-tests/tests.h"
 
-static int callCount[2] = {0, 0};
+static int callCounts[2] = {0, 0};
 
 static void *
 callCountHook(JSContext *cx, JSAbstractFramePtr frame, bool isConstructing, bool before,
               bool *ok, void *closure)
 {
-    callCount[before]++;
+    callCounts[before]++;
 
     JS::RootedValue thisv(cx);
     frame.getThisValue(cx, &thisv); // assert if fp is incomplete
 
     return cx;  // any non-null value causes the hook to be called again after
 }
 
 BEGIN_TEST(testDebugger_bug519719)
 {
     CHECK(JS_SetDebugMode(cx, true));
     JS_SetCallHook(rt, callCountHook, nullptr);
     EXEC("function call(fn) { fn(0); }\n"
          "function f(g) { for (var i = 0; i < 9; i++) call(g); }\n"
          "f(Math.sin);\n"    // record loop, starting in f
          "f(Math.cos);\n");  // side exit in f -> call
-    CHECK_EQUAL(callCount[0], 20);
-    CHECK_EQUAL(callCount[1], 20);
+    CHECK_EQUAL(callCounts[0], 20);
+    CHECK_EQUAL(callCounts[1], 20);
     return true;
 }
 END_TEST(testDebugger_bug519719)
 
 static void *
 nonStrictThisHook(JSContext *cx, JSAbstractFramePtr frame, bool isConstructing, bool before,
                   bool *ok, void *closure)
 {
@@ -107,23 +107,23 @@ BEGIN_TEST(testDebugger_getThisStrict)
          "(42).strict();\n"
          "strict.call(undefined);\n"
          "strict.call(null);\n");
     CHECK(!anyWrapped);
     return true;
 }
 END_TEST(testDebugger_getThisStrict)
 
-bool called = false;
+static bool calledThrowHook = false;
 
 static JSTrapStatus
 ThrowHook(JSContext *cx, JSScript *, jsbytecode *, jsval *rval, void *closure)
 {
     JS_ASSERT(!closure);
-    called = true;
+    calledThrowHook = true;
 
     JS::RootedObject global(cx, JS::CurrentGlobalOrNull(cx));
 
     char text[] = "new Error()";
     jsval _;
     JS_EvaluateScript(cx, global, text, strlen(text), "", 0, &_);
 
     return JSTRAP_CONTINUE;
@@ -135,17 +135,17 @@ BEGIN_TEST(testDebugger_throwHook)
     CHECK(JS_SetThrowHook(rt, ThrowHook, nullptr));
     EXEC("function foo() { throw 3 };\n"
          "for (var i = 0; i < 10; ++i) { \n"
          "  var x = {}\n"
          "  try {\n"
          "    foo(); \n"
          "  } catch(e) {}\n"
          "}\n");
-    CHECK(called);
+    CHECK(calledThrowHook);
     CHECK(JS_SetThrowHook(rt, nullptr, nullptr));
     return true;
 }
 END_TEST(testDebugger_throwHook)
 
 BEGIN_TEST(testDebugger_debuggerObjectVsDebugMode)
 {
     CHECK(JS_DefineDebuggerObject(cx, global));
--- a/js/src/jsapi-tests/testDefineGetterSetterNonEnumerable.cpp
+++ b/js/src/jsapi-tests/testDefineGetterSetterNonEnumerable.cpp
@@ -3,36 +3,36 @@
  */
 /* 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 "jsapi-tests/tests.h"
 
 static bool
-native(JSContext *cx, unsigned argc, jsval *vp)
+NativeGetterSetter(JSContext *cx, unsigned argc, jsval *vp)
 {
     return true;
 }
 
-static const char PROPERTY_NAME[] = "foo";
-
 BEGIN_TEST(testDefineGetterSetterNonEnumerable)
 {
+    static const char PROPERTY_NAME[] = "foo";
+
     JS::RootedValue vobj(cx);
     JS::RootedObject obj(cx, JS_NewObject(cx, nullptr, nullptr, nullptr));
     CHECK(obj);
     vobj = OBJECT_TO_JSVAL(obj);
 
-    JSFunction *funGet = JS_NewFunction(cx, native, 0, 0, nullptr, "get");
+    JSFunction *funGet = JS_NewFunction(cx, NativeGetterSetter, 0, 0, nullptr, "get");
     CHECK(funGet);
     JS::RootedObject funGetObj(cx, JS_GetFunctionObject(funGet));
     JS::RootedValue vget(cx, OBJECT_TO_JSVAL(funGetObj));
 
-    JSFunction *funSet = JS_NewFunction(cx, native, 1, 0, nullptr, "set");
+    JSFunction *funSet = JS_NewFunction(cx, NativeGetterSetter, 1, 0, nullptr, "set");
     CHECK(funSet);
     JS::RootedObject funSetObj(cx, JS_GetFunctionObject(funSet));
     JS::RootedValue vset(cx, OBJECT_TO_JSVAL(funSetObj));
 
     JS::RootedObject vObject(cx, JSVAL_TO_OBJECT(vobj));
     CHECK(JS_DefineProperty(cx, vObject, PROPERTY_NAME,
                             JSVAL_VOID,
                             JS_DATA_TO_FUNC_PTR(JSPropertyOp, (JSObject*) funGetObj),
--- a/js/src/jsapi-tests/testEnclosingFunction.cpp
+++ b/js/src/jsapi-tests/testEnclosingFunction.cpp
@@ -9,57 +9,57 @@
 
 #include "jsfriendapi.h"
 
 #include "js/OldDebugAPI.h"
 #include "jsapi-tests/tests.h"
 
 using namespace js;
 
-JSScript *found = nullptr;
+static JSScript *foundScript = nullptr;
 
-bool
+static bool
 CheckEnclosing(JSContext *cx, unsigned argc, Value *vp)
 {
     CallArgs args = CallArgsFromVp(argc, vp);
 
-    found = js::GetOutermostEnclosingFunctionOfScriptedCaller(cx);
+    foundScript = js::GetOutermostEnclosingFunctionOfScriptedCaller(cx);
 
     args.rval().set(UndefinedValue());
     return true;
 }
 
 BEGIN_TEST(test_enclosingFunction)
 {
     CHECK(JS_DefineFunction(cx, global, "checkEnclosing", CheckEnclosing, 0, 0));
 
     EXEC("checkEnclosing()");
-    CHECK(found == nullptr);
+    CHECK(foundScript == nullptr);
 
     RootedFunction fun(cx);
 
     JS::CompileOptions options(cx);
     options.setFileAndLine(__FILE__, __LINE__);
 
     const char s1chars[] = "checkEnclosing()";
     fun = JS_CompileFunction(cx, global, "s1", 0, nullptr, s1chars,
                              strlen(s1chars), options);
     CHECK(fun);
     EXEC("s1()");
-    CHECK(found == JS_GetFunctionScript(cx, fun));
+    CHECK(foundScript == JS_GetFunctionScript(cx, fun));
 
     const char s2chars[] = "return function() { checkEnclosing() }";
     fun = JS_CompileFunction(cx, global, "s2", 0, nullptr, s2chars,
                              strlen(s2chars), options);
     CHECK(fun);
     EXEC("s2()()");
-    CHECK(found == JS_GetFunctionScript(cx, fun));
+    CHECK(foundScript == JS_GetFunctionScript(cx, fun));
 
     const char s3chars[] = "return function() { let (x) { function g() { checkEnclosing() } return g() } }";
     fun = JS_CompileFunction(cx, global, "s3", 0, nullptr, s3chars,
                              strlen(s3chars), options);
     CHECK(fun);
     EXEC("s3()()");
-    CHECK(found == JS_GetFunctionScript(cx, fun));
+    CHECK(foundScript == JS_GetFunctionScript(cx, fun));
 
     return true;
 }
 END_TEST(test_enclosingFunction)
--- a/js/src/jsapi-tests/testErrorCopying.cpp
+++ b/js/src/jsapi-tests/testErrorCopying.cpp
@@ -7,27 +7,28 @@
 /* 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 "jsapi-tests/tests.h"
 
 static uint32_t column = 0;
 
-static void
-my_ErrorReporter(JSContext *cx, const char *message, JSErrorReport *report)
-{
-    column = report->column;
-}
-
 BEGIN_TEST(testErrorCopying_columnCopied)
 {
         //0         1         2
         //0123456789012345678901234567
     EXEC("function check() { Object; foo; }");
 
     JS::RootedValue rval(cx);
     JS_SetErrorReporter(cx, my_ErrorReporter);
     CHECK(!JS_CallFunctionName(cx, global, "check", 0, nullptr, rval.address()));
     CHECK(column == 27);
     return true;
 }
+
+static void
+my_ErrorReporter(JSContext *cx, const char *message, JSErrorReport *report)
+{
+    column = report->column;
+}
+
 END_TEST(testErrorCopying_columnCopied)
--- a/js/src/jsapi-tests/testGCFinalizeCallback.cpp
+++ b/js/src/jsapi-tests/testGCFinalizeCallback.cpp
@@ -1,29 +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/. */
 
 #include "jsapi-tests/tests.h"
 
-const unsigned BufferSize = 20;
+static const unsigned BufferSize = 20;
 static unsigned FinalizeCalls = 0;
 static JSFinalizeStatus StatusBuffer[BufferSize];
 static bool IsCompartmentGCBuffer[BufferSize];
 
-static void
-FinalizeCallback(JSFreeOp *fop, JSFinalizeStatus status, bool isCompartmentGC)
-{
-    if (FinalizeCalls < BufferSize) {
-        StatusBuffer[FinalizeCalls] = status;
-        IsCompartmentGCBuffer[FinalizeCalls] = isCompartmentGC;
-    }
-    ++FinalizeCalls;
-}
-
 BEGIN_TEST(testGCFinalizeCallback)
 {
     JS_SetGCParameter(rt, JSGC_MODE, JSGC_MODE_INCREMENTAL);
     JS_SetFinalizeCallback(rt, FinalizeCallback);
 
     /* Full GC, non-incremental. */
     FinalizeCalls = 0;
     JS_GC(rt);
@@ -166,9 +156,18 @@ bool checkFinalizeStatus()
 bool checkFinalizeIsCompartmentGC(bool isCompartmentGC)
 {
     for (unsigned i = 0; i < FinalizeCalls; ++i)
         CHECK(IsCompartmentGCBuffer[i] == isCompartmentGC);
 
     return true;
 }
 
+static void
+FinalizeCallback(JSFreeOp *fop, JSFinalizeStatus status, bool isCompartmentGC)
+{
+    if (FinalizeCalls < BufferSize) {
+        StatusBuffer[FinalizeCalls] = status;
+        IsCompartmentGCBuffer[FinalizeCalls] = isCompartmentGC;
+    }
+    ++FinalizeCalls;
+}
 END_TEST(testGCFinalizeCallback)
--- a/js/src/jsapi-tests/testIndexToString.cpp
+++ b/js/src/jsapi-tests/testIndexToString.cpp
@@ -11,22 +11,16 @@
 #include "jsstr.h"
 
 #include "jsapi-tests/tests.h"
 
 #include "vm/String-inl.h"
 
 using mozilla::ArrayLength;
 
-template<size_t N> JSFlatString *
-NewString(JSContext *cx, const jschar (&chars)[N])
-{
-    return js_NewStringCopyN<js::CanGC>(cx, chars, N);
-}
-
 static const struct TestPair {
     uint32_t num;
     const char *expected;
 } tests[] = {
     { 0, "0" },
     { 1, "1" },
     { 2, "2" },
     { 9, "9" },
@@ -108,9 +102,16 @@ BEGIN_TEST(testStringToPropertyName)
     static const jschar maxPlusOneChars[] = { '4', '2', '9', '4', '9', '6', '7', '2', '9', '6' };
     JSFlatString *maxPlusOneStr = NewString(cx, maxPlusOneChars);
     CHECK(maxPlusOneStr);
     CHECK(!maxPlusOneStr->isIndex(&index));
     CHECK(maxPlusOneStr->toPropertyName(cx) != nullptr);
 
     return true;
 }
+
+template<size_t N> static JSFlatString *
+NewString(JSContext *cx, const jschar (&chars)[N])
+{
+    return js_NewStringCopyN<js::CanGC>(cx, chars, N);
+}
+
 END_TEST(testStringToPropertyName)
--- a/js/src/jsapi-tests/testIntern.cpp
+++ b/js/src/jsapi-tests/testIntern.cpp
@@ -23,26 +23,26 @@ BEGIN_TEST(testAtomizedIsNotInterned)
 END_TEST(testAtomizedIsNotInterned)
 
 struct StringWrapperStruct
 {
     JSString *str;
     bool     strOk;
 } sw;
 
-void
-FinalizeCallback(JSFreeOp *fop, JSFinalizeStatus status, bool isCompartmentGC)
-{
-    if (status == JSFINALIZE_GROUP_START)
-        sw.strOk = js::gc::IsStringMarked(&sw.str);
-}
-
 BEGIN_TEST(testInternAcrossGC)
 {
     sw.str = JS_InternString(cx, "wrapped chars that another test shouldn't be using");
     sw.strOk = false;
     CHECK(sw.str);
     JS_SetFinalizeCallback(rt, FinalizeCallback);
     JS_GC(rt);
     CHECK(sw.strOk);
     return true;
 }
+
+static void
+FinalizeCallback(JSFreeOp *fop, JSFinalizeStatus status, bool isCompartmentGC)
+{
+    if (status == JSFINALIZE_GROUP_START)
+        sw.strOk = js::gc::IsStringMarked(&sw.str);
+}
 END_TEST(testInternAcrossGC)
--- a/js/src/jsapi-tests/testNewObject.cpp
+++ b/js/src/jsapi-tests/testNewObject.cpp
@@ -2,19 +2,16 @@
  * vim: set ts=8 sts=4 et sw=4 tw=99:
  */
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #include "jsapi-tests/tests.h"
 
-const size_t N = 1000;
-static jsval argv[N];
-
 static bool
 constructHook(JSContext *cx, unsigned argc, jsval *vp)
 {
     JS::CallArgs args = CallArgsFromVp(argc, vp);
 
     // Check that arguments were passed properly from JS_New.
 
     JS::RootedObject obj(cx, JS_NewObject(cx, js::Jsvalify(&JSObject::class_), nullptr, nullptr));
@@ -51,16 +48,19 @@ constructHook(JSContext *cx, unsigned ar
     args[1].setUndefined();
     args[2].setUndefined();
 
     return true;
 }
 
 BEGIN_TEST(testNewObject_1)
 {
+    static const size_t N = 1000;
+    jsval argv[N];
+
     // Root the global argv test array. Only the first 2 entries really need to
     // be rooted, since we're only putting integers in the rest.
     CHECK(JS_AddNamedValueRoot(cx, &argv[0], "argv0"));
     CHECK(JS_AddNamedValueRoot(cx, &argv[1], "argv1"));
 
     JS::RootedValue v(cx);
     EVAL("Array", v.address());
     JS::RootedObject Array(cx, JSVAL_TO_OBJECT(v));
--- a/js/src/jsapi-tests/testOriginPrincipals.cpp
+++ b/js/src/jsapi-tests/testOriginPrincipals.cpp
@@ -1,25 +1,18 @@
 /* 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 "js/OldDebugAPI.h"
 #include "jsapi-tests/tests.h"
 
-JSPrincipals *sOriginPrincipalsInErrorReporter = nullptr;
-
-static void
-ErrorReporter(JSContext *cx, const char *message, JSErrorReport *report)
-{
-    sOriginPrincipalsInErrorReporter = report->originPrincipals;
-}
-
-JSPrincipals prin1 = { 1 };
-JSPrincipals prin2 = { 1 };
+static JSPrincipals *sOriginPrincipalsInErrorReporter = nullptr;
+static JSPrincipals prin1 = { 1 };
+static JSPrincipals prin2 = { 1 };
 
 BEGIN_TEST(testOriginPrincipals)
 {
     /*
      * Currently, the only way to set a non-trivial originPrincipal is to use
      * JS_EvaluateUCScriptForPrincipalsVersionOrigin. This does not expose the
      * compiled script, so we can only test nested scripts.
      */
@@ -46,16 +39,22 @@ BEGIN_TEST(testOriginPrincipals)
      * NB: uncaught exceptions, when reported, have nothing on the stack so
      * both the filename and originPrincipals are null. E.g., this would fail:
      *
      *   CHECK(testError("throw 3"));
      */
     return true;
 }
 
+static void
+ErrorReporter(JSContext *cx, const char *message, JSErrorReport *report)
+{
+    sOriginPrincipalsInErrorReporter = report->originPrincipals;
+}
+
 bool
 eval(const char *asciiChars, JSPrincipals *principals, JSPrincipals *originPrincipals, jsval *rval)
 {
     size_t len = strlen(asciiChars);
     jschar *chars = new jschar[len+1];
     for (size_t i = 0; i < len; ++i)
         chars[i] = asciiChars[i];
     chars[len] = 0;
--- a/js/src/jsapi-tests/testParseJSON.cpp
+++ b/js/src/jsapi-tests/testParseJSON.cpp
@@ -30,22 +30,16 @@ class AutoInflatedString {
         if (!chars_)
             abort();
     }
 
     const jschar *chars() const { return chars_; }
     size_t length() const { return length_; }
 };
 
-template<size_t N> JSFlatString *
-NewString(JSContext *cx, const jschar (&chars)[N])
-{
-    return js_NewStringCopyN<CanGC>(cx, chars, N);
-}
-
 BEGIN_TEST(testParseJSON_success)
 {
     // Primitives
     JS::RootedValue expected(cx);
     expected = JSVAL_TRUE;
     CHECK(TryParse(cx, "true", expected));
 
     expected = JSVAL_FALSE;
@@ -136,16 +130,22 @@ BEGIN_TEST(testParseJSON_success)
     obj = JSVAL_TO_OBJECT(v);
     CHECK(!JS_IsArrayObject(cx, obj));
     CHECK(JS_GetProperty(cx, obj, "f", &v2));
     CHECK_SAME(v2, INT_TO_JSVAL(17));
 
     return true;
 }
 
+template<size_t N> static JSFlatString *
+NewString(JSContext *cx, const jschar (&chars)[N])
+{
+    return js_NewStringCopyN<CanGC>(cx, chars, N);
+}
+
 template<size_t N> inline bool
 Parse(JSContext *cx, const char (&input)[N], JS::MutableHandleValue vp)
 {
     AutoInflatedString str(cx);
     str = input;
     CHECK(JS_ParseJSON(cx, str.chars(), str.length(), vp));
     return true;
 }
--- a/js/src/jsapi-tests/testScriptInfo.cpp
+++ b/js/src/jsapi-tests/testScriptInfo.cpp
@@ -17,26 +17,16 @@ try {              \n\
 	 xx += 1;  \n\
 }                  \n\
 catch (e)          \n\
 {                  \n\
 	 xx += 1;  \n\
 }\n\
 //@ sourceMappingURL=http://example.com/path/to/source-map.json";
 
-
-static bool
-CharsMatch(const jschar *p, const char *q) {
-    while (*q) {
-        if (*p++ != *q++)
-            return false;
-    }
-    return true;
-}
-
 // Bug 670958 - fix JS_GetScriptLineExtent, among others
 BEGIN_TEST(testScriptInfo)
 {
     unsigned startLine = 1000;
 
     JS::CompileOptions options(cx);
     options.setFileAndLine(__FILE__, startLine);
     JS::RootedScript script(cx, JS_CompileScript(cx, global, code, strlen(code),
@@ -50,9 +40,18 @@ BEGIN_TEST(testScriptInfo)
     CHECK_EQUAL(JS_GetScriptLineExtent(cx, script), 11);
     CHECK(strcmp(JS_GetScriptFilename(cx, script), __FILE__) == 0);
     const jschar *sourceMap = JS_GetScriptSourceMap(cx, script);
     CHECK(sourceMap);
     CHECK(CharsMatch(sourceMap, "http://example.com/path/to/source-map.json"));
 
     return true;
 }
+static bool
+CharsMatch(const jschar *p, const char *q)
+{
+    while (*q) {
+        if (*p++ != *q++)
+            return false;
+    }
+    return true;
+}
 END_TEST(testScriptInfo)
--- a/js/src/jsapi-tests/testSetProperty.cpp
+++ b/js/src/jsapi-tests/testSetProperty.cpp
@@ -2,35 +2,28 @@
  * vim: set ts=8 sts=4 et sw=4 tw=99:
  */
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #include "jsapi-tests/tests.h"
 
-static bool
-nativeGet(JSContext *cx, JS::HandleObject obj, JS::HandleId id, JS::MutableHandleValue vp)
-{
-    vp.set(INT_TO_JSVAL(17));
-    return true;
-}
-
 BEGIN_TEST(testSetProperty_NativeGetterStubSetter)
 {
     JS::RootedObject obj(cx, JS_NewObject(cx, nullptr, nullptr, nullptr));
     CHECK(obj);
     JS::RootedValue vobj(cx, OBJECT_TO_JSVAL(obj));
 
     CHECK(JS_DefineProperty(cx, global, "globalProp", vobj,
                             JS_PropertyStub, JS_StrictPropertyStub,
                             JSPROP_ENUMERATE));
 
     CHECK(JS_DefineProperty(cx, obj, "prop", JSVAL_VOID,
-                            nativeGet, JS_StrictPropertyStub,
+                            NativeGet, JS_StrictPropertyStub,
                             JSPROP_SHARED));
 
     EXEC("'use strict';                                     \n"
          "var error, passed = false;                        \n"
          "try                                               \n"
          "{                                                 \n"
          "  this.globalProp.prop = 42;                      \n"
          "  throw new Error('setting property succeeded!'); \n"
@@ -59,16 +52,22 @@ BEGIN_TEST(testSetProperty_NativeGetterS
          "  error = e;                                      \n"
          "}                                                 \n"
          "                                                  \n"
          "if (!passed)                                      \n"
          "  throw error;                                    \n");
 
     return true;
 }
+static bool
+NativeGet(JSContext *cx, JS::HandleObject obj, JS::HandleId id, JS::MutableHandleValue vp)
+{
+    vp.set(INT_TO_JSVAL(17));
+    return true;
+}
 END_TEST(testSetProperty_NativeGetterStubSetter)
 
 BEGIN_TEST(testSetProperty_InheritedGlobalSetter)
 {
     // This is a JSAPI test because jsapi-test globals do not have a resolve
     // hook and therefore can use the property cache in some cases where the
     // shell can't.
     JS_ASSERT(JS_GetClass(global)->resolve == &JS_ResolveStub);
--- a/js/src/jsapi-tests/testSlowScript.cpp
+++ b/js/src/jsapi-tests/testSlowScript.cpp
@@ -1,23 +1,23 @@
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #include "jsapi-tests/tests.h"
 
-bool
+static bool
 OperationCallback(JSContext *cx)
 {
     return false;
 }
 
 static unsigned sRemain;
 
-bool
+static bool
 TriggerOperationCallback(JSContext *cx, unsigned argc, jsval *vp)
 {
     if (!sRemain--)
         JS_TriggerOperationCallback(JS_GetRuntime(cx));
     *vp = JSVAL_VOID;
     return true;
 }
 
--- a/js/src/jsapi-tests/testSourcePolicy.cpp
+++ b/js/src/jsapi-tests/testSourcePolicy.cpp
@@ -19,30 +19,30 @@ BEGIN_TEST(testBug795104)
     CHECK(JS::Evaluate(cx, global, opts, s, strLen, nullptr));
     CHECK(JS::CompileFunction(cx, global, opts, "f", 0, nullptr, s, strLen));
     JS_free(cx, s);
 
     return true;
 }
 END_TEST(testBug795104)
 
-const char *simpleSource = "var x = 4;";
-
-static void
-newScriptHook(JSContext *cx, const char *fn, unsigned lineno,
-              JSScript *script, JSFunction *fun, void *data)
-{
-    if (!JS_StringEqualsAscii(cx, script->sourceData(cx), simpleSource, (bool *)data))
-        *((bool *)data) = false;
-}
+static const char *const simpleSource = "var x = 4;";
 
 BEGIN_TEST(testScriptSourceReentrant)
 {
     JS::CompileOptions opts(cx);
     bool match = false;
-    JS_SetNewScriptHook(rt, newScriptHook, &match);
+    JS_SetNewScriptHook(rt, NewScriptHook, &match);
     CHECK(JS::Evaluate(cx, global, opts, simpleSource, strlen(simpleSource), nullptr));
     CHECK(match);
     JS_SetNewScriptHook(rt, nullptr, nullptr);
 
     return true;
 }
+
+static void
+NewScriptHook(JSContext *cx, const char *fn, unsigned lineno,
+              JSScript *script, JSFunction *fun, void *data)
+{
+    if (!JS_StringEqualsAscii(cx, script->sourceData(cx), simpleSource, (bool *)data))
+        *((bool *)data) = false;
+}
 END_TEST(testScriptSourceReentrant)
--- a/js/src/jsapi-tests/testXDR.cpp
+++ b/js/src/jsapi-tests/testXDR.cpp
@@ -31,17 +31,17 @@ CompileScriptForPrincipalsVersionOrigin(
            .setOriginPrincipals(originPrincipals)
            .setFileAndLine(filename, lineno)
            .setVersion(version);
     JSScript *script = JS::Compile(cx, obj, options, chars, nchars);
     free(chars);
     return script;
 }
 
-JSScript *
+static JSScript *
 FreezeThaw(JSContext *cx, JS::HandleScript script)
 {
     // freeze
     uint32_t nbytes;
     void *memory = JS_EncodeScript(cx, script, &nbytes);
     if (!memory)
         return nullptr;
 
@@ -53,17 +53,17 @@ FreezeThaw(JSContext *cx, JS::HandleScri
 }
 
 static JSScript *
 GetScript(JSContext *cx, JS::HandleObject funobj)
 {
     return JS_GetFunctionScript(cx, JS_GetObjectFunction(funobj));
 }
 
-JSObject *
+static JSObject *
 FreezeThaw(JSContext *cx, JS::HandleObject funobj)
 {
     // freeze
     uint32_t nbytes;
     void *memory = JS_EncodeInterpretedFunction(cx, funobj, &nbytes);
     if (!memory)
         return nullptr;
 
--- a/js/src/jsarray.cpp
+++ b/js/src/jsarray.cpp
@@ -1486,20 +1486,20 @@ CompareLexicographicInt32(JSContext *cx,
 
 static inline bool
 CompareSubStringValues(JSContext *cx, const jschar *s1, size_t l1,
                        const jschar *s2, size_t l2, bool *lessOrEqualp)
 {
     if (!JS_CHECK_OPERATION_LIMIT(cx))
         return false;
 
-    int32_t result;
-    if (!s1 || !s2 || !CompareChars(s1, l1, s2, l2, &result))
+    if (!s1 || !s2)
         return false;
 
+    int32_t result = CompareChars(s1, l1, s2, l2);
     *lessOrEqualp = (result <= 0);
     return true;
 }
 
 struct SortComparatorStrings
 {
     JSContext   *const cx;
 
--- a/js/src/jscompartment.cpp
+++ b/js/src/jscompartment.cpp
@@ -722,17 +722,17 @@ CreateLazyScriptsForCompartment(JSContex
             }
         }
     }
 
     return true;
 }
 
 bool
-JSCompartment::setDebugModeFromC(JSContext *cx, bool b, AutoDebugModeGC &dmgc)
+JSCompartment::setDebugModeFromC(JSContext *cx, bool b, AutoDebugModeInvalidation &invalidate)
 {
     bool enabledBefore = debugMode();
     bool enabledAfter = (debugModeBits & ~unsigned(DebugFromC)) || b;
 
     // Debug mode can be enabled only when no scripts from the target
     // compartment are on the stack. It would even be incorrect to discard just
     // the non-live scripts' JITScripts because they might share ICs with live
     // scripts (bug 632343).
@@ -751,110 +751,102 @@ JSCompartment::setDebugModeFromC(JSConte
         }
         if (enabledAfter && !CreateLazyScriptsForCompartment(cx))
             return false;
     }
 
     debugModeBits = (debugModeBits & ~unsigned(DebugFromC)) | (b ? DebugFromC : 0);
     JS_ASSERT(debugMode() == enabledAfter);
     if (enabledBefore != enabledAfter) {
-        updateForDebugMode(cx->runtime()->defaultFreeOp(), dmgc);
+        updateForDebugMode(cx->runtime()->defaultFreeOp(), invalidate);
         if (!enabledAfter)
             DebugScopes::onCompartmentLeaveDebugMode(this);
     }
     return true;
 }
 
 void
-JSCompartment::updateForDebugMode(FreeOp *fop, AutoDebugModeGC &dmgc)
+JSCompartment::updateForDebugMode(FreeOp *fop, AutoDebugModeInvalidation &invalidate)
 {
     JSRuntime *rt = runtimeFromMainThread();
 
     for (ContextIter acx(rt); !acx.done(); acx.next()) {
         if (acx->compartment() == this)
             acx->updateJITEnabled();
     }
 
 #ifdef JS_ION
+    MOZ_ASSERT(invalidate.isFor(this));
     JS_ASSERT_IF(debugMode(), !hasScriptsOnStack());
 
-    // When we change a compartment's debug mode, whether we're turning it
-    // on or off, we must always throw away all analyses: debug mode
-    // affects various aspects of the analysis, which then get baked into
-    // SSA results, which affects code generation in complicated ways. We
-    // must also throw away all JIT code, as its soundness depends on the
-    // analyses.
+    // Invalidate all JIT code since debug mode invalidates assumptions made
+    // by the JIT.
     //
-    // It suffices to do a garbage collection cycle or to finish the
-    // ongoing GC cycle. The necessary cleanup happens in
-    // JSCompartment::sweep.
-    //
-    // dmgc makes sure we can't forget to GC, but it is also important not
-    // to run any scripts in this compartment until the dmgc is destroyed.
-    // That is the caller's responsibility.
-    if (!rt->isHeapBusy())
-        dmgc.scheduleGC(zone());
+    // The AutoDebugModeInvalidation argument makes sure we can't forget to
+    // invalidate, but it is also important not to run any scripts in this
+    // compartment until the invalidate is destroyed.  That is the caller's
+    // responsibility.
+    invalidate.scheduleInvalidation(debugMode());
 #endif
 }
 
 bool
 JSCompartment::addDebuggee(JSContext *cx, js::GlobalObject *global)
 {
-    AutoDebugModeGC dmgc(cx->runtime());
-    return addDebuggee(cx, global, dmgc);
+    AutoDebugModeInvalidation invalidate(this);
+    return addDebuggee(cx, global, invalidate);
 }
 
 bool
 JSCompartment::addDebuggee(JSContext *cx,
                            GlobalObject *globalArg,
-                           AutoDebugModeGC &dmgc)
+                           AutoDebugModeInvalidation &invalidate)
 {
     Rooted<GlobalObject*> global(cx, globalArg);
 
     bool wasEnabled = debugMode();
     if (!wasEnabled && !CreateLazyScriptsForCompartment(cx))
         return false;
     if (!debuggees.put(global)) {
         js_ReportOutOfMemory(cx);
         return false;
     }
     debugModeBits |= DebugFromJS;
-    if (!wasEnabled) {
-        updateForDebugMode(cx->runtime()->defaultFreeOp(), dmgc);
-    }
+    if (!wasEnabled)
+        updateForDebugMode(cx->runtime()->defaultFreeOp(), invalidate);
     return true;
 }
 
 void
 JSCompartment::removeDebuggee(FreeOp *fop,
                               js::GlobalObject *global,
                               js::GlobalObjectSet::Enum *debuggeesEnum)
 {
-    AutoDebugModeGC dmgc(fop->runtime());
-    return removeDebuggee(fop, global, dmgc, debuggeesEnum);
+    AutoDebugModeInvalidation invalidate(this);
+    return removeDebuggee(fop, global, invalidate, debuggeesEnum);
 }
 
 void
 JSCompartment::removeDebuggee(FreeOp *fop,
                               js::GlobalObject *global,
-                              AutoDebugModeGC &dmgc,
+                              AutoDebugModeInvalidation &invalidate,
                               js::GlobalObjectSet::Enum *debuggeesEnum)
 {
     bool wasEnabled = debugMode();
     JS_ASSERT(debuggees.has(global));
     if (debuggeesEnum)
         debuggeesEnum->removeFront();
     else
         debuggees.remove(global);
 
     if (debuggees.empty()) {
         debugModeBits &= ~DebugFromJS;
         if (wasEnabled && !debugMode()) {
             DebugScopes::onCompartmentLeaveDebugMode(this);
-            updateForDebugMode(fop, dmgc);
+            updateForDebugMode(fop, invalidate);
         }
     }
 }
 
 void
 JSCompartment::clearBreakpointsIn(FreeOp *fop, js::Debugger *dbg, JSObject *handler)
 {
     for (gc::CellIter i(zone(), gc::FINALIZE_SCRIPT); !i.done(); i.next()) {
--- a/js/src/jscompartment.h
+++ b/js/src/jscompartment.h
@@ -105,17 +105,17 @@ typedef HashMap<CrossCompartmentKey, Rea
 
 } /* namespace js */
 
 namespace JS {
 struct TypeInferenceSizes;
 }
 
 namespace js {
-class AutoDebugModeGC;
+class AutoDebugModeInvalidation;
 class ArrayBufferObject;
 class DebugScopes;
 class WeakMapBase;
 }
 
 struct JSCompartment
 {
     JS::CompartmentOptions       options_;
@@ -359,29 +359,30 @@ struct JSCompartment
      */
     bool debugMode() const { return !!debugModeBits; }
 
     /* True if any scripts from this compartment are on the JS stack. */
     bool hasScriptsOnStack();
 
   private:
     /* This is called only when debugMode() has just toggled. */
-    void updateForDebugMode(js::FreeOp *fop, js::AutoDebugModeGC &dmgc);
+    void updateForDebugMode(js::FreeOp *fop, js::AutoDebugModeInvalidation &invalidate);
 
   public:
     js::GlobalObjectSet &getDebuggees() { return debuggees; }
     bool addDebuggee(JSContext *cx, js::GlobalObject *global);
     bool addDebuggee(JSContext *cx, js::GlobalObject *global,
-                     js::AutoDebugModeGC &dmgc);
+                     js::AutoDebugModeInvalidation &invalidate);
     void removeDebuggee(js::FreeOp *fop, js::GlobalObject *global,
                         js::GlobalObjectSet::Enum *debuggeesEnum = nullptr);
     void removeDebuggee(js::FreeOp *fop, js::GlobalObject *global,
-                        js::AutoDebugModeGC &dmgc,
+                        js::AutoDebugModeInvalidation &invalidate,
                         js::GlobalObjectSet::Enum *debuggeesEnum = nullptr);
-    bool setDebugModeFromC(JSContext *cx, bool b, js::AutoDebugModeGC &dmgc);
+    bool setDebugModeFromC(JSContext *cx, bool b,
+                           js::AutoDebugModeInvalidation &invalidate);
 
     void clearBreakpointsIn(js::FreeOp *fop, js::Debugger *dbg, JSObject *handler);
     void clearTraps(js::FreeOp *fop);
 
   private:
     void sweepBreakpoints(js::FreeOp *fop);
 
   public:
@@ -417,39 +418,66 @@ struct JSCompartment
 
 inline bool
 JSRuntime::isAtomsZone(JS::Zone *zone)
 {
     return zone == atomsCompartment_->zone();
 }
 
 // For use when changing the debug mode flag on one or more compartments.
-// Do not run scripts in any compartment that is scheduled for GC using this
-// object. See comment in updateForDebugMode.
+// Invalidate and discard JIT code since debug mode breaks JIT assumptions.
+//
+// AutoDebugModeInvalidation has two modes: compartment or zone
+// invalidation. While it is correct to always use compartment invalidation,
+// if you know ahead of time you need to invalidate a whole zone, it is faster
+// to invalidate the zone.
+//
+// Compartment invalidation only invalidates scripts belonging to that
+// compartment.
+//
+// Zone invalidation invalidates all scripts belonging to non-special
+// (i.e. those with principals) compartments of the zone.
 //
-class js::AutoDebugModeGC
+// FIXME: Remove entirely once bug 716647 lands.
+//
+class js::AutoDebugModeInvalidation
 {
-    JSRuntime *rt;
-    bool needGC;
+    JSCompartment *comp_;
+    JS::Zone *zone_;
+
+    enum {
+        NoNeed = 0,
+        ToggledOn = 1,
+        ToggledOff = 2
+    } needInvalidation_;
+
   public:
-    explicit AutoDebugModeGC(JSRuntime *rt) : rt(rt), needGC(false) {}
+    explicit AutoDebugModeInvalidation(JSCompartment *comp)
+      : comp_(comp), zone_(nullptr), needInvalidation_(NoNeed)