Merge m-c to fx-team.
authorRyan VanderMeulen <ryanvm@gmail.com>
Thu, 06 Feb 2014 16:34:33 -0500
changeset 184625 373a24c89dd98d2efdc0d1b0af059fec08344e69
parent 184624 f9c1a27f64bbff197dd42d4c5bad3e39f07e35e3 (current diff)
parent 184518 262e73a6b7cd4da56cae4e5ac83eaad7a78f3656 (diff)
child 184626 40af3220c80006d28a224e222469968c1eed1326
push id3503
push userraliiev@mozilla.com
push dateMon, 28 Apr 2014 18:51:11 +0000
treeherdermozilla-beta@c95ac01e332e [default view] [failures only]
perfherder[talos] [build metrics] [platform microbench] (compared to previous push)
milestone30.0a1
first release with
nightly linux32
nightly linux64
nightly mac
nightly win32
nightly win64
last release without
nightly linux32
nightly linux64
nightly mac
nightly win32
nightly win64
Merge m-c to fx-team.
content/media/webaudio/EnableWebAudioCheck.cpp
content/media/webaudio/EnableWebAudioCheck.h
dom/nfc/MozNdefRecord.cpp
dom/nfc/MozNdefRecord.h
dom/webidl/MozNdefRecord.webidl
--- a/b2g/app/b2g.js
+++ b/b2g/app/b2g.js
@@ -869,16 +869,17 @@ pref("osfile.reset_worker_delay", 5000);
 // The URL of the Firefox Accounts auth server backend
 pref("identity.fxaccounts.auth.uri", "https://api-accounts.dev.lcip.org/v1");
 
 // APZC preferences.
 //
 // Gaia relies heavily on scroll events for now, so lets fire them
 // more often than the default value (100).
 pref("apz.asyncscroll.throttle", 40);
+pref("apz.pan_repaint_interval", 40);
 
 // This preference allows FirefoxOS apps (and content, I think) to force
 // the use of software (instead of hardware accelerated) 2D canvases by
 // creating a context like this:
 //
 //   canvas.getContext('2d', { willReadFrequently: true })
 //
 // Using a software canvas can save memory when JS calls getImageData()
--- a/b2g/config/emulator-ics/sources.xml
+++ b/b2g/config/emulator-ics/sources.xml
@@ -7,17 +7,17 @@
   <remote fetch="https://git.mozilla.org/releases" name="mozillaorg"/>
   <remote fetch="https://git.mozilla.org/external/apitrace" name="apitrace"/>
   <default remote="caf" revision="refs/tags/android-4.0.4_r2.1" sync-j="4"/>
   <!-- Gonk specific things and forks -->
   <project name="platform_build" path="build" remote="b2g" revision="59605a7c026ff06cc1613af3938579b1dddc6cfe">
     <copyfile dest="Makefile" src="core/root.mk"/>
   </project>
   <project name="fake-dalvik" path="dalvik" remote="b2g" revision="ca1f327d5acc198bb4be62fa51db2c039032c9ce"/>
-  <project name="gaia.git" path="gaia" remote="mozillaorg" revision="743afeb3a5a3e354b5cf20f64bd57f65dcccd995"/>
+  <project name="gaia.git" path="gaia" remote="mozillaorg" revision="ea4a1f0d94a995486ed219f47132949071ecc172"/>
   <project name="gonk-misc" path="gonk-misc" remote="b2g" revision="49c722fa1a5e1873fa0010829fd97d0b74009ca5"/>
   <project name="rilproxy" path="rilproxy" remote="b2g" revision="827214fcf38d6569aeb5c6d6f31cb296d1f09272"/>
   <project name="platform_hardware_ril" path="hardware/ril" remote="b2g" revision="eda08beb3ba9a159843c70ffde0f9660ec351eb9"/>
   <project name="platform_external_qemu" path="external/qemu" remote="b2g" revision="87aa8679560ce09f6445621d6f370d9de722cdba"/>
   <project name="moztt" path="external/moztt" remote="b2g" revision="e33ea242b4328fb0d1824c951f379332b5021512"/>
   <project name="apitrace" path="external/apitrace" remote="apitrace" revision="788d9ce293a9b44f64536130cf4ad577e8101dbe"/>
   <!-- Stock Android things -->
   <project name="platform/abi/cpp" path="abi/cpp" revision="dd924f92906085b831bf1cbbc7484d3c043d613c"/>
--- a/b2g/config/emulator-jb/sources.xml
+++ b/b2g/config/emulator-jb/sources.xml
@@ -6,17 +6,17 @@
   <remote fetch="https://git.mozilla.org/external/caf" name="caf"/>
   <remote fetch="https://git.mozilla.org/releases" name="mozillaorg"/>
   <!-- B2G specific things. -->
   <project name="platform_build" path="build" remote="b2g" revision="317f25e0a4cb3e8e86e2b76c37a14081372f0307">
     <copyfile dest="Makefile" src="core/root.mk"/>
   </project>
   <project name="rilproxy" path="rilproxy" remote="b2g" revision="827214fcf38d6569aeb5c6d6f31cb296d1f09272"/>
   <project name="fake-libdvm" path="dalvik" remote="b2g" revision="d50ae982b19f42f0b66d08b9eb306be81687869f"/>
-  <project name="gaia" path="gaia" remote="mozillaorg" revision="743afeb3a5a3e354b5cf20f64bd57f65dcccd995"/>
+  <project name="gaia" path="gaia" remote="mozillaorg" revision="ea4a1f0d94a995486ed219f47132949071ecc172"/>
   <project name="gonk-misc" path="gonk-misc" remote="b2g" revision="49c722fa1a5e1873fa0010829fd97d0b74009ca5"/>
   <project name="moztt" path="external/moztt" remote="b2g" revision="e33ea242b4328fb0d1824c951f379332b5021512"/>
   <project name="apitrace" path="external/apitrace" remote="apitrace" revision="788d9ce293a9b44f64536130cf4ad577e8101dbe"/>
   <project name="valgrind" path="external/valgrind" remote="b2g" revision="905bfa3548eb75cf1792d0d8412b92113bbd4318"/>
   <project name="vex" path="external/VEX" remote="b2g" revision="c3d7efc45414f1b44cd9c479bb2758c91c4707c0"/>
   <!-- Stock Android things -->
   <project groups="linux" name="platform/prebuilts/clang/linux-x86/3.1" path="prebuilts/clang/linux-x86/3.1" revision="5c45f43419d5582949284eee9cef0c43d866e03b"/>
   <project groups="linux" name="platform/prebuilts/clang/linux-x86/3.2" path="prebuilts/clang/linux-x86/3.2" revision="3748b4168e7bd8d46457d4b6786003bc6a5223ce"/>
@@ -119,12 +119,12 @@
   <default remote="caf" revision="refs/tags/android-4.3_r2.1" sync-j="4"/>
   <!-- Emulator specific things -->
   <project name="device/generic/armv7-a-neon" path="device/generic/armv7-a-neon" revision="3a9a17613cc685aa232432566ad6cc607eab4ec1"/>
   <project name="device_generic_goldfish" path="device/generic/goldfish" remote="b2g" revision="09485b73629856b21b2ed6073e327ab0e69a1189"/>
   <project name="platform/external/libnfc-nci" path="external/libnfc-nci" revision="7d33aaf740bbf6c7c6e9c34a92b371eda311b66b"/>
   <project name="platform_external_qemu" path="external/qemu" remote="b2g" revision="8f7c9ac889ae2c778197b4a4c0529d60530f480b"/>
   <project name="platform/external/wpa_supplicant_8" path="external/wpa_supplicant_8" revision="0e56e450367cd802241b27164a2979188242b95f"/>
   <project name="platform_hardware_ril" path="hardware/ril" remote="b2g" revision="2838a77ce4b8c09fa6a46fe25410bb3a4474cbd4"/>
-  <project name="platform_system_nfcd" path="system/nfcd" remote="b2g" revision="f995ccdb7c023b7edd8064c9d06fbea8f7108c45"/>
+  <project name="platform_system_nfcd" path="system/nfcd" remote="b2g" revision="5af419c0af0650066c0c58a5e99125b1002a62c5"/>
   <project name="platform/development" path="development" revision="1f18cfe031ce23b7fb838fe3d4379dd802b49e71"/>
   <project name="android-sdk" path="sdk" remote="b2g" revision="8b1365af38c9a653df97349ee53a3f5d64fd590a"/>
 </manifest>
--- a/b2g/config/emulator/sources.xml
+++ b/b2g/config/emulator/sources.xml
@@ -7,17 +7,17 @@
   <remote fetch="https://git.mozilla.org/releases" name="mozillaorg"/>
   <remote fetch="https://git.mozilla.org/external/apitrace" name="apitrace"/>
   <default remote="caf" revision="refs/tags/android-4.0.4_r2.1" sync-j="4"/>
   <!-- Gonk specific things and forks -->
   <project name="platform_build" path="build" remote="b2g" revision="59605a7c026ff06cc1613af3938579b1dddc6cfe">
     <copyfile dest="Makefile" src="core/root.mk"/>
   </project>
   <project name="fake-dalvik" path="dalvik" remote="b2g" revision="ca1f327d5acc198bb4be62fa51db2c039032c9ce"/>
-  <project name="gaia.git" path="gaia" remote="mozillaorg" revision="743afeb3a5a3e354b5cf20f64bd57f65dcccd995"/>
+  <project name="gaia.git" path="gaia" remote="mozillaorg" revision="ea4a1f0d94a995486ed219f47132949071ecc172"/>
   <project name="gonk-misc" path="gonk-misc" remote="b2g" revision="49c722fa1a5e1873fa0010829fd97d0b74009ca5"/>
   <project name="rilproxy" path="rilproxy" remote="b2g" revision="827214fcf38d6569aeb5c6d6f31cb296d1f09272"/>
   <project name="platform_hardware_ril" path="hardware/ril" remote="b2g" revision="eda08beb3ba9a159843c70ffde0f9660ec351eb9"/>
   <project name="platform_external_qemu" path="external/qemu" remote="b2g" revision="87aa8679560ce09f6445621d6f370d9de722cdba"/>
   <project name="moztt" path="external/moztt" remote="b2g" revision="e33ea242b4328fb0d1824c951f379332b5021512"/>
   <project name="apitrace" path="external/apitrace" remote="apitrace" revision="788d9ce293a9b44f64536130cf4ad577e8101dbe"/>
   <!-- Stock Android things -->
   <project name="platform/abi/cpp" path="abi/cpp" revision="dd924f92906085b831bf1cbbc7484d3c043d613c"/>
--- a/b2g/config/gaia.json
+++ b/b2g/config/gaia.json
@@ -1,4 +1,4 @@
 {
-    "revision": "9e58b7068dc8cc4883ed092c8599ece51ebb2575", 
+    "revision": "b82f9138def9e1b0ce69667ca29069cd8b785d5e", 
     "repo_path": "/integration/gaia-central"
 }
--- a/b2g/config/hamachi/sources.xml
+++ b/b2g/config/hamachi/sources.xml
@@ -6,17 +6,17 @@
   <remote fetch="https://git.mozilla.org/releases" name="mozillaorg"/>
   <remote fetch="https://git.mozilla.org/external/apitrace" name="apitrace"/>
   <default remote="caf" revision="b2g/ics_strawberry" sync-j="4"/>
   <!-- Gonk specific things and forks -->
   <project name="platform_build" path="build" remote="b2g" revision="59605a7c026ff06cc1613af3938579b1dddc6cfe">
     <copyfile dest="Makefile" src="core/root.mk"/>
   </project>
   <project name="fake-dalvik" path="dalvik" remote="b2g" revision="ca1f327d5acc198bb4be62fa51db2c039032c9ce"/>
-  <project name="gaia.git" path="gaia" remote="mozillaorg" revision="743afeb3a5a3e354b5cf20f64bd57f65dcccd995"/>
+  <project name="gaia.git" path="gaia" remote="mozillaorg" revision="ea4a1f0d94a995486ed219f47132949071ecc172"/>
   <project name="gonk-misc" path="gonk-misc" remote="b2g" revision="49c722fa1a5e1873fa0010829fd97d0b74009ca5"/>
   <project name="rilproxy" path="rilproxy" remote="b2g" revision="827214fcf38d6569aeb5c6d6f31cb296d1f09272"/>
   <project name="librecovery" path="librecovery" remote="b2g" revision="84f2f2fce22605e17d511ff1767e54770067b5b5"/>
   <project name="moztt" path="external/moztt" remote="b2g" revision="e33ea242b4328fb0d1824c951f379332b5021512"/>
   <project name="apitrace" path="external/apitrace" remote="apitrace" revision="788d9ce293a9b44f64536130cf4ad577e8101dbe"/>
   <!-- Stock Android things -->
   <project name="platform/abi/cpp" path="abi/cpp" revision="6426040f1be4a844082c9769171ce7f5341a5528"/>
   <project name="platform/bionic" path="bionic" revision="d2eb6c7b6e1bc7643c17df2d9d9bcb1704d0b9ab"/>
--- a/b2g/config/helix/sources.xml
+++ b/b2g/config/helix/sources.xml
@@ -5,17 +5,17 @@
   <remote fetch="https://git.mozilla.org/external/caf" name="caf"/>
   <remote fetch="https://git.mozilla.org/releases" name="mozillaorg"/>
   <default remote="caf" revision="b2g/ics_strawberry" sync-j="4"/>
   <!-- Gonk specific things and forks -->
   <project name="platform_build" path="build" remote="b2g" revision="59605a7c026ff06cc1613af3938579b1dddc6cfe">
     <copyfile dest="Makefile" src="core/root.mk"/>
   </project>
   <project name="fake-dalvik" path="dalvik" remote="b2g" revision="ca1f327d5acc198bb4be62fa51db2c039032c9ce"/>
-  <project name="gaia.git" path="gaia" remote="mozillaorg" revision="743afeb3a5a3e354b5cf20f64bd57f65dcccd995"/>
+  <project name="gaia.git" path="gaia" remote="mozillaorg" revision="ea4a1f0d94a995486ed219f47132949071ecc172"/>
   <project name="gonk-misc" path="gonk-misc" remote="b2g" revision="49c722fa1a5e1873fa0010829fd97d0b74009ca5"/>
   <project name="rilproxy" path="rilproxy" remote="b2g" revision="827214fcf38d6569aeb5c6d6f31cb296d1f09272"/>
   <project name="librecovery" path="librecovery" remote="b2g" revision="84f2f2fce22605e17d511ff1767e54770067b5b5"/>
   <project name="moztt" path="external/moztt" remote="b2g" revision="e33ea242b4328fb0d1824c951f379332b5021512"/>
   <project name="gonk-patches" path="patches" remote="b2g" revision="223a2421006e8f5da33f516f6891c87cae86b0f6"/>
   <!-- Stock Android things -->
   <project name="platform/abi/cpp" path="abi/cpp" revision="6426040f1be4a844082c9769171ce7f5341a5528"/>
   <project name="platform/bionic" path="bionic" revision="d2eb6c7b6e1bc7643c17df2d9d9bcb1704d0b9ab"/>
--- a/b2g/config/inari/sources.xml
+++ b/b2g/config/inari/sources.xml
@@ -7,17 +7,17 @@
   <remote fetch="https://git.mozilla.org/releases" name="mozillaorg"/>
   <remote fetch="https://git.mozilla.org/external/apitrace" name="apitrace"/>
   <default remote="caf" revision="ics_chocolate_rb4.2" sync-j="4"/>
   <!-- Gonk specific things and forks -->
   <project name="platform_build" path="build" remote="b2g" revision="59605a7c026ff06cc1613af3938579b1dddc6cfe">
     <copyfile dest="Makefile" src="core/root.mk"/>
   </project>
   <project name="fake-dalvik" path="dalvik" remote="b2g" revision="ca1f327d5acc198bb4be62fa51db2c039032c9ce"/>
-  <project name="gaia.git" path="gaia" remote="mozillaorg" revision="743afeb3a5a3e354b5cf20f64bd57f65dcccd995"/>
+  <project name="gaia.git" path="gaia" remote="mozillaorg" revision="ea4a1f0d94a995486ed219f47132949071ecc172"/>
   <project name="gonk-misc" path="gonk-misc" remote="b2g" revision="49c722fa1a5e1873fa0010829fd97d0b74009ca5"/>
   <project name="rilproxy" path="rilproxy" remote="b2g" revision="827214fcf38d6569aeb5c6d6f31cb296d1f09272"/>
   <project name="librecovery" path="librecovery" remote="b2g" revision="84f2f2fce22605e17d511ff1767e54770067b5b5"/>
   <project name="moztt" path="external/moztt" remote="b2g" revision="e33ea242b4328fb0d1824c951f379332b5021512"/>
   <project name="apitrace" path="external/apitrace" remote="apitrace" revision="788d9ce293a9b44f64536130cf4ad577e8101dbe"/>
   <!-- Stock Android things -->
   <project name="platform/abi/cpp" path="abi/cpp" revision="6426040f1be4a844082c9769171ce7f5341a5528"/>
   <project name="platform/bionic" path="bionic" revision="cd5dfce80bc3f0139a56b58aca633202ccaee7f8"/>
--- a/b2g/config/leo/sources.xml
+++ b/b2g/config/leo/sources.xml
@@ -6,17 +6,17 @@
   <remote fetch="https://git.mozilla.org/releases" name="mozillaorg"/>
   <remote fetch="https://git.mozilla.org/external/apitrace" name="apitrace"/>
   <default remote="caf" revision="b2g/ics_strawberry" sync-j="4"/>
   <!-- Gonk specific things and forks -->
   <project name="platform_build" path="build" remote="b2g" revision="59605a7c026ff06cc1613af3938579b1dddc6cfe">
     <copyfile dest="Makefile" src="core/root.mk"/>
   </project>
   <project name="fake-dalvik" path="dalvik" remote="b2g" revision="ca1f327d5acc198bb4be62fa51db2c039032c9ce"/>
-  <project name="gaia.git" path="gaia" remote="mozillaorg" revision="743afeb3a5a3e354b5cf20f64bd57f65dcccd995"/>
+  <project name="gaia.git" path="gaia" remote="mozillaorg" revision="ea4a1f0d94a995486ed219f47132949071ecc172"/>
   <project name="gonk-misc" path="gonk-misc" remote="b2g" revision="49c722fa1a5e1873fa0010829fd97d0b74009ca5"/>
   <project name="rilproxy" path="rilproxy" remote="b2g" revision="827214fcf38d6569aeb5c6d6f31cb296d1f09272"/>
   <project name="librecovery" path="librecovery" remote="b2g" revision="84f2f2fce22605e17d511ff1767e54770067b5b5"/>
   <project name="moztt" path="external/moztt" remote="b2g" revision="e33ea242b4328fb0d1824c951f379332b5021512"/>
   <project name="apitrace" path="external/apitrace" remote="apitrace" revision="788d9ce293a9b44f64536130cf4ad577e8101dbe"/>
   <project name="gonk-patches" path="patches" remote="b2g" revision="223a2421006e8f5da33f516f6891c87cae86b0f6"/>
   <!-- Stock Android things -->
   <project name="platform/abi/cpp" path="abi/cpp" revision="6426040f1be4a844082c9769171ce7f5341a5528"/>
--- a/b2g/config/mako/sources.xml
+++ b/b2g/config/mako/sources.xml
@@ -6,17 +6,17 @@
   <remote fetch="https://git.mozilla.org/external/caf" name="caf"/>
   <remote fetch="https://git.mozilla.org/releases" name="mozillaorg"/>
   <!-- B2G specific things. -->
   <project name="platform_build" path="build" remote="b2g" revision="317f25e0a4cb3e8e86e2b76c37a14081372f0307">
     <copyfile dest="Makefile" src="core/root.mk"/>
   </project>
   <project name="rilproxy" path="rilproxy" remote="b2g" revision="827214fcf38d6569aeb5c6d6f31cb296d1f09272"/>
   <project name="fake-libdvm" path="dalvik" remote="b2g" revision="d50ae982b19f42f0b66d08b9eb306be81687869f"/>
-  <project name="gaia" path="gaia" remote="mozillaorg" revision="743afeb3a5a3e354b5cf20f64bd57f65dcccd995"/>
+  <project name="gaia" path="gaia" remote="mozillaorg" revision="ea4a1f0d94a995486ed219f47132949071ecc172"/>
   <project name="gonk-misc" path="gonk-misc" remote="b2g" revision="49c722fa1a5e1873fa0010829fd97d0b74009ca5"/>
   <project name="moztt" path="external/moztt" remote="b2g" revision="e33ea242b4328fb0d1824c951f379332b5021512"/>
   <project name="apitrace" path="external/apitrace" remote="apitrace" revision="788d9ce293a9b44f64536130cf4ad577e8101dbe"/>
   <project name="valgrind" path="external/valgrind" remote="b2g" revision="905bfa3548eb75cf1792d0d8412b92113bbd4318"/>
   <project name="vex" path="external/VEX" remote="b2g" revision="c3d7efc45414f1b44cd9c479bb2758c91c4707c0"/>
   <!-- Stock Android things -->
   <project groups="linux" name="platform/prebuilts/clang/linux-x86/3.1" path="prebuilts/clang/linux-x86/3.1" revision="5c45f43419d5582949284eee9cef0c43d866e03b"/>
   <project groups="linux" name="platform/prebuilts/clang/linux-x86/3.2" path="prebuilts/clang/linux-x86/3.2" revision="3748b4168e7bd8d46457d4b6786003bc6a5223ce"/>
@@ -116,17 +116,17 @@
   <project name="platform/system/netd" path="system/netd" revision="56112dd7b811301b718d0643a82fd5cac9522073"/>
   <project name="platform/system/security" path="system/security" revision="f48ff68fedbcdc12b570b7699745abb6e7574907"/>
   <project name="platform/system/vold" path="system/vold" revision="8de05d4a52b5a91e7336e6baa4592f945a6ddbea"/>
   <default remote="caf" revision="refs/tags/android-4.3_r2.1" sync-j="4"/>
   <!-- Nexus 4 specific things -->
   <project name="device-mako" path="device/lge/mako" remote="b2g" revision="78d17f0c117f0c66dd55ee8d5c5dde8ccc93ecba"/>
   <project name="device/generic/armv7-a-neon" path="device/generic/armv7-a-neon" revision="3a9a17613cc685aa232432566ad6cc607eab4ec1"/>
   <project name="device/lge/mako-kernel" path="device/lge/mako-kernel" revision="d1729e53d71d711c8fde25eab8728ff2b9b4df0e"/>
-  <project name="platform_system_nfcd" path="system/nfcd" remote="b2g" revision="f995ccdb7c023b7edd8064c9d06fbea8f7108c45"/>
+  <project name="platform_system_nfcd" path="system/nfcd" remote="b2g" revision="5af419c0af0650066c0c58a5e99125b1002a62c5"/>
   <project name="platform/external/libnfc-nci" path="external/libnfc-nci" revision="7d33aaf740bbf6c7c6e9c34a92b371eda311b66b"/>
   <project name="platform/external/wpa_supplicant_8" path="external/wpa_supplicant_8" revision="0e56e450367cd802241b27164a2979188242b95f"/>
   <project name="platform/hardware/broadcom/wlan" path="hardware/broadcom/wlan" revision="0e1929fa3aa38bf9d40e9e953d619fab8164c82e"/>
   <project name="platform/hardware/qcom/audio" path="hardware/qcom/audio" revision="b0a528d839cfd9d170d092fe3743b5252b4243a6"/>
   <project name="platform/hardware/qcom/bt" path="hardware/qcom/bt" revision="380945eaa249a2dbdde0daa4c8adb8ca325edba6"/>
   <project name="platform/hardware/qcom/display" path="hardware/qcom/display" revision="6f3b0272cefaffeaed2a7d2bb8f633059f163ddc"/>
   <project name="platform/hardware/qcom/keymaster" path="hardware/qcom/keymaster" revision="16da8262c997a5a0d797885788a64a0771b26910"/>
   <project name="platform/hardware/qcom/media" path="hardware/qcom/media" revision="689b476ba3eb46c34b81343295fe144a0e81a18e"/>
--- a/b2g/config/wasabi/sources.xml
+++ b/b2g/config/wasabi/sources.xml
@@ -6,17 +6,17 @@
   <remote fetch="https://git.mozilla.org/releases" name="mozillaorg"/>
   <remote fetch="https://git.mozilla.org/external/apitrace" name="apitrace"/>
   <default remote="caf" revision="ics_chocolate_rb4.2" sync-j="4"/>
   <!-- Gonk specific things and forks -->
   <project name="platform_build" path="build" remote="b2g" revision="59605a7c026ff06cc1613af3938579b1dddc6cfe">
     <copyfile dest="Makefile" src="core/root.mk"/>
   </project>
   <project name="fake-dalvik" path="dalvik" remote="b2g" revision="ca1f327d5acc198bb4be62fa51db2c039032c9ce"/>
-  <project name="gaia.git" path="gaia" remote="mozillaorg" revision="743afeb3a5a3e354b5cf20f64bd57f65dcccd995"/>
+  <project name="gaia.git" path="gaia" remote="mozillaorg" revision="ea4a1f0d94a995486ed219f47132949071ecc172"/>
   <project name="gonk-misc" path="gonk-misc" remote="b2g" revision="49c722fa1a5e1873fa0010829fd97d0b74009ca5"/>
   <project name="rilproxy" path="rilproxy" remote="b2g" revision="827214fcf38d6569aeb5c6d6f31cb296d1f09272"/>
   <project name="librecovery" path="librecovery" remote="b2g" revision="84f2f2fce22605e17d511ff1767e54770067b5b5"/>
   <project name="moztt" path="external/moztt" remote="b2g" revision="e33ea242b4328fb0d1824c951f379332b5021512"/>
   <project name="apitrace" path="external/apitrace" remote="apitrace" revision="788d9ce293a9b44f64536130cf4ad577e8101dbe"/>
   <project name="gonk-patches" path="patches" remote="b2g" revision="223a2421006e8f5da33f516f6891c87cae86b0f6"/>
   <!-- Stock Android things -->
   <project name="platform/abi/cpp" path="abi/cpp" revision="6426040f1be4a844082c9769171ce7f5341a5528"/>
--- a/build/pgo/server-locations.txt
+++ b/build/pgo/server-locations.txt
@@ -200,8 +200,15 @@ http://xn--lve-6lad.w3c-test.org:83
 # HTTPS versions of the above
 https://w3c-test.org:443
 https://www.w3c-test.org:443
 https://www1.w3c-test.org:443
 https://www2.w3c-test.org:443
 https://xn--n8j6ds53lwwkrqhv28a.w3c-test.org:443
 https://xn--lve-6lad.w3c-test.org:443
 http://test.w3.org:80
+
+# Hosts for testing TLD-based fallback encoding
+http://example.tw:80                privileged
+http://example.cn:80                privileged
+http://example.co.jp:80             privileged
+http://example.fi:80                privileged
+
--- a/content/html/document/src/nsHTMLDocument.cpp
+++ b/content/html/document/src/nsHTMLDocument.cpp
@@ -431,16 +431,76 @@ nsHTMLDocument::TryParentCharset(nsIDocS
     }
 
     aCharset.Assign(parentCharset);
     aCharsetSource = kCharsetFromParentFrame;
   }
 }
 
 void
+nsHTMLDocument::TryTLD(int32_t& aCharsetSource, nsACString& aCharset)
+{
+  if (aCharsetSource >= kCharsetFromTopLevelDomain) {
+    return;
+  }
+  if (!FallbackEncoding::sGuessFallbackFromTopLevelDomain) {
+    return;
+  }
+  if (!mDocumentURI) {
+    return;
+  }
+  nsAutoCString host;
+  mDocumentURI->GetAsciiHost(host);
+  if (host.IsEmpty()) {
+    return;
+  }
+  // First let's see if the host is DNS-absolute and ends with a dot and
+  // get rid of that one.
+  if (host.Last() == '.') {
+    host.SetLength(host.Length() - 1);
+    if (host.IsEmpty()) {
+      return;
+    }
+  }
+  // If we still have a dot, the host is weird, so let's continue only
+  // if we have something other than a dot now.
+  if (host.Last() == '.') {
+    return;
+  }
+  int32_t index = host.RFindChar('.');
+  if (index == kNotFound) {
+    // We have an intranet host, Gecko-internal URL or an IPv6 address.
+    return;
+  }
+  // Since the string didn't end with a dot and we found a dot,
+  // there is at least one character between the dot and the end of
+  // the string, so taking the substring below is safe.
+  nsAutoCString tld;
+  ToLowerCase(Substring(host, index + 1, host.Length() - (index + 1)), tld);
+  // Reject generic TLDs and country TLDs that need more research
+  if (!FallbackEncoding::IsParticipatingTopLevelDomain(tld)) {
+    return;
+  }
+  // Check if we have an IPv4 address
+  bool seenNonDigit = false;
+  for (size_t i = 0; i < tld.Length(); ++i) {
+    char c = tld.CharAt(i);
+    if (c < '0' || c > '9') {
+      seenNonDigit = true;
+      break;
+    }
+  }
+  if (!seenNonDigit) {
+    return;
+  }
+  aCharsetSource = kCharsetFromTopLevelDomain;
+  FallbackEncoding::FromTopLevelDomain(tld, aCharset);
+}
+
+void
 nsHTMLDocument::TryFallback(int32_t& aCharsetSource, nsACString& aCharset)
 {
   if (kCharsetFromFallback <= aCharsetSource)
     return;
 
   aCharsetSource = kCharsetFromFallback;
   FallbackEncoding::FromLocale(aCharset);
 }
@@ -656,16 +716,17 @@ nsHTMLDocument::StartDocumentLoad(const 
 
     TryHintCharset(muCV, charsetSource, charset); // XXX mailnews-only
     TryParentCharset(docShell, charsetSource, charset);
 
     if (cachingChan && !urlSpec.IsEmpty()) {
       TryCacheCharset(cachingChan, charsetSource, charset);
     }
 
+    TryTLD(charsetSource, charset);
     TryFallback(charsetSource, charset);
 
     if (wyciwygChannel) {
       // We know for sure that the parser needs to be using UTF16.
       parserCharset = "UTF-16";
       parserCharsetSource = charsetSource < kCharsetFromChannel ?
         kCharsetFromChannel : charsetSource;
         
--- a/content/html/document/src/nsHTMLDocument.h
+++ b/content/html/document/src/nsHTMLDocument.h
@@ -308,16 +308,17 @@ protected:
                             nsIDocShell*  aDocShell,
                             int32_t& aCharsetSource,
                             nsACString& aCharset);
   static void TryCacheCharset(nsICachingChannel* aCachingChannel,
                                 int32_t& aCharsetSource,
                                 nsACString& aCharset);
   void TryParentCharset(nsIDocShell*  aDocShell,
                         int32_t& charsetSource, nsACString& aCharset);
+  void TryTLD(int32_t& aCharsetSource, nsACString& aCharset);
   static void TryFallback(int32_t& aCharsetSource, nsACString& aCharset);
 
   // Override so we can munge the charset on our wyciwyg channel as needed.
   virtual void SetDocumentCharacterSet(const nsACString& aCharSetID) MOZ_OVERRIDE;
 
   // Tracks if we are currently processing any document.write calls (either
   // implicit or explicit). Note that if a write call writes out something which
   // would block the parser, then mWriteLevel will be incorrect until the parser
--- a/content/media/test/crashtests/crashtests.list
+++ b/content/media/test/crashtests/crashtests.list
@@ -34,17 +34,17 @@ load 876252.html
 load 876834.html
 load 877820.html
 load 878014.html
 load 878328.html
 load 878407.html
 load 878478.html
 load 877527.html
 load 880129.html
-skip-if(B2G) test-pref(media.webaudio.enabled,true) load 880202.html # load failed, bug 908306 for B2G
+skip-if(B2G) load 880202.html # load failed, bug 908306 for B2G
 load 880342-1.html
 load 880342-2.html
 load 880384.html
 load 880404.html
 load 880724.html
 load 881775.html
 load 882956.html
 test-pref(media.webvtt.enabled,true) load 882549.html
--- a/content/media/test/test_bug654550.html
+++ b/content/media/test/test_bug654550.html
@@ -35,40 +35,47 @@ https://bugzilla.mozilla.org/show_bug.cg
       ok(!v.mozPresentedFrames,
         "mozPresentedFrames should be 0 if stats are disabled");
       ok(!v.mozPaintedFrames,
         "mozPaintedFrames should be 0 if stats are disabled");
     }
 
   }
 
-  function ontimeupdate(event) {
+  function ontimeupdate_statsEnabled(event) {
     var v = event.target;
-    if (SpecialPowers.getBoolPref("media.video_stats.enabled")) {
-      checkStats(v, true);
-      SpecialPowers.setBoolPref("media.video_stats.enabled", false);
-    } else {
-      checkStats(v, false);
-      SpecialPowers.setBoolPref("media.video_stats.enabled", true);
-      v.removeEventListener("timeupdate", ontimeupdate);
-      SpecialPowers.clearUserPref("media.video_stats.enabled");
-      removeNodeAndSource(v);
-      manager.finished(v.token);
-    }
+    v.removeEventListener('timeupdate', ontimeupdate_statsEnabled, false);
+    checkStats(v, true);
+    SpecialPowers.popPrefEnv(
+      function() {
+        v.addEventListener("timeupdate", ontimeupdate_statsDisabled);
+    });
   }
 
+  function ontimeupdate_statsDisabled(event) {
+    var v = event.target;
+    v.removeEventListener('timeupdate', ontimeupdate_statsDisabled, false);
+    checkStats(v, false);
+    removeNodeAndSource(v);
+    manager.finished(v.token);
+  }
 
   function startTest(test, token) {
     var v = document.createElement('video');
     v.token = token;
     v.src = test.name;
     manager.started(token);
-    v.play();
-    SpecialPowers.setBoolPref("media.video_stats.enabled", true);
-    v.addEventListener("timeupdate", ontimeupdate);
+    SpecialPowers.pushPrefEnv({"set": [["media.video_stats.enabled", true]]},
+      function() {
+        v.play();
+        v.addEventListener("timeupdate", ontimeupdate_statsEnabled);
+    });
   }
 
-  manager.runTests(gVideoTests, startTest);
+  SpecialPowers.pushPrefEnv({"set": [["media.video_stats.enabled", false]]},
+    function() {
+      manager.runTests(gVideoTests, startTest);
+  });
 
 </script>
 </pre>
 </body>
 </html>
--- a/content/media/test/test_mediarecorder_creation_fail.html
+++ b/content/media/test/test_mediarecorder_creation_fail.html
@@ -6,34 +6,30 @@
   <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
   <script type="text/javascript" src="manifest.js"></script>
 </head>
 <body>
 <pre id="test">
 <script class="testbody" type="text/javascript">
 
 function startTest() {
-  var element = document.createElement('audio');
-
-  element.src = 'detodos.opus';
-  element.stream = element.mozCaptureStream();
   // the expect sequence should be
   // 1. onerror
   // 2. ondataavailable
   // 3. onstop
   var callbackStep = 0;
-  var mediaRecorder = new MediaRecorder(element.stream);
+  var stream = new AudioContext().createMediaStreamDestination().stream;
+  var mediaRecorder = new MediaRecorder(stream);
 
   mediaRecorder.onerror = function (e) {
     is(callbackStep, 0, 'should fired onstop callback');
     is(e.name, 'GenericError', 'error name should be GenericError');
     is(mediaRecorder.mimeType, '', 'mimetype should be empty');
     is(mediaRecorder.state, 'recording', 'state is recording');
     info('onerror callback fired');
-    SpecialPowers.setBoolPref('media.ogg.enabled', true);
     callbackStep = 1;
   };
 
   mediaRecorder.onwarning = function () {
     ok(false, 'Unexpected onwarning callback fired');
   };
 
   mediaRecorder.onstop = function () {
@@ -49,26 +45,22 @@ function startTest() {
     is(callbackStep, 1, 'should fired ondataavailable callback');
     is(evt.data.size, 0, 'data size should be zero');
     ok(evt instanceof BlobEvent,
        'Events fired from ondataavailable should be BlobEvent');
     is(evt.data.type, '', 'encoder start fail, blob miemType should be empty');
     callbackStep = 2;
   };
 
-  // Start recording once canplaythrough fires
-  element.oncanplaythrough = function() {
-    SpecialPowers.setBoolPref("media.ogg.enabled", false);
-    mediaRecorder.start(250);
-    is(mediaRecorder.state, 'recording', 'Media recorder should be recording');
-    is(mediaRecorder.stream, element.stream,
-       'Media recorder stream = element stream at the start of recording');
-  };
-
-  element.play();
+  // Start recording
+  mediaRecorder.start(250);
+  is(mediaRecorder.state, 'recording', 'Media recorder should be recording');
+  is(mediaRecorder.stream, stream,
+     'Media recorder stream = element stream at the start of recording');
 }
 
-startTest();
 SimpleTest.waitForExplicitFinish();
+SpecialPowers.pushPrefEnv({"set": [["media.ogg.enabled", false]]}, startTest);
+
 </script>
 </pre>
 </body>
 </html>
--- a/content/media/webaudio/AudioBuffer.h
+++ b/content/media/webaudio/AudioBuffer.h
@@ -5,17 +5,16 @@
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #ifndef AudioBuffer_h_
 #define AudioBuffer_h_
 
 #include "nsWrapperCache.h"
 #include "nsCycleCollectionParticipant.h"
 #include "mozilla/Attributes.h"
-#include "EnableWebAudioCheck.h"
 #include "nsAutoPtr.h"
 #include "nsTArray.h"
 #include "AudioContext.h"
 #include "js/TypeDecls.h"
 #include "mozilla/MemoryReporting.h"
 
 namespace mozilla {
 
@@ -26,18 +25,17 @@ namespace dom {
 
 class AudioContext;
 
 /**
  * An AudioBuffer keeps its data either in the mJSChannels objects, which
  * are Float32Arrays, or in mSharedChannels if the mJSChannels objects have
  * been neutered.
  */
-class AudioBuffer MOZ_FINAL : public nsWrapperCache,
-                              public EnableWebAudioCheck
+class AudioBuffer MOZ_FINAL : public nsWrapperCache
 {
 public:
   AudioBuffer(AudioContext* aContext, uint32_t aLength,
               float aSampleRate);
   ~AudioBuffer();
 
   size_t SizeOfIncludingThis(mozilla::MallocSizeOf aMallocSizeOf) const;
 
--- a/content/media/webaudio/AudioContext.h
+++ b/content/media/webaudio/AudioContext.h
@@ -3,17 +3,16 @@
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #ifndef AudioContext_h_
 #define AudioContext_h_
 
 #include "mozilla/dom/AudioChannelBinding.h"
-#include "EnableWebAudioCheck.h"
 #include "MediaBufferDecoder.h"
 #include "mozilla/Attributes.h"
 #include "mozilla/dom/TypedArray.h"
 #include "nsAutoPtr.h"
 #include "nsCOMPtr.h"
 #include "nsCycleCollectionParticipant.h"
 #include "nsDOMEventTargetHelper.h"
 #include "nsHashKeys.h"
@@ -59,18 +58,17 @@ class MediaStreamAudioDestinationNode;
 class MediaStreamAudioSourceNode;
 class OscillatorNode;
 class PannerNode;
 class ScriptProcessorNode;
 class WaveShaperNode;
 class PeriodicWave;
 
 class AudioContext MOZ_FINAL : public nsDOMEventTargetHelper,
-                               public nsIMemoryReporter,
-                               public EnableWebAudioCheck
+                               public nsIMemoryReporter
 {
   AudioContext(nsPIDOMWindow* aParentWindow,
                bool aIsOffline,
                uint32_t aNumberOfChannels = 0,
                uint32_t aLength = 0,
                float aSampleRate = 0.0f);
   ~AudioContext();
 
--- a/content/media/webaudio/AudioListener.h
+++ b/content/media/webaudio/AudioListener.h
@@ -5,31 +5,29 @@
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #ifndef AudioListener_h_
 #define AudioListener_h_
 
 #include "nsWrapperCache.h"
 #include "nsCycleCollectionParticipant.h"
 #include "mozilla/Attributes.h"
-#include "EnableWebAudioCheck.h"
 #include "nsAutoPtr.h"
 #include "ThreeDPoint.h"
 #include "AudioContext.h"
 #include "PannerNode.h"
 #include "WebAudioUtils.h"
 #include "js/TypeDecls.h"
 #include "mozilla/MemoryReporting.h"
 
 namespace mozilla {
 
 namespace dom {
 
-class AudioListener MOZ_FINAL : public nsWrapperCache,
-                                public EnableWebAudioCheck
+class AudioListener MOZ_FINAL : public nsWrapperCache
 {
 public:
   explicit AudioListener(AudioContext* aContext);
 
   NS_INLINE_DECL_CYCLE_COLLECTING_NATIVE_REFCOUNTING(AudioListener)
   NS_DECL_CYCLE_COLLECTION_SCRIPT_HOLDER_NATIVE_CLASS(AudioListener)
 
   size_t SizeOfIncludingThis(mozilla::MallocSizeOf aMallocSizeOf) const;
--- a/content/media/webaudio/AudioNode.h
+++ b/content/media/webaudio/AudioNode.h
@@ -5,17 +5,16 @@
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #ifndef AudioNode_h_
 #define AudioNode_h_
 
 #include "nsDOMEventTargetHelper.h"
 #include "mozilla/dom/AudioNodeBinding.h"
 #include "nsCycleCollectionParticipant.h"
-#include "EnableWebAudioCheck.h"
 #include "nsAutoPtr.h"
 #include "nsTArray.h"
 #include "AudioContext.h"
 #include "MediaStreamGraph.h"
 #include "WebAudioUtils.h"
 
 namespace mozilla {
 
@@ -77,18 +76,17 @@ private:
  * finished do so strictly *after* producing and returning their last block.
  * In this way, an engine that receives non-null input knows that the input
  * comes from nodes that are still alive and will keep their output nodes
  * alive for at least as long as it takes to process messages from the graph
  * thread.  i.e. the engine receiving non-null input knows that its node is
  * still alive, and will still be alive when it receives a message from the
  * engine.
  */
-class AudioNode : public nsDOMEventTargetHelper,
-                  public EnableWebAudioCheck
+class AudioNode : public nsDOMEventTargetHelper
 {
 protected:
   // You can only use refcounting to delete this object
   virtual ~AudioNode();
 
 public:
   AudioNode(AudioContext* aContext,
             uint32_t aChannelCount,
--- a/content/media/webaudio/AudioParam.h
+++ b/content/media/webaudio/AudioParam.h
@@ -5,29 +5,27 @@
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #ifndef AudioParam_h_
 #define AudioParam_h_
 
 #include "AudioParamTimeline.h"
 #include "nsWrapperCache.h"
 #include "nsCycleCollectionParticipant.h"
-#include "EnableWebAudioCheck.h"
 #include "nsAutoPtr.h"
 #include "AudioNode.h"
 #include "mozilla/dom/TypedArray.h"
 #include "WebAudioUtils.h"
 #include "js/TypeDecls.h"
 
 namespace mozilla {
 
 namespace dom {
 
 class AudioParam MOZ_FINAL : public nsWrapperCache,
-                             public EnableWebAudioCheck,
                              public AudioParamTimeline
 {
 public:
   typedef void (*CallbackType)(AudioNode*);
 
   AudioParam(AudioNode* aNode,
              CallbackType aCallback,
              float aDefaultValue);
--- a/content/media/webaudio/AudioProcessingEvent.h
+++ b/content/media/webaudio/AudioProcessingEvent.h
@@ -9,18 +9,17 @@
 
 #include "nsDOMEvent.h"
 #include "AudioBuffer.h"
 #include "ScriptProcessorNode.h"
 
 namespace mozilla {
 namespace dom {
 
-class AudioProcessingEvent : public nsDOMEvent,
-                             public EnableWebAudioCheck
+class AudioProcessingEvent : public nsDOMEvent
 {
 public:
   AudioProcessingEvent(ScriptProcessorNode* aOwner,
                        nsPresContext* aPresContext,
                        WidgetEvent* aEvent);
 
   NS_DECL_ISUPPORTS_INHERITED
   NS_FORWARD_TO_NSDOMEVENT
deleted file mode 100644
--- a/content/media/webaudio/EnableWebAudioCheck.cpp
+++ /dev/null
@@ -1,32 +0,0 @@
-/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
-/* vim:set ts=2 sw=2 sts=2 et cindent: */
-/* 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 "EnableWebAudioCheck.h"
-#include "mozilla/Preferences.h"
-
-namespace {
-
-bool gPrefInitialized = false;
-bool gWebAudioEnabled = false;
-
-}
-
-namespace mozilla {
-namespace dom {
-
-/* static */ bool
-EnableWebAudioCheck::PrefEnabled()
-{
-  if (!gPrefInitialized) {
-    Preferences::AddBoolVarCache(&gWebAudioEnabled, "media.webaudio.enabled");
-    gPrefInitialized = true;
-  }
-  return gWebAudioEnabled;
-}
-
-}
-}
-
deleted file mode 100644
--- a/content/media/webaudio/EnableWebAudioCheck.h
+++ /dev/null
@@ -1,24 +0,0 @@
-/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
-/* vim:set ts=2 sw=2 sts=2 et cindent: */
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-#ifndef EnableWebAudioCheck_h_
-#define EnableWebAudioCheck_h_
-
-namespace mozilla {
-namespace dom {
-
-// This is a helper class which enables Web Audio to be enabled or disabled
-// as whole.  Individual Web Audio object classes should inherit from this.
-class EnableWebAudioCheck {
-public:
-  static bool PrefEnabled();
-};
-
-}
-}
-
-#endif
-
--- a/content/media/webaudio/OfflineAudioCompletionEvent.h
+++ b/content/media/webaudio/OfflineAudioCompletionEvent.h
@@ -10,18 +10,17 @@
 #include "nsDOMEvent.h"
 #include "AudioBuffer.h"
 
 namespace mozilla {
 namespace dom {
 
 class AudioContext;
 
-class OfflineAudioCompletionEvent : public nsDOMEvent,
-                                    public EnableWebAudioCheck
+class OfflineAudioCompletionEvent : public nsDOMEvent
 {
 public:
   OfflineAudioCompletionEvent(AudioContext* aOwner,
                               nsPresContext* aPresContext,
                               WidgetEvent* aEvent);
 
   NS_DECL_ISUPPORTS_INHERITED
   NS_FORWARD_TO_NSDOMEVENT
--- a/content/media/webaudio/PeriodicWave.h
+++ b/content/media/webaudio/PeriodicWave.h
@@ -5,27 +5,25 @@
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #ifndef PeriodicWave_h_
 #define PeriodicWave_h_
 
 #include "nsWrapperCache.h"
 #include "nsCycleCollectionParticipant.h"
 #include "mozilla/Attributes.h"
-#include "EnableWebAudioCheck.h"
 #include "AudioContext.h"
 #include "AudioNodeEngine.h"
 #include "nsAutoPtr.h"
 
 namespace mozilla {
 
 namespace dom {
 
-class PeriodicWave MOZ_FINAL : public nsWrapperCache,
-                               public EnableWebAudioCheck
+class PeriodicWave MOZ_FINAL : public nsWrapperCache
 {
 public:
   PeriodicWave(AudioContext* aContext,
                const float* aRealData,
                const float* aImagData,
                const uint32_t aLength,
                ErrorResult& aRv);
 
--- a/content/media/webaudio/moz.build
+++ b/content/media/webaudio/moz.build
@@ -31,17 +31,16 @@ EXPORTS.mozilla.dom += [
     'AudioParam.h',
     'AudioProcessingEvent.h',
     'BiquadFilterNode.h',
     'ChannelMergerNode.h',
     'ChannelSplitterNode.h',
     'ConvolverNode.h',
     'DelayNode.h',
     'DynamicsCompressorNode.h',
-    'EnableWebAudioCheck.h',
     'GainNode.h',
     'MediaElementAudioSourceNode.h',
     'MediaStreamAudioDestinationNode.h',
     'MediaStreamAudioSourceNode.h',
     'OfflineAudioCompletionEvent.h',
     'OscillatorNode.h',
     'PannerNode.h',
     'PeriodicWave.h',
@@ -61,17 +60,16 @@ UNIFIED_SOURCES += [
     'AudioProcessingEvent.cpp',
     'BiquadFilterNode.cpp',
     'ChannelMergerNode.cpp',
     'ChannelSplitterNode.cpp',
     'ConvolverNode.cpp',
     'DelayNode.cpp',
     'DelayProcessor.cpp',
     'DynamicsCompressorNode.cpp',
-    'EnableWebAudioCheck.cpp',
     'FFTBlock.cpp',
     'GainNode.cpp',
     'MediaBufferDecoder.cpp',
     'MediaElementAudioSourceNode.cpp',
     'MediaStreamAudioDestinationNode.cpp',
     'MediaStreamAudioSourceNode.cpp',
     'OfflineAudioCompletionEvent.cpp',
     'OscillatorNode.cpp',
--- a/content/media/webrtc/MediaEngineWebRTCVideo.cpp
+++ b/content/media/webrtc/MediaEngineWebRTCVideo.cpp
@@ -597,16 +597,19 @@ MediaEngineWebRTCVideoSource::HandleEven
   mCallbackMonitor.Notify();
   return NS_OK;
 }
 
 //Except this one. This callback should called on camera preview thread.
 void
 MediaEngineWebRTCVideoSource::OnNewFrame(const gfxIntSize& aIntrinsicSize, layers::Image* aImage) {
   MonitorAutoLock enter(mMonitor);
+  if (mState == kStopped) {
+    return;
+  }
   mImage = aImage;
   if (mWidth != aIntrinsicSize.width || mHeight != aIntrinsicSize.height) {
     mWidth = aIntrinsicSize.width;
     mHeight = aIntrinsicSize.height;
     LOG(("Video FrameSizeChange: %ux%u", mWidth, mHeight));
   }
 }
 #endif
--- a/docshell/base/nsDocShell.cpp
+++ b/docshell/base/nsDocShell.cpp
@@ -1989,16 +1989,20 @@ nsDocShell::GatherCharsetMenuTelemetry()
   bool isFileURL = false;
   nsIURI* url = doc->GetOriginalURI();
   if (url) {
     url->SchemeIs("file", &isFileURL);
   }
 
   int32_t charsetSource = doc->GetDocumentCharacterSetSource();
   switch (charsetSource) {
+    case kCharsetFromTopLevelDomain:
+      // Unlabeled doc on a domain that we map to a fallback encoding
+      Telemetry::Accumulate(Telemetry::CHARSET_OVERRIDE_SITUATION, 7);
+      break;
     case kCharsetFromFallback:
     case kCharsetFromDocTypeDefault:
     case kCharsetFromCache:
     case kCharsetFromParentFrame:
     case kCharsetFromHintPrevDoc:
       // Changing charset on an unlabeled doc.
       if (isFileURL) {
         Telemetry::Accumulate(Telemetry::CHARSET_OVERRIDE_SITUATION, 0);
--- a/dom/bluetooth/bluez/linux/BluetoothDBusService.cpp
+++ b/dom/bluetooth/bluez/linux/BluetoothDBusService.cpp
@@ -1318,17 +1318,16 @@ private:
                                               nullptr)) {
       BT_WARNING("%s: Can't register object path %s for agent!",
                  __FUNCTION__, KEY_LOCAL_AGENT);
       return false;
     }
 
     nsRefPtr<RegisterAgentReplyHandler> handler =
       new RegisterAgentReplyHandler(aAgentVTable);
-    MOZ_ASSERT(handler.get());
     MOZ_ASSERT(!sAdapterPath.IsEmpty());
 
     bool success = connection->SendWithReply(
       RegisterAgentReplyHandler::Callback, handler.get(), -1,
       NS_ConvertUTF16toUTF8(sAdapterPath).get(),
       DBUS_ADAPTER_IFACE, "RegisterAgent",
       DBUS_TYPE_OBJECT_PATH, &agentPath,
       DBUS_TYPE_STRING, &capabilities,
@@ -1337,61 +1336,80 @@ private:
     NS_ENSURE_TRUE(success, false);
 
     handler.forget();
 
     return true;
   }
 };
 
+class AddReservedServiceRecordsTask : public Task
+{
+public:
+  AddReservedServiceRecordsTask(const nsACString& aAdapterPath)
+    : mAdapterPath(aAdapterPath)
+  {
+    MOZ_ASSERT(!aAdapterPath.IsEmpty());
+  }
+
+  void Run()
+  {
+    static const dbus_uint32_t sServices[] = {
+      BluetoothServiceClass::HANDSFREE_AG,
+      BluetoothServiceClass::HEADSET_AG,
+      BluetoothServiceClass::OBJECT_PUSH
+    };
+
+    MOZ_ASSERT(!NS_IsMainThread()); // I/O thread
+
+    RawDBusConnection* connection = GetDBusConnection();
+    if (!connection) {
+      BT_WARNING("%s: DBus connection has been closed.", __FUNCTION__);
+      return;
+    }
+
+    nsRefPtr<DBusReplyHandler> handler =
+      new AddReservedServiceRecordsReplyHandler();
+
+    const dbus_uint32_t* services = sServices;
+
+    bool success = connection->SendWithReply(
+      DBusReplyHandler::Callback, handler.get(), -1,
+      mAdapterPath.get(),
+      DBUS_ADAPTER_IFACE, "AddReservedServiceRecords",
+      DBUS_TYPE_ARRAY, DBUS_TYPE_UINT32,
+      &services, ArrayLength(sServices), DBUS_TYPE_INVALID);
+
+    NS_ENSURE_TRUE_VOID(success);
+
+    handler.forget();
+  }
+
+private:
+  const nsCString mAdapterPath;
+};
+
 class PrepareAdapterRunnable : public nsRunnable
 {
 public:
   PrepareAdapterRunnable(const nsAString& aAdapterPath)
     : mAdapterPath(aAdapterPath)
   { }
 
   NS_IMETHOD Run()
   {
     MOZ_ASSERT(NS_IsMainThread());
 
-    static const dbus_uint32_t sServices[] = {
-      BluetoothServiceClass::HANDSFREE_AG,
-      BluetoothServiceClass::HEADSET_AG,
-      BluetoothServiceClass::OBJECT_PUSH
-    };
-
-    MOZ_ASSERT(NS_IsMainThread());
-
-    RawDBusConnection* connection = GetDBusConnection();
-
-    if (!connection) {
-      BT_WARNING("%s: DBus connection has been closed.", __FUNCTION__);
-      return NS_ERROR_FAILURE;
-    }
-
     sAdapterPath = mAdapterPath;
     sAuthorizedServiceClass.AppendElement(BluetoothServiceClass::A2DP);
     sAuthorizedServiceClass.AppendElement(BluetoothServiceClass::HID);
 
-    nsRefPtr<DBusReplyHandler> handler =
-      new AddReservedServiceRecordsReplyHandler();
-
-    const dbus_uint32_t* services = sServices;
-
-    bool success = connection->SendWithReply(
-      DBusReplyHandler::Callback, handler.get(), -1,
-      NS_ConvertUTF16toUTF8(sAdapterPath).get(),
-      DBUS_ADAPTER_IFACE, "AddReservedServiceRecords",
-      DBUS_TYPE_ARRAY, DBUS_TYPE_UINT32,
-      &services, ArrayLength(sServices), DBUS_TYPE_INVALID);
-
-    NS_ENSURE_TRUE(success, NS_ERROR_FAILURE);
-
-    handler.forget();
+    Task* task = new
+      AddReservedServiceRecordsTask(NS_ConvertUTF16toUTF8(sAdapterPath));
+    DispatchToDBusThread(task);
 
     return NS_OK;
   }
 
 private:
   nsString mAdapterPath;
 };
 
@@ -1960,43 +1978,63 @@ protected:
     return true;
   }
 
 private:
   nsRefPtr<BluetoothReplyRunnable> mRunnable;
   nsString mAdapterPath;
 };
 
+class DefaultAdapterTask : public Task
+{
+public:
+  DefaultAdapterTask(BluetoothReplyRunnable* aRunnable)
+    : mRunnable(aRunnable)
+  {
+    MOZ_ASSERT(mRunnable);
+  }
+
+  void Run() MOZ_OVERRIDE
+  {
+    MOZ_ASSERT(!NS_IsMainThread()); // I/O thread
+
+    nsRefPtr<DefaultAdapterPathReplyHandler> handler =
+      new DefaultAdapterPathReplyHandler(mRunnable);
+
+    RawDBusConnection* connection = GetDBusConnection();
+    MOZ_ASSERT(connection);
+
+    bool success = connection->SendWithReply(
+      DefaultAdapterPathReplyHandler::Callback,
+      handler.get(), 1000,
+      "/", DBUS_MANAGER_IFACE, "DefaultAdapter",
+      DBUS_TYPE_INVALID);
+    NS_ENSURE_TRUE_VOID(success);
+
+    handler.forget();
+  }
+
+private:
+  nsRefPtr<BluetoothReplyRunnable> mRunnable;
+};
+
 nsresult
 BluetoothDBusService::GetDefaultAdapterPathInternal(
                                               BluetoothReplyRunnable* aRunnable)
 {
   MOZ_ASSERT(NS_IsMainThread());
 
   if (!IsReady()) {
     NS_NAMED_LITERAL_STRING(errorStr, "Bluetooth service is not ready yet!");
     DispatchBluetoothReply(aRunnable, BluetoothValue(), errorStr);
     return NS_OK;
   }
 
-  nsRefPtr<DefaultAdapterPathReplyHandler> handler =
-    new DefaultAdapterPathReplyHandler(aRunnable);
-
-  RawDBusConnection* connection = GetDBusConnection();
-  MOZ_ASSERT(connection);
-
-  bool success = connection->SendWithReply(
-    DefaultAdapterPathReplyHandler::Callback,
-    handler.get(), 1000,
-    "/", DBUS_MANAGER_IFACE, "DefaultAdapter",
-    DBUS_TYPE_INVALID);
-
-  NS_ENSURE_TRUE(success, NS_ERROR_FAILURE);
-
-  handler.forget();
+  Task* task = new DefaultAdapterTask(aRunnable);
+  DispatchToDBusThread(task);
 
   return NS_OK;
 }
 
 static void
 OnSendDiscoveryMessageReply(DBusMessage *aReply, void *aData)
 {
   MOZ_ASSERT(!NS_IsMainThread());
@@ -2008,44 +2046,71 @@ OnSendDiscoveryMessageReply(DBusMessage 
   }
 
   nsRefPtr<BluetoothReplyRunnable> runnable =
     dont_AddRef<BluetoothReplyRunnable>(static_cast<BluetoothReplyRunnable*>(aData));
 
   DispatchBluetoothReply(runnable.get(), BluetoothValue(true), errorStr);
 }
 
+class SendDiscoveryMessageTask : public Task
+{
+public:
+  SendDiscoveryMessageTask(const nsACString& aAdapterPath,
+                           const char* aMessageName,
+                           BluetoothReplyRunnable* aRunnable)
+    : mAdapterPath(aAdapterPath)
+    , mMessageName(aMessageName)
+    , mRunnable(aRunnable)
+  {
+    MOZ_ASSERT(!mAdapterPath.IsEmpty());
+    MOZ_ASSERT(!mMessageName.IsEmpty());
+    MOZ_ASSERT(mRunnable);
+  }
+
+  void Run() MOZ_OVERRIDE
+  {
+    MOZ_ASSERT(!NS_IsMainThread()); // I/O thread
+
+    RawDBusConnection* connection = GetDBusConnection();
+    MOZ_ASSERT(connection);
+
+    bool success = connection->SendWithReply(
+      OnSendDiscoveryMessageReply,
+      static_cast<void*>(mRunnable.get()), -1,
+      mAdapterPath.get(),
+      DBUS_ADAPTER_IFACE, mMessageName.get(),
+      DBUS_TYPE_INVALID);
+    NS_ENSURE_TRUE_VOID(success);
+
+    mRunnable.forget();
+  }
+
+private:
+  const nsCString mAdapterPath;
+  const nsCString mMessageName;
+  nsRefPtr<BluetoothReplyRunnable> mRunnable;
+};
+
 nsresult
 BluetoothDBusService::SendDiscoveryMessage(const char* aMessageName,
                                            BluetoothReplyRunnable* aRunnable)
 {
   MOZ_ASSERT(NS_IsMainThread());
   MOZ_ASSERT(!sAdapterPath.IsEmpty());
 
   if (!IsReady()) {
     NS_NAMED_LITERAL_STRING(errorStr, "Bluetooth service is not ready yet!");
     DispatchBluetoothReply(aRunnable, BluetoothValue(), errorStr);
     return NS_OK;
   }
 
-  nsRefPtr<BluetoothReplyRunnable> runnable(aRunnable);
-
-  RawDBusConnection* connection = GetDBusConnection();
-  MOZ_ASSERT(connection);
-
-  bool success = connection->SendWithReply(
-    OnSendDiscoveryMessageReply,
-    static_cast<void*>(aRunnable), -1,
-    NS_ConvertUTF16toUTF8(sAdapterPath).get(),
-    DBUS_ADAPTER_IFACE, aMessageName,
-    DBUS_TYPE_INVALID);
-
-  NS_ENSURE_TRUE(success, NS_ERROR_FAILURE);
-
-  runnable.forget();
+  Task* task = new SendDiscoveryMessageTask(
+    NS_ConvertUTF16toUTF8(sAdapterPath), aMessageName, aRunnable);
+  DispatchToDBusThread(task);
 
   return NS_OK;
 }
 
 nsresult
 BluetoothDBusService::SendInputMessage(const nsAString& aDeviceAddress,
                                        const nsAString& aMessage)
 {
@@ -2059,50 +2124,88 @@ BluetoothDBusService::SendInputMessage(c
     return NS_ERROR_FAILURE;
   }
 
   MOZ_ASSERT(!sAdapterPath.IsEmpty());
   nsString objectPath = GetObjectPathFromAddress(sAdapterPath, aDeviceAddress);
   return SendAsyncDBusMessage(objectPath, DBUS_INPUT_IFACE, aMessage, callback);
 }
 
+class SendAsyncDBusMessageTask : public Task
+{
+public:
+  SendAsyncDBusMessageTask(DBusReplyCallback aCallback,
+                           BluetoothServiceClass* aServiceClass,
+                           const nsACString& aObjectPath,
+                           const char* aInterface,
+                           const nsACString& aMessage)
+    : mCallback(aCallback)
+    , mServiceClass(aServiceClass)
+    , mObjectPath(aObjectPath)
+    , mInterface(aInterface)
+    , mMessage(aMessage)
+  {
+    MOZ_ASSERT(mServiceClass);
+    MOZ_ASSERT(!mObjectPath.IsEmpty());
+    MOZ_ASSERT(!mInterface.IsEmpty());
+    MOZ_ASSERT(!mMessage.IsEmpty());
+  }
+
+  void Run() MOZ_OVERRIDE
+  {
+    MOZ_ASSERT(!NS_IsMainThread()); // I/O thread
+
+    RawDBusConnection* connection = GetDBusConnection();
+    MOZ_ASSERT(connection);
+
+    bool success = connection->SendWithReply(
+      mCallback, static_cast<void*>(mServiceClass), -1,
+      mObjectPath.get(), mInterface.get(), mMessage.get(),
+      DBUS_TYPE_INVALID);
+    NS_ENSURE_TRUE_VOID(success);
+
+    mServiceClass.forget();
+  }
+
+private:
+  DBusReplyCallback mCallback;
+  nsAutoPtr<BluetoothServiceClass> mServiceClass;
+  const nsCString mObjectPath;
+  const nsCString mInterface;
+  const nsCString mMessage;
+};
+
 nsresult
 BluetoothDBusService::SendAsyncDBusMessage(const nsAString& aObjectPath,
                                            const char* aInterface,
                                            const nsAString& aMessage,
                                            DBusReplyCallback aCallback)
 {
   MOZ_ASSERT(NS_IsMainThread());
   MOZ_ASSERT(IsEnabled());
   MOZ_ASSERT(aCallback);
   MOZ_ASSERT(!aObjectPath.IsEmpty());
   MOZ_ASSERT(aInterface);
 
-  NS_ENSURE_TRUE(GetDBusConnection(), NS_ERROR_FAILURE);
-
   nsAutoPtr<BluetoothServiceClass> serviceClass(new BluetoothServiceClass());
   if (!strcmp(aInterface, DBUS_SINK_IFACE)) {
     *serviceClass = BluetoothServiceClass::A2DP;
   } else if (!strcmp(aInterface, DBUS_INPUT_IFACE)) {
     *serviceClass = BluetoothServiceClass::HID;
   } else {
     MOZ_ASSERT(false);
     return NS_ERROR_FAILURE;
   }
 
-  RawDBusConnection* connection = GetDBusConnection();
-  MOZ_ASSERT(connection);
-
-  bool ret = connection->SendWithReply(
-    aCallback, static_cast<void*>(serviceClass.forget()), -1,
-    NS_ConvertUTF16toUTF8(aObjectPath).get(),
-    aInterface, NS_ConvertUTF16toUTF8(aMessage).get(),
-    DBUS_TYPE_INVALID);
-
-  NS_ENSURE_TRUE(ret, NS_ERROR_FAILURE);
+  Task* task = new SendAsyncDBusMessageTask(aCallback,
+                                            serviceClass.forget(),
+                                            NS_ConvertUTF16toUTF8(aObjectPath),
+                                            aInterface,
+                                            NS_ConvertUTF16toUTF8(aMessage));
+  DispatchToDBusThread(task);
 
   return NS_OK;
 }
 
 nsresult
 BluetoothDBusService::SendSinkMessage(const nsAString& aDeviceAddress,
                                       const nsAString& aMessage)
 {
@@ -2132,24 +2235,27 @@ BluetoothDBusService::StartDiscoveryInte
 {
   return SendDiscoveryMessage("StartDiscovery", aRunnable);
 }
 
 class BluetoothArrayOfDevicePropertiesReplyHandler : public DBusReplyHandler
 {
 public:
   BluetoothArrayOfDevicePropertiesReplyHandler(
+    const nsString& aAdapterPath,
     const nsTArray<nsString>& aDeviceAddresses,
     const FilterFunc aFilterFunc, BluetoothReplyRunnable* aRunnable)
-    : mDeviceAddresses(aDeviceAddresses)
+    : mAdapterPath(aAdapterPath)
+    , mDeviceAddresses(aDeviceAddresses)
     , mProcessedDeviceAddresses(0)
     , mFilterFunc(aFilterFunc)
     , mRunnable(aRunnable)
     , mValues(InfallibleTArray<BluetoothNamedValue>())
   {
+    MOZ_ASSERT(!mAdapterPath.IsEmpty());
     MOZ_ASSERT(mRunnable);
   }
 
   void Handle(DBusMessage* aReply) MOZ_OVERRIDE
   {
     MOZ_ASSERT(!NS_IsMainThread()); // DBus thread
     MOZ_ASSERT(!mObjectPath.IsEmpty());
     MOZ_ASSERT(mProcessedDeviceAddresses < mDeviceAddresses.Length());
@@ -2225,20 +2331,20 @@ public:
       DispatchBluetoothReply(mRunnable, mValues, EmptyString());
     }
   }
 
 protected:
   bool SendNextGetProperties()
   {
     MOZ_ASSERT(mProcessedDeviceAddresses < mDeviceAddresses.Length());
-    MOZ_ASSERT(!sAdapterPath.IsEmpty());
+    MOZ_ASSERT(!mAdapterPath.IsEmpty());
 
     // cache object path for reply
-    mObjectPath = GetObjectPathFromAddress(sAdapterPath,
+    mObjectPath = GetObjectPathFromAddress(mAdapterPath,
       mDeviceAddresses[mProcessedDeviceAddresses]);
 
     RawDBusConnection* connection = GetDBusConnection();
 
     if (!connection) {
       BT_WARNING("%s: DBus connection has been closed.", __FUNCTION__);
       return false;
     }
@@ -2255,24 +2361,50 @@ protected:
     NS_ENSURE_TRUE(success, false);
 
     handler.forget();
 
     return true;
   }
 
 private:
+  nsString mAdapterPath;
   nsString mObjectPath;
   const nsTArray<nsString> mDeviceAddresses;
   nsTArray<nsString>::size_type mProcessedDeviceAddresses;
   const FilterFunc mFilterFunc;
   nsRefPtr<BluetoothReplyRunnable> mRunnable;
   BluetoothValue mValues;
 };
 
+class ProcessRemainingDeviceAddressesTask : public Task
+{
+public:
+  ProcessRemainingDeviceAddressesTask(
+    BluetoothArrayOfDevicePropertiesReplyHandler* aHandler,
+    BluetoothReplyRunnable* aRunnable)
+    : mHandler(aHandler)
+    , mRunnable(aRunnable)
+  {
+    MOZ_ASSERT(mHandler);
+    MOZ_ASSERT(mRunnable);
+  }
+
+  void Run() MOZ_OVERRIDE
+  {
+    MOZ_ASSERT(!NS_IsMainThread()); // I/O thread
+
+    mHandler->ProcessRemainingDeviceAddresses();
+  }
+
+private:
+  nsRefPtr<BluetoothArrayOfDevicePropertiesReplyHandler> mHandler;
+  nsRefPtr<BluetoothReplyRunnable> mRunnable;
+};
+
 nsresult
 BluetoothDBusService::GetConnectedDevicePropertiesInternal(uint16_t aServiceUuid,
                                               BluetoothReplyRunnable* aRunnable)
 {
   MOZ_ASSERT(NS_IsMainThread());
 
   nsAutoString errorStr;
   BluetoothValue values = InfallibleTArray<BluetoothNamedValue>();
@@ -2292,22 +2424,23 @@ BluetoothDBusService::GetConnectedDevice
   }
 
   if (profile->IsConnected()) {
     nsString address;
     profile->GetAddress(address);
     deviceAddresses.AppendElement(address);
   }
 
-  nsRefPtr<BluetoothReplyRunnable> runnable = aRunnable;
-  nsRefPtr<BluetoothArrayOfDevicePropertiesReplyHandler> handler =
-    new BluetoothArrayOfDevicePropertiesReplyHandler(deviceAddresses,
+  BluetoothArrayOfDevicePropertiesReplyHandler* handler =
+    new BluetoothArrayOfDevicePropertiesReplyHandler(sAdapterPath,
+                                                     deviceAddresses,
                                                      GetConnectedDevicesFilter,
-                                                     runnable);
-  handler->ProcessRemainingDeviceAddresses();
+                                                     aRunnable);
+  Task* task = new ProcessRemainingDeviceAddressesTask(handler, aRunnable);
+  DispatchToDBusThread(task);
 
   return NS_OK;
 }
 
 nsresult
 BluetoothDBusService::GetPairedDevicePropertiesInternal(
                                      const nsTArray<nsString>& aDeviceAddresses,
                                      BluetoothReplyRunnable* aRunnable)
@@ -2315,364 +2448,592 @@ BluetoothDBusService::GetPairedDevicePro
   MOZ_ASSERT(NS_IsMainThread());
 
   if (!IsReady()) {
     NS_NAMED_LITERAL_STRING(errorStr, "Bluetooth service is not ready yet!");
     DispatchBluetoothReply(aRunnable, BluetoothValue(), errorStr);
     return NS_OK;
   }
 
-  nsRefPtr<BluetoothReplyRunnable> runnable = aRunnable;
-  nsRefPtr<BluetoothArrayOfDevicePropertiesReplyHandler> handler =
-    new BluetoothArrayOfDevicePropertiesReplyHandler(aDeviceAddresses,
+  BluetoothArrayOfDevicePropertiesReplyHandler* handler =
+    new BluetoothArrayOfDevicePropertiesReplyHandler(sAdapterPath,
+                                                     aDeviceAddresses,
                                                      GetPairedDevicesFilter,
-                                                     runnable);
-  handler->ProcessRemainingDeviceAddresses();
+                                                     aRunnable);
+  Task* task = new ProcessRemainingDeviceAddressesTask(handler, aRunnable);
+  DispatchToDBusThread(task);
 
   return NS_OK;
 }
 
+class SetPropertyTask : public Task
+{
+public:
+  SetPropertyTask(const nsACString& aAdapterPath,
+                  BluetoothObjectType aType,
+                  const nsACString& aName,
+                  BluetoothReplyRunnable* aRunnable)
+    : mAdapterPath(aAdapterPath)
+    , mType(aType)
+    , mName(aName)
+    , mRunnable(aRunnable)
+  {
+    MOZ_ASSERT(!mAdapterPath.IsEmpty());
+    MOZ_ASSERT(mRunnable);
+  }
+
+  void Send(unsigned int aType, const void* aValue)
+  {
+    MOZ_ASSERT(!NS_IsMainThread()); // I/O thread
+
+    DBusMessage* msg =
+      dbus_message_new_method_call("org.bluez",
+                                   mAdapterPath.get(),
+                                   sBluetoothDBusIfaces[mType],
+                                   "SetProperty");
+    if (!msg) {
+      BT_WARNING("Could not allocate D-Bus message object!");
+      return;
+    }
+
+    const char* name = mName.get();
+    if (!dbus_message_append_args(msg, DBUS_TYPE_STRING, &name,
+                                  DBUS_TYPE_INVALID)) {
+      BT_WARNING("Couldn't append arguments to dbus message!");
+      return;
+    }
+
+    DBusMessageIter value_iter, iter;
+    dbus_message_iter_init_append(msg, &iter);
+    char var_type[2] = {(char)aType, '\0'};
+    if (!dbus_message_iter_open_container(&iter, DBUS_TYPE_VARIANT,
+                                          var_type, &value_iter) ||
+        !dbus_message_iter_append_basic(&value_iter, aType, aValue) ||
+        !dbus_message_iter_close_container(&iter, &value_iter)) {
+      BT_WARNING("Could not append argument to method call!");
+      dbus_message_unref(msg);
+      return;
+    }
+
+    RawDBusConnection* connection = GetDBusConnection();
+    MOZ_ASSERT(connection);
+
+    // msg is unref'd as part of SendWithReply
+    bool success = connection->SendWithReply(GetVoidCallback,
+                                             static_cast<void*>(mRunnable),
+                                             1000, msg);
+    NS_ENSURE_TRUE_VOID(success);
+
+    mRunnable.forget();
+  }
+
+private:
+  const nsCString mAdapterPath;
+  BluetoothObjectType mType;
+  const nsCString mName;
+  nsRefPtr<BluetoothReplyRunnable> mRunnable;
+};
+
+class SetUInt32PropertyTask : public SetPropertyTask
+{
+public:
+  SetUInt32PropertyTask(const nsACString& aAdapterPath,
+                        BluetoothObjectType aType,
+                        const nsACString& aName,
+                        uint32_t aValue,
+                        BluetoothReplyRunnable* aRunnable)
+    : SetPropertyTask(aAdapterPath, aType, aName, aRunnable)
+    , mValue(aValue)
+  {
+  }
+
+  void Run() MOZ_OVERRIDE
+  {
+    Send(DBUS_TYPE_UINT32, &mValue);
+  }
+
+private:
+  dbus_uint32_t mValue;
+};
+
+class SetStringPropertyTask : public SetPropertyTask
+{
+public:
+  SetStringPropertyTask(const nsACString& aAdapterPath,
+                        BluetoothObjectType aType,
+                        const nsACString& aName,
+                        const nsACString& aValue,
+                        BluetoothReplyRunnable* aRunnable)
+    : SetPropertyTask(aAdapterPath, aType, aName, aRunnable)
+    , mValue(aValue)
+  {
+  }
+
+  void Run() MOZ_OVERRIDE
+  {
+    const char* value = mValue.get();
+    Send(DBUS_TYPE_STRING, &value);
+  }
+
+private:
+  const nsCString mValue;
+};
+
+class SetBooleanPropertyTask : public SetPropertyTask
+{
+public:
+  SetBooleanPropertyTask(const nsACString& aAdapterPath,
+                         BluetoothObjectType aType,
+                         const nsACString& aName,
+                         dbus_bool_t aValue,
+                         BluetoothReplyRunnable* aRunnable)
+    : SetPropertyTask(aAdapterPath, aType, aName, aRunnable)
+    , mValue(aValue)
+  {
+  }
+
+  void Run() MOZ_OVERRIDE
+  {
+    Send(DBUS_TYPE_BOOLEAN, &mValue);
+  }
+
+private:
+  dbus_bool_t mValue;
+};
+
 nsresult
 BluetoothDBusService::SetProperty(BluetoothObjectType aType,
                                   const BluetoothNamedValue& aValue,
                                   BluetoothReplyRunnable* aRunnable)
 {
   MOZ_ASSERT(NS_IsMainThread());
 
   if (!IsReady()) {
     NS_NAMED_LITERAL_STRING(errorStr, "Bluetooth service is not ready yet!");
     DispatchBluetoothReply(aRunnable, BluetoothValue(), errorStr);
     return NS_OK;
   }
 
-  MOZ_ASSERT(aType < (int)ArrayLength(sBluetoothDBusIfaces));
-  MOZ_ASSERT(!sAdapterPath.IsEmpty());
-  const char* interface = sBluetoothDBusIfaces[aType];
-
-  /* Compose the command */
-  DBusMessage* msg = dbus_message_new_method_call(
-                                      "org.bluez",
-                                      NS_ConvertUTF16toUTF8(sAdapterPath).get(),
-                                      interface,
-                                      "SetProperty");
-
-  if (!msg) {
-    BT_WARNING("Could not allocate D-Bus message object!");
-    return NS_ERROR_FAILURE;
-  }
-
-  nsCString intermediatePropName(NS_ConvertUTF16toUTF8(aValue.name()));
-  const char* propName = intermediatePropName.get();
-  if (!dbus_message_append_args(msg, DBUS_TYPE_STRING, &propName,
-                                DBUS_TYPE_INVALID)) {
-    BT_WARNING("Couldn't append arguments to dbus message!");
+  Task* task;
+
+  if (aValue.value().type() == BluetoothValue::Tuint32_t) {
+    task = new SetUInt32PropertyTask(
+      NS_ConvertUTF16toUTF8(sAdapterPath), aType,
+      NS_ConvertUTF16toUTF8(aValue.name()),
+      aValue.value().get_uint32_t(), aRunnable);
+  } else if (aValue.value().type() == BluetoothValue::TnsString) {
+    task = new SetStringPropertyTask(
+      NS_ConvertUTF16toUTF8(sAdapterPath), aType,
+      NS_ConvertUTF16toUTF8(aValue.name()),
+      NS_ConvertUTF16toUTF8(aValue.value().get_nsString()), aRunnable);
+  } else if (aValue.value().type() == BluetoothValue::Tbool) {
+    task = new SetBooleanPropertyTask(
+      NS_ConvertUTF16toUTF8(sAdapterPath), aType,
+      NS_ConvertUTF16toUTF8(aValue.name()),
+      aValue.value().get_bool(), aRunnable);
+  } else {
+    BT_WARNING("Property type not handled!");
     return NS_ERROR_FAILURE;
   }
-
-  int type;
-  int tmp_int;
-  void* val;
-  const char* tempStr;
-  nsCString str;
-  if (aValue.value().type() == BluetoothValue::Tuint32_t) {
-    tmp_int = aValue.value().get_uint32_t();
-    val = &tmp_int;
-    type = DBUS_TYPE_UINT32;
-  } else if (aValue.value().type() == BluetoothValue::TnsString) {
-    str = NS_ConvertUTF16toUTF8(aValue.value().get_nsString());
-    tempStr = str.get();
-    val = &tempStr;
-    type = DBUS_TYPE_STRING;
-  } else if (aValue.value().type() == BluetoothValue::Tbool) {
-    tmp_int = aValue.value().get_bool() ? 1 : 0;
-    val = &(tmp_int);
-    type = DBUS_TYPE_BOOLEAN;
-  } else {
-    BT_WARNING("Property type not handled!");
-    dbus_message_unref(msg);
-    return NS_ERROR_FAILURE;
-  }
-
-  DBusMessageIter value_iter, iter;
-  dbus_message_iter_init_append(msg, &iter);
-  char var_type[2] = {(char)type, '\0'};
-  if (!dbus_message_iter_open_container(&iter, DBUS_TYPE_VARIANT,
-                                        var_type, &value_iter) ||
-      !dbus_message_iter_append_basic(&value_iter, type, val) ||
-      !dbus_message_iter_close_container(&iter, &value_iter)) {
-    BT_WARNING("Could not append argument to method call!");
-    dbus_message_unref(msg);
-    return NS_ERROR_FAILURE;
-  }
-
-  nsRefPtr<BluetoothReplyRunnable> runnable = aRunnable;
-
-  RawDBusConnection* connection = GetDBusConnection();
-  MOZ_ASSERT(connection);
-
-  // msg is unref'd as part of SendWithReply
-  bool success = connection->SendWithReply(GetVoidCallback,
-                                           (void*)aRunnable,
-                                           1000, msg);
-  if (!success) {
-    BT_WARNING("SendWithReply failed");
-    return NS_ERROR_FAILURE;
-  }
-  runnable.forget();
+  DispatchToDBusThread(task);
+
   return NS_OK;
 }
 
+class CreatePairedDeviceInternalTask : public Task
+{
+public:
+  CreatePairedDeviceInternalTask(const nsACString& aAdapterPath,
+                                 const nsACString& aDeviceAddress,
+                                 int aTimeout,
+                                 BluetoothReplyRunnable* aRunnable)
+    : mAdapterPath(aAdapterPath)
+    , mDeviceAddress(aDeviceAddress)
+    , mTimeout(aTimeout)
+    , mRunnable(aRunnable)
+  {
+    MOZ_ASSERT(!mAdapterPath.IsEmpty());
+    MOZ_ASSERT(!mDeviceAddress.IsEmpty());
+    MOZ_ASSERT(mRunnable);
+  }
+
+  void Run() MOZ_OVERRIDE
+  {
+    MOZ_ASSERT(!NS_IsMainThread()); // I/O thread
+
+    const char *deviceAddress = mDeviceAddress.get();
+    const char *deviceAgentPath = KEY_REMOTE_AGENT;
+    const char *capabilities = B2G_AGENT_CAPABILITIES;
+
+    RawDBusConnection* connection = GetDBusConnection();
+    MOZ_ASSERT(connection);
+
+    // Then send CreatePairedDevice, it will register a temp device agent then
+    // unregister it after pairing process is over
+    bool success = connection->SendWithReply(
+      GetObjectPathCallback, static_cast<void*>(mRunnable), mTimeout,
+      mAdapterPath.get(),
+      DBUS_ADAPTER_IFACE,
+      "CreatePairedDevice",
+      DBUS_TYPE_STRING, &deviceAddress,
+      DBUS_TYPE_OBJECT_PATH, &deviceAgentPath,
+      DBUS_TYPE_STRING, &capabilities,
+      DBUS_TYPE_INVALID);
+    NS_ENSURE_SUCCESS_VOID(success);
+
+    mRunnable.forget();
+
+    /**
+     * FIXME: Bug 820274
+     *
+     * If the user turns off Bluetooth in the middle of pairing process,
+     * the callback function GetObjectPathCallback may still be called
+     * while enabling next time by dbus daemon. To prevent this from
+     * happening, added a flag to distinguish if Bluetooth has been
+     * turned off. Nevertheless, we need a check if there is a better
+     * solution.
+     *
+     * Please see Bug 818696 for more information.
+     */
+    sIsPairing++;
+  }
+
+private:
+  const nsCString mAdapterPath;
+  const nsCString mDeviceAddress;
+  int mTimeout;
+  nsRefPtr<BluetoothReplyRunnable> mRunnable;
+};
+
 nsresult
 BluetoothDBusService::CreatePairedDeviceInternal(
                                               const nsAString& aDeviceAddress,
                                               int aTimeout,
                                               BluetoothReplyRunnable* aRunnable)
 {
-  const char *capabilities = B2G_AGENT_CAPABILITIES;
-  const char *deviceAgentPath = KEY_REMOTE_AGENT;
-
-  nsCString tempDeviceAddress = NS_ConvertUTF16toUTF8(aDeviceAddress);
-  const char *deviceAddress = tempDeviceAddress.get();
-
-  /**
-   * FIXME: Bug 820274
-   *
-   * If the user turns off Bluetooth in the middle of pairing process, the
-   * callback function GetObjectPathCallback (see the third argument of the
-   * function call above) may still be called while enabling next time by
-   * dbus daemon. To prevent this from happening, added a flag to distinguish
-   * if Bluetooth has been turned off. Nevertheless, we need a check if there
-   * is a better solution.
-   *
-   * Please see Bug 818696 for more information.
-   */
-  sIsPairing++;
-
-  nsRefPtr<BluetoothReplyRunnable> runnable = aRunnable;
-  MOZ_ASSERT(!sAdapterPath.IsEmpty());
-
-  RawDBusConnection* connection = GetDBusConnection();
-  MOZ_ASSERT(connection);
-
-  // Then send CreatePairedDevice, it will register a temp device agent then
-  // unregister it after pairing process is over
-  bool ret = connection->SendWithReply(
-    GetObjectPathCallback, (void*)runnable, aTimeout,
-    NS_ConvertUTF16toUTF8(sAdapterPath).get(),
-    DBUS_ADAPTER_IFACE,
-    "CreatePairedDevice",
-    DBUS_TYPE_STRING, &deviceAddress,
-    DBUS_TYPE_OBJECT_PATH, &deviceAgentPath,
-    DBUS_TYPE_STRING, &capabilities,
-    DBUS_TYPE_INVALID);
-  if (!ret) {
-    BT_WARNING("Could not start async function!");
-    return NS_ERROR_FAILURE;
-  }
-
-  runnable.forget();
+  Task* task = new CreatePairedDeviceInternalTask(
+    NS_ConvertUTF16toUTF8(sAdapterPath),
+    NS_ConvertUTF16toUTF8(aDeviceAddress),
+    aTimeout, aRunnable);
+  DispatchToDBusThread(task);
+
   return NS_OK;
 }
 
-static void
-OnRemoveDeviceReply(DBusMessage *aReply, void *aData)
+class RemoveDeviceTask : public Task
 {
-  nsAutoString errorStr;
-
-  if (!aReply) {
-    errorStr.AssignLiteral("RemoveDevice failed");
+public:
+  RemoveDeviceTask(const nsString& aAdapterPath,
+                   const nsAString& aDeviceAddress,
+                   BluetoothReplyRunnable* aRunnable)
+    : mAdapterPath(aAdapterPath)
+    , mDeviceAddress(aDeviceAddress)
+    , mRunnable(aRunnable)
+  {
+    MOZ_ASSERT(!mAdapterPath.IsEmpty());
+    MOZ_ASSERT(!mDeviceAddress.IsEmpty());
+    MOZ_ASSERT(mRunnable);
   }
 
-  nsRefPtr<BluetoothReplyRunnable> runnable =
-    dont_AddRef<BluetoothReplyRunnable>(static_cast<BluetoothReplyRunnable*>(aData));
-
-  DispatchBluetoothReply(runnable.get(), BluetoothValue(true), errorStr);
-}
+  void Run() MOZ_OVERRIDE
+  {
+    MOZ_ASSERT(!NS_IsMainThread()); // I/O thread
+
+    nsCString deviceObjectPath =
+      NS_ConvertUTF16toUTF8(GetObjectPathFromAddress(mAdapterPath,
+                                                     mDeviceAddress));
+    const char* cstrDeviceObjectPath = deviceObjectPath.get();
+
+    RawDBusConnection* connection = GetDBusConnection();
+    MOZ_ASSERT(connection);
+
+    bool success = connection->SendWithReply(
+      OnRemoveDeviceReply, static_cast<void*>(mRunnable.get()), -1,
+      NS_ConvertUTF16toUTF8(mAdapterPath).get(),
+      DBUS_ADAPTER_IFACE, "RemoveDevice",
+      DBUS_TYPE_OBJECT_PATH, &cstrDeviceObjectPath,
+      DBUS_TYPE_INVALID);
+    NS_ENSURE_TRUE_VOID(success);
+
+    mRunnable.forget();
+  }
+
+protected:
+  static void OnRemoveDeviceReply(DBusMessage* aReply, void* aData)
+  {
+    nsAutoString errorStr;
+
+    if (!aReply) {
+      errorStr.AssignLiteral("RemoveDevice failed");
+    }
+
+    nsRefPtr<BluetoothReplyRunnable> runnable =
+      dont_AddRef<BluetoothReplyRunnable>(
+        static_cast<BluetoothReplyRunnable*>(aData));
+
+    DispatchBluetoothReply(runnable.get(), BluetoothValue(true), errorStr);
+  }
+
+private:
+  const nsString mAdapterPath;
+  const nsString mDeviceAddress;
+  nsRefPtr<BluetoothReplyRunnable> mRunnable;
+};
 
 nsresult
 BluetoothDBusService::RemoveDeviceInternal(const nsAString& aDeviceAddress,
                                            BluetoothReplyRunnable* aRunnable)
 {
   MOZ_ASSERT(NS_IsMainThread());
 
   if (!IsReady()) {
     NS_NAMED_LITERAL_STRING(errorStr, "Bluetooth service is not ready yet!");
     DispatchBluetoothReply(aRunnable, BluetoothValue(), errorStr);
     return NS_OK;
   }
 
-  MOZ_ASSERT(!sAdapterPath.IsEmpty());
-  nsCString deviceObjectPath =
-    NS_ConvertUTF16toUTF8(GetObjectPathFromAddress(sAdapterPath,
-                                                   aDeviceAddress));
-  const char* cstrDeviceObjectPath = deviceObjectPath.get();
-
-  nsRefPtr<BluetoothReplyRunnable> runnable(aRunnable);
-
-  RawDBusConnection* connection = GetDBusConnection();
-  MOZ_ASSERT(connection);
-
-  bool success = connection->SendWithReply(
-    OnRemoveDeviceReply, static_cast<void*>(runnable.get()), -1,
-    NS_ConvertUTF16toUTF8(sAdapterPath).get(),
-    DBUS_ADAPTER_IFACE, "RemoveDevice",
-    DBUS_TYPE_OBJECT_PATH, &cstrDeviceObjectPath,
-    DBUS_TYPE_INVALID);
-
-  NS_ENSURE_TRUE(success, NS_ERROR_FAILURE);
-
-  runnable.forget();
+  Task* task = new RemoveDeviceTask(sAdapterPath, aDeviceAddress, aRunnable);
+  DispatchToDBusThread(task);
 
   return NS_OK;
 }
 
+class SetPinCodeTask : public Task
+{
+public:
+  SetPinCodeTask(const nsAString& aDeviceAddress,
+                 const nsACString& aPinCode,
+                 BluetoothReplyRunnable* aRunnable)
+    : mDeviceAddress(aDeviceAddress)
+    , mPinCode(aPinCode)
+    , mRunnable(aRunnable)
+  {
+    MOZ_ASSERT(!mDeviceAddress.IsEmpty());
+    MOZ_ASSERT(mRunnable);
+  }
+
+  void Run() MOZ_OVERRIDE
+  {
+    MOZ_ASSERT(!NS_IsMainThread()); // I/O thread
+
+    nsAutoString errorStr;
+    BluetoothValue v = true;
+    DBusMessage *msg;
+    if (!sPairingReqTable->Get(mDeviceAddress, &msg)) {
+      BT_WARNING("%s: Couldn't get original request message.", __FUNCTION__);
+      errorStr.AssignLiteral("Couldn't get original request message.");
+      DispatchBluetoothReply(mRunnable, v, errorStr);
+      return;
+    }
+
+    DBusMessage *reply = dbus_message_new_method_return(msg);
+
+    if (!reply) {
+      BT_WARNING("%s: Memory can't be allocated for the message.", __FUNCTION__);
+      dbus_message_unref(msg);
+      errorStr.AssignLiteral("Memory can't be allocated for the message.");
+      DispatchBluetoothReply(mRunnable, v, errorStr);
+      return;
+    }
+
+    const char* pinCode = mPinCode.get();
+
+    if (!dbus_message_append_args(reply,
+                                  DBUS_TYPE_STRING, &pinCode,
+                                  DBUS_TYPE_INVALID)) {
+      BT_WARNING("%s: Couldn't append arguments to dbus message.", __FUNCTION__);
+      errorStr.AssignLiteral("Couldn't append arguments to dbus message.");
+    } else {
+      RawDBusConnection* connection = GetDBusConnection();
+      MOZ_ASSERT(connection);
+      connection->Send(reply);
+    }
+
+    dbus_message_unref(msg);
+    dbus_message_unref(reply);
+
+    sPairingReqTable->Remove(mDeviceAddress);
+    DispatchBluetoothReply(mRunnable, v, errorStr);
+  }
+
+private:
+  const nsString mDeviceAddress;
+  const nsCString mPinCode;
+  nsRefPtr<BluetoothReplyRunnable> mRunnable;
+};
+
 bool
 BluetoothDBusService::SetPinCodeInternal(const nsAString& aDeviceAddress,
                                          const nsAString& aPinCode,
                                          BluetoothReplyRunnable* aRunnable)
 {
-  nsAutoString errorStr;
-  BluetoothValue v = true;
-  DBusMessage *msg;
-  if (!sPairingReqTable->Get(aDeviceAddress, &msg)) {
-    BT_WARNING("%s: Couldn't get original request message.", __FUNCTION__);
-    errorStr.AssignLiteral("Couldn't get original request message.");
-    DispatchBluetoothReply(aRunnable, v, errorStr);
-    return false;
-  }
-
-  DBusMessage *reply = dbus_message_new_method_return(msg);
-
-  if (!reply) {
-    BT_WARNING("%s: Memory can't be allocated for the message.", __FUNCTION__);
-    dbus_message_unref(msg);
-    errorStr.AssignLiteral("Memory can't be allocated for the message.");
-    DispatchBluetoothReply(aRunnable, v, errorStr);
-    return false;
+  Task* task = new SetPinCodeTask(aDeviceAddress,
+                                  NS_ConvertUTF16toUTF8(aPinCode),
+                                  aRunnable);
+  DispatchToDBusThread(task);
+
+  return true;
+}
+
+class SetPasskeyTask : public Task
+{
+public:
+  SetPasskeyTask(const nsAString& aDeviceAddress,
+                 uint32_t aPasskey,
+                 BluetoothReplyRunnable* aRunnable)
+    : mDeviceAddress(aDeviceAddress)
+    , mPasskey(aPasskey)
+    , mRunnable(aRunnable)
+  {
+    MOZ_ASSERT(!mDeviceAddress.IsEmpty());
+    MOZ_ASSERT(mRunnable);
   }
 
-  bool result;
-
-  nsCString tempPinCode = NS_ConvertUTF16toUTF8(aPinCode);
-  const char* pinCode = tempPinCode.get();
-
-  if (!dbus_message_append_args(reply,
-                                DBUS_TYPE_STRING, &pinCode,
-                                DBUS_TYPE_INVALID)) {
-    BT_WARNING("%s: Couldn't append arguments to dbus message.", __FUNCTION__);
-    errorStr.AssignLiteral("Couldn't append arguments to dbus message.");
-    result = false;
-  } else {
-    RawDBusConnection* connection = GetDBusConnection();
-    MOZ_ASSERT(connection);
-    result = connection->Send(reply);
+  void Run() MOZ_OVERRIDE
+  {
+    MOZ_ASSERT(!NS_IsMainThread()); // I/O thread
+
+    nsAutoString errorStr;
+    BluetoothValue v = true;
+    DBusMessage *msg;
+    if (!sPairingReqTable->Get(mDeviceAddress, &msg)) {
+      BT_WARNING("%s: Couldn't get original request message.", __FUNCTION__);
+      errorStr.AssignLiteral("Couldn't get original request message.");
+      DispatchBluetoothReply(mRunnable, v, errorStr);
+      return;
+    }
+
+    DBusMessage *reply = dbus_message_new_method_return(msg);
+
+    if (!reply) {
+      BT_WARNING("%s: Memory can't be allocated for the message.", __FUNCTION__);
+      dbus_message_unref(msg);
+      errorStr.AssignLiteral("Memory can't be allocated for the message.");
+      DispatchBluetoothReply(mRunnable, v, errorStr);
+      return;
+    }
+
+    uint32_t passkey = mPasskey;
+
+    if (!dbus_message_append_args(reply,
+                                  DBUS_TYPE_UINT32, &passkey,
+                                  DBUS_TYPE_INVALID)) {
+      BT_WARNING("%s: Couldn't append arguments to dbus message.", __FUNCTION__);
+      errorStr.AssignLiteral("Couldn't append arguments to dbus message.");
+    } else {
+      RawDBusConnection* connection = GetDBusConnection();
+      MOZ_ASSERT(connection);
+      connection->Send(reply);
+    }
+
+    dbus_message_unref(msg);
+    dbus_message_unref(reply);
+
+    sPairingReqTable->Remove(mDeviceAddress);
+    DispatchBluetoothReply(mRunnable, v, errorStr);
   }
 
-  dbus_message_unref(msg);
-  dbus_message_unref(reply);
-
-  sPairingReqTable->Remove(aDeviceAddress);
-  DispatchBluetoothReply(aRunnable, v, errorStr);
-  return result;
-}
+private:
+  nsString mDeviceAddress;
+  uint32_t mPasskey;
+  nsRefPtr<BluetoothReplyRunnable> mRunnable;
+};
 
 bool
 BluetoothDBusService::SetPasskeyInternal(const nsAString& aDeviceAddress,
                                          uint32_t aPasskey,
                                          BluetoothReplyRunnable* aRunnable)
 {
-  nsAutoString errorStr;
-  BluetoothValue v = true;
-  DBusMessage *msg;
-  if (!sPairingReqTable->Get(aDeviceAddress, &msg)) {
-    BT_WARNING("%s: Couldn't get original request message.", __FUNCTION__);
-    errorStr.AssignLiteral("Couldn't get original request message.");
-    DispatchBluetoothReply(aRunnable, v, errorStr);
-    return false;
+  Task* task = new SetPasskeyTask(aDeviceAddress,
+                                  aPasskey,
+                                  aRunnable);
+  DispatchToDBusThread(task);
+
+  return true;
+}
+
+class SetPairingConfirmationTask : public Task
+{
+public:
+  SetPairingConfirmationTask(const nsAString& aDeviceAddress,
+                             bool aConfirm,
+                             BluetoothReplyRunnable* aRunnable)
+    : mDeviceAddress(aDeviceAddress)
+    , mConfirm(aConfirm)
+    , mRunnable(aRunnable)
+  {
+    MOZ_ASSERT(!mDeviceAddress.IsEmpty());
+    MOZ_ASSERT(mRunnable);
   }
 
-  DBusMessage *reply = dbus_message_new_method_return(msg);
-
-  if (!reply) {
-    BT_WARNING("%s: Memory can't be allocated for the message.", __FUNCTION__);
-    dbus_message_unref(msg);
-    errorStr.AssignLiteral("Memory can't be allocated for the message.");
-    DispatchBluetoothReply(aRunnable, v, errorStr);
-    return false;
-  }
-
-  uint32_t passkey = aPasskey;
-  bool result;
-
-  if (!dbus_message_append_args(reply,
-                                DBUS_TYPE_UINT32, &passkey,
-                                DBUS_TYPE_INVALID)) {
-    BT_WARNING("%s: Couldn't append arguments to dbus message.", __FUNCTION__);
-    errorStr.AssignLiteral("Couldn't append arguments to dbus message.");
-    result = false;
-  } else {
+  void Run() MOZ_OVERRIDE
+  {
+    MOZ_ASSERT(!NS_IsMainThread()); // I/O thread
+
+    nsAutoString errorStr;
+    BluetoothValue v = true;
+    DBusMessage *msg;
+    if (!sPairingReqTable->Get(mDeviceAddress, &msg)) {
+      BT_WARNING("%s: Couldn't get original request message.", __FUNCTION__);
+      errorStr.AssignLiteral("Couldn't get original request message.");
+      DispatchBluetoothReply(mRunnable, v, errorStr);
+      return;
+    }
+
+    DBusMessage *reply;
+
+    if (mConfirm) {
+      reply = dbus_message_new_method_return(msg);
+    } else {
+      reply = dbus_message_new_error(msg, "org.bluez.Error.Rejected",
+                                     "User rejected confirmation");
+    }
+
+    if (!reply) {
+      BT_WARNING("%s: Memory can't be allocated for the message.", __FUNCTION__);
+      dbus_message_unref(msg);
+      errorStr.AssignLiteral("Memory can't be allocated for the message.");
+      DispatchBluetoothReply(mRunnable, v, errorStr);
+      return;
+    }
+
     RawDBusConnection* connection = GetDBusConnection();
     MOZ_ASSERT(connection);
-    result = connection->Send(reply);
+
+    bool result = connection->Send(reply);
+    if (!result) {
+      errorStr.AssignLiteral("Can't send message!");
+    }
+    dbus_message_unref(msg);
+    dbus_message_unref(reply);
+
+    sPairingReqTable->Remove(mDeviceAddress);
+    DispatchBluetoothReply(mRunnable, v, errorStr);
   }
 
-  dbus_message_unref(msg);
-  dbus_message_unref(reply);
-
-  sPairingReqTable->Remove(aDeviceAddress);
-  DispatchBluetoothReply(aRunnable, v, errorStr);
-  return result;
-}
+private:
+  nsString mDeviceAddress;
+  bool mConfirm;
+  nsRefPtr<BluetoothReplyRunnable> mRunnable;
+};
 
 bool
 BluetoothDBusService::SetPairingConfirmationInternal(
                                               const nsAString& aDeviceAddress,
                                               bool aConfirm,
                                               BluetoothReplyRunnable* aRunnable)
 {
-  nsAutoString errorStr;
-  BluetoothValue v = true;
-  DBusMessage *msg;
-  if (!sPairingReqTable->Get(aDeviceAddress, &msg)) {
-    BT_WARNING("%s: Couldn't get original request message.", __FUNCTION__);
-    errorStr.AssignLiteral("Couldn't get original request message.");
-    DispatchBluetoothReply(aRunnable, v, errorStr);
-    return false;
-  }
-
-  DBusMessage *reply;
-
-  if (aConfirm) {
-    reply = dbus_message_new_method_return(msg);
-  } else {
-    reply = dbus_message_new_error(msg, "org.bluez.Error.Rejected",
-                                   "User rejected confirmation");
-  }
-
-  if (!reply) {
-    BT_WARNING("%s: Memory can't be allocated for the message.", __FUNCTION__);
-    dbus_message_unref(msg);
-    errorStr.AssignLiteral("Memory can't be allocated for the message.");
-    DispatchBluetoothReply(aRunnable, v, errorStr);
-    return false;
-  }
-
-  RawDBusConnection* connection = GetDBusConnection();
-  MOZ_ASSERT(connection);
-
-  bool result = connection->Send(reply);
-  if (!result) {
-    errorStr.AssignLiteral("Can't send message!");
-  }
-  dbus_message_unref(msg);
-  dbus_message_unref(reply);
-
-  sPairingReqTable->Remove(aDeviceAddress);
-  DispatchBluetoothReply(aRunnable, v, errorStr);
-  return result;
+  MOZ_ASSERT(NS_IsMainThread());
+
+  Task* task = new SetPairingConfirmationTask(aDeviceAddress,
+                                              aConfirm,
+                                              aRunnable);
+  DispatchToDBusThread(task);
+
+  return true;
 }
 
 static void
 NextBluetoothProfileController()
 {
   MOZ_ASSERT(NS_IsMainThread());
 
   // First, remove the task at the front which has been already done.
@@ -2875,108 +3236,171 @@ public:
   }
 
 private:
   nsString mObjectPath;
   nsString mServiceUUID;
   BluetoothProfileManagerBase* mBluetoothProfileManager;
 };
 
+class GetServiceChannelTask : public Task
+{
+public:
+  GetServiceChannelTask(const nsString& aAdapterPath,
+                        const nsAString& aDeviceAddress,
+                        const nsAString& aServiceUUID,
+                        BluetoothProfileManagerBase* aBluetoothProfileManager)
+    : mAdapterPath(aAdapterPath)
+    , mDeviceAddress(aDeviceAddress)
+    , mServiceUUID(aServiceUUID)
+    , mBluetoothProfileManager(aBluetoothProfileManager)
+  {
+    MOZ_ASSERT(!mAdapterPath.IsEmpty());
+    MOZ_ASSERT(!mDeviceAddress.IsEmpty());
+    MOZ_ASSERT(mBluetoothProfileManager);
+  }
+
+  void Run() MOZ_OVERRIDE
+  {
+    static const int sProtocolDescriptorList = 0x0004;
+
+    MOZ_ASSERT(!NS_IsMainThread()); // I/O thread
+
+    nsString objectPath =
+      GetObjectPathFromAddress(mAdapterPath, mDeviceAddress);
+
+    nsRefPtr<OnGetServiceChannelReplyHandler> handler =
+      new OnGetServiceChannelReplyHandler(objectPath, mServiceUUID,
+                                          mBluetoothProfileManager);
+
+    nsCString serviceUUID = NS_ConvertUTF16toUTF8(mServiceUUID);
+    const char* cstrServiceUUID = serviceUUID.get();
+
+    RawDBusConnection* connection = GetDBusConnection();
+    MOZ_ASSERT(connection);
+
+    bool success = connection->SendWithReply(
+      OnGetServiceChannelReplyHandler::Callback, handler, -1,
+      NS_ConvertUTF16toUTF8(objectPath).get(),
+      DBUS_DEVICE_IFACE, "GetServiceAttributeValue",
+      DBUS_TYPE_STRING, &cstrServiceUUID,
+      DBUS_TYPE_UINT16, &sProtocolDescriptorList,
+      DBUS_TYPE_INVALID);
+    NS_ENSURE_TRUE_VOID(success);
+
+    handler.forget();
+  }
+
+private:
+  nsString mAdapterPath;
+  nsString mDeviceAddress;
+  nsString mServiceUUID;
+  BluetoothProfileManagerBase* mBluetoothProfileManager;
+};
+
 nsresult
 BluetoothDBusService::GetServiceChannel(const nsAString& aDeviceAddress,
                                         const nsAString& aServiceUUID,
                                         BluetoothProfileManagerBase* aManager)
 {
   MOZ_ASSERT(NS_IsMainThread());
 
   if (!IsReady()) {
     NS_NAMED_LITERAL_STRING(errorStr, "Bluetooth service is not ready yet!");
     return NS_OK;
   }
 
-  MOZ_ASSERT(!sAdapterPath.IsEmpty());
-  nsString objectPath(GetObjectPathFromAddress(sAdapterPath, aDeviceAddress));
-
 #ifdef MOZ_WIDGET_GONK
-  static const int sProtocolDescriptorList = 0x0004;
-
   // GetServiceAttributeValue only exists in android's bluez dbus binding
   // implementation
-  nsCString serviceUUID = NS_ConvertUTF16toUTF8(aServiceUUID);
-  const char* cstrServiceUUID = serviceUUID.get();
-
-  nsRefPtr<OnGetServiceChannelReplyHandler> handler =
-    new OnGetServiceChannelReplyHandler(objectPath, aServiceUUID, aManager);
-
-  RawDBusConnection* connection = GetDBusConnection();
-  MOZ_ASSERT(connection);
-
-  bool success = connection->SendWithReply(
-    OnGetServiceChannelReplyHandler::Callback, handler, -1,
-    NS_ConvertUTF16toUTF8(objectPath).get(),
-    DBUS_DEVICE_IFACE, "GetServiceAttributeValue",
-    DBUS_TYPE_STRING, &cstrServiceUUID,
-    DBUS_TYPE_UINT16, &sProtocolDescriptorList,
-    DBUS_TYPE_INVALID);
-  NS_ENSURE_TRUE(success, NS_ERROR_FAILURE);
-
-  handler.forget();
+
+  Task* task = new GetServiceChannelTask(sAdapterPath,
+                                         aDeviceAddress,
+                                         aServiceUUID,
+                                         aManager);
+  DispatchToDBusThread(task);
 #else
+  MOZ_ASSERT(!sAdapterPath.IsEmpty());
+  nsString objectPath(GetObjectPathFromAddress(sAdapterPath, aDeviceAddress));
+
   // FIXME/Bug 793977 qdot: Just set something for desktop, until we have a
   // parser for the GetServiceAttributes xml block
   //
   // Even though we are on the main thread already, we need to dispatch a
   // runnable here. OnGetServiceChannel needs mRunnable to be set, which
   // happens after GetServiceChannel returns.
   nsRefPtr<nsRunnable> r = new OnGetServiceChannelRunnable(objectPath,
                                                            aServiceUUID,
                                                            1,
                                                            aManager);
   NS_DispatchToMainThread(r);
 #endif
 
   return NS_OK;
 }
 
-static void
-DiscoverServicesCallback(DBusMessage* aMsg, void* aData)
+class UpdateSdpRecordsTask : public Task
 {
-  MOZ_ASSERT(!NS_IsMainThread());
-
-  nsRefPtr<OnUpdateSdpRecordsRunnable> r(
-    static_cast<OnUpdateSdpRecordsRunnable*>(aData));
-  NS_DispatchToMainThread(r);
-}
+public:
+  UpdateSdpRecordsTask(const nsString& aObjectPath,
+                       BluetoothProfileManagerBase* aBluetoothProfileManager)
+    : mObjectPath(aObjectPath)
+    , mBluetoothProfileManager(aBluetoothProfileManager)
+  {
+    MOZ_ASSERT(!mObjectPath.IsEmpty());
+    MOZ_ASSERT(mBluetoothProfileManager);
+  }
+
+  void Run() MOZ_OVERRIDE
+  {
+    MOZ_ASSERT(!NS_IsMainThread()); // I/O thread
+
+    // I choose to use raw pointer here because this is going to be passed as an
+    // argument into SendWithReply() at once.
+    OnUpdateSdpRecordsRunnable* callbackRunnable =
+      new OnUpdateSdpRecordsRunnable(mObjectPath, mBluetoothProfileManager);
+
+    RawDBusConnection* connection = GetDBusConnection();
+    MOZ_ASSERT(connection);
+
+    connection->SendWithReply(DiscoverServicesCallback,
+                              (void*)callbackRunnable, -1,
+                              NS_ConvertUTF16toUTF8(mObjectPath).get(),
+                              DBUS_DEVICE_IFACE,
+                              "DiscoverServices",
+                              DBUS_TYPE_STRING, &EmptyCString(),
+                              DBUS_TYPE_INVALID);
+  }
+
+protected:
+  static void DiscoverServicesCallback(DBusMessage* aMsg, void* aData)
+  {
+    MOZ_ASSERT(!NS_IsMainThread()); // I/O thread
+
+    nsRefPtr<OnUpdateSdpRecordsRunnable> r(
+      static_cast<OnUpdateSdpRecordsRunnable*>(aData));
+    NS_DispatchToMainThread(r);
+  }
+
+private:
+  const nsString mObjectPath;
+  BluetoothProfileManagerBase* mBluetoothProfileManager;
+};
 
 bool
 BluetoothDBusService::UpdateSdpRecords(const nsAString& aDeviceAddress,
                                        BluetoothProfileManagerBase* aManager)
 {
   MOZ_ASSERT(NS_IsMainThread());
-  MOZ_ASSERT(!aDeviceAddress.IsEmpty());
-  MOZ_ASSERT(!sAdapterPath.IsEmpty());
-  MOZ_ASSERT(aManager);
-
-  nsString objectPath(GetObjectPathFromAddress(sAdapterPath, aDeviceAddress));
-
-  // I choose to use raw pointer here because this is going to be passed as an
-  // argument into SendWithReply() at once.
-  OnUpdateSdpRecordsRunnable* callbackRunnable =
-    new OnUpdateSdpRecordsRunnable(objectPath, aManager);
-
-  RawDBusConnection* connection = GetDBusConnection();
-  MOZ_ASSERT(connection);
-
-  return connection->SendWithReply(DiscoverServicesCallback,
-                                   (void*)callbackRunnable, -1,
-                                   NS_ConvertUTF16toUTF8(objectPath).get(),
-                                   DBUS_DEVICE_IFACE,
-                                   "DiscoverServices",
-                                   DBUS_TYPE_STRING, &EmptyCString(),
-                                   DBUS_TYPE_INVALID);
+
+  Task* task = new UpdateSdpRecordsTask(
+    GetObjectPathFromAddress(sAdapterPath, aDeviceAddress), aManager);
+  DispatchToDBusThread(task);
+
+  return true;
 }
 
 void
 BluetoothDBusService::SendFile(const nsAString& aDeviceAddress,
                                BlobParent* aBlobParent,
                                BlobChild* aBlobChild,
                                BluetoothReplyRunnable* aRunnable)
 {
@@ -3071,16 +3495,102 @@ BluetoothDBusService::IsScoConnected(Blu
     NS_NAMED_LITERAL_STRING(replyError, "Fail to get BluetoothHfpManager");
     DispatchBluetoothReply(aRunnable, BluetoothValue(), replyError);
     return;
   }
 
   DispatchBluetoothReply(aRunnable, hfp->IsScoConnected(), EmptyString());
 }
 
+class SendMetadataTask : public Task
+{
+public:
+  SendMetadataTask(const nsACString& aObjectPath,
+                   const nsACString& aTitle,
+                   const nsACString& aArtist,
+                   const nsACString& aAlbum,
+                   int64_t aMediaNumber,
+                   int64_t aTotalMediaCount,
+                   int64_t aDuration,
+                   BluetoothReplyRunnable* aRunnable)
+    : mObjectPath(aObjectPath)
+    , mTitle(aTitle)
+    , mArtist(aArtist)
+    , mAlbum(aAlbum)
+    , mMediaNumber(aMediaNumber)
+    , mTotalMediaCount(aTotalMediaCount)
+    , mDuration(aDuration)
+    , mRunnable(aRunnable)
+  {
+    MOZ_ASSERT(!mObjectPath.IsEmpty());
+    MOZ_ASSERT(mRunnable);
+  }
+
+  void Run() MOZ_OVERRIDE
+  {
+    MOZ_ASSERT(!NS_IsMainThread()); // I/O thread
+
+    // We currently don't support genre field in music player.
+    // In order to send media metadata through AVRCP, we set genre to an empty
+    // string to match the BlueZ method "UpdateMetaData" with signature "sssssss",
+    // which takes genre field as the last parameter.
+    nsCString tempGenre = EmptyCString();
+    nsCString tempMediaNumber = EmptyCString();
+    nsCString tempTotalMediaCount = EmptyCString();
+    nsCString tempDuration = EmptyCString();
+
+    if (mMediaNumber >= 0) {
+      tempMediaNumber.AppendInt(mMediaNumber);
+    }
+    if (mTotalMediaCount >= 0) {
+      tempTotalMediaCount.AppendInt(mTotalMediaCount);
+    }
+    if (mDuration >= 0) {
+      tempDuration.AppendInt(mDuration);
+    }
+
+    const char* title = mTitle.get();
+    const char* album = mAlbum.get();
+    const char* artist = mArtist.get();
+    const char* mediaNumber = tempMediaNumber.get();
+    const char* totalMediaCount = tempTotalMediaCount.get();
+    const char* duration = tempDuration.get();
+    const char* genre = tempGenre.get();
+
+    RawDBusConnection* connection = GetDBusConnection();
+    MOZ_ASSERT(connection);
+
+    bool success = connection->SendWithReply(
+      GetVoidCallback, static_cast<void*>(mRunnable.get()), -1,
+      mObjectPath.get(),
+      DBUS_CTL_IFACE, "UpdateMetaData",
+      DBUS_TYPE_STRING, &title,
+      DBUS_TYPE_STRING, &artist,
+      DBUS_TYPE_STRING, &album,
+      DBUS_TYPE_STRING, &mediaNumber,
+      DBUS_TYPE_STRING, &totalMediaCount,
+      DBUS_TYPE_STRING, &duration,
+      DBUS_TYPE_STRING, &genre,
+      DBUS_TYPE_INVALID);
+    NS_ENSURE_TRUE_VOID(success);
+
+    mRunnable.forget();
+  }
+
+private:
+  const nsCString mObjectPath;
+  const nsCString mTitle;
+  const nsCString mArtist;
+  const nsCString mAlbum;
+  int64_t mMediaNumber;
+  int64_t mTotalMediaCount;
+  int64_t mDuration;
+  nsRefPtr<BluetoothReplyRunnable> mRunnable;
+};
+
 void
 BluetoothDBusService::SendMetaData(const nsAString& aTitle,
                                    const nsAString& aArtist,
                                    const nsAString& aAlbum,
                                    int64_t aMediaNumber,
                                    int64_t aTotalMediaCount,
                                    int64_t aDuration,
                                    BluetoothReplyRunnable* aRunnable)
@@ -3101,84 +3611,39 @@ BluetoothDBusService::SendMetaData(const
                            NS_LITERAL_STRING(ERR_A2DP_IS_DISCONNECTED));
     return;
   } else if (!a2dp->IsAvrcpConnected()) {
     DispatchBluetoothReply(aRunnable, BluetoothValue(),
                            NS_LITERAL_STRING(ERR_AVRCP_IS_DISCONNECTED));
     return;
   }
 
-  MOZ_ASSERT(!sAdapterPath.IsEmpty());
-  nsAutoString address;
-  a2dp->GetAddress(address);
-  nsString objectPath =
-    GetObjectPathFromAddress(sAdapterPath, address);
-
-  nsCString tempTitle = NS_ConvertUTF16toUTF8(aTitle);
-  nsCString tempArtist = NS_ConvertUTF16toUTF8(aArtist);
-  nsCString tempAlbum = NS_ConvertUTF16toUTF8(aAlbum);
-
-  nsCString tempMediaNumber = EmptyCString();
-  nsCString tempTotalMediaCount = EmptyCString();
-  nsCString tempDuration = EmptyCString();
-
-  // We currently don't support genre field in music player.
-  // In order to send media metadata through AVRCP, we set genre to an empty
-  // string to match the BlueZ method "UpdateMetaData" with signature "sssssss",
-  // which takes genre field as the last parameter.
-  nsCString tempGenre = EmptyCString();
-
-  if (aMediaNumber >= 0) {
-    tempMediaNumber.AppendInt(aMediaNumber);
-  }
-  if (aTotalMediaCount >= 0) {
-    tempTotalMediaCount.AppendInt(aTotalMediaCount);
-  }
-  if (aDuration >= 0) {
-    tempDuration.AppendInt(aDuration);
-  }
-
-  const char* title = tempTitle.get();
-  const char* album = tempAlbum.get();
-  const char* artist = tempArtist.get();
-  const char* mediaNumber = tempMediaNumber.get();
-  const char* totalMediaCount = tempTotalMediaCount.get();
-  const char* duration = tempDuration.get();
-  const char* genre = tempGenre.get();
-
   nsAutoString prevTitle, prevAlbum;
   a2dp->GetTitle(prevTitle);
   a2dp->GetAlbum(prevAlbum);
 
   if (aMediaNumber != a2dp->GetMediaNumber() ||
       !aTitle.Equals(prevTitle) ||
       !aAlbum.Equals(prevAlbum)) {
     UpdateNotification(ControlEventId::EVENT_TRACK_CHANGED, aMediaNumber);
   }
 
-  nsRefPtr<BluetoothReplyRunnable> runnable(aRunnable);
-
-  RawDBusConnection* connection = GetDBusConnection();
-  MOZ_ASSERT(connection);
-
-  bool ret = connection->SendWithReply(
-    GetVoidCallback, (void*)runnable.get(), -1,
-    NS_ConvertUTF16toUTF8(objectPath).get(),
-    DBUS_CTL_IFACE, "UpdateMetaData",
-    DBUS_TYPE_STRING, &title,
-    DBUS_TYPE_STRING, &artist,
-    DBUS_TYPE_STRING, &album,
-    DBUS_TYPE_STRING, &mediaNumber,
-    DBUS_TYPE_STRING, &totalMediaCount,
-    DBUS_TYPE_STRING, &duration,
-    DBUS_TYPE_STRING, &genre,
-    DBUS_TYPE_INVALID);
-  NS_ENSURE_TRUE_VOID(ret);
-
-  runnable.forget();
+  nsAutoString address;
+  a2dp->GetAddress(address);
+
+  Task* task = new SendMetadataTask(
+    NS_ConvertUTF16toUTF8(GetObjectPathFromAddress(sAdapterPath, address)),
+    NS_ConvertUTF16toUTF8(aTitle),
+    NS_ConvertUTF16toUTF8(aArtist),
+    NS_ConvertUTF16toUTF8(aAlbum),
+    aMediaNumber,
+    aTotalMediaCount,
+    aDuration,
+    aRunnable);
+  DispatchToDBusThread(task);
 
   a2dp->UpdateMetaData(aTitle, aArtist, aAlbum,
                        aMediaNumber, aTotalMediaCount, aDuration);
 }
 
 static ControlPlayStatus
 PlayStatusStringToControlPlayStatus(const nsAString& aPlayStatus)
 {
@@ -3195,16 +3660,64 @@ PlayStatusStringToControlPlayStatus(cons
     playStatus = ControlPlayStatus::PLAYSTATUS_REV_SEEK;
   } else if (aPlayStatus.EqualsLiteral("ERROR")) {
     playStatus = ControlPlayStatus::PLAYSTATUS_ERROR;
   }
 
   return playStatus;
 }
 
+class SendPlayStatusTask : public Task
+{
+public:
+  SendPlayStatusTask(const nsACString& aObjectPath,
+                     int64_t aDuration,
+                     int64_t aPosition,
+                     ControlPlayStatus aPlayStatus,
+                     BluetoothReplyRunnable* aRunnable)
+    : mObjectPath(aObjectPath)
+    , mDuration(aDuration)
+    , mPosition(aPosition)
+    , mPlayStatus(aPlayStatus)
+    , mRunnable(aRunnable)
+  {
+    MOZ_ASSERT(!mObjectPath.IsEmpty());
+    MOZ_ASSERT(mRunnable);
+  }
+
+  void Run() MOZ_OVERRIDE
+  {
+    MOZ_ASSERT(!NS_IsMainThread()); // I/O thread
+
+    uint32_t tempPlayStatus = mPlayStatus;
+
+    RawDBusConnection* connection = GetDBusConnection();
+    MOZ_ASSERT(connection);
+
+    bool success = connection->SendWithReply(
+      GetVoidCallback, static_cast<void*>(mRunnable.get()), -1,
+      mObjectPath.get(),
+      DBUS_CTL_IFACE, "UpdatePlayStatus",
+      DBUS_TYPE_UINT32, &mDuration,
+      DBUS_TYPE_UINT32, &mPosition,
+      DBUS_TYPE_UINT32, &tempPlayStatus,
+      DBUS_TYPE_INVALID);
+    NS_ENSURE_TRUE_VOID(success);
+
+    mRunnable.forget();
+  }
+
+private:
+  const nsCString mObjectPath;
+  int64_t mDuration;
+  int64_t mPosition;
+  ControlPlayStatus mPlayStatus;
+  nsRefPtr<BluetoothReplyRunnable> mRunnable;
+};
+
 void
 BluetoothDBusService::SendPlayStatus(int64_t aDuration,
                                      int64_t aPosition,
                                      const nsAString& aPlayStatus,
                                      BluetoothReplyRunnable* aRunnable)
 {
   MOZ_ASSERT(NS_IsMainThread());
 
@@ -3238,46 +3751,33 @@ BluetoothDBusService::SendPlayStatus(int
                            NS_LITERAL_STRING(ERR_A2DP_IS_DISCONNECTED));
     return;
   } else if (!a2dp->IsAvrcpConnected()) {
     DispatchBluetoothReply(aRunnable, BluetoothValue(),
                            NS_LITERAL_STRING(ERR_AVRCP_IS_DISCONNECTED));
     return;
   }
 
-  uint32_t tempPlayStatus = playStatus;
   if (playStatus != a2dp->GetPlayStatus()) {
     UpdateNotification(ControlEventId::EVENT_PLAYBACK_STATUS_CHANGED,
-                       tempPlayStatus);
+                       playStatus);
   } else if (aPosition != a2dp->GetPosition()) {
     UpdateNotification(ControlEventId::EVENT_PLAYBACK_POS_CHANGED, aPosition);
   }
 
-  MOZ_ASSERT(!sAdapterPath.IsEmpty());
   nsAutoString address;
   a2dp->GetAddress(address);
-  nsString objectPath =
-    GetObjectPathFromAddress(sAdapterPath, address);
-
-  nsRefPtr<BluetoothReplyRunnable> runnable(aRunnable);
-
-  RawDBusConnection* connection = GetDBusConnection();
-  MOZ_ASSERT(connection);
-
-  bool ret = connection->SendWithReply(
-    GetVoidCallback, (void*)runnable.get(), -1,
-    NS_ConvertUTF16toUTF8(objectPath).get(),
-    DBUS_CTL_IFACE, "UpdatePlayStatus",
-    DBUS_TYPE_UINT32, &aDuration,
-    DBUS_TYPE_UINT32, &aPosition,
-    DBUS_TYPE_UINT32, &tempPlayStatus,
-    DBUS_TYPE_INVALID);
-  NS_ENSURE_TRUE_VOID(ret);
-
-  runnable.forget();
+
+  Task* task = new SendPlayStatusTask(
+    NS_ConvertUTF16toUTF8(GetObjectPathFromAddress(sAdapterPath, address)),
+    aDuration,
+    aPosition,
+    playStatus,
+    aRunnable);
+  DispatchToDBusThread(task);
 
   a2dp->UpdatePlayStatus(aDuration, aPosition, playStatus);
 }
 
 static void
 ControlCallback(DBusMessage* aMsg, void* aParam)
 {
   NS_ENSURE_TRUE_VOID(aMsg);
@@ -3285,74 +3785,135 @@ ControlCallback(DBusMessage* aMsg, void*
   BluetoothValue v;
   nsAutoString replyError;
   UnpackVoidMessage(aMsg, nullptr, v, replyError);
   if (!v.get_bool()) {
     BT_WARNING(NS_ConvertUTF16toUTF8(replyError).get());
   }
 }
 
+class UpdatePlayStatusTask : public Task
+{
+public:
+  UpdatePlayStatusTask(const nsACString& aObjectPath,
+                       int32_t aDuration,
+                       int32_t aPosition,
+                       ControlPlayStatus aPlayStatus)
+    : mObjectPath(aObjectPath)
+    , mDuration(aDuration)
+    , mPosition(aPosition)
+    , mPlayStatus(aPlayStatus)
+  {
+    MOZ_ASSERT(!mObjectPath.IsEmpty());
+  }
+
+  void Run() MOZ_OVERRIDE
+  {
+    MOZ_ASSERT(!NS_IsMainThread()); // I/O thread
+
+    uint32_t tempPlayStatus = mPlayStatus;
+
+    RawDBusConnection* connection = GetDBusConnection();
+    MOZ_ASSERT(connection);
+
+    bool success = connection->SendWithReply(
+      ControlCallback, nullptr, -1,
+      mObjectPath.get(),
+      DBUS_CTL_IFACE, "UpdatePlayStatus",
+      DBUS_TYPE_UINT32, &mDuration,
+      DBUS_TYPE_UINT32, &mPosition,
+      DBUS_TYPE_UINT32, &tempPlayStatus,
+      DBUS_TYPE_INVALID);
+    NS_ENSURE_TRUE_VOID(success);
+  }
+
+private:
+  const nsCString mObjectPath;
+  int32_t mDuration;
+  int32_t mPosition;
+  ControlPlayStatus mPlayStatus;
+};
+
 void
 BluetoothDBusService::UpdatePlayStatus(uint32_t aDuration,
                                        uint32_t aPosition,
                                        ControlPlayStatus aPlayStatus)
 {
   MOZ_ASSERT(NS_IsMainThread());
   NS_ENSURE_TRUE_VOID(this->IsReady());
 
   BluetoothA2dpManager* a2dp = BluetoothA2dpManager::Get();
   NS_ENSURE_TRUE_VOID(a2dp);
   MOZ_ASSERT(a2dp->IsConnected());
   MOZ_ASSERT(a2dp->IsAvrcpConnected());
   MOZ_ASSERT(!sAdapterPath.IsEmpty());
 
   nsAutoString address;
   a2dp->GetAddress(address);
-  nsString objectPath =
-    GetObjectPathFromAddress(sAdapterPath, address);
-
-  uint32_t tempPlayStatus = aPlayStatus;
-
-  RawDBusConnection* connection = GetDBusConnection();
-  MOZ_ASSERT(connection);
-
-  bool ret = connection->SendWithReply(
-    ControlCallback, nullptr, -1,
-    NS_ConvertUTF16toUTF8(objectPath).get(),
-    DBUS_CTL_IFACE, "UpdatePlayStatus",
-    DBUS_TYPE_UINT32, &aDuration,
-    DBUS_TYPE_UINT32, &aPosition,
-    DBUS_TYPE_UINT32, &tempPlayStatus,
-    DBUS_TYPE_INVALID);
-  NS_ENSURE_TRUE_VOID(ret);
+
+  Task* task = new UpdatePlayStatusTask(
+    NS_ConvertUTF16toUTF8(GetObjectPathFromAddress(sAdapterPath, address)),
+    aDuration,
+    aPosition,
+    aPlayStatus);
+  DispatchToDBusThread(task);
 }
 
+class UpdateNotificationTask : public Task
+{
+public:
+  UpdateNotificationTask(const nsACString& aObjectPath,
+                         BluetoothDBusService::ControlEventId aEventId,
+                         uint64_t aData)
+    : mObjectPath(aObjectPath)
+    , mEventId(aEventId)
+    , mData(aData)
+  {
+    MOZ_ASSERT(!mObjectPath.IsEmpty());
+  }
+
+  void Run() MOZ_OVERRIDE
+  {
+    MOZ_ASSERT(!NS_IsMainThread()); // I/O thread
+
+    uint16_t eventId = mEventId;
+
+    RawDBusConnection* connection = GetDBusConnection();
+    MOZ_ASSERT(connection);
+
+    bool success = connection->SendWithReply(
+      ControlCallback, nullptr, -1,
+      mObjectPath.get(),
+      DBUS_CTL_IFACE, "UpdateNotification",
+      DBUS_TYPE_UINT16, &eventId,
+      DBUS_TYPE_UINT64, &mData,
+      DBUS_TYPE_INVALID);
+    NS_ENSURE_TRUE_VOID(success);
+  }
+
+private:
+  const nsCString mObjectPath;
+  int16_t mEventId;
+  int32_t mData;
+};
+
 void
 BluetoothDBusService::UpdateNotification(ControlEventId aEventId,
                                          uint64_t aData)
 {
   MOZ_ASSERT(NS_IsMainThread());
   NS_ENSURE_TRUE_VOID(this->IsReady());
 
   BluetoothA2dpManager* a2dp = BluetoothA2dpManager::Get();
   NS_ENSURE_TRUE_VOID(a2dp);
   MOZ_ASSERT(a2dp->IsConnected());
   MOZ_ASSERT(a2dp->IsAvrcpConnected());
   MOZ_ASSERT(!sAdapterPath.IsEmpty());
 
   nsAutoString address;
   a2dp->GetAddress(address);
-  nsString objectPath =
-    GetObjectPathFromAddress(sAdapterPath, address);
-  uint16_t eventId = aEventId;
-
-  RawDBusConnection* connection = GetDBusConnection();
-  MOZ_ASSERT(connection);
-
-  bool ret = connection->SendWithReply(
-    ControlCallback, nullptr, -1,
-    NS_ConvertUTF16toUTF8(objectPath).get(),
-    DBUS_CTL_IFACE, "UpdateNotification",
-    DBUS_TYPE_UINT16, &eventId,
-    DBUS_TYPE_UINT64, &aData,
-    DBUS_TYPE_INVALID);
-  NS_ENSURE_TRUE_VOID(ret);
+
+  Task* task = new UpdateNotificationTask(
+    NS_ConvertUTF16toUTF8(GetObjectPathFromAddress(sAdapterPath, address)),
+    aEventId,
+    aData);
+  DispatchToDBusThread(task);
 }
--- a/dom/bluetooth/bluez/linux/BluetoothDBusService.h
+++ b/dom/bluetooth/bluez/linux/BluetoothDBusService.h
@@ -19,16 +19,33 @@ BEGIN_BLUETOOTH_NAMESPACE
 /**
  * BluetoothDBusService is the implementation of BluetoothService for DBus on
  * linux/android/B2G. Function comments are in BluetoothService.h
  */
 
 class BluetoothDBusService : public BluetoothService
 {
 public:
+  /**
+   * For DBus Control method of "UpdateNotification", event id should be
+   * specified as following:
+   * (Please see specification of AVRCP 1.3, Table 5.28 for more details.)
+   */
+  enum ControlEventId {
+    EVENT_PLAYBACK_STATUS_CHANGED            = 0x01,
+    EVENT_TRACK_CHANGED                      = 0x02,
+    EVENT_TRACK_REACHED_END                  = 0x03,
+    EVENT_TRACK_REACHED_START                = 0x04,
+    EVENT_PLAYBACK_POS_CHANGED               = 0x05,
+    EVENT_BATT_STATUS_CHANGED                = 0x06,
+    EVENT_SYSTEM_STATUS_CHANGED              = 0x07,
+    EVENT_PLAYER_APPLICATION_SETTING_CHANGED = 0x08,
+    EVENT_UNKNOWN
+  };
+
   BluetoothDBusService();
   ~BluetoothDBusService();
 
   bool IsReady();
 
   virtual nsresult StartInternal() MOZ_OVERRIDE;
 
   virtual nsresult StopInternal() MOZ_OVERRIDE;
@@ -154,33 +171,16 @@ public:
   virtual nsresult
   SendSinkMessage(const nsAString& aDeviceAddresses,
                   const nsAString& aMessage) MOZ_OVERRIDE;
 
   virtual nsresult
   SendInputMessage(const nsAString& aDeviceAddresses,
                    const nsAString& aMessage) MOZ_OVERRIDE;
 private:
-  /**
-   * For DBus Control method of "UpdateNotification", event id should be
-   * specified as following:
-   * (Please see specification of AVRCP 1.3, Table 5.28 for more details.)
-   */
-  enum ControlEventId {
-    EVENT_PLAYBACK_STATUS_CHANGED            = 0x01,
-    EVENT_TRACK_CHANGED                      = 0x02,
-    EVENT_TRACK_REACHED_END                  = 0x03,
-    EVENT_TRACK_REACHED_START                = 0x04,
-    EVENT_PLAYBACK_POS_CHANGED               = 0x05,
-    EVENT_BATT_STATUS_CHANGED                = 0x06,
-    EVENT_SYSTEM_STATUS_CHANGED              = 0x07,
-    EVENT_PLAYER_APPLICATION_SETTING_CHANGED = 0x08,
-    EVENT_UNKNOWN
-  };
-
   nsresult SendGetPropertyMessage(const nsAString& aPath,
                                   const char* aInterface,
                                   void (*aCB)(DBusMessage *, void *),
                                   BluetoothReplyRunnable* aRunnable);
 
   nsresult SendDiscoveryMessage(const char* aMessageName,
                                 BluetoothReplyRunnable* aRunnable);
 
--- a/dom/encoding/FallbackEncoding.cpp
+++ b/dom/encoding/FallbackEncoding.cpp
@@ -12,17 +12,26 @@
 
 namespace mozilla {
 namespace dom {
 
 static const char* localesFallbacks[][3] = {
 #include "localesfallbacks.properties.h"
 };
 
+static const char* domainsFallbacks[][3] = {
+#include "domainsfallbacks.properties.h"
+};
+
+static const char* nonParticipatingDomains[][3] = {
+#include "nonparticipatingdomains.properties.h"
+};
+
 FallbackEncoding* FallbackEncoding::sInstance = nullptr;
+bool FallbackEncoding::sGuessFallbackFromTopLevelDomain = true;
 
 FallbackEncoding::FallbackEncoding()
 {
   MOZ_COUNT_CTOR(FallbackEncoding);
   MOZ_ASSERT(!FallbackEncoding::sInstance,
              "Singleton already exists.");
 }
 
@@ -116,21 +125,44 @@ FallbackEncoding::Initialize()
              "Initializing pre-existing fallback cache.");
   FallbackEncoding::sInstance = new FallbackEncoding;
   Preferences::RegisterCallback(FallbackEncoding::PrefChanged,
                                 "intl.charset.fallback.override",
                                 nullptr);
   Preferences::RegisterCallback(FallbackEncoding::PrefChanged,
                                 "general.useragent.locale",
                                 nullptr);
+  Preferences::AddBoolVarCache(&sGuessFallbackFromTopLevelDomain,
+                               "intl.charset.fallback.tld");
 }
 
 void
 FallbackEncoding::Shutdown()
 {
   MOZ_ASSERT(FallbackEncoding::sInstance,
              "Releasing non-existent fallback cache.");
   delete FallbackEncoding::sInstance;
   FallbackEncoding::sInstance = nullptr;
 }
 
+bool
+FallbackEncoding::IsParticipatingTopLevelDomain(const nsACString& aTLD)
+{
+  nsAutoCString dummy;
+  return NS_FAILED(nsUConvPropertySearch::SearchPropertyValue(
+      nonParticipatingDomains,
+      ArrayLength(nonParticipatingDomains),
+      aTLD,
+      dummy));
+}
+
+void
+FallbackEncoding::FromTopLevelDomain(const nsACString& aTLD,
+                                     nsACString& aFallback)
+{
+  if (NS_FAILED(nsUConvPropertySearch::SearchPropertyValue(
+      domainsFallbacks, ArrayLength(domainsFallbacks), aTLD, aFallback))) {
+    aFallback.AssignLiteral("windows-1252");
+  }
+}
+
 } // namespace dom
 } // namespace mozilla
--- a/dom/encoding/FallbackEncoding.h
+++ b/dom/encoding/FallbackEncoding.h
@@ -10,23 +10,45 @@
 namespace mozilla {
 namespace dom {
 
 class FallbackEncoding
 {
 public:
 
   /**
+   * Whether FromTopLevelDomain() should be used.
+   */
+  static bool sGuessFallbackFromTopLevelDomain;
+
+  /**
    * Gets the locale-dependent fallback encoding for legacy HTML and plain
    * text content.
    *
    * @param aFallback the outparam for the fallback encoding
    */
   static void FromLocale(nsACString& aFallback);
 
+  /**
+   * Checks if it is appropriate to call FromTopLevelDomain() for a given TLD.
+   *
+   * @param aTLD the top-level domain (in Punycode)
+   * @return true if OK to call FromTopLevelDomain()
+   */
+  static bool IsParticipatingTopLevelDomain(const nsACString& aTLD);
+
+  /**
+   * Gets a top-level domain-depedendent fallback encoding for legacy HTML
+   * and plain text content
+   *
+   * @param aTLD the top-level domain (in Punycode)
+   * @param aFallback the outparam for the fallback encoding
+   */
+  static void FromTopLevelDomain(const nsACString& aTLD, nsACString& aFallback);
+
   // public API ends here!
 
   /**
    * Allocate sInstance used by FromLocale().
    * To be called from nsLayoutStatics only.
    */
   static void Initialize();
 
--- a/dom/encoding/Makefile.in
+++ b/dom/encoding/Makefile.in
@@ -4,8 +4,12 @@
 
 include $(topsrcdir)/config/rules.mk
 
 PROPS2ARRAYS = $(topsrcdir)/intl/locale/src/props2arrays.py
 labelsencodings.properties.h: $(PROPS2ARRAYS) labelsencodings.properties
 	$(PYTHON) $^ $@
 localesfallbacks.properties.h: $(PROPS2ARRAYS) localesfallbacks.properties
 	$(PYTHON) $^ $@
+domainsfallbacks.properties.h: $(PROPS2ARRAYS) domainsfallbacks.properties
+	$(PYTHON) $^ $@
+nonparticipatingdomains.properties.h: $(PROPS2ARRAYS) nonparticipatingdomains.properties
+	$(PYTHON) $^ $@
new file mode 100644
--- /dev/null
+++ b/dom/encoding/domainsfallbacks.properties
@@ -0,0 +1,167 @@
+# This Source Code Form is subject to the terms of the Mozilla Public
+# License, v. 2.0. If a copy of the MPL was not distributed with this
+# file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+# This file contains educated guesses about which top-level domains are
+# likely to host legacy content that assumes a non-windows-1252 encoding.
+# Punycode TLDs are included on the theory that legacy content might appear
+# behind those relatively new TLDs if DNS just points to a legacy server.
+#
+# Encodings for which a confident-enough educated guess is missing are
+# listed in nonparticipatingdomains.properties. Domains that are listed 
+# neither there nor here get windows-1252 as the associated fallback.
+#
+# The list below includes Arabic-script TLDs not on IANA list but on the 
+# ICANN list:
+# http://www.icann.org/en/resources/idn/fast-track/string-evaluation-completion
+# Otherwise, the list includes non-windows-1252-affilited country TLDs from
+# https://data.iana.org/TLD/tlds-alpha-by-domain.txt
+#
+# The guesses are assigned as follows:
+# * If the country has a dominant country-affiliated language and that language
+#   is part of the languages to fallbacks mapping, use the encoding for that
+#   language from that mapping.
+# * Use windows-1256 for countries that have a dominant Arabic-script
+#   language or whose all languages are Arabic-script languages.
+# * Use windows-1251 likewise but for Cyrillic script.
+
+ae=windows-1256
+xn--mgbaam7a8h=windows-1256
+
+af=windows-1256
+
+bg=windows-1251
+
+bh=windows-1256
+
+by=windows-1251
+
+cn=gbk
+xn--fiqs8s=gbk
+# Assume that Traditional Chinese TLD is meant to work if URL input happens to 
+# be in the traditional mode. Expect content to be simplified anyway.
+xn--fiqz9s=gbk
+
+cz=windows-1250
+
+dz=windows-1256
+xn--lgbbat1ad8j=windows-1256
+
+ee=windows-1257
+
+eg=windows-1256
+xn--wgbh1c=windows-1256
+
+gr=ISO-8859-7
+
+hk=Big5-HKSCS
+xn--j6w193g=Big5-HKSCS
+
+hr=windows-1250
+
+hu=ISO-8859-2
+
+iq=windows-1256
+
+ir=windows-1256
+xn--mgba3a4f16a=windows-1256
+
+jo=windows-1256
+xn--mgbayh7gpa=windows-1256
+
+jp=Shift_JIS
+
+kg=windows-1251
+
+kp=EUC-KR
+
+kr=EUC-KR
+xn--3e0b707e=EUC-KR
+
+kw=windows-1256
+
+kz=windows-1251
+xn--80ao21a=windows-1251
+
+lb=windows-1256
+
+lt=windows-1257
+
+lv=windows-1257
+
+ma=windows-1256
+xn--mgbc0a9azcg=windows-1256
+
+mk=windows-1251
+
+mn=windows-1251
+xn--l1acc=windows-1251
+
+mo=Big5
+
+# my
+xn--mgbx4cd0ab=windows-1256
+
+om=windows-1256
+xn--mgb9awbf=windows-1256
+
+#pk
+xn--mgbai9azgqp6j=windows-1256
+
+pl=ISO-8859-2
+
+ps=windows-1256
+xn--ygbi2ammx=windows-1256
+
+qa=windows-1256
+xn--wgbl6a=windows-1256
+
+rs=windows-1251
+xn--90a3ac=windows-1251
+
+ru=windows-1251
+xn--p1ai=windows-1251
+
+sa=windows-1256
+xn--mgberp4a5d4ar=windows-1256
+
+sd=windows-1256
+xn--mgbpl2fh=windows-1256
+
+sg=gbk
+xn--yfro4i67o=gbk
+
+si=ISO-8859-2
+
+sk=windows-1250
+
+su=windows-1251
+
+sy=windows-1256
+xn--mgbtf8fl=windows-1256
+
+th=windows-874
+xn--o3cw4h=windows-874
+
+tj=windows-1251
+
+tn=windows-1256
+xn--pgbs0dh=windows-1256
+
+tr=windows-1254
+
+tw=Big5
+# Assume that the Simplified Chinese TLD is meant to work when URL input
+# happens in the simplified mode. Assume content is tradition anyway.
+xn--kprw13d=Big5
+xn--kpry57d=Big5
+
+ua=windows-1251
+xn--j1amh=windows-1251
+
+uz=windows-1251
+
+vn=windows-1258
+
+ye=windows-1256
+xn--mgb2ddes=windows-1256
--- a/dom/encoding/moz.build
+++ b/dom/encoding/moz.build
@@ -23,11 +23,13 @@ UNIFIED_SOURCES += [
 FAIL_ON_WARNINGS = True
 
 FINAL_LIBRARY = 'gklayout'
 LOCAL_INCLUDES += [
     '/intl/locale/src',
 ]
 
 GENERATED_FILES += [
+    'domainsfallbacks.properties.h',
     'labelsencodings.properties.h',
     'localesfallbacks.properties.h',
+    'nonparticipatingdomains.properties.h',
 ]
new file mode 100644
--- /dev/null
+++ b/dom/encoding/nonparticipatingdomains.properties
@@ -0,0 +1,51 @@
+# 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/.
+
+# Top-level domains listed here do not participate in TLD-based guessing.
+#
+# We should do Web crawls to see if domains listed here can migrate to
+# domainsfallbacks.properties.
+#
+# The value to the right of the = sign is ignored and serves as a placeholder.
+
+# Generic
+com=windows-1252
+net=windows-1252
+org=windows-1252
+
+# No Firefox localization for Azeri
+az=windows-1254
+
+# windows-1251 or windows-1250?
+ba=???
+
+# ISO-8859-7 or windows-1254?
+cy=???
+
+# Is there enough unlabeled windows-1256 content for a windows-1255 to break
+# too much?
+il=windows-1255
+
+# Out-of-country English use
+ly=windows-1256
+
+# Out-of-country English use
+# md=windows-1250
+
+# Out-of-country English use
+# me=windows-1251
+
+# Malaysia has an Arabic-script TLD, official script is latin, possibly Chinese-script publications
+my=???
+
+# No Firefox localization for Urdu; potential for minority-language sites
+# relying on windows-1252 hacks.
+pk=windows-1256
+
+# The Romanian localization says windows-1252, even though the Windows legacy
+# differs.
+ro=windows-1250
+
+tm=windows-1250
+
new file mode 100644
--- /dev/null
+++ b/dom/encoding/test/file_TLD.html
@@ -0,0 +1,7 @@
+<!DOCTYPE html>
+<script>
+function report() {
+  window.parent.postMessage(document.characterSet, "*");
+}
+</script>
+<body onload="report();">
--- a/dom/encoding/test/mochitest.ini
+++ b/dom/encoding/test/mochitest.ini
@@ -2,18 +2,20 @@
 support-files =
   file_utf16_be_bom.css
   file_utf16_be_bom.js
   file_utf16_be_bom.xhtml
   file_utf16_le_bom.css
   file_utf16_le_bom.js
   file_utf16_le_bom.xhtml
   file_utf16_le_nobom.xhtml
+  file_TLD.html
   worker_helper.js
 
 [test_BOMEncoding.js]
 [test_TextDecoder.html]
 [test_TextDecoder.js]
 [test_TextEncoder.html]
 [test_TextEncoder.js]
 [test_stringencoding.html]
 [test_submit_euckr.html]
+[test_TLD.html]
 [test_utf16_files.html]
new file mode 100644
--- /dev/null
+++ b/dom/encoding/test/test_TLD.html
@@ -0,0 +1,57 @@
+<!DOCTYPE HTML>
+<html>
+<!--
+https://bugzilla.mozilla.org/show_bug.cgi?id=910211
+-->
+<head>
+  <meta charset="utf-8">
+  <title>Test for Bug 910211</title>
+  <script type="application/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
+  <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css"/>
+  <script type="application/javascript">
+
+  /** Test for Bug 910211 **/
+
+  SimpleTest.waitForExplicitFinish();
+
+  var tlds = [
+    {'tld': 'tw', 'encoding': 'Big5'},
+    {'tld': 'cn', 'encoding': 'gbk'},
+    {'tld': 'co.jp', 'encoding': 'Shift_JIS'},
+    {'tld': 'fi', 'encoding': 'windows-1252'},
+  ];
+
+  var iframe = null;
+
+  var current = null;
+
+  function runTest() {
+    iframe = document.getElementsByTagName("iframe")[0];
+    window.addEventListener("message", next);
+    next(null);
+  }
+
+  function next(event) {
+    if (event) {
+      is(event.data, current['encoding'], "Got bad encoding for " + current["tld"]);
+    }
+    current = tlds.shift();
+    if (!current) {
+      SimpleTest.finish();
+      return;
+    }
+    iframe.src = "http://example." + current["tld"] + "/tests/dom/encoding/test/file_TLD.html";
+  }
+
+  </script>
+</head>
+<body onload="runTest();">
+<a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=910211">Mozilla Bug 910211</a>
+<p id="display"></p>
+<div id="content" style="display: none">
+<iframe></iframe>
+</div>
+<pre id="test">
+</pre>
+</body>
+</html>
rename from dom/nfc/MozNdefRecord.cpp
rename to dom/nfc/MozNDEFRecord.cpp
--- a/dom/nfc/MozNdefRecord.cpp
+++ b/dom/nfc/MozNDEFRecord.cpp
@@ -1,116 +1,116 @@
 /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
 /* vim:set ts=2 sw=2 sts=2 et cindent: */
 /* 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/. */
 
 /* Copyright © 2013 Deutsche Telekom, Inc. */
 
-#include "MozNdefRecord.h"
-#include "mozilla/dom/MozNdefRecordBinding.h"
+#include "MozNDEFRecord.h"
+#include "mozilla/dom/MozNDEFRecordBinding.h"
 #include "mozilla/HoldDropJSObjects.h"
 #include "nsContentUtils.h"
 
 
 namespace mozilla {
 namespace dom {
 
 
-NS_IMPL_CYCLE_COLLECTION_CLASS(MozNdefRecord)
+NS_IMPL_CYCLE_COLLECTION_CLASS(MozNDEFRecord)
 
-NS_IMPL_CYCLE_COLLECTION_UNLINK_BEGIN(MozNdefRecord)
+NS_IMPL_CYCLE_COLLECTION_UNLINK_BEGIN(MozNDEFRecord)
   NS_IMPL_CYCLE_COLLECTION_UNLINK(mWindow)
   NS_IMPL_CYCLE_COLLECTION_UNLINK_PRESERVED_WRAPPER
 NS_IMPL_CYCLE_COLLECTION_UNLINK_END
 
-NS_IMPL_CYCLE_COLLECTION_TRAVERSE_BEGIN(MozNdefRecord)
+NS_IMPL_CYCLE_COLLECTION_TRAVERSE_BEGIN(MozNDEFRecord)
   NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mWindow)
   NS_IMPL_CYCLE_COLLECTION_TRAVERSE_SCRIPT_OBJECTS
 NS_IMPL_CYCLE_COLLECTION_TRAVERSE_END
 
-NS_IMPL_CYCLE_COLLECTION_TRACE_BEGIN(MozNdefRecord)
+NS_IMPL_CYCLE_COLLECTION_TRACE_BEGIN(MozNDEFRecord)
   NS_IMPL_CYCLE_COLLECTION_TRACE_JS_MEMBER_CALLBACK(mType)
   NS_IMPL_CYCLE_COLLECTION_TRACE_JS_MEMBER_CALLBACK(mId)
   NS_IMPL_CYCLE_COLLECTION_TRACE_JS_MEMBER_CALLBACK(mPayload)
   NS_IMPL_CYCLE_COLLECTION_TRACE_PRESERVED_WRAPPER
 NS_IMPL_CYCLE_COLLECTION_TRACE_END
 
-NS_IMPL_CYCLE_COLLECTING_ADDREF(MozNdefRecord)
-NS_IMPL_CYCLE_COLLECTING_RELEASE(MozNdefRecord)
-NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION(MozNdefRecord)
+NS_IMPL_CYCLE_COLLECTING_ADDREF(MozNDEFRecord)
+NS_IMPL_CYCLE_COLLECTING_RELEASE(MozNDEFRecord)
+NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION(MozNDEFRecord)
   NS_WRAPPERCACHE_INTERFACE_MAP_ENTRY
   NS_INTERFACE_MAP_ENTRY(nsISupports)
 NS_INTERFACE_MAP_END
 
 void
-MozNdefRecord::HoldData()
+MozNDEFRecord::HoldData()
 {
   mozilla::HoldJSObjects(this);
 }
 
 void
-MozNdefRecord::DropData()
+MozNDEFRecord::DropData()
 {
   if (mType) {
     mType = nullptr;
   }
   if (mId) {
     mId = nullptr;
   }
   if (mPayload) {
     mPayload = nullptr;
   }
   mozilla::DropJSObjects(this);
 }
 
 /* static */
-already_AddRefed<MozNdefRecord>
-MozNdefRecord::Constructor(const GlobalObject& aGlobal,
+already_AddRefed<MozNDEFRecord>
+MozNDEFRecord::Constructor(const GlobalObject& aGlobal,
                            uint8_t aTnf, const Uint8Array& aType,
                            const Uint8Array& aId, const Uint8Array& aPayload,
                            ErrorResult& aRv)
 {
   nsCOMPtr<nsPIDOMWindow> win = do_QueryInterface(aGlobal.GetAsSupports());
   if (!win) {
     aRv.Throw(NS_ERROR_FAILURE);
     return nullptr;
   }
 
-  nsRefPtr<MozNdefRecord> ndefrecord = new MozNdefRecord(aGlobal.GetContext(),
+  nsRefPtr<MozNDEFRecord> ndefrecord = new MozNDEFRecord(aGlobal.GetContext(),
                                                          win, aTnf, aType, aId,
                                                          aPayload);
   if (!ndefrecord) {
     aRv.Throw(NS_ERROR_FAILURE);
     return nullptr;
   }
   return ndefrecord.forget();
 }
 
-MozNdefRecord::MozNdefRecord(JSContext* aCx, nsPIDOMWindow* aWindow,
+MozNDEFRecord::MozNDEFRecord(JSContext* aCx, nsPIDOMWindow* aWindow,
                              uint8_t aTnf, const Uint8Array& aType,
                              const Uint8Array& aId, const Uint8Array& aPayload)
   : mTnf(aTnf)
 {
   mWindow = aWindow; // For GetParentObject()
 
   mType = Uint8Array::Create(aCx, this, aType.Length(), aType.Data());
   mId = Uint8Array::Create(aCx, this, aId.Length(), aId.Data());
   mPayload = Uint8Array::Create(aCx, this, aPayload.Length(), aPayload.Data());
 
   SetIsDOMBinding();
   HoldData();
 }
 
-MozNdefRecord::~MozNdefRecord()
+MozNDEFRecord::~MozNDEFRecord()
 {
   DropData();
 }
 
 JSObject*
-MozNdefRecord::WrapObject(JSContext* aCx, JS::Handle<JSObject*> aScope)
+MozNDEFRecord::WrapObject(JSContext* aCx, JS::Handle<JSObject*> aScope)
 {
-  return MozNdefRecordBinding::Wrap(aCx, aScope, this);
+  return MozNDEFRecordBinding::Wrap(aCx, aScope, this);
 }
 
 } // namespace dom
 } // namespace mozilla
rename from dom/nfc/MozNdefRecord.h
rename to dom/nfc/MozNDEFRecord.h
--- a/dom/nfc/MozNdefRecord.h
+++ b/dom/nfc/MozNDEFRecord.h
@@ -1,18 +1,18 @@
 /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
 /* vim:set ts=2 sw=2 sts=2 et cindent: */
 /* 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/. */
 
 /* Copyright © 2013 Deutsche Telekom, Inc. */
 
-#ifndef mozilla_dom_MozNdefRecord_h__
-#define mozilla_dom_MozNdefRecord_h__
+#ifndef mozilla_dom_MozNDEFRecord_h__
+#define mozilla_dom_MozNDEFRecord_h__
 
 #include "mozilla/Attributes.h"
 #include "mozilla/ErrorResult.h"
 #include "nsCycleCollectionParticipant.h"
 #include "nsWrapperCache.h"
 #include "jsapi.h"
 
 #include "nsIDocument.h"
@@ -21,40 +21,40 @@
 #include "jsfriendapi.h"
 #include "js/GCAPI.h"
 
 struct JSContext;
 
 namespace mozilla {
 namespace dom {
 
-class MozNdefRecord MOZ_FINAL : public nsISupports,
+class MozNDEFRecord MOZ_FINAL : public nsISupports,
                                 public nsWrapperCache
 {
 public:
   NS_DECL_CYCLE_COLLECTING_ISUPPORTS
-  NS_DECL_CYCLE_COLLECTION_SCRIPT_HOLDER_CLASS(MozNdefRecord)
+  NS_DECL_CYCLE_COLLECTION_SCRIPT_HOLDER_CLASS(MozNDEFRecord)
 
 public:
 
-  MozNdefRecord(JSContext* aCx, nsPIDOMWindow* aWindow, uint8_t aTnf,
+  MozNDEFRecord(JSContext* aCx, nsPIDOMWindow* aWindow, uint8_t aTnf,
                 const Uint8Array& aType, const Uint8Array& aId,
                 const Uint8Array& aPlayload);
 
-  ~MozNdefRecord();
+  ~MozNDEFRecord();
 
   nsIDOMWindow* GetParentObject() const
   {
     return mWindow;
   }
 
   virtual JSObject* WrapObject(JSContext* aCx,
                                JS::Handle<JSObject*> aScope) MOZ_OVERRIDE;
 
-  static already_AddRefed<MozNdefRecord>
+  static already_AddRefed<MozNDEFRecord>
                   Constructor(const GlobalObject& aGlobal, uint8_t aTnf,
                               const Uint8Array& aType, const Uint8Array& aId,
                               const Uint8Array& aPayload, ErrorResult& aRv);
 
   uint8_t Tnf() const
   {
     return mTnf;
   }
@@ -85,23 +85,23 @@ public:
   }
   JSObject* GetPayloadObject() const
   {
     JS::ExposeObjectToActiveJS(mPayload);
     return mPayload;
   }
 
 private:
-  MozNdefRecord() MOZ_DELETE;
+  MozNDEFRecord() MOZ_DELETE;
   nsRefPtr<nsPIDOMWindow> mWindow;
   void HoldData();
   void DropData();
 
   uint8_t mTnf;
   JS::Heap<JSObject*> mType;
   JS::Heap<JSObject*> mId;
   JS::Heap<JSObject*> mPayload;
 };
 
 } // namespace dom
 } // namespace mozilla
 
-#endif // mozilla_dom_MozNdefRecord_h__
+#endif // mozilla_dom_MozNDEFRecord_h__
--- a/dom/nfc/moz.build
+++ b/dom/nfc/moz.build
@@ -2,20 +2,20 @@
 # 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/.
 #
 # Copyright © 2013 Deutsche Telekom, Inc.
 
 if CONFIG['MOZ_NFC']:
     EXPORTS.mozilla.dom += [
-        'MozNdefRecord.h',
+        'MozNDEFRecord.h',
     ]
     SOURCES += [
-        'MozNdefRecord.cpp',
+        'MozNDEFRecord.cpp',
     ]
     EXTRA_COMPONENTS += [
       'nsNfc.js',
       'nsNfc.manifest',
     ]
 
 FAIL_ON_WARNINGS = True
 
--- a/dom/settings/SettingsDB.jsm
+++ b/dom/settings/SettingsDB.jsm
@@ -14,17 +14,17 @@ Cu.import("resource://gre/modules/Object
 this.EXPORTED_SYMBOLS = ["SettingsDB", "SETTINGSDB_NAME", "SETTINGSSTORE_NAME"];
 
 const DEBUG = false;
 function debug(s) {
   if (DEBUG) dump("-*- SettingsDB: " + s + "\n");
 }
 
 this.SETTINGSDB_NAME = "settings";
-this.SETTINGSDB_VERSION = 2;
+this.SETTINGSDB_VERSION = 3;
 this.SETTINGSSTORE_NAME = "settings";
 
 Cu.import("resource://gre/modules/IndexedDBHelper.jsm");
 Cu.import("resource://gre/modules/FileUtils.jsm");
 Cu.import("resource://gre/modules/NetUtil.jsm");
 
 this.SettingsDB = function SettingsDB() {}
 
--- a/dom/system/gonk/NfcContentHelper.js
+++ b/dom/system/gonk/NfcContentHelper.js
@@ -87,17 +87,17 @@ NfcContentHelper.prototype = {
 
   _requestMap: null,
   peerEventsCallbackMap: null,
 
   /* TODO: Bug 815526: This is a limitation when a DOMString is used in sequences of Moz DOM Objects.
    *       Strings such as 'type', 'id' 'payload' will not be acccessible to NfcWorker.
    *       Therefore this function exists till the bug is addressed.
    */
-  encodeNdefRecords: function encodeNdefRecords(records) {
+  encodeNDEFRecords: function encodeNDEFRecords(records) {
     let encodedRecords = [];
     for (let i = 0; i < records.length; i++) {
       let record = records[i];
       encodedRecords.push({
         tnf: record.tnf,
         type: record.type,
         id: record.id,
         payload: record.payload,
@@ -156,17 +156,17 @@ NfcContentHelper.prototype = {
     if (window == null) {
       throw Components.Exception("Can't get window object",
                                   Cr.NS_ERROR_UNEXPECTED);
     }
     let request = Services.DOMRequest.createRequest(window);
     let requestId = btoa(this.getRequestId(request));
     this._requestMap[requestId] = window;
 
-    let encodedRecords = this.encodeNdefRecords(records);
+    let encodedRecords = this.encodeNDEFRecords(records);
     cpmm.sendAsyncMessage("NFC:WriteNDEF", {
       requestId: requestId,
       sessionToken: sessionToken,
       records: encodedRecords
     });
     return request;
   },
 
@@ -385,17 +385,17 @@ NfcContentHelper.prototype = {
     let requestId = atob(message.requestId);
 
     if (message.status !== NFC.GECKO_NFC_ERROR_SUCCESS) {
       this.fireRequestError(requestId, message.status);
     } else {
       let ndefMsg = [];
       for (let i = 0; i < records.length; i++) {
         let record = records[i];
-        ndefMsg.push(new requester.MozNdefRecord(record.tnf,
+        ndefMsg.push(new requester.MozNDEFRecord(record.tnf,
                                                  record.type,
                                                  record.id,
                                                  record.payload));
       }
       this.fireRequestSuccess(requestId, ndefMsg);
     }
   },
 
--- a/dom/tests/mochitest/general/test_interfaces.html
+++ b/dom/tests/mochitest/general/test_interfaces.html
@@ -638,17 +638,17 @@ var interfaceNamesInGlobalScope =
     {name: "MozMobileConnectionArray", b2g: true, pref: "dom.mobileconnection.enabled"},
 // IMPORTANT: Do not change this list without review from a DOM peer!
     "MozMobileMessageManager",
 // IMPORTANT: Do not change this list without review from a DOM peer!
     "MozMobileMessageThread",
 // IMPORTANT: Do not change this list without review from a DOM peer!
     "MozNamedAttrMap",
 // IMPORTANT: Do not change this list without review from a DOM peer!
-    {name: "MozNdefRecord", b2g: true},
+    {name: "MozNDEFRecord", b2g: true},
 // IMPORTANT: Do not change this list without review from a DOM peer!
     {name: "MozNFCPeer", b2g: true},
 // IMPORTANT: Do not change this list without review from a DOM peer!
     {name: "MozNFCTag", b2g: true},
 // IMPORTANT: Do not change this list without review from a DOM peer!
     {name: "MozOtaStatusEvent", b2g: true, pref: "dom.mobileconnection.enabled"},
 // IMPORTANT: Do not change this list without review from a DOM peer!
     "MozPowerManager",
--- a/dom/webidl/AnalyserNode.webidl
+++ b/dom/webidl/AnalyserNode.webidl
@@ -5,17 +5,16 @@
  *
  * The origin of this IDL file is
  * https://dvcs.w3.org/hg/audio/raw-file/tip/webaudio/specification.html
  *
  * Copyright © 2012 W3C® (MIT, ERCIM, Keio), All Rights Reserved. W3C
  * liability, trademark and document use rules apply.
  */
 
-[PrefControlled]
 interface AnalyserNode : AudioNode {
 
     // Real-time frequency-domain data 
     void getFloatFrequencyData(Float32Array array);
     void getByteFrequencyData(Uint8Array array);
 
     // Real-time waveform data 
     void getByteTimeDomainData(Uint8Array array);
--- a/dom/webidl/AudioBuffer.webidl
+++ b/dom/webidl/AudioBuffer.webidl
@@ -5,17 +5,16 @@
  *
  * The origin of this IDL file is
  * https://dvcs.w3.org/hg/audio/raw-file/tip/webaudio/specification.html
  *
  * Copyright © 2012 W3C® (MIT, ERCIM, Keio), All Rights Reserved. W3C
  * liability, trademark and document use rules apply.
  */
 
-[PrefControlled]
 interface AudioBuffer {
 
     readonly attribute float sampleRate;
     readonly attribute long length;
 
     // in seconds 
     readonly attribute double duration;
 
--- a/dom/webidl/AudioBufferSourceNode.webidl
+++ b/dom/webidl/AudioBufferSourceNode.webidl
@@ -5,17 +5,16 @@
  *
  * The origin of this IDL file is
  * https://dvcs.w3.org/hg/audio/raw-file/tip/webaudio/specification.html
  *
  * Copyright © 2012 W3C® (MIT, ERCIM, Keio), All Rights Reserved. W3C
  * liability, trademark and document use rules apply.
  */
 
-[PrefControlled]
 interface AudioBufferSourceNode : AudioNode {
 
     attribute AudioBuffer? buffer;
 
     readonly attribute AudioParam playbackRate;
 
     attribute boolean loop;
     attribute double loopStart;
@@ -29,17 +28,16 @@ interface AudioBufferSourceNode : AudioN
 
     attribute EventHandler onended;
 };
 
 /*
  * The origin of this IDL file is
  * https://dvcs.w3.org/hg/audio/raw-file/tip/webaudio/specification.html#AlternateNames
  */
-[PrefControlled]
 partial interface AudioBufferSourceNode {
     // Same as start()
     [Throws,Pref="media.webaudio.legacy.AudioBufferSourceNode"]
     void noteOn(double when);
     [Throws,Pref="media.webaudio.legacy.AudioBufferSourceNode"]
     void noteGrainOn(double when, double grainOffset, double grainDuration);
     
     [Throws,Pref="media.webaudio.legacy.AudioBufferSourceNode"]
--- a/dom/webidl/AudioContext.webidl
+++ b/dom/webidl/AudioContext.webidl
@@ -8,17 +8,17 @@
  *
  * Copyright © 2012 W3C® (MIT, ERCIM, Keio), All Rights Reserved. W3C
  * liability, trademark and document use rules apply.
  */
 
 callback DecodeSuccessCallback = void (AudioBuffer decodedData);
 callback DecodeErrorCallback = void ();
 
-[Constructor, PrefControlled]
+[Constructor]
 interface AudioContext : EventTarget {
 
     readonly attribute AudioDestinationNode destination;
     readonly attribute float sampleRate;
     readonly attribute double currentTime;
     readonly attribute AudioListener listener;
 
     [NewObject, Throws]
@@ -73,17 +73,16 @@ interface AudioContext : EventTarget {
     PeriodicWave createPeriodicWave(Float32Array real, Float32Array imag);
 
 };
 
 /*
  * The origin of this IDL file is
  * https://dvcs.w3.org/hg/audio/raw-file/tip/webaudio/specification.html#AlternateNames
  */
-[PrefControlled]
 partial interface AudioContext {
     [NewObject, Throws]
     AudioBuffer? createBuffer(ArrayBuffer buffer, boolean mixToMono);
 
     // Same as createGain()
     [NewObject,Pref="media.webaudio.legacy.AudioContext"]
     GainNode createGainNode();
 
--- a/dom/webidl/AudioDestinationNode.webidl
+++ b/dom/webidl/AudioDestinationNode.webidl
@@ -5,15 +5,14 @@
  *
  * The origin of this IDL file is
  * https://dvcs.w3.org/hg/audio/raw-file/tip/webaudio/specification.html
  *
  * Copyright © 2012 W3C® (MIT, ERCIM, Keio), All Rights Reserved. W3C
  * liability, trademark and document use rules apply.
  */
 
-[PrefControlled]
 interface AudioDestinationNode : AudioNode {
 
     readonly attribute unsigned long maxChannelCount;
 
 };
 
--- a/dom/webidl/AudioListener.webidl
+++ b/dom/webidl/AudioListener.webidl
@@ -5,17 +5,16 @@
  *
  * The origin of this IDL file is
  * https://dvcs.w3.org/hg/audio/raw-file/tip/webaudio/specification.html
  *
  * Copyright © 2012 W3C® (MIT, ERCIM, Keio), All Rights Reserved. W3C
  * liability, trademark and document use rules apply.
  */
 
-[PrefControlled]
 interface AudioListener {
 
     // same as OpenAL (default 1) 
     attribute double dopplerFactor;
 
     // in meters / second (default 343.3) 
     attribute double speedOfSound;
 
--- a/dom/webidl/AudioNode.webidl
+++ b/dom/webidl/AudioNode.webidl
@@ -16,17 +16,16 @@ enum ChannelCountMode {
     "explicit"
 };
 
 enum ChannelInterpretation {
     "speakers",
     "discrete"
 };
 
-[PrefControlled]
 interface AudioNode : EventTarget {
 
     [Throws]
     void connect(AudioNode destination, optional unsigned long output = 0, optional unsigned long input = 0);
     [Throws]
     void connect(AudioParam destination, optional unsigned long output = 0);
     [Throws]
     void disconnect(optional unsigned long output = 0);
--- a/dom/webidl/AudioParam.webidl
+++ b/dom/webidl/AudioParam.webidl
@@ -5,17 +5,16 @@
  *
  * The origin of this IDL file is
  * https://dvcs.w3.org/hg/audio/raw-file/tip/webaudio/specification.html
  *
  * Copyright © 2012 W3C® (MIT, ERCIM, Keio), All Rights Reserved. W3C
  * liability, trademark and document use rules apply.
  */
 
-[PrefControlled]
 interface AudioParam {
 
     attribute float value;
     readonly attribute float defaultValue;
 
     // Parameter automation. 
     [Throws]
     void setValueAtTime(float value, double startTime);
@@ -38,15 +37,14 @@ interface AudioParam {
     void cancelScheduledValues(double startTime);
 
 };
 
 /*
  * The origin of this IDL file is
  * https://dvcs.w3.org/hg/audio/raw-file/tip/webaudio/specification.html#AlternateNames
  */
-[PrefControlled]
 partial interface AudioParam {
     // Same as setTargetAtTime()
     [Throws,Pref="media.webaudio.legacy.AudioParam"]
     void setTargetValueAtTime(float target, double startTime, double timeConstant);
 };
 
--- a/dom/webidl/AudioProcessingEvent.webidl
+++ b/dom/webidl/AudioProcessingEvent.webidl
@@ -5,17 +5,16 @@
  *
  * The origin of this IDL file is
  * https://dvcs.w3.org/hg/audio/raw-file/tip/webaudio/specification.html
  *
  * Copyright © 2012 W3C® (MIT, ERCIM, Keio), All Rights Reserved. W3C
  * liability, trademark and document use rules apply.
  */
 
-[PrefControlled]
 interface AudioProcessingEvent : Event {
 
     readonly attribute double playbackTime;
     readonly attribute AudioBuffer inputBuffer;
     readonly attribute AudioBuffer outputBuffer;
 
 };
 
--- a/dom/webidl/BiquadFilterNode.webidl
+++ b/dom/webidl/BiquadFilterNode.webidl
@@ -19,17 +19,16 @@ enum BiquadFilterType {
   "bandpass",
   "lowshelf",
   "highshelf",
   "peaking",
   "notch",
   "allpass"
 };
 
-[PrefControlled]
 interface BiquadFilterNode : AudioNode {
 
     attribute BiquadFilterType type;
     readonly attribute AudioParam frequency; // in Hertz
     readonly attribute AudioParam detune; // in Cents
     readonly attribute AudioParam Q; // Quality factor
     readonly attribute AudioParam gain; // in Decibels
 
@@ -38,17 +37,16 @@ interface BiquadFilterNode : AudioNode {
                               Float32Array phaseResponse);
 
 };
 
 /*
  * The origin of this IDL file is
  * https://dvcs.w3.org/hg/audio/raw-file/tip/webaudio/specification.html#AlternateNames
  */
-[PrefControlled]
 partial interface BiquadFilterNode {
     [Pref="media.webaudio.legacy.BiquadFilterNode"]
     const unsigned short LOWPASS = 0;
     [Pref="media.webaudio.legacy.BiquadFilterNode"]
     const unsigned short HIGHPASS = 1;
     [Pref="media.webaudio.legacy.BiquadFilterNode"]
     const unsigned short BANDPASS = 2;
     [Pref="media.webaudio.legacy.BiquadFilterNode"]
--- a/dom/webidl/ChannelMergerNode.webidl
+++ b/dom/webidl/ChannelMergerNode.webidl
@@ -5,13 +5,12 @@
  *
  * The origin of this IDL file is
  * https://dvcs.w3.org/hg/audio/raw-file/tip/webaudio/specification.html
  *
  * Copyright © 2012 W3C® (MIT, ERCIM, Keio), All Rights Reserved. W3C
  * liability, trademark and document use rules apply.
  */
 
-[PrefControlled]
 interface ChannelMergerNode : AudioNode {
 
 };
 
--- a/dom/webidl/ChannelSplitterNode.webidl
+++ b/dom/webidl/ChannelSplitterNode.webidl
@@ -5,13 +5,12 @@
  *
  * The origin of this IDL file is
  * https://dvcs.w3.org/hg/audio/raw-file/tip/webaudio/specification.html
  *
  * Copyright © 2012 W3C® (MIT, ERCIM, Keio), All Rights Reserved. W3C
  * liability, trademark and document use rules apply.
  */
 
-[PrefControlled]
 interface ChannelSplitterNode : AudioNode {
 
 };
 
--- a/dom/webidl/ConvolverNode.webidl
+++ b/dom/webidl/ConvolverNode.webidl
@@ -5,17 +5,16 @@
  *
  * The origin of this IDL file is
  * https://dvcs.w3.org/hg/audio/raw-file/tip/webaudio/specification.html
  *
  * Copyright © 2012 W3C® (MIT, ERCIM, Keio), All Rights Reserved. W3C
  * liability, trademark and document use rules apply.
  */
 
-[PrefControlled]
 interface ConvolverNode : AudioNode {
 
       [SetterThrows]
       attribute AudioBuffer? buffer;
       attribute boolean normalize;
 
 };
 
--- a/dom/webidl/DelayNode.webidl
+++ b/dom/webidl/DelayNode.webidl
@@ -5,15 +5,14 @@
  *
  * The origin of this IDL file is
  * https://dvcs.w3.org/hg/audio/raw-file/tip/webaudio/specification.html
  *
  * Copyright © 2012 W3C® (MIT, ERCIM, Keio), All Rights Reserved. W3C
  * liability, trademark and document use rules apply.
  */
 
-[PrefControlled]
 interface DelayNode : AudioNode {
 
     readonly attribute AudioParam delayTime;
 
 };
 
--- a/dom/webidl/DynamicsCompressorNode.webidl
+++ b/dom/webidl/DynamicsCompressorNode.webidl
@@ -5,17 +5,16 @@
  *
  * The origin of this IDL file is
  * https://dvcs.w3.org/hg/audio/raw-file/tip/webaudio/specification.html
  *
  * Copyright © 2012 W3C® (MIT, ERCIM, Keio), All Rights Reserved. W3C
  * liability, trademark and document use rules apply.
  */
 
-[PrefControlled]
 interface DynamicsCompressorNode : AudioNode {
 
     readonly attribute AudioParam threshold; // in Decibels
     readonly attribute AudioParam knee; // in Decibels
     readonly attribute AudioParam ratio; // unit-less
     readonly attribute AudioParam reduction; // in Decibels
     readonly attribute AudioParam attack; // in Seconds
     readonly attribute AudioParam release; // in Seconds
--- a/dom/webidl/GainNode.webidl
+++ b/dom/webidl/GainNode.webidl
@@ -5,15 +5,14 @@
  *
  * The origin of this IDL file is
  * https://dvcs.w3.org/hg/audio/raw-file/tip/webaudio/specification.html
  *
  * Copyright © 2012 W3C® (MIT, ERCIM, Keio), All Rights Reserved. W3C
  * liability, trademark and document use rules apply.
  */
 
-[PrefControlled]
 interface GainNode : AudioNode {
 
     readonly attribute AudioParam gain;
 
 };
 
--- a/dom/webidl/MediaElementAudioSourceNode.webidl
+++ b/dom/webidl/MediaElementAudioSourceNode.webidl
@@ -5,13 +5,12 @@
  *
  * The origin of this IDL file is
  * https://dvcs.w3.org/hg/audio/raw-file/tip/webaudio/specification.html
  *
  * Copyright © 2012 W3C® (MIT, ERCIM, Keio), All Rights Reserved. W3C
  * liability, trademark and document use rules apply.
  */
 
-[PrefControlled]
 interface MediaElementAudioSourceNode : AudioNode {
 
 };
 
--- a/dom/webidl/MediaStreamAudioDestinationNode.webidl
+++ b/dom/webidl/MediaStreamAudioDestinationNode.webidl
@@ -5,14 +5,13 @@
  *
  * The origin of this IDL file is
  * https://dvcs.w3.org/hg/audio/raw-file/tip/webaudio/specification.html
  *
  * Copyright © 2012 W3C® (MIT, ERCIM, Keio), All Rights Reserved. W3C
  * liability, trademark and document use rules apply.
  */
 
-[PrefControlled]
 interface MediaStreamAudioDestinationNode : AudioNode {
 
     readonly attribute MediaStream stream;
 
-};
\ No newline at end of file
+};
rename from dom/webidl/MozNdefRecord.webidl
rename to dom/webidl/MozNDEFRecord.webidl
--- a/dom/webidl/MozNdefRecord.webidl
+++ b/dom/webidl/MozNDEFRecord.webidl
@@ -1,17 +1,17 @@
 /* -*- Mode: IDL; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 /* Copyright © 2013 Deutsche Telekom, Inc. */
 
 [Constructor(octet tnf, Uint8Array type, Uint8Array id, Uint8Array payload)]
-interface MozNdefRecord
+interface MozNDEFRecord
 {
   /**
    * Type Name Field (3-bits) - Specifies the NDEF record type in general.
    *   tnf_empty: 0x00
    *   tnf_well_known: 0x01
    *   tnf_mime_media: 0x02
    *   tnf_absolute_uri: 0x03
    *   tnf_external type: 0x04
--- a/dom/webidl/MozNFCPeer.webidl
+++ b/dom/webidl/MozNFCPeer.webidl
@@ -5,17 +5,17 @@
  * Part of this IDL file is from:
  * http://w3c.github.io/nfc/proposals/common/nfc.html#idl-def-NFCPeer
  *
  * Copyright © 2013 Deutsche Telekom, Inc.
  */
 
 [JSImplementation="@mozilla.org/nfc/NFCPeer;1"]
 interface MozNFCPeer {
-  DOMRequest sendNDEF(sequence<MozNdefRecord> records);
+  DOMRequest sendNDEF(sequence<MozNDEFRecord> records);
   DOMRequest sendFile(Blob blob);
 };
 
 // Mozilla Only
 partial interface MozNFCPeer {
   [ChromeOnly]
   attribute DOMString session;
   [ChromeOnly]
--- a/dom/webidl/MozNFCTag.webidl
+++ b/dom/webidl/MozNFCTag.webidl
@@ -22,17 +22,17 @@ enum NFCTechType {
   "P2P",
   "UNKNOWN_TECH"
 };
 
 [JSImplementation="@mozilla.org/nfc/NFCTag;1"]
 interface MozNFCTag {
   DOMRequest getDetailsNDEF();
   DOMRequest readNDEF();
-  DOMRequest writeNDEF(sequence<MozNdefRecord> records);
+  DOMRequest writeNDEF(sequence<MozNDEFRecord> records);
   DOMRequest makeReadOnlyNDEF();
 
   DOMRequest connect(NFCTechType techType);
   DOMRequest close();
 };
 
 // Mozilla Only
 partial interface MozNFCTag {
--- a/dom/webidl/OfflineAudioCompletionEvent.webidl
+++ b/dom/webidl/OfflineAudioCompletionEvent.webidl
@@ -5,15 +5,14 @@
  *
  * The origin of this IDL file is
  * https://dvcs.w3.org/hg/audio/raw-file/tip/webaudio/specification.html
  *
  * Copyright © 2012 W3C® (MIT, ERCIM, Keio), All Rights Reserved. W3C
  * liability, trademark and document use rules apply.
  */
 
-[PrefControlled]
 interface OfflineAudioCompletionEvent : Event {
 
     readonly attribute AudioBuffer renderedBuffer;
 
 };
 
--- a/dom/webidl/OfflineAudioContext.webidl
+++ b/dom/webidl/OfflineAudioContext.webidl
@@ -7,18 +7,17 @@
  * https://dvcs.w3.org/hg/audio/raw-file/tip/webaudio/specification.html
  *
  * Copyright © 2012 W3C® (MIT, ERCIM, Keio), All Rights Reserved. W3C
  * liability, trademark and document use rules apply.
  */
 
 callback OfflineRenderSuccessCallback = void (AudioBuffer renderedData);
 
-[Constructor(unsigned long numberOfChannels, unsigned long length, float sampleRate),
- PrefControlled]
+[Constructor(unsigned long numberOfChannels, unsigned long length, float sampleRate)]
 interface OfflineAudioContext : AudioContext {
 
     [Throws]
     void startRendering();
 
     attribute EventHandler oncomplete;
 
 };
--- a/dom/webidl/OscillatorNode.webidl
+++ b/dom/webidl/OscillatorNode.webidl
@@ -16,17 +16,16 @@ enum OscillatorType {
 
   "sine",
   "square",
   "sawtooth",
   "triangle",
   "custom"
 };
 
-[PrefControlled]
 interface OscillatorNode : AudioNode {
 
     [SetterThrows]
     attribute OscillatorType type;
 
     readonly attribute AudioParam frequency; // in Hertz
     readonly attribute AudioParam detune; // in Cents
 
--- a/dom/webidl/PannerNode.webidl
+++ b/dom/webidl/PannerNode.webidl
@@ -22,17 +22,16 @@ enum DistanceModelType {
   // Hack: Use numbers to support alternate enum values
   "0", "1", "2",
 
   "linear",
   "inverse",
   "exponential"
 };
 
-[PrefControlled]
 interface PannerNode : AudioNode {
 
     // Default for stereo is HRTF 
     attribute PanningModelType panningModel;
 
     // Uses a 3D cartesian coordinate system 
     void setPosition(double x, double y, double z);
     void setOrientation(double x, double y, double z);
@@ -50,17 +49,16 @@ interface PannerNode : AudioNode {
     attribute double coneOuterGain;
 
 };
 
 /*
  * The origin of this IDL file is
  * https://dvcs.w3.org/hg/audio/raw-file/tip/webaudio/specification.html#AlternateNames
  */
-[PrefControlled]
 partial interface PannerNode {
     [Pref="media.webaudio.legacy.PannerNode"]
     const unsigned short EQUALPOWER = 0;
     [Pref="media.webaudio.legacy.PannerNode"]
     const unsigned short HRTF = 1;
 
     [Pref="media.webaudio.legacy.PannerNode"]
     const unsigned short LINEAR_DISTANCE = 0;
--- a/dom/webidl/PeriodicWave.webidl
+++ b/dom/webidl/PeriodicWave.webidl
@@ -5,13 +5,12 @@
  *
  * The origin of this IDL file is
  * https://dvcs.w3.org/hg/audio/raw-file/tip/webaudio/specification.html
  *
  * Copyright © 2012 W3C® (MIT, ERCIM, Keio), All Rights Reserved. W3C
  * liability, trademark and document use rules apply.
  */
 
-[PrefControlled]
 interface PeriodicWave {
 
 };
 
--- a/dom/webidl/ScriptProcessorNode.webidl
+++ b/dom/webidl/ScriptProcessorNode.webidl
@@ -5,17 +5,16 @@
  *
  * The origin of this IDL file is
  * https://dvcs.w3.org/hg/audio/raw-file/tip/webaudio/specification.html
  *
  * Copyright © 2012 W3C® (MIT, ERCIM, Keio), All Rights Reserved. W3C
  * liability, trademark and document use rules apply.
  */
 
-[PrefControlled]
 interface ScriptProcessorNode : AudioNode {
 
     attribute EventHandler onaudioprocess;
 
     readonly attribute long bufferSize;
 
 };
 
--- a/dom/webidl/WaveShaperNode.webidl
+++ b/dom/webidl/WaveShaperNode.webidl
@@ -11,16 +11,15 @@
  */
 
 enum OverSampleType {
   "none",
   "2x",
   "4x"
 };
 
-[PrefControlled]
 interface WaveShaperNode : AudioNode {
 
       attribute Float32Array? curve;
       attribute OverSampleType oversample;
 
 };
 
--- a/dom/webidl/moz.build
+++ b/dom/webidl/moz.build
@@ -524,17 +524,17 @@ if CONFIG['MOZ_B2G_RIL']:
         'MozIcc.webidl',
         'MozMobileConnectionArray.webidl',
         'MozVoicemail.webidl',
         'MozVoicemailEvent.webidl',
     ]
 
 if CONFIG['MOZ_NFC']:
     WEBIDL_FILES += [
-         'MozNdefRecord.webidl',
+         'MozNDEFRecord.webidl',
          'MozNfc.webidl',
          'MozNFCPeer.webidl',
          'MozNFCTag.webidl',
     ]
 
 if CONFIG['MOZ_WIDGET_TOOLKIT'] == 'gonk':
     WEBIDL_FILES += [
         'MozSpeakerManager.webidl',
--- a/dom/workers/RuntimeService.cpp
+++ b/dom/workers/RuntimeService.cpp
@@ -270,16 +270,40 @@ GetWorkerPref(const nsACString& aPref,
     else {
       result = aDefault;
     }
   }
 
   return result;
 }
 
+// This function creates a key for a SharedWorker composed by "name|scriptSpec".
+// If the name contains a '|', this will be replaced by '||'.
+void
+GenerateSharedWorkerKey(const nsACString& aScriptSpec, const nsACString& aName,
+                        nsCString& aKey)
+{
+  aKey.Truncate();
+  aKey.SetCapacity(aScriptSpec.Length() + aName.Length() + 1);
+
+  nsACString::const_iterator start, end;
+  aName.BeginReading(start);
+  aName.EndReading(end);
+  for (; start != end; ++start) {
+    if (*start == '|') {
+      aKey.AppendASCII("||");
+    } else {
+      aKey.Append(*start);
+    }
+  }
+
+  aKey.Append('|');
+  aKey.Append(aScriptSpec);
+}
+
 void
 LoadJSContextOptions(const char* aPrefName, void* /* aClosure */)
 {
   AssertIsOnMainThread();
 
   RuntimeService* rts = RuntimeService::GetService();
   if (!rts && !gRuntimeServiceDuringInit) {
     // May be shutting down, just bail.
@@ -1252,17 +1276,17 @@ RuntimeService::RegisterWorker(JSContext
     if (mShuttingDown) {
       JS_ReportError(aCx, "Cannot create worker during shutdown!");
       return false;
     }
   }
 
   bool isSharedWorker = aWorkerPrivate->IsSharedWorker();
 
-  const nsString& sharedWorkerName = aWorkerPrivate->SharedWorkerName();
+  const nsCString& sharedWorkerName = aWorkerPrivate->SharedWorkerName();
   nsCString sharedWorkerScriptSpec;
 
   if (isSharedWorker) {
     AssertIsOnMainThread();
 
     nsCOMPtr<nsIURI> scriptURI = aWorkerPrivate->GetResolvedScriptURI();
     NS_ASSERTION(scriptURI, "Null script URI!");
 
@@ -1301,23 +1325,24 @@ RuntimeService::RegisterWorker(JSContext
     else if (parent) {
       domainInfo->mChildWorkerCount++;
     }
     else {
       domainInfo->mActiveWorkers.AppendElement(aWorkerPrivate);
     }
 
     if (isSharedWorker) {
-      MOZ_ASSERT(!domainInfo->mSharedWorkerInfos.Get(sharedWorkerScriptSpec));
+      nsAutoCString key;
+      GenerateSharedWorkerKey(sharedWorkerScriptSpec, sharedWorkerName, key);
+      MOZ_ASSERT(!domainInfo->mSharedWorkerInfos.Get(key));
 
       SharedWorkerInfo* sharedWorkerInfo =
         new SharedWorkerInfo(aWorkerPrivate, sharedWorkerScriptSpec,
                              sharedWorkerName);
-      domainInfo->mSharedWorkerInfos.Put(sharedWorkerScriptSpec,
-                                         sharedWorkerInfo);
+      domainInfo->mSharedWorkerInfos.Put(key, sharedWorkerInfo);
     }
   }
 
   // From here on out we must call UnregisterWorker if something fails!
   if (parent) {
     if (!parent->AddChildWorker(aCx, aWorkerPrivate)) {
       UnregisterWorker(aCx, aWorkerPrivate);
       return false;
@@ -1397,18 +1422,20 @@ RuntimeService::UnregisterWorker(JSConte
     }
 
     if (aWorkerPrivate->IsSharedWorker()) {
       MatchSharedWorkerInfo match(aWorkerPrivate);
       domainInfo->mSharedWorkerInfos.EnumerateRead(FindSharedWorkerInfo,
                                                    &match);
 
       if (match.mSharedWorkerInfo) {
-        domainInfo->mSharedWorkerInfos.Remove(
-          match.mSharedWorkerInfo->mScriptSpec);
+        nsAutoCString key;
+        GenerateSharedWorkerKey(match.mSharedWorkerInfo->mScriptSpec,
+                                match.mSharedWorkerInfo->mName, key);
+        domainInfo->mSharedWorkerInfos.Remove(key);
       }
     }
 
     // See if there's a queued worker we can schedule.
     if (domainInfo->ActiveWorkerCount() < gMaxWorkersPerDomain &&
         !domainInfo->mQueuedWorkers.IsEmpty()) {
       queuedWorker = domainInfo->mQueuedWorkers[0];
       domainInfo->mQueuedWorkers.RemoveElementAt(0);
@@ -2046,17 +2073,17 @@ RuntimeService::ResumeWorkersForWindow(n
       }
     }
   }
 }
 
 nsresult
 RuntimeService::CreateSharedWorker(const GlobalObject& aGlobal,
                                    const nsAString& aScriptURL,
-                                   const nsAString& aName,
+                                   const nsACString& aName,
                                    SharedWorker** aSharedWorker)
 {
   AssertIsOnMainThread();
 
   nsCOMPtr<nsPIDOMWindow> window = do_QueryInterface(aGlobal.GetAsSupports());
   MOZ_ASSERT(window);
 
   JSContext* cx = aGlobal.GetContext();
@@ -2074,19 +2101,21 @@ RuntimeService::CreateSharedWorker(const
 
   nsRefPtr<WorkerPrivate> workerPrivate;
   {
     MutexAutoLock lock(mMutex);
 
     WorkerDomainInfo* domainInfo;
     SharedWorkerInfo* sharedWorkerInfo;
 
+    nsAutoCString key;
+    GenerateSharedWorkerKey(scriptSpec, aName, key);
+
     if (mDomainMap.Get(loadInfo.mDomain, &domainInfo) &&
-        domainInfo->mSharedWorkerInfos.Get(scriptSpec, &sharedWorkerInfo) &&
-        sharedWorkerInfo->mName == aName) {
+        domainInfo->mSharedWorkerInfos.Get(key, &sharedWorkerInfo)) {
       workerPrivate = sharedWorkerInfo->mWorkerPrivate;
     }
   }
 
   bool created = false;
 
   if (!workerPrivate) {
     ErrorResult rv;
@@ -2139,18 +2168,20 @@ RuntimeService::ForgetSharedWorker(Worke
 
   WorkerDomainInfo* domainInfo;
   if (mDomainMap.Get(aWorkerPrivate->Domain(), &domainInfo)) {
     MatchSharedWorkerInfo match(aWorkerPrivate);
     domainInfo->mSharedWorkerInfos.EnumerateRead(FindSharedWorkerInfo,
                                                  &match);
 
     if (match.mSharedWorkerInfo) {
-      domainInfo->mSharedWorkerInfos.Remove(
-        match.mSharedWorkerInfo->mScriptSpec);
+      nsAutoCString key;
+      GenerateSharedWorkerKey(match.mSharedWorkerInfo->mScriptSpec,
+                              match.mSharedWorkerInfo->mName, key);
+      domainInfo->mSharedWorkerInfos.Remove(key);
     }
   }
 }
 
 void
 RuntimeService::NoteIdleThread(WorkerThread* aThread)
 {
   AssertIsOnMainThread();
--- a/dom/workers/RuntimeService.h
+++ b/dom/workers/RuntimeService.h
@@ -32,21 +32,21 @@ class RuntimeService MOZ_FINAL : public 
 public:
   class WorkerThread;
 
 private:
   struct SharedWorkerInfo
   {
     WorkerPrivate* mWorkerPrivate;
     nsCString mScriptSpec;
-    nsString mName;
+    nsCString mName;
 
     SharedWorkerInfo(WorkerPrivate* aWorkerPrivate,
                      const nsACString& aScriptSpec,
-                     const nsAString& aName)
+                     const nsACString& aName)
     : mWorkerPrivate(aWorkerPrivate), mScriptSpec(aScriptSpec), mName(aName)
     { }
   };
 
   struct WorkerDomainInfo
   {
     nsCString mDomain;
     nsTArray<WorkerPrivate*> mActiveWorkers;
@@ -139,17 +139,17 @@ public:
   SuspendWorkersForWindow(nsPIDOMWindow* aWindow);
 
   void
   ResumeWorkersForWindow(nsPIDOMWindow* aWindow);
 
   nsresult
   CreateSharedWorker(const GlobalObject& aGlobal,
                      const nsAString& aScriptURL,
-                     const nsAString& aName,
+                     const nsACString& aName,
                      SharedWorker** aSharedWorker);
 
   void
   ForgetSharedWorker(WorkerPrivate* aWorkerPrivate);
 
   const NavigatorProperties&
   GetNavigatorProperties() const
   {
--- a/dom/workers/SharedWorker.cpp
+++ b/dom/workers/SharedWorker.cpp
@@ -67,19 +67,19 @@ SharedWorker::Constructor(const GlobalOb
   AssertIsOnMainThread();
 
   RuntimeService* rts = RuntimeService::GetOrCreateService();
   if (!rts) {
     aRv = NS_ERROR_NOT_AVAILABLE;
     return nullptr;
   }
 
-  nsString name;
+  nsCString name;
   if (aName.WasPassed()) {
-    name = aName.Value();
+    name = NS_ConvertUTF16toUTF8(aName.Value());
   }
 
   nsRefPtr<SharedWorker> sharedWorker;
   nsresult rv = rts->CreateSharedWorker(aGlobal, aScriptURL, name,
                                         getter_AddRefs(sharedWorker));
   if (NS_FAILED(rv)) {
     aRv = rv;
     return nullptr;
--- a/dom/workers/WorkerPrivate.cpp
+++ b/dom/workers/WorkerPrivate.cpp
@@ -2087,23 +2087,23 @@ WorkerPrivate::SyncLoopInfo::SyncLoopInf
 // templates.
 template <class Derived>
 typename WorkerPrivateParent<Derived>::cycleCollection
   WorkerPrivateParent<Derived>::_cycleCollectorGlobal =
     WorkerPrivateParent<Derived>::cycleCollection();
 
 template <class Derived>
 WorkerPrivateParent<Derived>::WorkerPrivateParent(
-                                             JSContext* aCx,
-                                             WorkerPrivate* aParent,
-                                             const nsAString& aScriptURL,
-                                             bool aIsChromeWorker,
-                                             WorkerType aWorkerType,
-                                             const nsAString& aSharedWorkerName,
-                                             LoadInfo& aLoadInfo)
+                                           JSContext* aCx,
+                                           WorkerPrivate* aParent,
+                                           const nsAString& aScriptURL,
+                                           bool aIsChromeWorker,
+                                           WorkerType aWorkerType,
+                                           const nsACString& aSharedWorkerName,
+                                           LoadInfo& aLoadInfo)
 : mMutex("WorkerPrivateParent Mutex"),
   mCondVar(mMutex, "WorkerPrivateParent CondVar"),
   mMemoryReportCondVar(mMutex, "WorkerPrivateParent Memory Report CondVar"),
   mParent(aParent), mScriptURL(aScriptURL),
   mSharedWorkerName(aSharedWorkerName), mBusyCount(0), mMessagePortSerial(0),
   mParentStatus(Pending), mParentSuspended(false),
   mIsChromeWorker(aIsChromeWorker), mMainThreadObjectsForgotten(false),
   mWorkerType(aWorkerType)
@@ -3518,17 +3518,17 @@ WorkerPrivateParent<Derived>::AssertInne
                "Inner window no longer correct!");
 }
 
 #endif
 WorkerPrivate::WorkerPrivate(JSContext* aCx,
                              WorkerPrivate* aParent,
                              const nsAString& aScriptURL,
                              bool aIsChromeWorker, WorkerType aWorkerType,
-                             const nsAString& aSharedWorkerName,
+                             const nsACString& aSharedWorkerName,
                              LoadInfo& aLoadInfo)
 : WorkerPrivateParent<WorkerPrivate>(aCx, aParent, aScriptURL,
                                      aIsChromeWorker, aWorkerType,
                                      aSharedWorkerName, aLoadInfo),
   mJSContext(nullptr), mErrorHandlerRecursionCount(0), mNextTimeoutId(1),
   mStatus(Pending), mSuspended(false), mTimerRunning(false),
   mRunningExpiredTimeouts(false), mCloseHandlerStarted(false),
   mCloseHandlerFinished(false), mMemoryReporterRunning(false),
@@ -3558,18 +3558,19 @@ WorkerPrivate::~WorkerPrivate()
 }
 
 // static
 already_AddRefed<WorkerPrivate>
 WorkerPrivate::Constructor(const GlobalObject& aGlobal,
                            const nsAString& aScriptURL,
                            ErrorResult& aRv)
 {
-  return WorkerPrivate::Constructor(aGlobal, aScriptURL, false, WorkerTypeDedicated,
-                                    EmptyString(), nullptr, aRv);
+  return WorkerPrivate::Constructor(aGlobal, aScriptURL, false,
+                                    WorkerTypeDedicated, EmptyCString(),
+                                    nullptr, aRv);
 }
 
 // static
 bool
 WorkerPrivate::WorkerAvailable(JSContext* /* unused */, JSObject* /* unused */)
 {
   // If we're already on a worker workers are clearly enabled.
   if (!NS_IsMainThread()) {
@@ -3586,35 +3587,37 @@ WorkerPrivate::WorkerAvailable(JSContext
 }
 
 // static
 already_AddRefed<ChromeWorkerPrivate>
 ChromeWorkerPrivate::Constructor(const GlobalObject& aGlobal,
                                  const nsAString& aScriptURL,
                                  ErrorResult& aRv)
 {
-  return WorkerPrivate::Constructor(aGlobal, aScriptURL, true, WorkerTypeDedicated,
-                                    EmptyString(), nullptr, aRv).downcast<ChromeWorkerPrivate>();
+  return WorkerPrivate::Constructor(aGlobal, aScriptURL, true,
+                                    WorkerTypeDedicated, EmptyCString(),
+                                    nullptr, aRv)
+                                    .downcast<ChromeWorkerPrivate>();
 }
 
 // static
 bool
 ChromeWorkerPrivate::WorkerAvailable(JSContext* /* unused */, JSObject* /* unused */)
 {
   // Chrome is always allowed to use workers, and content is never allowed to
   // use ChromeWorker, so all we have to check is the caller.
   return nsContentUtils::ThreadsafeIsCallerChrome();
 }
 
 // static
 already_AddRefed<WorkerPrivate>
 WorkerPrivate::Constructor(const GlobalObject& aGlobal,
                            const nsAString& aScriptURL,
                            bool aIsChromeWorker, WorkerType aWorkerType,
-                           const nsAString& aSharedWorkerName,
+                           const nsACString& aSharedWorkerName,
                            LoadInfo* aLoadInfo, ErrorResult& aRv)
 {
   WorkerPrivate* parent = NS_IsMainThread() ?
                           nullptr :
                           GetCurrentThreadWorkerPrivate();
   if (parent) {
     parent->AssertIsOnWorkerThread();
   } else {
--- a/dom/workers/WorkerPrivate.h
+++ b/dom/workers/WorkerPrivate.h
@@ -209,17 +209,17 @@ protected:
 
   // Protected by mMutex.
   nsRefPtr<EventTarget> mEventTarget;
   nsTArray<nsRefPtr<WorkerRunnable>> mPreStartRunnables;
 
 private:
   WorkerPrivate* mParent;
   nsString mScriptURL;
-  nsString mSharedWorkerName;
+  nsCString mSharedWorkerName;
   LocationInfo mLocationInfo;
   // The lifetime of these objects within LoadInfo is managed explicitly;
   // they do not need to be cycle collected.
   LoadInfo mLoadInfo;
 
   // Only used for top level workers.
   nsTArray<nsCOMPtr<nsIRunnable>> mQueuedRunnables;
   nsRevocableEventPtr<SynchronizeAndResumeRunnable> mSynchronizeRunnable;
@@ -246,17 +246,18 @@ protected:
   // The worker is owned by its thread, which is represented here.  This is set
   // in Construct() and emptied by WorkerFinishedRunnable, and conditionally
   // traversed by the cycle collector if the busy count is zero.
   nsRefPtr<WorkerPrivate> mSelfRef;
 
   WorkerPrivateParent(JSContext* aCx, WorkerPrivate* aParent,
                       const nsAString& aScriptURL, bool aIsChromeWorker,
                       WorkerType aWorkerType,
-                      const nsAString& aSharedWorkerName, LoadInfo& aLoadInfo);
+                      const nsACString& aSharedWorkerName,
+                      LoadInfo& aLoadInfo);
 
   ~WorkerPrivateParent();
 
 private:
   Derived*
   ParentAsWorkerPrivate() const
   {
     return static_cast<Derived*>(const_cast<WorkerPrivateParent*>(this));
@@ -643,17 +644,17 @@ public:
   }
 
   bool
   IsSharedWorker() const
   {
     return mWorkerType == WorkerTypeShared;
   }
 
-  const nsString&
+  const nsCString&
   SharedWorkerName() const
   {
     return mSharedWorkerName;
   }
 
   uint64_t
   NextMessagePortSerial()
   {
@@ -783,17 +784,17 @@ protected:
 public:
   static already_AddRefed<WorkerPrivate>
   Constructor(const GlobalObject& aGlobal, const nsAString& aScriptURL,
               ErrorResult& aRv);
 
   static already_AddRefed<WorkerPrivate>
   Constructor(const GlobalObject& aGlobal, const nsAString& aScriptURL,
               bool aIsChromeWorker, WorkerType aWorkerType,
-              const nsAString& aSharedWorkerName,
+              const nsACString& aSharedWorkerName,
               LoadInfo* aLoadInfo, ErrorResult& aRv);
 
   static bool
   WorkerAvailable(JSContext* /* unused */, JSObject* /* unused */);
 
   static nsresult
   GetLoadInfo(JSContext* aCx, nsPIDOMWindow* aWindow, WorkerPrivate* aParent,
               const nsAString& aScriptURL, bool aIsChromeWorker,
@@ -1037,17 +1038,17 @@ public:
   ;
 #else
   { }
 #endif
 
 private:
   WorkerPrivate(JSContext* aCx, WorkerPrivate* aParent,
                 const nsAString& aScriptURL, bool aIsChromeWorker,
-                WorkerType aWorkerType, const nsAString& aSharedWorkerName,
+                WorkerType aWorkerType, const nsACString& aSharedWorkerName,
                 LoadInfo& aLoadInfo);
 
   void
   ClearMainEventQueue();
 
   bool
   MayContinueRunning()
   {
--- a/dom/workers/WorkerScope.cpp
+++ b/dom/workers/WorkerScope.cpp
@@ -306,17 +306,17 @@ DedicatedWorkerGlobalScope::PostMessage(
                                         const Optional<Sequence<JS::Value>>& aTransferable,
                                         ErrorResult& aRv)
 {
   mWorkerPrivate->AssertIsOnWorkerThread();
   mWorkerPrivate->PostMessageToParent(aCx, aMessage, aTransferable, aRv);
 }
 
 SharedWorkerGlobalScope::SharedWorkerGlobalScope(WorkerPrivate* aWorkerPrivate,
-                                                 const nsString& aName)
+                                                 const nsCString& aName)
 : WorkerGlobalScope(aWorkerPrivate), mName(aName)
 {
 }
 
 /* static */ bool
 SharedWorkerGlobalScope::Visible(JSContext* aCx, JSObject* aObj)
 {
   SharedWorkerGlobalScope* self = nullptr;
--- a/dom/workers/WorkerScope.h
+++ b/dom/workers/WorkerScope.h
@@ -133,31 +133,32 @@ public:
               const Optional<Sequence<JS::Value>>& aTransferable,
               ErrorResult& aRv);
 
   IMPL_EVENT_HANDLER(message)
 };
 
 class SharedWorkerGlobalScope MOZ_FINAL : public WorkerGlobalScope
 {
-  const nsString mName;
+  const nsCString mName;
 
   ~SharedWorkerGlobalScope() { }
 
 public:
-  SharedWorkerGlobalScope(WorkerPrivate* aWorkerPrivate, const nsString& aName);
+  SharedWorkerGlobalScope(WorkerPrivate* aWorkerPrivate,
+                          const nsCString& aName);
 
   static bool
   Visible(JSContext* aCx, JSObject* aObj);
 
   virtual JSObject*
   WrapGlobalObject(JSContext* aCx) MOZ_OVERRIDE;
 
   void GetName(DOMString& aName) const {
-    aName.AsAString() = mName;
+    aName.AsAString() = NS_ConvertUTF8toUTF16(mName);
   }
 
   IMPL_EVENT_HANDLER(connect)
 };
 
 JSObject*
 CreateGlobalScope(JSContext* aCx);
 
--- a/dom/workers/test/mochitest.ini
+++ b/dom/workers/test/mochitest.ini
@@ -66,16 +66,17 @@ support-files =
   subdir/relativeLoad_sub_worker.js
   subdir/relativeLoad_sub_worker2.js
   subdir/relativeLoad_sub_import.js
 
 [test_404.html]
 [test_atob.html]
 [test_blobConstructor.html]
 [test_blobWorkers.html]
+[test_bug949946.html]
 [test_chromeWorker.html]
 [test_clearTimeouts.html]
 [test_close.html]
 [test_closeOnGC.html]
 [test_console.html]
 [test_consoleReplaceable.html]
 [test_contentWorker.html]
 [test_csp.html]
new file mode 100644
--- /dev/null
+++ b/dom/workers/test/test_bug949946.html
@@ -0,0 +1,31 @@
+<!--
+  Any copyright is dedicated to the Public Domain.
+  http://creativecommons.org/publicdomain/zero/1.0/
+-->
+<!DOCTYPE HTML>
+<html>
+<head>
+  <title>Test for bug 949946</title>
+  <script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
+  <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
+</head>
+<body>
+<p id="display"></p>
+<div id="content" style="display: none"></div>
+<pre id="test"></pre>
+<script class="testbody" type="text/javascript">
+
+  SpecialPowers.pushPrefEnv({ set: [["dom.workers.sharedWorkers.enabled", true]] }, function() {
+    new SharedWorker('sharedWorker_sharedWorker.js');
+    new SharedWorker('sharedWorker_sharedWorker.js', ':');
+    new SharedWorker('sharedWorker_sharedWorker.js', '|||');
+    ok(true, "3 SharedWorkers created!");
+    SimpleTest.finish();
+  });
+
+  SimpleTest.waitForExplicitFinish();
+
+</script>
+</pre>
+</body>
+</html>
--- a/gfx/layers/client/ContentClient.cpp
+++ b/gfx/layers/client/ContentClient.cpp
@@ -288,19 +288,21 @@ ContentClientRemoteBuffer::Updated(const
                                    const nsIntRegion& aVisibleRegion,
                                    bool aDidSelfCopy)
 {
   nsIntRegion updatedRegion = GetUpdatedRegion(aRegionToDraw,
                                                aVisibleRegion,
                                                aDidSelfCopy);
 
   MOZ_ASSERT(mTextureClient);
-  mForwarder->UseTexture(this, mTextureClient);
   if (mTextureClientOnWhite) {
-    mForwarder->UseTexture(this, mTextureClientOnWhite);
+    mForwarder->UseComponentAlphaTextures(this, mTextureClient,
+                                          mTextureClientOnWhite);
+  } else {
+    mForwarder->UseTexture(this, mTextureClient);
   }
   mForwarder->UpdateTextureRegion(this,
                                   ThebesBufferData(BufferRect(),
                                                    BufferRotation()),
                                   updatedRegion);
 }
 
 void
--- a/gfx/layers/client/ContentClient.h
+++ b/gfx/layers/client/ContentClient.h
@@ -104,16 +104,17 @@ public:
   // Called as part of the layers transation reply. Conveys data about our
   // buffer(s) from the compositor. If appropriate we should swap references
   // to our buffers.
   virtual void SwapBuffers(const nsIntRegion& aFrontUpdatedRegion) {}
 
   // call before and after painting into this content client
   virtual void BeginPaint() {}
   virtual void EndPaint() {}
+
 };
 
 /**
  * A ContentClient for use with OMTC.
  */
 class ContentClientRemote : public ContentClient
 {
 public:
--- a/gfx/layers/composite/CompositableHost.cpp
+++ b/gfx/layers/composite/CompositableHost.cpp
@@ -44,16 +44,27 @@ CompositableHost::UseTextureHost(Texture
   if (!aTexture) {
     return;
   }
   aTexture->SetCompositor(GetCompositor());
   aTexture->SetCompositableBackendSpecificData(GetCompositableBackendSpecificData());
 }
 
 void
+CompositableHost::UseComponentAlphaTextures(TextureHost* aTextureOnBlack,
+                                            TextureHost* aTextureOnWhite)
+{
+  MOZ_ASSERT(aTextureOnBlack && aTextureOnWhite);
+  aTextureOnBlack->SetCompositor(GetCompositor());
+  aTextureOnBlack->SetCompositableBackendSpecificData(GetCompositableBackendSpecificData());
+  aTextureOnWhite->SetCompositor(GetCompositor());
+  aTextureOnWhite->SetCompositableBackendSpecificData(GetCompositableBackendSpecificData());
+}
+
+void
 CompositableHost::SetCompositor(Compositor* aCompositor)
 {
   mCompositor = aCompositor;
 }
 
 bool
 CompositableHost::Update(const SurfaceDescriptor& aImage,
                          SurfaceDescriptor* aResult)
--- a/gfx/layers/composite/CompositableHost.h
+++ b/gfx/layers/composite/CompositableHost.h
@@ -283,16 +283,18 @@ public:
   static void DumpTextureHost(FILE* aFile, TextureHost* aTexture);
 
   virtual TemporaryRef<gfx::DataSourceSurface> GetAsSurface() { return nullptr; }
 #endif
 
   virtual void PrintInfo(nsACString& aTo, const char* aPrefix) { }
 
   virtual void UseTextureHost(TextureHost* aTexture);
+  virtual void UseComponentAlphaTextures(TextureHost* aTextureOnBlack,
+                                         TextureHost* aTextureOnWhite);
 
 protected:
   TextureInfo mTextureInfo;
   Compositor* mCompositor;
   Layer* mLayer;
   RefPtr<CompositableBackendSpecificData> mBackendData;
   bool mAttached;
   bool mKeepAttached;
--- a/gfx/layers/composite/ContentHost.cpp
+++ b/gfx/layers/composite/ContentHost.cpp
@@ -215,23 +215,28 @@ ContentHostBase::Composite(EffectChain& 
   diagnostics |= iterOnWhite ? DIAGNOSTIC_COMPONENT_ALPHA : 0;
   GetCompositor()->DrawDiagnostics(diagnostics, *aVisibleRegion, aClipRect, aTransform);
 }
 
 
 void
 ContentHostBase::UseTextureHost(TextureHost* aTexture)
 {
-  if (aTexture->GetFlags() & TEXTURE_ON_WHITE) {
-    mTextureHostOnWhite = aTexture;
-    mTextureHostOnWhite->SetCompositor(GetCompositor());
-  } else {
-    mTextureHost = aTexture;
-    mTextureHost->SetCompositor(GetCompositor());
-  }
+  mTextureHost = aTexture;
+  mTextureHostOnWhite = nullptr;
+  mTextureHost->SetCompositor(GetCompositor());
+}
+
+void
+ContentHostBase::UseComponentAlphaTextures(TextureHost* aTextureOnBlack,
+                                           TextureHost* aTextureOnWhite)
+{
+  CompositableHost::UseComponentAlphaTextures(aTextureOnBlack, aTextureOnWhite);
+  mTextureHost = aTextureOnBlack;
+  mTextureHostOnWhite = aTextureOnWhite;
 }
 
 void
 ContentHostBase::SetCompositor(Compositor* aCompositor)
 {
   CompositableHost::SetCompositor(aCompositor);
   if (mTextureHost) {
     mTextureHost->SetCompositor(aCompositor);
--- a/gfx/layers/composite/ContentHost.h
+++ b/gfx/layers/composite/ContentHost.h
@@ -111,16 +111,18 @@ public:
                     bool aDumpHtml=false) MOZ_OVERRIDE;
 #endif
 
   virtual void PrintInfo(nsACString& aTo, const char* aPrefix) MOZ_OVERRIDE;
 
   virtual TextureHost* GetAsTextureHost() MOZ_OVERRIDE;
 
   virtual void UseTextureHost(TextureHost* aTexture) MOZ_OVERRIDE;
+  virtual void UseComponentAlphaTextures(TextureHost* aTextureOnBlack,
+                                         TextureHost* aTextureOnWhite) MOZ_OVERRIDE;
 
   virtual void SetPaintWillResample(bool aResample) { mPaintWillResample = aResample; }
 
 protected:
   virtual nsIntPoint GetOriginOffset()
   {
     return mBufferRect.TopLeft() - mBufferRotation;
   }
--- a/gfx/layers/ipc/CompositableForwarder.h
+++ b/gfx/layers/ipc/CompositableForwarder.h
@@ -185,16 +185,19 @@ public:
   }
 
   /**
    * Tell the CompositableHost on the compositor side what texture to use for
    * the next composition.
    */
   virtual void UseTexture(CompositableClient* aCompositable,
                           TextureClient* aClient) = 0;
+  virtual void UseComponentAlphaTextures(CompositableClient* aCompositable,
+                                         TextureClient* aClientOnBlack,
+                                         TextureClient* aClientOnWhite) = 0;
 
   /**
    * Tell the compositor side that the shared data has been modified so that
    * it can react accordingly (upload textures, etc.).
    */
   virtual void UpdatedTexture(CompositableClient* aCompositable,
                               TextureClient* aTexture,
                               nsIntRegion* aRegion) = 0;
--- a/gfx/layers/ipc/CompositableTransactionParent.cpp
+++ b/gfx/layers/ipc/CompositableTransactionParent.cpp
@@ -228,16 +228,30 @@ CompositableParentManager::ReceiveCompos
       MOZ_ASSERT(tex.get());
       compositable->UseTextureHost(tex);
 
       if (IsAsync()) {
         ScheduleComposition(op);
       }
       break;
     }
+    case CompositableOperation::TOpUseComponentAlphaTextures: {
+      const OpUseComponentAlphaTextures& op = aEdit.get_OpUseComponentAlphaTextures();
+      CompositableHost* compositable = AsCompositable(op);
+      RefPtr<TextureHost> texOnBlack = TextureHost::AsTextureHost(op.textureOnBlackParent());
+      RefPtr<TextureHost> texOnWhite = TextureHost::AsTextureHost(op.textureOnWhiteParent());
+
+      MOZ_ASSERT(texOnBlack && texOnWhite);
+      compositable->UseComponentAlphaTextures(texOnBlack, texOnWhite);
+
+      if (IsAsync()) {
+        ScheduleComposition(op);
+      }
+      break;
+    }
     case CompositableOperation::TOpUpdateTexture: {
       const OpUpdateTexture& op = aEdit.get_OpUpdateTexture();
       RefPtr<TextureHost> texture = TextureHost::AsTextureHost(op.textureParent());
       MOZ_ASSERT(texture);
 
       texture->Updated(op.region().type() == MaybeRegion::TnsIntRegion
                        ? &op.region().get_nsIntRegion()
                        : nullptr); // no region means invalidate the entire surface
--- a/gfx/layers/ipc/ImageBridgeChild.cpp
+++ b/gfx/layers/ipc/ImageBridgeChild.cpp
@@ -110,16 +110,26 @@ void
 ImageBridgeChild::UseTexture(CompositableClient* aCompositable,
                              TextureClient* aTexture)
 {
   mTxn->AddNoSwapEdit(OpUseTexture(nullptr, aCompositable->GetIPDLActor(),
                                    nullptr, aTexture->GetIPDLActor()));
 }
 
 void
+ImageBridgeChild::UseComponentAlphaTextures(CompositableClient* aCompositable,
+                                            TextureClient* aTextureOnBlack,
+                                            TextureClient* aTextureOnWhite)
+{
+  mTxn->AddNoSwapEdit(OpUseComponentAlphaTextures(nullptr, aCompositable->GetIPDLActor(),
+                                                  nullptr, aTextureOnBlack->GetIPDLActor(),
+                                                  nullptr, aTextureOnWhite->GetIPDLActor()));
+}
+
+void
 ImageBridgeChild::UpdatedTexture(CompositableClient* aCompositable,
                                  TextureClient* aTexture,
                                  nsIntRegion* aRegion)
 {
   MaybeRegion region = aRegion ? MaybeRegion(*aRegion)
                                : MaybeRegion(null_t());
   mTxn->AddNoSwapEdit(OpUpdateTexture(nullptr, aCompositable->GetIPDLActor(),
                                       nullptr, aTexture->GetIPDLActor(),
--- a/gfx/layers/ipc/ImageBridgeChild.h
+++ b/gfx/layers/ipc/ImageBridgeChild.h
@@ -266,16 +266,19 @@ public:
                               TextureClient* aTexture,
                               nsIntRegion* aRegion) MOZ_OVERRIDE;
 
   /**
    * See CompositableForwarder::UseTexture
    */
   virtual void UseTexture(CompositableClient* aCompositable,
                           TextureClient* aClient) MOZ_OVERRIDE;
+  virtual void UseComponentAlphaTextures(CompositableClient* aCompositable,
+                                         TextureClient* aClientOnBlack,
+                                         TextureClient* aClientOnWhite) MOZ_OVERRIDE;
 
   virtual void RemoveTexture(TextureClient* aTexture) MOZ_OVERRIDE;
 
   virtual void PaintedTiledLayerBuffer(CompositableClient* aCompositable,
                                        const SurfaceDescriptorTiles& aTileLayerDescriptor) MOZ_OVERRIDE
   {
     NS_RUNTIMEABORT("should not be called");
   }
--- a/gfx/layers/ipc/LayersMessages.ipdlh
+++ b/gfx/layers/ipc/LayersMessages.ipdlh
@@ -307,16 +307,22 @@ struct OpUpdatePictureRect {
  * Tells the compositor-side which texture to use (for example, as front buffer
  * if there is several textures for double buffering)
  */
 struct OpUseTexture {
   PCompositable compositable;
   PTexture texture;
 };
 
+struct OpUseComponentAlphaTextures {
+  PCompositable compositable;
+  PTexture textureOnBlack;
+  PTexture textureOnWhite;
+};
+
 union MaybeRegion {
   nsIntRegion;
   null_t;
 };
 
 struct OpUpdateTexture {
   PCompositable compositable;
   PTexture texture;
@@ -333,16 +339,17 @@ union CompositableOperation {
   OpPaintTexture;
   OpPaintTextureRegion;
   OpPaintTextureIncremental;
 
   OpPaintTiledLayerBuffer;
 
   OpUpdateTexture;
   OpUseTexture;
+  OpUseComponentAlphaTextures;
 };
 
 // A unit of a changeset; a set of these comprise a changeset
 union Edit {
   OpCreateThebesLayer;
   OpCreateContainerLayer;
   OpCreateImageLayer;
   OpCreateColorLayer;
--- a/gfx/layers/ipc/ShadowLayers.cpp
+++ b/gfx/layers/ipc/ShadowLayers.cpp
@@ -431,16 +431,26 @@ void
 ShadowLayerForwarder::UseTexture(CompositableClient* aCompositable,
                                  TextureClient* aTexture)
 {
   mTxn->AddEdit(OpUseTexture(nullptr, aCompositable->GetIPDLActor(),
                              nullptr, aTexture->GetIPDLActor()));
 }
 
 void
+ShadowLayerForwarder::UseComponentAlphaTextures(CompositableClient* aCompositable,
+                                                TextureClient* aTextureOnBlack,
+                                                TextureClient* aTextureOnWhite)
+{
+  mTxn->AddEdit(OpUseComponentAlphaTextures(nullptr, aCompositable->GetIPDLActor(),
+                                            nullptr, aTextureOnBlack->GetIPDLActor(),
+                                            nullptr, aTextureOnWhite->GetIPDLActor()));
+}
+
+void
 ShadowLayerForwarder::RemoveTexture(TextureClient* aTexture)
 {
   aTexture->ForceRemove();
 }
 
 bool
 ShadowLayerForwarder::EndTransaction(InfallibleTArray<EditReply>* aReplies, bool aScheduleComposite, bool* aSent)
 {
--- a/gfx/layers/ipc/ShadowLayers.h
+++ b/gfx/layers/ipc/ShadowLayers.h
@@ -316,16 +316,19 @@ public:
                               TextureClient* aTexture,
                               nsIntRegion* aRegion) MOZ_OVERRIDE;
 
   /**
    * See CompositableForwarder::UseTexture
    */
   virtual void UseTexture(CompositableClient* aCompositable,
                           TextureClient* aClient) MOZ_OVERRIDE;
+  virtual void UseComponentAlphaTextures(CompositableClient* aCompositable,
+                                         TextureClient* aClientOnBlack,
+                                         TextureClient* aClientOnWhite) MOZ_OVERRIDE;
 
   /**
    * End the current transaction and forward it to LayerManagerComposite.
    * |aReplies| are directions from the LayerManagerComposite to the
    * caller of EndTransaction().
    */
   bool EndTransaction(InfallibleTArray<EditReply>* aReplies, bool aScheduleComposite, bool* aSent);
 
--- a/ipc/dbus/RawDBusConnection.cpp
+++ b/ipc/dbus/RawDBusConnection.cpp
@@ -1,186 +1,81 @@
 /* -*- Mode: c++; c-basic-offset: 2; indent-tabs-mode: nil; tab-width: 40 -*- */
 /* vim: set ts=2 et sw=2 tw=80: */
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this file,
  * You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #include <dbus/dbus.h>
 #include "base/message_loop.h"
-#include "mozilla/Monitor.h"
 #include "nsThreadUtils.h"
-#include "DBusThread.h"
-#include "DBusUtils.h"
 #include "RawDBusConnection.h"
 
 #ifdef CHROMIUM_LOG
 #undef CHROMIUM_LOG
 #endif
 
 #if defined(MOZ_WIDGET_GONK)
 #include <android/log.h>
 #define CHROMIUM_LOG(args...)  __android_log_print(ANDROID_LOG_INFO, "Gonk", args);
 #else
 #define CHROMIUM_LOG(args...)  printf(args);
 #endif
 
 /* TODO: Remove BlueZ constant */
 #define BLUEZ_DBUS_BASE_IFC "org.bluez"
 
-using namespace mozilla::ipc;
-
 //
 // Runnables
 //
 
 namespace mozilla {
 namespace ipc {
 
-class DBusConnectionSendTaskBase : public Task
+class Notification
 {
 public:
-  virtual ~DBusConnectionSendTaskBase()
+  Notification(DBusReplyCallback aCallback, void* aData)
+  : mCallback(aCallback),
+    mData(aData)
   { }
 
-protected:
-  DBusConnectionSendTaskBase(DBusConnection* aConnection,
-                             DBusMessage* aMessage)
-  : mConnection(aConnection),
-    mMessage(aMessage)
+  // Callback function for DBus replies. Only run it on I/O thread.
+  //
+  static void Handle(DBusPendingCall* aCall, void* aData)
   {
-    MOZ_ASSERT(mConnection);
-    MOZ_ASSERT(mMessage);
-  }
-
-  DBusConnection*   mConnection;
-  DBusMessageRefPtr mMessage;
-};
-
-//
-// Sends a message and returns the message's serial number to the
-// disaptching thread. Only run it in DBus thread.
-//
-class DBusConnectionSendTask : public DBusConnectionSendTaskBase
-{
-public:
-  DBusConnectionSendTask(DBusConnection* aConnection,
-                         DBusMessage* aMessage)
-  : DBusConnectionSendTaskBase(aConnection, aMessage)
-  { }
-
-  virtual ~DBusConnectionSendTask()
-  { }
-
-  void Run() MOZ_OVERRIDE
-  {
+    MOZ_ASSERT(!NS_IsMainThread());
     MOZ_ASSERT(MessageLoop::current());
 
-    dbus_bool_t success = dbus_connection_send(mConnection,
-                                               mMessage,
-                                               nullptr);
-    NS_ENSURE_TRUE_VOID(success == TRUE);
-  }
-};
-
-//
-// Sends a message and executes a callback function for the reply. Only
-// run it in DBus thread.
-//
-class DBusConnectionSendWithReplyTask : public DBusConnectionSendTaskBase
-{
-private:
-  class NotifyData
-  {
-  public:
-    NotifyData(DBusReplyCallback aCallback, void* aData)
-    : mCallback(aCallback),
-      mData(aData)
-    { }
+    nsAutoPtr<Notification> ntfn(static_cast<Notification*>(aData));
 
-    void RunNotifyCallback(DBusMessage* aMessage)
-    {
-      if (mCallback) {
-        mCallback(aMessage, mData);
-      }
-    }
-
-  private:
-    DBusReplyCallback mCallback;
-    void*             mData;
-  };
-
-  // Callback function for DBus replies. Only run it in DBus thread.
-  //
-  static void Notify(DBusPendingCall* aCall, void* aData)
-  {
-    MOZ_ASSERT(!NS_IsMainThread());
-
-    nsAutoPtr<NotifyData> data(static_cast<NotifyData*>(aData));
-
-    // The reply can be non-null if the timeout
-    // has been reached.
+    // The reply can be non-null if the timeout has been reached.
     DBusMessage* reply = dbus_pending_call_steal_reply(aCall);
 
     if (reply) {
-      data->RunNotifyCallback(reply);
+      ntfn->RunCallback(reply);
       dbus_message_unref(reply);
     }
 
     dbus_pending_call_cancel(aCall);
     dbus_pending_call_unref(aCall);
   }
 
-public:
-  DBusConnectionSendWithReplyTask(DBusConnection* aConnection,
-                                  DBusMessage* aMessage,
-                                  int aTimeout,
-                                  DBusReplyCallback aCallback,
-                                  void* aData)
-  : DBusConnectionSendTaskBase(aConnection, aMessage),
-    mCallback(aCallback),
-    mData(aData),
-    mTimeout(aTimeout)
-  { }
-
-  virtual ~DBusConnectionSendWithReplyTask()
-  { }
-
-  void Run() MOZ_OVERRIDE
+private:
+  void RunCallback(DBusMessage* aMessage)
   {
-    MOZ_ASSERT(MessageLoop::current());
+    if (mCallback) {
+      mCallback(aMessage, mData);
+    }
+  }
 
-    // Freed at end of Notify
-    nsAutoPtr<NotifyData> data(new NotifyData(mCallback, mData));
-    NS_ENSURE_TRUE_VOID(data);
-
-    DBusPendingCall* call;
-
-    dbus_bool_t success = dbus_connection_send_with_reply(mConnection,
-                                                          mMessage,
-                                                          &call,
-                                                          mTimeout);
-    NS_ENSURE_TRUE_VOID(success == TRUE);
-
-    success = dbus_pending_call_set_notify(call, Notify, data, nullptr);
-    NS_ENSURE_TRUE_VOID(success == TRUE);
-
-    data.forget();
-    dbus_message_unref(mMessage);
-  };
-
-private:
   DBusReplyCallback mCallback;
   void*             mData;
-  int               mTimeout;
 };
 
-}
-}
-
 //
 // RawDBusConnection
 //
 
 bool RawDBusConnection::sDBusIsInit(false);
 
 RawDBusConnection::RawDBusConnection()
 {
@@ -213,63 +108,70 @@ void RawDBusConnection::ScopedDBusConnec
   if (ptr) {
     dbus_connection_close(ptr);
     dbus_connection_unref(ptr);
   }
 }
 
 bool RawDBusConnection::Send(DBusMessage* aMessage)
 {
-  DBusConnectionSendTask* t =
-    new DBusConnectionSendTask(mConnection, aMessage);
-  MOZ_ASSERT(t);
+  MOZ_ASSERT(aMessage);
+  MOZ_ASSERT(!NS_IsMainThread());
+  MOZ_ASSERT(MessageLoop::current());
 
-  nsresult rv = DispatchToDBusThread(t);
-
-  if (NS_FAILED(rv)) {
-    if (aMessage) {
-      dbus_message_unref(aMessage);
-    }
+  dbus_bool_t success = dbus_connection_send(mConnection,
+                                             aMessage,
+                                             nullptr);
+  if (success != TRUE) {
+    dbus_message_unref(aMessage);
     return false;
   }
-
   return true;
 }
 
 bool RawDBusConnection::SendWithReply(DBusReplyCallback aCallback,
                                       void* aData,
                                       int aTimeout,
                                       DBusMessage* aMessage)
 {
-  DBusConnectionSendWithReplyTask* t =
-    new DBusConnectionSendWithReplyTask(mConnection, aMessage, aTimeout,
-                                        aCallback, aData);
-  MOZ_ASSERT(t);
+  MOZ_ASSERT(aMessage);
+  MOZ_ASSERT(!NS_IsMainThread());
+  MOZ_ASSERT(MessageLoop::current());
 
-  nsresult rv = DispatchToDBusThread(t);
+  nsAutoPtr<Notification> ntfn(new Notification(aCallback, aData));
+  NS_ENSURE_TRUE(ntfn, false);
+
+  DBusPendingCall* call;
 
-  if (NS_FAILED(rv)) {
-    if (aMessage) {
-      dbus_message_unref(aMessage);
-    }
-    return false;
-  }
+  dbus_bool_t success = dbus_connection_send_with_reply(mConnection,
+                                                        aMessage,
+                                                        &call,
+                                                        aTimeout);
+  NS_ENSURE_TRUE(success == TRUE, false);
+
+  success = dbus_pending_call_set_notify(call, Notification::Handle,
+                                         ntfn, nullptr);
+  NS_ENSURE_TRUE(success == TRUE, false);
+
+  ntfn.forget();
+  dbus_message_unref(aMessage);
 
   return true;
 }
 
 bool RawDBusConnection::SendWithReply(DBusReplyCallback aCallback,
                                       void* aData,
                                       int aTimeout,
                                       const char* aPath,
                                       const char* aIntf,
                                       const char* aFunc,
                                       int aFirstArgType,
                                       ...)
 {
+  MOZ_ASSERT(!NS_IsMainThread());
   va_list args;
 
   va_start(args, aFirstArgType);
   DBusMessage* msg = BuildDBusMessage(aPath, aIntf, aFunc,
                                       aFirstArgType, args);
   va_end(args);
 
   if (!msg) {
@@ -296,8 +198,11 @@ DBusMessage* RawDBusConnection::BuildDBu
   if (!dbus_message_append_args_valist(msg, aFirstArgType, aArgs)) {
     CHROMIUM_LOG("Could not append argument to method call!");
     dbus_message_unref(msg);
     return nullptr;
   }
 
   return msg;
 }
+
+}
+}
--- a/ipc/dbus/RawDBusConnection.h
+++ b/ipc/dbus/RawDBusConnection.h
@@ -2,24 +2,17 @@
 /* vim: set ts=2 et sw=2 tw=80: */
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this file,
  * You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #ifndef mozilla_ipc_dbus_gonk_rawdbusconnection_h__
 #define mozilla_ipc_dbus_gonk_rawdbusconnection_h__
 
-#include <stdarg.h>
-#include <stdint.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <string>
-#include "nscore.h"
 #include "mozilla/Scoped.h"
-#include <mozilla/Mutex.h>
 
 struct DBusConnection;
 struct DBusError;
 struct DBusMessage;
 
 namespace mozilla {
 namespace ipc {
 
--- a/ipc/ipdl/ipdl/lower.py
+++ b/ipc/ipdl/ipdl/lower.py
@@ -326,22 +326,32 @@ def _autoptrGet(expr):
     return ExprCall(ExprSelect(expr, '.', 'get'))
 
 def _autoptrForget(expr):
     return ExprCall(ExprSelect(expr, '.', 'forget'))
 
 def _cxxArrayType(basetype, const=0, ref=0):
     return Type('InfallibleTArray', T=basetype, const=const, ref=ref)
 
+def _cxxFallibleArrayType(basetype, const=0, ref=0):
+    return Type('FallibleTArray', T=basetype, const=const, ref=ref)
+
 def _callCxxArrayLength(arr):
     return ExprCall(ExprSelect(arr, '.', 'Length'))
 
-def _callCxxArraySetLength(arr, lenexpr, sel='.'):
-    return ExprCall(ExprSelect(arr, sel, 'SetLength'),
-                    args=[ lenexpr ])
+def _callCxxCheckedArraySetLength(arr, lenexpr, sel='.'):
+    ifbad = StmtIf(ExprNot(ExprCall(ExprSelect(arr, sel, 'SetLength'),
+                                    args=[ lenexpr ])))
+    ifbad.addifstmt(_fatalError('Error setting the array length'))
+    ifbad.addifstmt(StmtReturn.FALSE)
+    return ifbad
+
+def _callCxxSwapArrayElements(arr1, arr2, sel='.'):
+    return ExprCall(ExprSelect(arr1, sel, 'SwapElements'),
+                    args=[ arr2 ])
 
 def _callCxxArrayInsertSorted(arr, elt):
     return ExprCall(ExprSelect(arr, '.', 'InsertElementSorted'),
                     args=[ elt ])
 
 def _callCxxArrayRemoveSorted(arr, elt):
     return ExprCall(ExprSelect(arr, '.', 'RemoveElementSorted'),
                     args=[ elt ])
@@ -4454,36 +4464,36 @@ class _GenerateProtocolActorCode(ipdl.as
             StmtDecl(Decl(Type.UINT32, lenvar.name),
                      init=_callCxxArrayLength(var)),
             StmtExpr(self.write(None, lenvar, msgvar)),
             Whitespace.NL,
             forwrite
         ])
 
         read = MethodDefn(self.readMethodDecl(outtype, var))
-        avar = ExprVar('a')
+        favar = ExprVar('fa')
         forread = StmtFor(init=ExprAssn(Decl(Type.UINT32, ivar.name),
                                         ExprLiteral.ZERO),
                           cond=ExprBinary(ivar, '<', lenvar),
                           update=ExprPrefixUnop(ivar, '++'))
         forread.addstmt(
-            self.checkedRead(eltipdltype, ExprAddrOf(ExprIndex(avar, ivar)),
+            self.checkedRead(eltipdltype, ExprAddrOf(ExprIndex(favar, ivar)),
                              msgvar, itervar, errfnRead,
                              eltipdltype.name() + '[i]'))
         read.addstmts([
-            StmtDecl(Decl(_cxxRefType(arraytype, self.side), avar.name),
-                     init=ExprDeref(var)),
+            StmtDecl(Decl(_cxxFallibleArrayType(_cxxBareType(arraytype.basetype, self.side)), favar.name)),
             StmtDecl(Decl(Type.UINT32, lenvar.name)),
             self.checkedRead(None, ExprAddrOf(lenvar),
                              msgvar, itervar, errfnRead,
                              'length\' (' + Type.UINT32.name + ') of \'' +
                              arraytype.name()),
             Whitespace.NL,
-            StmtExpr(_callCxxArraySetLength(var, lenvar, '->')),
+            _callCxxCheckedArraySetLength(favar, lenvar),
             forread,
+            StmtExpr(_callCxxSwapArrayElements(var, favar, '->')),
             StmtReturn.TRUE
         ])
 
         self.cls.addstmts([ write, Whitespace.NL, read, Whitespace.NL ])
 
 
     def implementShmemPickling(self, shmemtype):
         msgvar = self.msgvar
--- a/layout/generic/nsHTMLReflowState.cpp
+++ b/layout/generic/nsHTMLReflowState.cpp
@@ -54,19 +54,20 @@ nsHTMLReflowState::nsHTMLReflowState(nsP
                                      nsIFrame*            aFrame,
                                      nsRenderingContext*  aRenderingContext,
                                      const nsSize&        aAvailableSpace,
                                      uint32_t             aFlags)
   : nsCSSOffsetState(aFrame, aRenderingContext)
   , mBlockDelta(0)
   , mReflowDepth(0)
 {
-  NS_PRECONDITION(aPresContext, "no pres context");
   NS_PRECONDITION(aRenderingContext, "no rendering context");
-  NS_PRECONDITION(aFrame, "no frame");
+  MOZ_ASSERT(aPresContext, "no pres context");
+  MOZ_ASSERT(aFrame, "no frame");
+  MOZ_ASSERT(aPresContext == aFrame->PresContext(), "wrong pres context");
   parentReflowState = nullptr;
   AvailableWidth() = aAvailableSpace.width;
   AvailableHeight() = aAvailableSpace.height;
   mFloatManager = nullptr;
   mLineLayout = nullptr;
   memset(&mFlags, 0, sizeof(mFlags));
   mDiscoveredClearance = nullptr;
   mPercentHeightObserver = nullptr;
@@ -154,18 +155,19 @@ nsHTMLReflowState::nsHTMLReflowState(nsP
                                      nscoord                  aContainingBlockWidth,
                                      nscoord                  aContainingBlockHeight,
                                      uint32_t                 aFlags)
   : nsCSSOffsetState(aFrame, aParentReflowState.rendContext)
   , mBlockDelta(0)
   , mReflowDepth(aParentReflowState.mReflowDepth + 1)
   , mFlags(aParentReflowState.mFlags)
 {
-  NS_PRECONDITION(aPresContext, "no pres context");
-  NS_PRECONDITION(aFrame, "no frame");
+  MOZ_ASSERT(aPresContext, "no pres context");
+  MOZ_ASSERT(aFrame, "no frame");
+  MOZ_ASSERT(aPresContext == aFrame->PresContext(), "wrong pres context");
   NS_PRECONDITION((aContainingBlockWidth == -1) ==
                     (aContainingBlockHeight == -1),
                   "cb width and height should only be non-default together");
   NS_PRECONDITION(!mFlags.mSpecialHeightReflow ||
                   !NS_SUBTREE_DIRTY(aFrame),
                   "frame should be clean when getting special height reflow");
 
   parentReflowState = &aParentReflowState;
--- a/modules/libpref/src/init/all.js
+++ b/modules/libpref/src/init/all.js
@@ -277,19 +277,16 @@ pref("media.webspeech.recognition.enable
 #endif
 #ifdef MOZ_WEBM_ENCODER
 pref("media.encoder.webm.enabled", true);
 #endif
 #ifdef MOZ_OMX_ENCODER
 pref("media.encoder.omx.enabled", true);
 #endif
 
-// Whether to enable Web Audio support
-pref("media.webaudio.enabled", true);
-
 // Whether to autostart a media element with an |autoplay| attribute
 pref("media.autoplay.enabled", true);
 
 // The default number of decoded video frames that are enqueued in
 // MediaDecoderReader's mVideoQueue.
 pref("media.video-queue.default-size", 10);
 
 // Whether to disable the video stats to prevent fingerprinting
@@ -1387,16 +1384,17 @@ pref("intl.charsetmenu.browser.more4",  
 pref("intl.charsetmenu.browser.more5",      "ISO-8859-6, windows-1256, ISO-8859-8-I, windows-1255, ISO-8859-8, IBM862");
 pref("intl.charsetmenu.mailedit",           "chrome://global/locale/intl.properties");
 pref("intl.charsetmenu.browser.cache",      "");
 pref("intl.charsetmenu.mailview.cache",     "");
 pref("intl.charsetmenu.composer.cache",     "");
 pref("intl.charsetmenu.browser.cache.size", 5);
 pref("intl.charset.detector",               "chrome://global/locale/intl.properties");
 pref("intl.charset.fallback.override",      "");
+pref("intl.charset.fallback.tld",           true);
 pref("intl.ellipsis",                       "chrome://global-platform/locale/intl.properties");
 pref("intl.locale.matchOS",                 false);
 // fallback charset list for Unicode conversion (converting from Unicode)
 // currently used for mail send only to handle symbol characters (e.g Euro, trademark, smartquotes)
 // for ISO-8859-1
 pref("intl.fallbackCharsetList.ISO-8859-1", "windows-1252");
 pref("font.language.group",                 "chrome://global/locale/intl.properties");
 
--- a/netwerk/test/unit/xpcshell.ini
+++ b/netwerk/test/unit/xpcshell.ini
@@ -26,16 +26,18 @@ support-files =
 [test_cache2-02-open-non-existing.js]
 [test_cache2-03-oncacheentryavail-throws.js]
 [test_cache2-04-oncacheentryavail-throws2x.js]
 [test_cache2-05-visit.js]
 [test_cache2-06-pb-mode.js]
 # Bug 675039, comment 6: "The difference is that the memory cache is disabled in Armv6 builds."
 skip-if = os == "android"
 [test_cache2-07-visit-memory.js]
+# Bug 675039, comment 6: "The difference is that the memory cache is disabled in Armv6 builds."
+skip-if = os == "android"
 [test_cache2-08-evict-disk-by-memory-storage.js]
 [test_cache2-09-evict-disk-by-uri.js]
 [test_cache2-10-evict-direct.js]
 [test_cache2-10b-evict-direct-immediate.js]
 [test_cache2-11-evict-memory.js]
 # Bug 675039, comment 6: "The difference is that the memory cache is disabled in Armv6 builds."
 skip-if = os == "android"
 [test_cache2-12-evict-disk.js]
--- a/parser/nsCharsetSource.h
+++ b/parser/nsCharsetSource.h
@@ -3,23 +3,24 @@
  * You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #ifndef nsCharsetSource_h_
 #define nsCharsetSource_h_
 
 // note: the value order defines the priority; higher numbers take priority
 #define kCharsetUninitialized           0
 #define kCharsetFromFallback            1
-#define kCharsetFromDocTypeDefault      2 // This and up confident for XHR
-#define kCharsetFromCache               3
-#define kCharsetFromParentFrame         4
-#define kCharsetFromAutoDetection       5
-#define kCharsetFromHintPrevDoc         6
-#define kCharsetFromMetaPrescan         7 // this one and smaller: HTML5 Tentative
-#define kCharsetFromMetaTag             8 // this one and greater: HTML5 Confident
-#define kCharsetFromIrreversibleAutoDetection 9
-#define kCharsetFromChannel            10
-#define kCharsetFromOtherComponent     11
-#define kCharsetFromParentForced       12 // propagates to child frames
-#define kCharsetFromUserForced         13 // propagates to child frames
-#define kCharsetFromByteOrderMark      14
+#define kCharsetFromTopLevelDomain      2
+#define kCharsetFromDocTypeDefault      3 // This and up confident for XHR
+#define kCharsetFromCache               4
+#define kCharsetFromParentFrame         5
+#define kCharsetFromAutoDetection       6
+#define kCharsetFromHintPrevDoc         7
+#define kCharsetFromMetaPrescan         8 // this one and smaller: HTML5 Tentative
+#define kCharsetFromMetaTag             9 // this one and greater: HTML5 Confident
+#define kCharsetFromIrreversibleAutoDetection 10
+#define kCharsetFromChannel            11
+#define kCharsetFromOtherComponent     12
+#define kCharsetFromParentForced       13 // propagates to child frames
+#define kCharsetFromUserForced         14 // propagates to child frames
+#define kCharsetFromByteOrderMark      15
 
 #endif /* nsCharsetSource_h_ */
--- a/python/mozboot/bin/bootstrap.py
+++ b/python/mozboot/bin/bootstrap.py
@@ -41,17 +41,27 @@ REPOSITORY_PATHS = [
     'mozboot/gentoo.py',
     'mozboot/openbsd.py',
     'mozboot/osx.py',
     'mozboot/ubuntu.py',
 ]
 
 TEMPDIR = None
 
+def setup_proxy():
+    # Some Linux environments define ALL_PROXY, which is a SOCKS proxy
+    # intended for all protocols. Python doesn't currently automatically
+    # detect this like it does for http_proxy and https_proxy.
+    if 'ALL_PROXY' in os.environ and 'https_proxy' not in os.environ:
+        os.environ['https_proxy'] = os.environ['ALL_PROXY']
+    if 'ALL_PROXY' in os.environ and 'http_proxy' not in os.environ:
+        os.environ['http_proxy'] = os.environ['ALL_PROXY']
+
 def fetch_files(repo_url, repo_type):
+    setup_proxy()
     repo_url = repo_url.rstrip('/')
 
     files = {}
 
     if repo_type == 'hgweb':
         for path in REPOSITORY_PATHS:
             url = repo_url + '/raw-file/default/python/mozboot/' + path
 
--- a/security/manager/ssl/src/SSLServerCertVerification.cpp
+++ b/security/manager/ssl/src/SSLServerCertVerification.cpp
@@ -501,44 +501,42 @@ CreateCertErrorRunnable(CertVerifier& ce
 
   RefPtr<nsNSSCertificate> nssCert(nsNSSCertificate::Create(cert));
   if (!nssCert) {
     NS_ERROR("nsNSSCertificate::Create failed");
     PR_SetError(SEC_ERROR_NO_MEMORY, 0);
     return nullptr;
   }
 
-  SECStatus srv;
-
   PLArenaPool* log_arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE);
   PLArenaPoolCleanerFalseParam log_arena_cleaner(log_arena);
   if (!log_arena) {
     NS_ERROR("PORT_NewArena failed");
     return nullptr; // PORT_NewArena set error code
   }
 
   CERTVerifyLog* verify_log = PORT_ArenaZNew(log_arena, CERTVerifyLog);
   if (!verify_log) {
     NS_ERROR("PORT_ArenaZNew failed");
     return nullptr; // PORT_ArenaZNew set error code
   }
   CERTVerifyLogContentsCleaner verify_log_cleaner(verify_log);
   verify_log->arena = log_arena;
 
-  // XXX TODO: convert to VerifySSLServerCert
-  // XXX TODO: get rid of error log
-  srv = certVerifier.VerifyCert(cert, stapledOCSPResponse,
-                                certificateUsageSSLServer, now,
-                                infoObject, 0, nullptr, nullptr, verify_log);
 
-  // We ignore the result code of the cert verification.
+  // We ignore the result code of the cert verification (i.e. VerifyCert's rv)
   // Either it is a failure, which is expected, and we'll process the
   //                         verify log below.
   // Or it is a success, then a domain mismatch is the only
   //                     possible failure.
+  // XXX TODO: convert to VerifySSLServerCert
+  // XXX TODO: get rid of error log
+  certVerifier.VerifyCert(cert, stapledOCSPResponse,
+                          certificateUsageSSLServer, now,
+                          infoObject, 0, nullptr, nullptr, verify_log);
 
   PRErrorCode errorCodeMismatch = 0;
   PRErrorCode errorCodeTrust = 0;
   PRErrorCode errorCodeExpired = 0;
 
   uint32_t collected_errors = 0;
 
   // Check the name field against the desired hostname.
--- a/security/manager/ssl/src/moz.build
+++ b/security/manager/ssl/src/moz.build
@@ -85,16 +85,18 @@ if CONFIG['MOZ_XUL']:
     UNIFIED_SOURCES += [
         'nsCertTree.cpp',
     ]
 
 UNIFIED_SOURCES += [
     'md4.c',
 ]
 
+FAIL_ON_WARNINGS = True
+
 FINAL_LIBRARY = 'xul'
 
 LOCAL_INCLUDES += [
     '../../../certverifier',
     '../../../insanity/include',
 ]
 
 
--- a/security/manager/ssl/src/nsNSSCertificate.cpp
+++ b/security/manager/ssl/src/nsNSSCertificate.cpp
@@ -818,27 +818,26 @@ nsNSSCertificate::GetChain(nsIArray** _r
   if (isAlreadyShutDown())
     return NS_ERROR_NOT_AVAILABLE;
 
   NS_ENSURE_ARG(_rvChain);
   nsresult rv;
   PR_LOG(gPIPNSSLog, PR_LOG_DEBUG, ("Getting chain for \"%s\"\n", mCert->nickname));
 
   ::insanity::pkix::ScopedCERTCertList nssChain;
-  SECStatus srv;
   RefPtr<SharedCertVerifier> certVerifier(GetDefaultCertVerifier());
   NS_ENSURE_TRUE(certVerifier, NS_ERROR_UNEXPECTED);
 
   // We want to test all usages, but we start with server because most of the
   // time Firefox users care about server certs.
-  srv = certVerifier->VerifyCert(mCert.get(), nullptr,
-                                 certificateUsageSSLServer, PR_Now(),
-                                 nullptr, /*XXX fixme*/
-                                 CertVerifier::FLAG_LOCAL_ONLY,
-                                 &nssChain);
+  certVerifier->VerifyCert(mCert.get(), nullptr,
+                           certificateUsageSSLServer, PR_Now(),
+                           nullptr, /*XXX fixme*/
+                           CertVerifier::FLAG_LOCAL_ONLY,
+                           &nssChain);
   // This is the whitelist of all non-SSLServer usages that are supported by
   // verifycert.
   const int otherUsagesToTest = certificateUsageSSLClient |
                                 certificateUsageSSLCA |
                                 certificateUsageEmailSigner |
                                 certificateUsageEmailRecipient |
                                 certificateUsageObjectSigner |
                                 certificateUsageStatusResponder;
@@ -846,21 +845,21 @@ nsNSSCertificate::GetChain(nsIArray** _r
        usage < certificateUsageAnyCA && !nssChain;
        usage = usage << 1) {
     if ((usage & otherUsagesToTest) == 0) {
       continue;
     }
     PR_LOG(gPIPNSSLog, PR_LOG_DEBUG,
            ("pipnss: PKIX attempting chain(%d) for '%s'\n",
             usage, mCert->nickname));
-    srv = certVerifier->VerifyCert(mCert.get(), nullptr,
-                                   usage, PR_Now(),
-                                   nullptr, /*XXX fixme*/
-                                   CertVerifier::FLAG_LOCAL_ONLY,
-                                   &nssChain);
+    certVerifier->VerifyCert(mCert.get(), nullptr,
+                             usage, PR_Now(),
+                             nullptr, /*XXX fixme*/
+                             CertVerifier::FLAG_LOCAL_ONLY,
+                             &nssChain);
   }
 
   if (!nssChain) {
     // There is not verified path for the chain, howeever we still want to 
     // present to the user as much of a possible chain as possible, in the case
     // where there was a problem with the cert or the issuers.
     PR_LOG(gPIPNSSLog, PR_LOG_DEBUG,
            ("pipnss: getchain :CertVerify failed to get chain for '%s'\n",
--- a/security/manager/ssl/src/nsUsageArrayHelper.cpp
+++ b/security/manager/ssl/src/nsUsageArrayHelper.cpp
@@ -127,30 +127,29 @@ nsUsageArrayHelper::check(uint32_t previ
     if (NS_SUCCEEDED(m_rv)) {
       outUsages[aCounter++] = ToNewUnicode(verifyDesc);
     }
     return nsIX509Cert::VERIFIED_OK;
   }
 
   PRErrorCode error = PR_GetError();
 
-  const char * errorString = PR_ErrorToName(error);
   uint32_t result = nsIX509Cert::NOT_VERIFIED_UNKNOWN;
   verifyFailed(&result, error);
 
   // USAGE_NOT_ALLOWED is the weakest non-fatal error; let all other errors
   // override it.
   if (result == nsIX509Cert::USAGE_NOT_ALLOWED &&
       previousCheckResult != nsIX509Cert::VERIFIED_OK) {
       result = previousCheckResult;
   }
 
   PR_LOG(gPIPNSSLog, PR_LOG_DEBUG,
           ("error validating certificate for usage %s: %s (%d) -> %ud \n",
-          typestr.get(), errorString, (int) error, (int) result));
+          typestr.get(), PR_ErrorToName(error), (int) error, (int) result));
 
   return result;
 }
 
 
 // Maps the error code to one of the Constants for certificate verification
 // results" in nsIX509Cert.
 void
--- a/testing/mochitest/b2g.json
+++ b/testing/mochitest/b2g.json
@@ -25,17 +25,16 @@
     "content/media/test/test_can_play_type_no_dash.html":"",
     "content/media/test/test_can_play_type_ogg.html":"",
     "content/media/test/test_chaining.html": "timed out",
     "content/media/test/test_delay_load.html": "6 failures",
     "content/media/test/test_framebuffer.html": "timed out",
     "content/media/test/test_info_leak.html": "2 failures",
     "content/media/test/test_media_selection.html": "timed out",
     "content/media/test/test_mediarecorder_record_4ch_audiocontext.html": "",
-    "content/media/test/test_mediarecorder_creation_fail.html": "",
     "content/media/test/test_playback.html": "Test timed out, bug 668973?",
     "content/media/test/test_playback_rate.html": "",
     "content/media/test/test_playback_rate_playpause.html": "",
     "content/media/test/test_played.html": "",
     "content/media/test/test_referer.html":"",
     "content/media/test/test_seekable3.html": "timed out",
     "content/media/test/test_seek.html": "",
     "content/media/test/test_streams_element_capture.html": "bug 900172 - timeouts",
@@ -171,17 +170,16 @@
     "content/html/content/test/test_iframe_sandbox_popups_inheritance.html":"multiple concurrent window.open()s fail on B2G",
     "content/html/content/test/test_iframe_sandbox_modal.html":"modal tests fail on B2G",
 
     "content/html/content/test/test_iframe_sandbox_plugins.html":"plugins not supported",
     "content/html/content/test/test_object_plugin_nav.html":"plugins not supported",
     "content/html/document/test/test_bug741266.html":"needs control of popup window size",
     "docshell/test/navigation/test_popup-navigates-children.html":"Needs multiple window.open support, also uses docshelltreenode",
     "docshell/test/test_bug590573.html":"queryinterfaces into webnavigation, might suffer from something similar as bug 823022",
-    "docshell/test/navigation/test_bug430723.html":"apz race condition, see bug 965351",
     "dom/devicestorage/ipc/test_ipc.html":"nested ipc not working",
 
     "dom/indexedDB/ipc/test_ipc.html":"nested ipc not working",
     "dom/indexedDB/test/test_lowDiskSpace.html":"this needs probably modification for notifyObserversInParentProcess to be similar as pushPermissions",
 
     "content/base/test/test_object.html":"needs plugin support",
     "content/base/test/test_bug827160.html": "needs plugin support",
 
@@ -266,17 +264,16 @@
     "dom/browser-element/mochitest/test_browserElement_oop_TargetBlank.html":"",
     "dom/events/test/test_bug226361.xhtml":"",
     "dom/events/test/test_bug238987.html":"",
     "dom/events/test/test_bug409604.html":"",
     "dom/events/test/test_bug457672.html":"",
     "dom/events/test/test_bug574663.html":"",
     "dom/events/test/test_bug607464.html":"",
     "dom/events/test/test_wheel_default_action.html":"",
-    "dom/events/test/test_bug946632.html":"apz race condition, see bug 965351",
 
     "dom/file/test/test_progress_events.html":"All of these fail fairly regularly with: UnknownError: The operation failed for reasons unrelated to the database itself and not covered by any other error code. at http://mochi.test:8888/tests/dom/file/test/helpers.js:126",
     "dom/file/test/test_request_readyState.html":"",
     "dom/file/test/test_stream_tracking.html":"",
     "dom/file/test/test_append_read_data.html":"",
     "dom/file/test/test_archivereader.html":"",
     "dom/file/test/test_archivereader_nonUnicode.html":"",
     "dom/file/test/test_archivereader_zip_in_zip.html":"",
@@ -378,17 +375,16 @@
     "layout/base/tests/test_bug603550.html":"Components.classes[@mozilla.org/widget/dragservice;1] is undefined",
     "layout/base/tests/test_bug629838.html":"depends on plugins support",
     "layout/base/tests/test_mozPaintCount.html":"depends on plugins support",
     "layout/forms/test/test_bug348236.html":"select form control popup",
     "layout/forms/test/test_bug446663.html":"needs copy support",
     "layout/forms/test/test_bug571352.html":"shift-click multi-select not working?",
     "layout/forms/test/test_textarea_resize.html":"resizing textarea not available in b2g",
     "layout/forms/test/test_bug903715.html":"select elements don't use an in-page popup in B2G",
-    "layout/forms/test/test_bug564115.html":"apz race condition, see bug 965351",
     "layout/generic/test/test_bug392746.html":"ctrl mouse select not working in b2g",
     "layout/generic/test/test_bug791616.html":"Target should not have scrolled - got 114.10000610351562, expected 115.39999389648438",
     "layout/generic/test/test_invalidate_during_plugin_paint.html":"plugins not supported",
     "layout/generic/test/test_plugin_focus.html":"plugins not supported",
     "layout/generic/test/test_plugin_mouse_coords.html":"plugins not supported",
     "layout/generic/test/test_selection_expanding.html":"mouse selection not working",
 
     "layout/style/test/test_transitions_per_property.html":"times out, needs more time + various failures",
--- a/testing/mozbase/Makefile.in
+++ b/testing/mozbase/Makefile.in
@@ -23,16 +23,18 @@ MOZBASE_PACKAGES = \
   mozdevice \
   moznetwork \
   mozsystemmonitor \
   moztest \
   $(NULL)
 
 MOZBASE_EXTRAS = \
   setup_development.py \
+  test.py \
+  test-manifest.ini \
   $(NULL)
 
 _DEST_DIR = $(DEPTH)/_tests/mozbase
 libs:: $(MOZBASE_PACKAGES)
 	$(PYTHON) $(topsrcdir)/config/nsinstall.py $^ $(_DEST_DIR)
 libs:: $(MOZBASE_EXTRAS)
 	$(PYTHON) $(topsrcdir)/config/nsinstall.py $^ $(_DEST_DIR)
 
--- a/testing/profiles/prefs_general.js
+++ b/testing/profiles/prefs_general.js
@@ -125,19 +125,16 @@ user_pref("dom.mozSettings.enabled", tru
 
 // Make sure the disk cache doesn't get auto disabled
 user_pref("network.http.bypass-cachelock-threshold", 200000);
 
 // Enable Gamepad
 user_pref("dom.gamepad.enabled", true);
 user_pref("dom.gamepad.non_standard_events.enabled", true);
 
-// Enable Web Audio
-user_pref("media.webaudio.enabled", true);
-
 // Enable Web Audio legacy APIs
 user_pref("media.webaudio.legacy.AudioBufferSourceNode", true);
 user_pref("media.webaudio.legacy.AudioContext", true);
 user_pref("media.webaudio.legacy.AudioParam", true);
 user_pref("media.webaudio.legacy.BiquadFilterNode", true);
 user_pref("media.webaudio.legacy.PannerNode", true);
 user_pref("media.webaudio.legacy.OscillatorNode", true);
 
--- a/toolkit/modules/InlineSpellChecker.jsm
+++ b/toolkit/modules/InlineSpellChecker.jsm
@@ -157,24 +157,37 @@ InlineSpellChecker.prototype = {
     spellchecker.GetDictionaryList(o1, o2);
     var list = o1.value;
     var listcount = o2.value;
     var curlang = "";
     try {
         curlang = spellchecker.GetCurrentDictionary();
     } catch(e) {}
 
+    var sortedList = [];
     for (var i = 0; i < list.length; i ++) {
-      this.mDictionaryNames.push(list[i]);
+      sortedList.push({"id": list[i],
+                       "label": this.getDictionaryDisplayName(list[i])});
+    }
+    sortedList.sort(function(a, b) {
+      if (a.label < b.label)
+        return -1;
+      if (a.label > b.label)
+        return 1;
+      return 0;
+    });
+
+    for (var i = 0; i < sortedList.length; i ++) {
+      this.mDictionaryNames.push(sortedList[i].id);
       var item = menu.ownerDocument.createElement("menuitem");
-      item.setAttribute("id", "spell-check-dictionary-" + list[i]);
-      item.setAttribute("label", this.getDictionaryDisplayName(list[i]));
+      item.setAttribute("id", "spell-check-dictionary-" + sortedList[i].id);
+      item.setAttribute("label", sortedList[i].label);
       item.setAttribute("type", "radio");
       this.mDictionaryItems.push(item);
-      if (curlang == list[i]) {
+      if (curlang == sortedList[i].id) {
         item.setAttribute("checked", "true");
       } else {
         var callback = function(me, val) { return function(evt) { me.selectDictionary(val); } };
         item.addEventListener("command", callback(this, i), true);
       }
       if (insertBefore)
         menu.insertBefore(item, insertBefore);
       else
--- a/tools/mercurial/hgsetup/wizard.py
+++ b/tools/mercurial/hgsetup/wizard.py
@@ -2,16 +2,17 @@
 # License, v. 2.0. If a copy of the MPL was not distributed with this,
 # file, You can obtain one at http://mozilla.org/MPL/2.0/.
 
 from __future__ import unicode_literals
 
 import difflib
 import errno
 import os
+import shutil
 import sys
 import which
 
 from configobj import ConfigObjError
 from StringIO import StringIO
 
 from mozversioncontrol.repoupdate import (
     update_mercurial_repo,
@@ -48,17 +49,17 @@ BAD_DIFF_SETTINGS = '''
 Mozilla developers produce patches in a standard format, but your Mercurial is
 not configured to produce patches in that format.
 '''.strip()
 
 BZEXPORT_INFO = '''
 If you plan on uploading patches to Mozilla, there is an extension called
 bzexport that makes it easy to upload patches from the command line via the
 |hg bzexport| command. More info is available at
-https://hg.mozilla.org/users/tmielczarek_mozilla.com/bzexport
+https://hg.mozilla.org/hgcustom/version-control-tools/file/default/hgext/bzexport/README
 '''.strip()
 
 MQEXT_INFO = '''
 The mqext extension (https://bitbucket.org/sfink/mqext) provides a number of
 useful abilities to Mercurial, including automatically committing changes to
 your mq patch queue.
 '''.strip()
 
@@ -82,16 +83,17 @@ should be up to date!
 
 
 class MercurialSetupWizard(object):
     """Command-line wizard to help users configure Mercurial."""
 
     def __init__(self, state_dir):
         self.state_dir = state_dir
         self.ext_dir = os.path.join(state_dir, 'mercurial', 'extensions')
+        self.vcs_tools_dir = os.path.join(state_dir, 'version-control-tools')
 
     def run(self, config_paths):
         try:
             os.makedirs(self.ext_dir)
         except OSError as e:
             if e.errno != errno.EEXIST:
                 raise
 
@@ -151,33 +153,33 @@ class MercurialSetupWizard(object):
         if 'rebase' not in active:
             if self._prompt_yn('Would you like to enable the rebase extension '
                 'to allow you to move changesets around (which can help '
                 'maintain a linear history)'):
                 c.activate_extension('rebase')
                 print('Activated rebase extension.')
                 print('')
 
-        update_bzexport = 'bzexport' in active
+        update_vcs_tools = False
+        activate_bzexport = False
+
         if 'bzexport' not in active:
             print(BZEXPORT_INFO)
             if self._prompt_yn('Would you like to activate bzexport'):
-                update_bzexport = True
-                c.activate_extension('bzexport', os.path.join(self.ext_dir,
-                    'bzexport'))
-                print('Activated bzexport extension.')
-                print('')
+                activate_bzexport = True
+                update_vcs_tools = True
+        else:
+            activate_bzexport = True
 
-        if update_bzexport:
-            self.update_mercurial_repo(
-                hg,
-                'https://hg.mozilla.org/users/tmielczarek_mozilla.com/bzexport',
-                os.path.join(self.ext_dir, 'bzexport'),
-                'default',
-                'Ensuring bzexport extension is up to date...')
+        if activate_bzexport:
+            update_vcs_tools = True
+            c.activate_extension('bzexport',
+                os.path.join(self.vcs_tools_dir, 'hgext', 'bzexport'))
+            print('Activated bzexport extension.')
+            print('')
 
         if 'mq' not in active:
             if self._prompt_yn('Would you like to activate the mq extension '
                 'to manage patches'):
                 c.activate_extension('mq')
                 print('Activated mq extension.')
                 print('')
 
@@ -225,16 +227,33 @@ class MercurialSetupWizard(object):
             if not c.have_qnew_currentuser_default():
                 print(QNEWCURRENTUSER_INFO)
                 if self._prompt_yn('Would you like qnew to set patch author by '
                                    'default'):
                     c.ensure_qnew_currentuser_default()
                     print('Configured qnew to set patch author by default.')
                     print('')
 
+        if update_vcs_tools:
+            self.update_mercurial_repo(
+                hg,
+                'https://hg.mozilla.org/hgcustom/version-control-tools',
+                self.vcs_tools_dir,
+                'default',
+                'Ensuring version-control-tools is up to date...')
+
+        # Look for and clean up old extensions.
+        for ext in {'bzexport',}:
+            path = os.path.join(self.ext_dir, ext)
+            if os.path.exists(path):
+                if self._prompt_yn('Would you like to remove the old and no '
+                    'longer referenced repository at %s' % path):
+                    print('Cleaning up old repository: %s' % path)
+                    shutil.rmtree(path)
+
         c.add_mozilla_host_fingerprints()
 
         b = StringIO()
         c.write(b)
         new_lines = [line.rstrip() for line in b.getvalue().splitlines()]
         old_lines = []
 
         config_path = c.config_path
--- a/widget/gonk/HwcComposer2D.cpp
+++ b/widget/gonk/HwcComposer2D.cpp
@@ -141,16 +141,33 @@ HwcComposer2D::ReallocLayerList()
         listrealloc->flags = 0;
     }
 
     mList = listrealloc;
     mMaxLayerCount += LAYER_COUNT_INCREMENTS;
     return true;
 }
 
+void
+HwcComposer2D::setCrop(HwcLayer* layer, hwc_rect_t srcCrop)
+{
+#if ANDROID_VERSION >= 19
+    if (mHwc->common.version >= HWC_DEVICE_API_VERSION_1_3) {
+        layer->sourceCropf.left = srcCrop.left;
+        layer->sourceCropf.top = srcCrop.top;
+        layer->sourceCropf.right = srcCrop.right;
+        layer->sourceCropf.bottom = srcCrop.bottom;
+    } else {
+        layer->sourceCrop = srcCrop;
+    }
+#else
+    layer->sourceCrop = srcCrop;
+#endif
+}
+
 bool
 HwcComposer2D::PrepareLayerList(Layer* aLayer,
                                 const nsIntRect& aClip,
                                 const gfxMatrix& aParentTransform,
                                 const gfxMatrix& aGLWorldTransform)
 {
     // NB: we fall off this path whenever there are container layers
     // that require intermediate surfaces.  That means all the
@@ -259,27 +276,29 @@ HwcComposer2D::PrepareLayerList(Layer* a
         } else {
             //Since the buffer doesn't have its own offset, assign the whole
             //surface size as its buffer bounds
             bufferRect = nsIntRect(0, 0, state.mSize.width, state.mSize.height);
         }
     }
 
     HwcLayer& hwcLayer = mList->hwLayers[current];
+    hwc_rect_t sourceCrop;
 
     if(!HwcUtils::PrepareLayerRects(visibleRect,
                           transform * aGLWorldTransform,
                           clip,
                           bufferRect,
-                          &(hwcLayer.sourceCrop),
+                          &(sourceCrop),
                           &(hwcLayer.displayFrame)))
     {
         return true;
     }
 
+    setCrop(&hwcLayer, sourceCrop);
     buffer_handle_t handle = fillColor ? nullptr : state.mSurface->getNativeBuffer()->handle;
     hwcLayer.handle = handle;
 
     hwcLayer.flags = 0;
     hwcLayer.hints = 0;
     hwcLayer.blending = HWC_BLENDING_PREMULT;
     if ((opacity == 0xFF) && (aLayer->GetContentFlags() & Layer::CONTENT_OPAQUE)) {
         hwcLayer.blending = HWC_BLENDING_NONE;
@@ -598,20 +617,20 @@ HwcComposer2D::Prepare(buffer_handle_t f
     mList->retireFenceFd = -1;
 
     mList->hwLayers[idx].hints = 0;
     mList->hwLayers[idx].flags = 0;
     mList->hwLayers[idx].transform = 0;
     mList->hwLayers[idx].handle = fbHandle;
     mList->hwLayers[idx].blending = HWC_BLENDING_PREMULT;
     mList->hwLayers[idx].compositionType = HWC_FRAMEBUFFER_TARGET;
-    mList->hwLayers[idx].sourceCrop = r;
+    setCrop(&mList->hwLayers[idx], r);
     mList->hwLayers[idx].displayFrame = r;
     mList->hwLayers[idx].visibleRegionScreen.numRects = 1;
-    mList->hwLayers[idx].visibleRegionScreen.rects = &mList->hwLayers[idx].sourceCrop;
+    mList->hwLayers[idx].visibleRegionScreen.rects = &mList->hwLayers[idx].displayFrame;
     mList->hwLayers[idx].acquireFenceFd = fence;
     mList->hwLayers[idx].releaseFenceFd = -1;
     mList->hwLayers[idx].planeAlpha = 0xFF;
 
     if (mPrepared) {
         LOGE("Multiple hwc prepare calls!");
     }
     mHwc->prepare(mHwc, HWC_NUM_DISPLAY_TYPES, displays);
--- a/widget/gonk/HwcComposer2D.h
+++ b/widget/gonk/HwcComposer2D.h
@@ -65,16 +65,17 @@ public:
 private:
     void Reset();
     void Prepare(buffer_handle_t fbHandle, int fence);
     bool Commit();
     bool TryHwComposition();
     bool ReallocLayerList();
     bool PrepareLayerList(layers::Layer* aContainer, const nsIntRect& aClip,
           const gfxMatrix& aParentTransform, const gfxMatrix& aGLWorldTransform);
+    void setCrop(HwcLayer* layer, hwc_rect_t srcCrop);
 
     HwcDevice*              mHwc;
     HwcList*                mList;
     hwc_display_t           mDpy;
     hwc_surface_t           mSur;
     nsIntRect               mScreenRect;
     int                     mMaxLayerCount;
     bool                    mColorFill;
--- a/widget/gonk/libdisplay/GonkDisplayJB.cpp
+++ b/widget/gonk/libdisplay/GonkDisplayJB.cpp
@@ -244,20 +244,31 @@ GonkDisplayJB::Post(buffer_handle_t buf,
     /* hwc module checks displayFrame even though it shouldn't */
     mList->hwLayers[0].displayFrame = r;
     mList->hwLayers[1].compositionType = HWC_FRAMEBUFFER_TARGET;
     mList->hwLayers[1].hints = 0;
     mList->hwLayers[1].flags = 0;
     mList->hwLayers[1].handle = buf;
     mList->hwLayers[1].transform = 0;
     mList->hwLayers[1].blending = HWC_BLENDING_PREMULT;
+#if ANDROID_VERSION >= 19
+    if (mHwc->common.version >= HWC_DEVICE_API_VERSION_1_3) {
+        mList->hwLayers[1].sourceCropf.left = 0;
+        mList->hwLayers[1].sourceCropf.top = 0;
+        mList->hwLayers[1].sourceCropf.right = mWidth;
+        mList->hwLayers[1].sourceCropf.bottom = mHeight;
+    } else {
+        mList->hwLayers[1].sourceCrop = r;
+    }
+#else
     mList->hwLayers[1].sourceCrop = r;
+#endif
     mList->hwLayers[1].displayFrame = r;
     mList->hwLayers[1].visibleRegionScreen.numRects = 1;
-    mList->hwLayers[1].visibleRegionScreen.rects = &mList->hwLayers[1].sourceCrop;
+    mList->hwLayers[1].visibleRegionScreen.rects = &mList->hwLayers[1].displayFrame;
     mList->hwLayers[1].acquireFenceFd = fence;
     mList->hwLayers[1].releaseFenceFd = -1;
 #if ANDROID_VERSION == 18
     mList->hwLayers[1].planeAlpha = 0xFF;
 #endif
     mHwc->prepare(mHwc, HWC_NUM_DISPLAY_TYPES, displays);
     int err = mHwc->set(mHwc, HWC_NUM_DISPLAY_TYPES, displays);
     mFBSurface->setReleaseFenceFd(mList->hwLayers[1].releaseFenceFd);
--- a/xpcom/base/SystemMemoryReporter.cpp
+++ b/xpcom/base/SystemMemoryReporter.cpp
@@ -340,17 +340,17 @@ private:
       return NS_ERROR_FAILURE;
     }
 
     nsAutoCString name, description;
     ProcessSizeKind kind;
     GetReporterNameAndDescription(path, perms, name, description, &kind);
 
     while (true) {
-      size_t pss;
+      size_t pss = 0;
       nsresult rv = ParseMapBody(aFile, aProcessName, name, description,
                                  aHandleReport, aData, &pss);
       if (NS_FAILED(rv))
         break;
 
       // Increment the appropriate aProcessSizes values, and the total.
       aProcessSizes->mSizes[kind] += pss;
       *aTotalPss += pss;
--- a/xpcom/base/nsMemoryReporterManager.cpp
+++ b/xpcom/base/nsMemoryReporterManager.cpp
@@ -633,17 +633,17 @@ PageFaultsHardDistinguishedAmount(int64_
 class PageFaultsHardReporter MOZ_FINAL : public nsIMemoryReporter
 {
 public:
     NS_DECL_ISUPPORTS
 
     NS_METHOD CollectReports(nsIHandleReportCallback* aHandleReport,
                              nsISupports* aData)
     {
-        int64_t amount;
+        int64_t amount = 0;
         nsresult rv = PageFaultsHardDistinguishedAmount(&amount);
         NS_ENSURE_SUCCESS(rv, rv);
 
         return MOZ_COLLECT_REPORT(
             "page-faults-hard", KIND_OTHER, UNITS_COUNT_CUMULATIVE, amount,
 "The number of hard page faults (also known as 'major page faults') that have "
 "occurred since the process started.  A hard page fault occurs when a process "
 "tries to access a page which is not present in physical memory. The "
--- a/xpcom/tests/TestDeadlockDetector.cpp
+++ b/xpcom/tests/TestDeadlockDetector.cpp
@@ -119,17 +119,16 @@ public:
     void RunToCompletion(uint32_t aWaitMs)
     {
         PR_Close(mStdinfd);
 
         PRPollDesc pollfds[2];
         int32_t nfds;
         bool stdoutOpen = true, stderrOpen = true;
         char buf[4096];
-        int32_t len;
 
         PRIntervalTime now = PR_IntervalNow();
         PRIntervalTime deadline = now + PR_MillisecondsToInterval(aWaitMs);
 
         while ((stdoutOpen || stderrOpen) && now < deadline) {
             nfds = 0;
             if (stdoutOpen) {
                 pollfds[nfds].fd = mStdoutfd;
@@ -153,25 +152,23 @@ public:
                 return;
             }
 
             for (int32_t i = 0; i < nfds; ++i) {
                 if (!pollfds[i].out_flags)
                     continue;
 
                 bool isStdout = mStdoutfd == pollfds[i].fd;
-                
+                int32_t len = 0;
+
                 if (PR_POLL_READ & pollfds[i].out_flags) {
                     len = PR_Read(pollfds[i].fd, buf, sizeof(buf) - 1);
                     NS_ASSERTION(0 <= len, PR_ErrorToName(PR_GetError()));
                 }
-                else if (PR_POLL_HUP & pollfds[i].out_flags) {
-                    len = 0;
-                }
-                else {
+                else if (!(PR_POLL_HUP & pollfds[i].out_flags)) {
                     NS_ERROR(PR_ErrorToName(PR_GetError()));
                 }
 
                 if (0 < len) {
                     buf[len] = '\0';
                     if (isStdout)
                         mStdout += buf;
                     else