Merge m-c to fx-team
authorCarsten "Tomcat" Book <cbook@mozilla.com>
Wed, 16 Apr 2014 15:18:12 +0200
changeset 197401 88cb9ce0d69df84607f37573b0db6174c8f8d81d
parent 197400 ba0fc8bc4aa0261660509e4e8f202d4698989873 (current diff)
parent 197297 b735e618c2a860972197942f6680c941e3c9a67f (diff)
child 197402 449e835346b55f9e5ca5e05621ffbf35e7c0e394
push id3624
push userasasaki@mozilla.com
push dateMon, 09 Jun 2014 21:49:01 +0000
treeherdermozilla-beta@b1a5da15899a [default view] [failures only]
perfherder[talos] [build metrics] [platform microbench] (compared to previous push)
milestone31.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
--- a/b2g/config/emulator-ics/sources.xml
+++ b/b2g/config/emulator-ics/sources.xml
@@ -14,17 +14,17 @@
   <!--original fetch url was git://github.com/apitrace/-->
   <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="1ad48c4be51b279f7f63c1a13025b52fe087d231">
     <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="3d4b4b06475d2376bad23ac46da185cd48a68d17"/>
+  <project name="gaia.git" path="gaia" remote="mozillaorg" revision="37d029e584d79aeaca8d30474c394eddcdfade03"/>
   <project name="gonk-misc" path="gonk-misc" remote="b2g" revision="266bca6e60dad43e395f38b66edabe8bdc882334"/>
   <project name="rilproxy" path="rilproxy" remote="b2g" revision="827214fcf38d6569aeb5c6d6f31cb296d1f09272"/>
   <project name="platform_hardware_ril" path="hardware/ril" remote="b2g" revision="55bcc2d7e44dc805c24b57d1e783fc26e8a2ee86"/>
   <project name="platform_external_qemu" path="external/qemu" remote="b2g" revision="99a67a75855d8ca077018c819aedd90bf0447d9b"/>
   <project name="moztt" path="external/moztt" remote="b2g" revision="ce95d372e6d285725b96490afdaaf489ad8f9ca9"/>
   <project name="apitrace" path="external/apitrace" remote="apitrace" revision="8d6c36d74ba9aefbc8c3618fc93dd4907a0dbf5e"/>
   <!-- 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
@@ -12,17 +12,17 @@
   <!--original fetch url was https://git.mozilla.org/releases-->
   <remote fetch="https://git.mozilla.org/releases" name="mozillaorg"/>
   <!-- B2G specific things. -->
   <project name="platform_build" path="build" remote="b2g" revision="e6383e6e785cc3ea237e902beb1092f9aa88e29d">
     <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="3d4b4b06475d2376bad23ac46da185cd48a68d17"/>
+  <project name="gaia" path="gaia" remote="mozillaorg" revision="37d029e584d79aeaca8d30474c394eddcdfade03"/>
   <project name="gonk-misc" path="gonk-misc" remote="b2g" revision="266bca6e60dad43e395f38b66edabe8bdc882334"/>
   <project name="moztt" path="external/moztt" remote="b2g" revision="ce95d372e6d285725b96490afdaaf489ad8f9ca9"/>
   <project name="apitrace" path="external/apitrace" remote="apitrace" revision="8d6c36d74ba9aefbc8c3618fc93dd4907a0dbf5e"/>
   <project name="valgrind" path="external/valgrind" remote="b2g" revision="daa61633c32b9606f58799a3186395fd2bbb8d8c"/>
   <project name="vex" path="external/VEX" remote="b2g" revision="47f031c320888fe9f3e656602588565b52d43010"/>
   <!-- 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"/>
--- a/b2g/config/emulator-kk/sources.xml
+++ b/b2g/config/emulator-kk/sources.xml
@@ -10,17 +10,17 @@
   <!--original fetch url was git://codeaurora.org/-->
   <remote fetch="https://git.mozilla.org/external/caf" name="caf"/>
   <!--original fetch url was https://git.mozilla.org/releases-->
   <remote fetch="https://git.mozilla.org/releases" name="mozillaorg"/>
   <!-- B2G specific things. -->
   <project name="platform_build" path="build" remote="b2g" revision="52c909ccead537f8f9dbf634f3e6639078a8b0bd">
     <copyfile dest="Makefile" src="core/root.mk"/>
   </project>
-  <project name="gaia" path="gaia" remote="mozillaorg" revision="3d4b4b06475d2376bad23ac46da185cd48a68d17"/>
+  <project name="gaia" path="gaia" remote="mozillaorg" revision="37d029e584d79aeaca8d30474c394eddcdfade03"/>
   <project name="fake-libdvm" path="dalvik" remote="b2g" revision="d50ae982b19f42f0b66d08b9eb306be81687869f"/>
   <project name="gonk-misc" path="gonk-misc" remote="b2g" revision="266bca6e60dad43e395f38b66edabe8bdc882334"/>
   <project name="moztt" path="external/moztt" remote="b2g" revision="ce95d372e6d285725b96490afdaaf489ad8f9ca9"/>
   <project name="rilproxy" path="rilproxy" remote="b2g" revision="827214fcf38d6569aeb5c6d6f31cb296d1f09272"/>
   <project name="valgrind" path="external/valgrind" remote="b2g" revision="daa61633c32b9606f58799a3186395fd2bbb8d8c"/>
   <project name="vex" path="external/VEX" remote="b2g" revision="47f031c320888fe9f3e656602588565b52d43010"/>
   <project name="apitrace" path="external/apitrace" remote="apitrace" revision="8d6c36d74ba9aefbc8c3618fc93dd4907a0dbf5e"/>
   <!-- Stock Android things -->
--- a/b2g/config/emulator/sources.xml
+++ b/b2g/config/emulator/sources.xml
@@ -14,17 +14,17 @@
   <!--original fetch url was git://github.com/apitrace/-->
   <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="1ad48c4be51b279f7f63c1a13025b52fe087d231">
     <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="3d4b4b06475d2376bad23ac46da185cd48a68d17"/>
+  <project name="gaia.git" path="gaia" remote="mozillaorg" revision="37d029e584d79aeaca8d30474c394eddcdfade03"/>
   <project name="gonk-misc" path="gonk-misc" remote="b2g" revision="266bca6e60dad43e395f38b66edabe8bdc882334"/>
   <project name="rilproxy" path="rilproxy" remote="b2g" revision="827214fcf38d6569aeb5c6d6f31cb296d1f09272"/>
   <project name="platform_hardware_ril" path="hardware/ril" remote="b2g" revision="55bcc2d7e44dc805c24b57d1e783fc26e8a2ee86"/>
   <project name="platform_external_qemu" path="external/qemu" remote="b2g" revision="99a67a75855d8ca077018c819aedd90bf0447d9b"/>
   <project name="moztt" path="external/moztt" remote="b2g" revision="ce95d372e6d285725b96490afdaaf489ad8f9ca9"/>
   <project name="apitrace" path="external/apitrace" remote="apitrace" revision="8d6c36d74ba9aefbc8c3618fc93dd4907a0dbf5e"/>
   <!-- Stock Android things -->
   <project name="platform/abi/cpp" path="abi/cpp" revision="dd924f92906085b831bf1cbbc7484d3c043d613c"/>
--- a/b2g/config/flame/sources.xml
+++ b/b2g/config/flame/sources.xml
@@ -13,17 +13,17 @@
   <remote fetch="https://git.mozilla.org/releases" name="mozillaorg"/>
   <!-- B2G specific things. -->
   <project name="platform_build" path="build" remote="b2g" revision="e6383e6e785cc3ea237e902beb1092f9aa88e29d">
     <copyfile dest="Makefile" src="core/root.mk"/>
   </project>
   <project name="rilproxy" path="rilproxy" remote="b2g" revision="827214fcf38d6569aeb5c6d6f31cb296d1f09272"/>
   <project name="librecovery" path="librecovery" remote="b2g" revision="1f6a1fe07f81c5bc5e1d079c9b60f7f78ca2bf4f"/>
   <project name="fake-libdvm" path="dalvik" remote="b2g" revision="d50ae982b19f42f0b66d08b9eb306be81687869f"/>
-  <project name="gaia" path="gaia" remote="mozillaorg" revision="3d4b4b06475d2376bad23ac46da185cd48a68d17"/>
+  <project name="gaia" path="gaia" remote="mozillaorg" revision="37d029e584d79aeaca8d30474c394eddcdfade03"/>
   <project name="gonk-misc" path="gonk-misc" remote="b2g" revision="266bca6e60dad43e395f38b66edabe8bdc882334"/>
   <project name="moztt" path="external/moztt" remote="b2g" revision="ce95d372e6d285725b96490afdaaf489ad8f9ca9"/>
   <project name="apitrace" path="external/apitrace" remote="apitrace" revision="8d6c36d74ba9aefbc8c3618fc93dd4907a0dbf5e"/>
   <project name="valgrind" path="external/valgrind" remote="b2g" revision="daa61633c32b9606f58799a3186395fd2bbb8d8c"/>
   <project name="vex" path="external/VEX" remote="b2g" revision="47f031c320888fe9f3e656602588565b52d43010"/>
   <!-- Stock Android things -->
   <project groups="linux" name="platform/prebuilts/clang/linux-x86/3.1" path="prebuilts/clang/linux-x86/3.1" revision="e95b4ce22c825da44d14299e1190ea39a5260bde"/>
   <project groups="linux" name="platform/prebuilts/clang/linux-x86/3.2" path="prebuilts/clang/linux-x86/3.2" revision="471afab478649078ad7c75ec6b252481a59e19b8"/>
--- a/b2g/config/gaia.json
+++ b/b2g/config/gaia.json
@@ -1,9 +1,9 @@
 {
     "git": {
         "git_revision": "", 
         "remote": "", 
         "branch": ""
     }, 
-    "revision": "b43fa272b6a254e7b15a79bb7771133a6d950c49", 
+    "revision": "f1f04d6c6f247e9a83960903e2f15774f07ca579", 
     "repo_path": "/integration/gaia-central"
 }
--- a/b2g/config/hamachi/sources.xml
+++ b/b2g/config/hamachi/sources.xml
@@ -12,17 +12,17 @@
   <!--original fetch url was git://github.com/apitrace/-->
   <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="1ad48c4be51b279f7f63c1a13025b52fe087d231">
     <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="3d4b4b06475d2376bad23ac46da185cd48a68d17"/>
+  <project name="gaia.git" path="gaia" remote="mozillaorg" revision="37d029e584d79aeaca8d30474c394eddcdfade03"/>
   <project name="gonk-misc" path="gonk-misc" remote="b2g" revision="266bca6e60dad43e395f38b66edabe8bdc882334"/>
   <project name="rilproxy" path="rilproxy" remote="b2g" revision="827214fcf38d6569aeb5c6d6f31cb296d1f09272"/>
   <project name="librecovery" path="librecovery" remote="b2g" revision="1f6a1fe07f81c5bc5e1d079c9b60f7f78ca2bf4f"/>
   <project name="moztt" path="external/moztt" remote="b2g" revision="ce95d372e6d285725b96490afdaaf489ad8f9ca9"/>
   <project name="apitrace" path="external/apitrace" remote="apitrace" revision="8d6c36d74ba9aefbc8c3618fc93dd4907a0dbf5e"/>
   <!-- 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
@@ -10,17 +10,17 @@
   <!--original fetch url was https://git.mozilla.org/releases-->
   <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="1ad48c4be51b279f7f63c1a13025b52fe087d231">
     <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="3d4b4b06475d2376bad23ac46da185cd48a68d17"/>
+  <project name="gaia.git" path="gaia" remote="mozillaorg" revision="37d029e584d79aeaca8d30474c394eddcdfade03"/>
   <project name="gonk-misc" path="gonk-misc" remote="b2g" revision="266bca6e60dad43e395f38b66edabe8bdc882334"/>
   <project name="rilproxy" path="rilproxy" remote="b2g" revision="827214fcf38d6569aeb5c6d6f31cb296d1f09272"/>
   <project name="librecovery" path="librecovery" remote="b2g" revision="1f6a1fe07f81c5bc5e1d079c9b60f7f78ca2bf4f"/>
   <project name="moztt" path="external/moztt" remote="b2g" revision="ce95d372e6d285725b96490afdaaf489ad8f9ca9"/>
   <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
@@ -14,17 +14,17 @@
   <!--original fetch url was git://github.com/apitrace/-->
   <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="1ad48c4be51b279f7f63c1a13025b52fe087d231">
     <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="3d4b4b06475d2376bad23ac46da185cd48a68d17"/>
+  <project name="gaia.git" path="gaia" remote="mozillaorg" revision="37d029e584d79aeaca8d30474c394eddcdfade03"/>
   <project name="gonk-misc" path="gonk-misc" remote="b2g" revision="266bca6e60dad43e395f38b66edabe8bdc882334"/>
   <project name="rilproxy" path="rilproxy" remote="b2g" revision="827214fcf38d6569aeb5c6d6f31cb296d1f09272"/>
   <project name="librecovery" path="librecovery" remote="b2g" revision="1f6a1fe07f81c5bc5e1d079c9b60f7f78ca2bf4f"/>
   <project name="moztt" path="external/moztt" remote="b2g" revision="ce95d372e6d285725b96490afdaaf489ad8f9ca9"/>
   <project name="apitrace" path="external/apitrace" remote="apitrace" revision="8d6c36d74ba9aefbc8c3618fc93dd4907a0dbf5e"/>
   <!-- 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
@@ -12,17 +12,17 @@
   <!--original fetch url was git://github.com/apitrace/-->
   <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="1ad48c4be51b279f7f63c1a13025b52fe087d231">
     <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="3d4b4b06475d2376bad23ac46da185cd48a68d17"/>
+  <project name="gaia.git" path="gaia" remote="mozillaorg" revision="37d029e584d79aeaca8d30474c394eddcdfade03"/>
   <project name="gonk-misc" path="gonk-misc" remote="b2g" revision="266bca6e60dad43e395f38b66edabe8bdc882334"/>
   <project name="rilproxy" path="rilproxy" remote="b2g" revision="827214fcf38d6569aeb5c6d6f31cb296d1f09272"/>
   <project name="librecovery" path="librecovery" remote="b2g" revision="1f6a1fe07f81c5bc5e1d079c9b60f7f78ca2bf4f"/>
   <project name="moztt" path="external/moztt" remote="b2g" revision="ce95d372e6d285725b96490afdaaf489ad8f9ca9"/>
   <project name="apitrace" path="external/apitrace" remote="apitrace" revision="8d6c36d74ba9aefbc8c3618fc93dd4907a0dbf5e"/>
   <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
@@ -12,17 +12,17 @@
   <!--original fetch url was https://git.mozilla.org/releases-->
   <remote fetch="https://git.mozilla.org/releases" name="mozillaorg"/>
   <!-- B2G specific things. -->
   <project name="platform_build" path="build" remote="b2g" revision="e6383e6e785cc3ea237e902beb1092f9aa88e29d">
     <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="3d4b4b06475d2376bad23ac46da185cd48a68d17"/>
+  <project name="gaia" path="gaia" remote="mozillaorg" revision="37d029e584d79aeaca8d30474c394eddcdfade03"/>
   <project name="gonk-misc" path="gonk-misc" remote="b2g" revision="266bca6e60dad43e395f38b66edabe8bdc882334"/>
   <project name="moztt" path="external/moztt" remote="b2g" revision="ce95d372e6d285725b96490afdaaf489ad8f9ca9"/>
   <project name="apitrace" path="external/apitrace" remote="apitrace" revision="8d6c36d74ba9aefbc8c3618fc93dd4907a0dbf5e"/>
   <project name="valgrind" path="external/valgrind" remote="b2g" revision="daa61633c32b9606f58799a3186395fd2bbb8d8c"/>
   <project name="vex" path="external/VEX" remote="b2g" revision="47f031c320888fe9f3e656602588565b52d43010"/>
   <!-- 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"/>
--- a/b2g/config/wasabi/sources.xml
+++ b/b2g/config/wasabi/sources.xml
@@ -12,17 +12,17 @@
   <!--original fetch url was git://github.com/apitrace/-->
   <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="1ad48c4be51b279f7f63c1a13025b52fe087d231">
     <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="3d4b4b06475d2376bad23ac46da185cd48a68d17"/>
+  <project name="gaia.git" path="gaia" remote="mozillaorg" revision="37d029e584d79aeaca8d30474c394eddcdfade03"/>
   <project name="gonk-misc" path="gonk-misc" remote="b2g" revision="266bca6e60dad43e395f38b66edabe8bdc882334"/>
   <project name="rilproxy" path="rilproxy" remote="b2g" revision="827214fcf38d6569aeb5c6d6f31cb296d1f09272"/>
   <project name="librecovery" path="librecovery" remote="b2g" revision="1f6a1fe07f81c5bc5e1d079c9b60f7f78ca2bf4f"/>
   <project name="moztt" path="external/moztt" remote="b2g" revision="ce95d372e6d285725b96490afdaaf489ad8f9ca9"/>
   <project name="apitrace" path="external/apitrace" remote="apitrace" revision="8d6c36d74ba9aefbc8c3618fc93dd4907a0dbf5e"/>
   <project name="gonk-patches" path="patches" remote="b2g" revision="223a2421006e8f5da33f516f6891c87cae86b0f6"/>
   <!-- Stock Android things -->
   <project name="platform/abi/cpp" path="abi/cpp" revision="6426040f1be4a844082c9769171ce7f5341a5528"/>
--- a/browser/base/content/test/general/browser_devices_get_user_media.js
+++ b/browser/base/content/test/general/browser_devices_get_user_media.js
@@ -766,17 +766,17 @@ function test() {
       }
     }).then(finish, ex => {
      ok(false, "Unexpected Exception: " + ex);
      finish();
     });
   }, true);
   let rootDir = getRootDirectory(gTestPath)
   rootDir = rootDir.replace("chrome://mochitests/content/",
-                            "http://127.0.0.1:8888/");
+                            "https://example.com/");
   content.location = rootDir + "get_user_media.html";
 }
 
 
 function wait(time) {
   let deferred = Promise.defer();
   setTimeout(deferred.resolve, time);
   return deferred.promise;
--- a/browser/modules/webrtcUI.jsm
+++ b/browser/modules/webrtcUI.jsm
@@ -61,23 +61,24 @@ function getBrowserForWindow(aContentWin
   return aContentWindow.QueryInterface(Ci.nsIInterfaceRequestor)
                        .getInterface(Ci.nsIWebNavigation)
                        .QueryInterface(Ci.nsIDocShell)
                        .chromeEventHandler;
 }
 
 function handleRequest(aSubject, aTopic, aData) {
   let constraints = aSubject.getConstraints();
+  let secure = aSubject.isSecure;
   let contentWindow = Services.wm.getOuterWindowWithId(aSubject.windowID);
 
   contentWindow.navigator.mozGetUserMediaDevices(
     constraints,
     function (devices) {
       prompt(contentWindow, aSubject.callID, constraints.audio,
-             constraints.video || constraints.picture, devices);
+             constraints.video || constraints.picture, devices, secure);
     },
     function (error) {
       // bug 827146 -- In the future, the UI should catch NO_DEVICES_FOUND
       // and allow the user to plug in a device, instead of immediately failing.
       denyRequest(aSubject.callID, error);
     },
     aSubject.innerWindowID);
 }
@@ -86,17 +87,17 @@ function denyRequest(aCallID, aError) {
   let msg = null;
   if (aError) {
     msg = Cc["@mozilla.org/supports-string;1"].createInstance(Ci.nsISupportsString);
     msg.data = aError;
   }
   Services.obs.notifyObservers(msg, "getUserMedia:response:deny", aCallID);
 }
 
-function prompt(aContentWindow, aCallID, aAudioRequested, aVideoRequested, aDevices) {
+function prompt(aContentWindow, aCallID, aAudioRequested, aVideoRequested, aDevices, aSecure) {
   let audioDevices = [];
   let videoDevices = [];
   for (let device of aDevices) {
     device = device.QueryInterface(Ci.nsIMediaDevice);
     switch (device.type) {
       case "audio":
         if (aAudioRequested)
           audioDevices.push(device);
@@ -138,31 +139,34 @@ function prompt(aContentWindow, aCallID,
     callback: function() {}
   };
 
   let secondaryActions = [
     {
       label: stringBundle.getString("getUserMedia.always.label"),
       accessKey: stringBundle.getString("getUserMedia.always.accesskey"),
       callback: function () {
-        mainAction.callback(true);
+        // don't save unless secure load!
+        mainAction.callback(aSecure);
       }
     },
     {
       label: stringBundle.getString("getUserMedia.denyRequest.label"),
       accessKey: stringBundle.getString("getUserMedia.denyRequest.accesskey"),
       callback: function () {
         denyRequest(aCallID);
       }
     },
     {
       label: stringBundle.getString("getUserMedia.never.label"),
       accessKey: stringBundle.getString("getUserMedia.never.accesskey"),
       callback: function () {
         denyRequest(aCallID);
+	// Let someone save "Never" for http sites so that they can be stopped from
+	// bothering you with doorhangers
         let perms = Services.perms;
         if (audioDevices.length)
           perms.add(uri, "microphone", perms.DENY_ACTION);
         if (videoDevices.length)
           perms.add(uri, "camera", perms.DENY_ACTION);
       }
     }
   ];
--- a/content/base/src/nsContentList.cpp
+++ b/content/base/src/nsContentList.cpp
@@ -18,16 +18,17 @@
 #include "nsWrapperCacheInlines.h"
 #include "nsContentUtils.h"
 #include "nsCCUncollectableMarker.h"
 #include "nsGkAtoms.h"
 #include "mozilla/dom/HTMLCollectionBinding.h"
 #include "mozilla/dom/NodeListBinding.h"
 #include "mozilla/Likely.h"
 #include "nsGenericHTMLElement.h"
+#include "jsfriendapi.h"
 #include <algorithm>
 
 // Form related includes
 #include "nsIDOMHTMLFormElement.h"
 
 #include "pldhash.h"
 
 #ifdef DEBUG_CONTENT_LIST
@@ -548,18 +549,22 @@ nsContentList::NamedItem(const nsAString
       return content->AsElement();
     }
   }
 
   return nullptr;
 }
 
 void
-nsContentList::GetSupportedNames(nsTArray<nsString>& aNames)
+nsContentList::GetSupportedNames(unsigned aFlags, nsTArray<nsString>& aNames)
 {
+  if (!(aFlags & JSITER_HIDDEN)) {
+    return;
+  }
+
   BringSelfUpToDate(true);
 
   nsAutoTArray<nsIAtom*, 8> atoms;
   for (uint32_t i = 0; i < mElements.Length(); ++i) {
     nsIContent *content = mElements.ElementAt(i);
     nsGenericHTMLElement* el = nsGenericHTMLElement::FromContent(content);
     if (el) {
       // XXXbz should we be checking for particular tags here?  How
--- a/content/base/src/nsContentList.h
+++ b/content/base/src/nsContentList.h
@@ -275,17 +275,18 @@ public:
   virtual mozilla::dom::Element* GetElementAt(uint32_t index) MOZ_OVERRIDE;
   virtual mozilla::dom::Element*
   GetFirstNamedElement(const nsAString& aName, bool& aFound) MOZ_OVERRIDE
   {
     mozilla::dom::Element* item = NamedItem(aName, true);
     aFound = !!item;
     return item;
   }
-  virtual void GetSupportedNames(nsTArray<nsString>& aNames) MOZ_OVERRIDE;
+  virtual void GetSupportedNames(unsigned aFlags,
+                                 nsTArray<nsString>& aNames) MOZ_OVERRIDE;
 
   // nsContentList public methods
   NS_HIDDEN_(uint32_t) Length(bool aDoFlush);
   NS_HIDDEN_(nsIContent*) Item(uint32_t aIndex, bool aDoFlush);
   NS_HIDDEN_(mozilla::dom::Element*)
   NamedItem(const nsAString& aName, bool aDoFlush);
 
   // nsIMutationObserver
--- a/content/base/src/nsDOMAttributeMap.cpp
+++ b/content/base/src/nsDOMAttributeMap.cpp
@@ -212,16 +212,22 @@ nsDOMAttributeMap::NamedGetter(const nsA
   if (!ni) {
     return nullptr;
   }
 
   aFound = true;
   return GetAttribute(ni, false);
 }
 
+bool
+nsDOMAttributeMap::NameIsEnumerable(const nsAString& aName)
+{
+  return true;
+}
+
 Attr*
 nsDOMAttributeMap::GetNamedItem(const nsAString& aAttrName)
 {
   bool dummy;
   return NamedGetter(aAttrName, dummy);
 }
 
 NS_IMETHODIMP
--- a/content/base/src/nsDOMAttributeMap.h
+++ b/content/base/src/nsDOMAttributeMap.h
@@ -141,16 +141,17 @@ public:
   {
     return mContent;
   }
   virtual JSObject* WrapObject(JSContext* aCx) MOZ_OVERRIDE;
 
   // WebIDL
   Attr* GetNamedItem(const nsAString& aAttrName);
   Attr* NamedGetter(const nsAString& aAttrName, bool& aFound);
+  bool NameIsEnumerable(const nsAString& aName);
   already_AddRefed<Attr>
   SetNamedItem(Attr& aAttr, ErrorResult& aError)
   {
     return SetNamedItemInternal(aAttr, false, aError);
   }
   already_AddRefed<Attr>
   RemoveNamedItem(const nsAString& aName, ErrorResult& aError);
  
@@ -165,17 +166,17 @@ public:
   SetNamedItemNS(Attr& aNode, ErrorResult& aError)
   {
     return SetNamedItemInternal(aNode, true, aError);
   }
   already_AddRefed<Attr>
   RemoveNamedItemNS(const nsAString& aNamespaceURI, const nsAString& aLocalName,
                     ErrorResult& aError);
 
-  void GetSupportedNames(nsTArray<nsString>& aNames)
+  void GetSupportedNames(unsigned, nsTArray<nsString>& aNames)
   {
     // No supported names we want to show up in iteration.
   }
 
   size_t SizeOfIncludingThis(mozilla::MallocSizeOf aMallocSizeOf) const;
 
 private:
   nsCOMPtr<Element> mContent;
--- a/content/canvas/src/CanvasImageCache.cpp
+++ b/content/canvas/src/CanvasImageCache.cpp
@@ -2,18 +2,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/. */
 
 #include "CanvasImageCache.h"
 #include "nsIImageLoadingContent.h"
 #include "nsExpirationTracker.h"
 #include "imgIRequest.h"
-#include "gfxASurface.h"
-#include "gfxPoint.h"
 #include "mozilla/dom/Element.h"
 #include "nsTHashtable.h"
 #include "mozilla/dom/HTMLCanvasElement.h"
 #include "nsContentUtils.h"
 #include "mozilla/Preferences.h"
 #include "mozilla/gfx/2D.h"
 
 namespace mozilla {
--- a/content/canvas/src/CanvasImageCache.h
+++ b/content/canvas/src/CanvasImageCache.h
@@ -1,29 +1,28 @@
 /* -*- Mode: C++; 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/. */
 
 #ifndef CANVASIMAGECACHE_H_
 #define CANVASIMAGECACHE_H_
 
+#include "nsSize.h"
+
 namespace mozilla {
 namespace dom {
 class Element;
 class HTMLCanvasElement;
 } // namespace dom
 namespace gfx {
 class SourceSurface;
 } // namespace gfx
 } // namespace mozilla
 class imgIRequest;
-class gfxASurface;
-
-#include "gfxPoint.h"
 
 namespace mozilla {
 
 class CanvasImageCache {
   typedef mozilla::gfx::SourceSurface SourceSurface;
 public:
   /**
    * Notify that image element aImage was (or is about to be) drawn to aCanvas
--- a/content/canvas/src/WebGLContext.h
+++ b/content/canvas/src/WebGLContext.h
@@ -18,17 +18,16 @@
 #include "nsIDOMWebGLRenderingContext.h"
 #include "nsICanvasRenderingContextInternal.h"
 #include "mozilla/dom/HTMLCanvasElement.h"
 #include "nsWrapperCache.h"
 #include "nsIObserver.h"
 #include "nsLayoutUtils.h"
 
 #include "GLContextProvider.h"
-#include "gfxImageSurface.h"
 
 #include "mozilla/LinkedList.h"
 #include "mozilla/CheckedInt.h"
 #include "mozilla/Scoped.h"
 #include "mozilla/gfx/2D.h"
 
 #ifdef XP_MACOSX
 #include "ForceDiscreteGPUHelperCGL.h"
--- a/content/canvas/src/WebGLContextGL.cpp
+++ b/content/canvas/src/WebGLContextGL.cpp
@@ -15,17 +15,16 @@
 #include "WebGLShaderPrecisionFormat.h"
 #include "WebGLTexture.h"
 #include "WebGLExtensions.h"
 #include "WebGLVertexArray.h"
 
 #include "nsString.h"
 #include "nsDebug.h"
 
-#include "gfxImageSurface.h"
 #include "gfxContext.h"
 #include "gfxPlatform.h"
 #include "GLContext.h"
 
 #include "nsContentUtils.h"
 #include "nsError.h"
 #include "nsLayoutUtils.h"
 
--- a/content/canvas/src/WebGLContextValidate.cpp
+++ b/content/canvas/src/WebGLContextValidate.cpp
@@ -924,16 +924,29 @@ WebGLContext::ValidateCompTexImageDataSi
  */
 bool
 WebGLContext::ValidateTexImageSize(GLenum target, GLint level,
                                    GLint width, GLint height, GLint depth,
                                    WebGLTexImageFunc func)
 {
     MOZ_ASSERT(level >= 0, "level should already be validated");
 
+    /* Bug 966630: maxTextureSize >> level runs into "undefined"
+     * behaviour depending on ISA. For example, on Intel shifts
+     * amounts are mod 64 (in 64-bit mode on 64-bit dest) and mod 32
+     * otherwise. This means 16384 >> 0x10000001 == 8192 which isn't
+     * what would be expected. Make the required behaviour explicit by
+     * clamping to a shift of 31 bits if level is greater than that
+     * ammount. This will give 0 that if (!maxAllowedSize) is
+     * expecting.
+     */
+
+    if (level > 31)
+        level = 31;
+
     const GLuint maxTexImageSize = MaxTextureSizeForTarget(target) >> level;
     const bool isCubemapTarget = IsTexImageCubemapTarget(target);
 
     if (isCubemapTarget && width != height) {
         /* GL ES Version 2.0.25 - 3.7.1 Texture Image Specification
          *   "When the target parameter to TexImage2D is one of the
          *   six cube map two-dimensional image targets, the error
          *   INVALID_VALUE is generated if the width and height
--- a/content/html/content/public/nsIHTMLCollection.h
+++ b/content/html/content/public/nsIHTMLCollection.h
@@ -64,20 +64,25 @@ public:
   {
     bool dummy;
     return NamedGetter(aName, dummy);
   }
   mozilla::dom::Element* NamedGetter(const nsAString& aName, bool& aFound)
   {
     return GetFirstNamedElement(aName, aFound);
   }
+  bool NameIsEnumerable(const nsAString& aName)
+  {
+    return false;
+  }
   virtual mozilla::dom::Element*
   GetFirstNamedElement(const nsAString& aName, bool& aFound) = 0;
 
-  virtual void GetSupportedNames(nsTArray<nsString>& aNames) = 0;
+  virtual void GetSupportedNames(unsigned aFlags,
+                                 nsTArray<nsString>& aNames) = 0;
 
   JSObject* GetWrapperPreserveColor()
   {
     return GetWrapperPreserveColorInternal();
   }
   virtual JSObject* WrapObject(JSContext* aCx) = 0;
 protected:
   virtual JSObject* GetWrapperPreserveColorInternal() = 0;
--- a/content/html/content/src/HTMLCanvasElement.cpp
+++ b/content/html/content/src/HTMLCanvasElement.cpp
@@ -3,17 +3,16 @@
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #include "mozilla/dom/HTMLCanvasElement.h"
 
 #include "ImageEncoder.h"
 #include "jsapi.h"
 #include "jsfriendapi.h"
-#include "gfxImageSurface.h"
 #include "Layers.h"
 #include "mozilla/Base64.h"
 #include "mozilla/CheckedInt.h"
 #include "mozilla/dom/CanvasRenderingContext2D.h"
 #include "mozilla/dom/HTMLCanvasElementBinding.h"
 #include "mozilla/dom/UnionTypes.h"
 #include "mozilla/gfx/Rect.h"
 #include "mozilla/Preferences.h"
--- a/content/html/content/src/HTMLFormControlsCollection.cpp
+++ b/content/html/content/src/HTMLFormControlsCollection.cpp
@@ -12,16 +12,17 @@
 #include "mozilla/dom/HTMLFormControlsCollectionBinding.h"
 #include "mozilla/dom/HTMLFormElement.h"
 #include "mozilla/dom/UnionTypes.h"
 #include "nsGenericHTMLElement.h" // nsGenericHTMLFormElement
 #include "nsIDocument.h"
 #include "nsIDOMNode.h"
 #include "nsIDOMNodeList.h"
 #include "nsIFormControl.h"
+#include "jsfriendapi.h"
 
 namespace mozilla {
 namespace dom {
 
 /* static */ bool
 HTMLFormControlsCollection::ShouldBeInElements(nsIFormControl* aFormControl)
 {
   // For backwards compatibility (with 4.x and IE) we must not add
@@ -390,18 +391,23 @@ CollectNames(const nsAString& aName,
              nsISupports* /* unused */,
              void* aClosure)
 {
   static_cast<nsTArray<nsString>*>(aClosure)->AppendElement(aName);
   return PL_DHASH_NEXT;
 }
 
 void
-HTMLFormControlsCollection::GetSupportedNames(nsTArray<nsString>& aNames)
+HTMLFormControlsCollection::GetSupportedNames(unsigned aFlags,
+                                              nsTArray<nsString>& aNames)
 {
+  if (!(aFlags & JSITER_HIDDEN)) {
+    return;
+  }
+
   FlushPendingNotifications();
   // Just enumerate mNameLookupTable.  This won't guarantee order, but
   // that's OK, because the HTML5 spec doesn't define an order for
   // this enumeration.
   mNameLookupTable.EnumerateRead(CollectNames, &aNames);
 }
 
 /* virtual */ JSObject*
--- a/content/html/content/src/HTMLFormControlsCollection.h
+++ b/content/html/content/src/HTMLFormControlsCollection.h
@@ -49,17 +49,18 @@ public:
               Nullable<OwningNodeListOrElement>& aResult);
   void
   NamedItem(const nsAString& aName,
             Nullable<OwningNodeListOrElement>& aResult)
   {
     bool dummy;
     NamedGetter(aName, dummy, aResult);
   }
-  virtual void GetSupportedNames(nsTArray<nsString>& aNames);
+  virtual void GetSupportedNames(unsigned aFlags,
+                                 nsTArray<nsString>& aNames) MOZ_OVERRIDE;
 
   nsresult AddElementToTable(nsGenericHTMLFormElement* aChild,
                              const nsAString& aName);
   nsresult AddImageElementToTable(HTMLImageElement* aChild,
                                   const nsAString& aName);
   nsresult RemoveElementFromTable(nsGenericHTMLFormElement* aChild,
                                   const nsAString& aName);
   nsresult IndexOfControl(nsIFormControl* aControl,
--- a/content/html/content/src/HTMLFormElement.cpp
+++ b/content/html/content/src/HTMLFormElement.cpp
@@ -1429,18 +1429,24 @@ HTMLFormElement::NamedGetter(const nsASt
   if (result) {
     return result.forget();
   }
 
   aFound = false;
   return nullptr;
 }
 
+bool
+HTMLFormElement::NameIsEnumerable(const nsAString& aName)
+{
+  return true;
+}
+
 void
-HTMLFormElement::GetSupportedNames(nsTArray<nsString >& aRetval)
+HTMLFormElement::GetSupportedNames(unsigned, nsTArray<nsString >& aRetval)
 {
   // TODO https://www.w3.org/Bugs/Public/show_bug.cgi?id=22320
 }
 
 already_AddRefed<nsISupports>
 HTMLFormElement::FindNamedItem(const nsAString& aName,
                                nsWrapperCache** aCache)
 {
--- a/content/html/content/src/HTMLFormElement.h
+++ b/content/html/content/src/HTMLFormElement.h
@@ -390,17 +390,19 @@ public:
   }
 
   Element*
   IndexedGetter(uint32_t aIndex, bool &aFound);
 
   already_AddRefed<nsISupports>
   NamedGetter(const nsAString& aName, bool &aFound);
 
-  void GetSupportedNames(nsTArray<nsString >& aRetval);
+  bool NameIsEnumerable(const nsAString& aName);
+
+  void GetSupportedNames(unsigned, nsTArray<nsString >& aRetval);
 
   static int32_t
   CompareFormControlPosition(Element* aElement1, Element* aElement2,
                              const nsIContent* aForm);
 #ifdef DEBUG
   static void
   AssertDocumentOrder(const nsTArray<nsGenericHTMLFormElement*>& aControls,
                       nsIContent* aForm);
--- a/content/html/content/src/HTMLOptionsCollection.cpp
+++ b/content/html/content/src/HTMLOptionsCollection.cpp
@@ -23,16 +23,17 @@
 #include "nsIForm.h"
 #include "nsIFormProcessor.h"
 #include "nsIListControlFrame.h"
 #include "nsLayoutUtils.h"
 #include "nsMappedAttributes.h"
 #include "nsRuleData.h"
 #include "nsServiceManagerUtils.h"
 #include "nsStyleConsts.h"
+#include "jsfriendapi.h"
 
 namespace mozilla {
 namespace dom {
 
 HTMLOptionsCollection::HTMLOptionsCollection(HTMLSelectElement* aSelect)
 {
   SetIsDOMBinding();
 
@@ -275,18 +276,23 @@ HTMLOptionsCollection::NamedItem(const n
                                  nsIDOMNode** aReturn)
 {
   NS_IF_ADDREF(*aReturn = GetNamedItem(aName));
 
   return NS_OK;
 }
 
 void
-HTMLOptionsCollection::GetSupportedNames(nsTArray<nsString>& aNames)
+HTMLOptionsCollection::GetSupportedNames(unsigned aFlags,
+                                         nsTArray<nsString>& aNames)
 {
+  if (!(aFlags & JSITER_HIDDEN)) {
+    return;
+  }
+
   nsAutoTArray<nsIAtom*, 8> atoms;
   for (uint32_t i = 0; i < mElements.Length(); ++i) {
     HTMLOptionElement* content = mElements.ElementAt(i);
     if (content) {
       // Note: HasName means the names is exposed on the document,
       // which is false for options, so we don't check it here.
       const nsAttrValue* val = content->GetParsedAttr(nsGkAtoms::name);
       if (val && val->Type() == nsAttrValue::eAtom) {
--- a/content/html/content/src/HTMLOptionsCollection.h
+++ b/content/html/content/src/HTMLOptionsCollection.h
@@ -145,17 +145,18 @@ public:
   void Remove(int32_t aIndex, ErrorResult& aError);
   int32_t GetSelectedIndex(ErrorResult& aError);
   void SetSelectedIndex(int32_t aSelectedIndex, ErrorResult& aError);
   void IndexedSetter(uint32_t aIndex, nsIDOMHTMLOptionElement* aOption,
                      ErrorResult& aError)
   {
     aError = SetOption(aIndex, aOption);
   }
-  virtual void GetSupportedNames(nsTArray<nsString>& aNames) MOZ_OVERRIDE;
+  virtual void GetSupportedNames(unsigned aFlags,
+                                 nsTArray<nsString>& aNames) MOZ_OVERRIDE;
 
 private:
   /** The list of options (holds strong references).  This is infallible, so
    * various members such as InsertOptionAt are also infallible. */
   nsTArray<nsRefPtr<mozilla::dom::HTMLOptionElement> > mElements;
   /** The select element that contains this array */
   HTMLSelectElement* mSelect;
 };
--- a/content/html/content/src/HTMLPropertiesCollection.cpp
+++ b/content/html/content/src/HTMLPropertiesCollection.cpp
@@ -292,17 +292,17 @@ HTMLPropertiesCollection::CrawlSubtree(E
       } else {
         aContent = element->GetNextNode(aElement);
       }
     }
   }
 }
 
 void
-HTMLPropertiesCollection::GetSupportedNames(nsTArray<nsString>& aNames)
+HTMLPropertiesCollection::GetSupportedNames(unsigned, nsTArray<nsString>& aNames)
 {
   EnsureFresh();
   mNames->CopyList(aNames);
 }
 
 PropertyNodeList::PropertyNodeList(HTMLPropertiesCollection* aCollection,
                                    nsIContent* aParent, const nsAString& aName)
   : mName(aName),
--- a/content/html/content/src/HTMLPropertiesCollection.h
+++ b/content/html/content/src/HTMLPropertiesCollection.h
@@ -81,22 +81,27 @@ public:
     return nullptr;
   }
   PropertyNodeList* NamedItem(const nsAString& aName);
   PropertyNodeList* NamedGetter(const nsAString& aName, bool& aFound)
   {
     aFound = IsSupportedNamedProperty(aName);
     return aFound ? NamedItem(aName) : nullptr;
   }
+  bool NameIsEnumerable(const nsAString& aName)
+  {
+    return true;
+  }
   DOMStringList* Names()
   {
     EnsureFresh();
     return mNames;
   }
-  virtual void GetSupportedNames(nsTArray<nsString>& aNames) MOZ_OVERRIDE;
+  virtual void GetSupportedNames(unsigned,
+                                 nsTArray<nsString>& aNames) MOZ_OVERRIDE;
 
   NS_DECL_NSIDOMHTMLCOLLECTION
 
   NS_DECL_CYCLE_COLLECTING_ISUPPORTS
 
   NS_DECL_NSIMUTATIONOBSERVER_ATTRIBUTECHANGED
   NS_DECL_NSIMUTATIONOBSERVER_CONTENTAPPENDED
   NS_DECL_NSIMUTATIONOBSERVER_CONTENTINSERTED
--- a/content/html/content/src/HTMLTableElement.cpp
+++ b/content/html/content/src/HTMLTableElement.cpp
@@ -7,16 +7,17 @@
 #include "nsAttrValueInlines.h"
 #include "nsRuleData.h"
 #include "nsHTMLStyleSheet.h"
 #include "nsMappedAttributes.h"
 #include "mozilla/dom/UnionTypes.h"
 #include "mozilla/dom/HTMLCollectionBinding.h"
 #include "mozilla/dom/HTMLTableElementBinding.h"
 #include "nsContentUtils.h"
+#include "jsfriendapi.h"
 
 NS_IMPL_NS_NEW_HTML_ELEMENT(Table)
 
 namespace mozilla {
 namespace dom {
 
 /* ------------------------------ TableRowsCollection -------------------------------- */
 /**
@@ -36,17 +37,18 @@ public:
   virtual Element* GetElementAt(uint32_t aIndex);
   virtual nsINode* GetParentObject()
   {
     return mParent;
   }
 
   virtual Element*
   GetFirstNamedElement(const nsAString& aName, bool& aFound) MOZ_OVERRIDE;
-  virtual void GetSupportedNames(nsTArray<nsString>& aNames);
+  virtual void GetSupportedNames(unsigned aFlags,
+                                 nsTArray<nsString>& aNames) MOZ_OVERRIDE;
 
   NS_IMETHOD    ParentDestroyed();
 
   NS_DECL_CYCLE_COLLECTION_SCRIPT_HOLDER_CLASS(TableRowsCollection)
 
   // nsWrapperCache
   using nsWrapperCache::GetWrapperPreserveColor;
   virtual JSObject* WrapObject(JSContext* aCx) MOZ_OVERRIDE;
@@ -229,23 +231,28 @@ TableRowsCollection::GetFirstNamedElemen
     if (aFound) {
       return item;
     }
   );
   return nullptr;
 }
 
 void
-TableRowsCollection::GetSupportedNames(nsTArray<nsString>& aNames)
+TableRowsCollection::GetSupportedNames(unsigned aFlags,
+                                       nsTArray<nsString>& aNames)
 {
+  if (!(aFlags & JSITER_HIDDEN)) {
+    return;
+  }
+
   DO_FOR_EACH_ROWGROUP(
     nsTArray<nsString> names;
     nsCOMPtr<nsIHTMLCollection> coll = do_QueryInterface(rows);
     if (coll) {
-      coll->GetSupportedNames(names);
+      coll->GetSupportedNames(aFlags, names);
       for (uint32_t i = 0; i < names.Length(); ++i) {
         if (!aNames.Contains(names[i])) {
           aNames.AppendElement(names[i]);
         }
       }
     }
   );
 }
--- a/content/html/content/src/nsDOMStringMap.cpp
+++ b/content/html/content/src/nsDOMStringMap.cpp
@@ -86,16 +86,22 @@ nsDOMStringMap::NamedGetter(const nsAStr
   if (!DataPropToAttr(aProp, attr)) {
     found = false;
     return;
   }
 
   found = mElement->GetAttr(attr, aResult);
 }
 
+bool
+nsDOMStringMap::NameIsEnumerable(const nsAString& aName)
+{
+  return true;
+}
+
 void
 nsDOMStringMap::NamedSetter(const nsAString& aProp,
                             const nsAString& aValue,
                             ErrorResult& rv)
 {
   nsAutoString attr;
   if (!DataPropToAttr(aProp, attr)) {
     rv.Throw(NS_ERROR_DOM_SYNTAX_ERR);
@@ -138,17 +144,17 @@ nsDOMStringMap::NamedDeleter(const nsASt
   if (found) {
     mRemovingProp = true;
     mElement->UnsetAttr(kNameSpaceID_None, attrAtom, true);
     mRemovingProp = false;
   }
 }
 
 void
-nsDOMStringMap::GetSupportedNames(nsTArray<nsString>& aNames)
+nsDOMStringMap::GetSupportedNames(unsigned, nsTArray<nsString>& aNames)
 {
   uint32_t attrCount = mElement->GetAttrCount();
 
   // Iterate through all the attributes and add property
   // names corresponding to data attributes to return array.
   for (uint32_t i = 0; i < attrCount; ++i) {
     const nsAttrName* attrName = mElement->GetAttrNameAt(i);
     // Skip the ones that are not in the null namespace
--- a/content/html/content/src/nsDOMStringMap.h
+++ b/content/html/content/src/nsDOMStringMap.h
@@ -37,17 +37,18 @@ public:
 
   // WebIDL API
   virtual JSObject* WrapObject(JSContext *cx) MOZ_OVERRIDE;
   void NamedGetter(const nsAString& aProp, bool& found,
                    mozilla::dom::DOMString& aResult) const;
   void NamedSetter(const nsAString& aProp, const nsAString& aValue,
                    mozilla::ErrorResult& rv);
   void NamedDeleter(const nsAString& aProp, bool &found);
-  void GetSupportedNames(nsTArray<nsString>& aNames);
+  bool NameIsEnumerable(const nsAString& aName);
+  void GetSupportedNames(unsigned, nsTArray<nsString>& aNames);
 
   js::ExpandoAndGeneration mExpandoAndGeneration;
 
 private:
   virtual ~nsDOMStringMap();
 
 protected:
   nsRefPtr<nsGenericHTMLElement> mElement;
--- a/content/html/content/test/test_formelements.html
+++ b/content/html/content/test/test_formelements.html
@@ -27,34 +27,43 @@ https://bugzilla.mozilla.org/show_bug.cg
 
 /** Test for Bug 772869 **/
 var x = $("f").elements;
 x.something = "another";
 names = [];
 for (var name in x) {
   names.push(name);
 }
-is(names.length, 14, "Should have 14 items");
+is(names.length, 10, "Should have 10 enumerated names");
+is(names[0], "0", "Enum entry 1");
+is(names[1], "1", "Enum entry 2");
+is(names[2], "2", "Enum entry 3");
+is(names[3], "3", "Enum entry 4");
+is(names[4], "4", "Enum entry 5");
+is(names[5], "something", "Enum entry 6");
+is(names[6], "namedItem", "Enum entry 7");
+is(names[7], "item", "Enum entry 8");
+is(names[8], "@@iterator", "Enum entry 9");
+is(names[9], "length", "Enum entry 10");
+
+names = Object.getOwnPropertyNames(x);
+is(names.length, 10, "Should have 10 items");
 // Now sort entries 5 through 8, for comparison purposes.  We don't sort the
 // whole array, because we want to make sure the ordering between the parts
 // is correct
 temp = names.slice(5, 9);
 temp.sort();
 names.splice.bind(names, 5, 4).apply(null, temp);
-is(names.length, 14, "Should have still have 14 items");
+is(names.length, 10, "Should still have 10 items");
 is(names[0], "0", "Entry 1")
 is(names[1], "1", "Entry 2")
 is(names[2], "2", "Entry 3")
 is(names[3], "3", "Entry 4")
 is(names[4], "4", "Entry 5")
 is(names[5], "w", "Entry 6")
 is(names[6], "x", "Entry 7")
 is(names[7], "y", "Entry 8")
 is(names[8], "z", "Entry 9")
 is(names[9], "something", "Entry 10")
-is(names[10], "namedItem", "Entry 11")
-is(names[11], "item", "Entry 12")
-is(names[12], "@@iterator", "Entry 13")
-is(names[13], "length", "Entry 14")
 </script>
 </pre>
 </body>
 </html>
--- a/content/html/content/test/test_htmlcollection.html
+++ b/content/html/content/test/test_htmlcollection.html
@@ -19,30 +19,38 @@ https://bugzilla.mozilla.org/show_bug.cg
   <form class="foo" name="z" id="w"></form>
 </div>
 <pre id="test">
 <script type="application/javascript">
 
 /** Test for Bug 772869 **/
 var x = document.getElementsByClassName("foo");
 x.something = "another";
-names = [];
+var names = [];
 for (var name in x) {
   names.push(name);
 }
-is(names.length, 13, "Should have 13 items");
+is(names.length, 9, "Should have 9 enumerated names");
+is(names[0], "0", "Enum entry 1")
+is(names[1], "1", "Enum entry 2")
+is(names[2], "2", "Enum entry 3")
+is(names[3], "3", "Enum entry 4")
+is(names[4], "something", "Enum entry 5")
+is(names[5], "item", "Enum entry 6")
+is(names[6], "namedItem", "Enum entry 7")
+is(names[7], "@@iterator", "Enum entry 8")
+is(names[8], "length", "Enum entry 9")
+
+names = Object.getOwnPropertyNames(x);
+is(names.length, 9, "Should have 9 items");
 is(names[0], "0", "Entry 1")
 is(names[1], "1", "Entry 2")
 is(names[2], "2", "Entry 3")
 is(names[3], "3", "Entry 4")
 is(names[4], "x", "Entry 5")
 is(names[5], "y", "Entry 6")
 is(names[6], "z", "Entry 7")
 is(names[7], "w", "Entry 8")
 is(names[8], "something", "Entry 9")
-is(names[9], "item", "Entry 10")
-is(names[10], "namedItem", "Entry 11")
-is(names[11], "@@iterator", "Entry 12")
-is(names[12], "length", "Entry 13")
 </script>
 </pre>
 </body>
 </html>
--- a/content/html/content/test/test_named_options.html
+++ b/content/html/content/test/test_named_options.html
@@ -22,31 +22,41 @@ https://bugzilla.mozilla.org/show_bug.cg
 </div>
 <pre id="test">
 <script type="application/javascript">
 
 /** Test for Bug 772869 **/
 var opt = $("s").options;
 opt.loopy = "something"
 var names = Object.getOwnPropertyNames(opt);
-is(names.length, 9, "Should have eight entries");
+is(names.length, 9, "Should have nine entries");
 is(names[0], "0", "Entry 1")
 is(names[1], "1", "Entry 2")
 is(names[2], "2", "Entry 3")
 is(names[3], "3", "Entry 4")
 is(names[4], "x", "Entry 5")
 is(names[5], "y", "Entry 6")
 is(names[6], "z", "Entry 7")
 is(names[7], "w", "Entry 8")
 is(names[8], "loopy", "Entry 9")
 
 var names2 = [];
 for (var name in opt) {
   names2.push(name);
 }
-for (var i = 0; i < names.length; ++i) {
-  is(names2[i], names[i], "Correct entry at " + i);
-}
+is(names2.length, 12, "Should have twelve enumerated names");
+is(names2[0], "0", "Enum entry 1")
+is(names2[1], "1", "Enum entry 2")
+is(names2[2], "2", "Enum entry 3")
+is(names2[3], "3", "Enum entry 4")
+is(names2[4], "loopy", "Enum entry 5")
+is(names2[5], "add", "Enum entrry 6")
+is(names2[6], "remove", "Enum entry 7")
+is(names2[7], "length", "Enum entry 8")
+is(names2[8], "selectedIndex", "Enum entry 9")
+is(names2[9], "item", "Enum entry 10")
+is(names2[10], "namedItem", "Enum entry 11")
+is(names2[11], "@@iterator", "Enum entry 12")
 
 </script>
 </pre>
 </body>
 </html>
--- a/content/html/content/test/test_rowscollection.html
+++ b/content/html/content/test/test_rowscollection.html
@@ -29,32 +29,42 @@ https://bugzilla.mozilla.org/show_bug.cg
   </table>
 </div>
 <pre id="test">
 <script type="application/javascript">
 
 /** Test for Bug 772869 **/
 var x = $("f").rows;
 x.something = "another";
-names = [];
+var names = [];
 for (var name in x) {
   names.push(name);
 }
-is(names.length, 15, "Should have 15 items");
+is(names.length, 11, "Should have 11 enumerated names");
+is(names[0], "0", "Enum entry 1")
+is(names[1], "1", "Enum entry 2")
+is(names[2], "2", "Enum entry 3")
+is(names[3], "3", "Enum entry 4")
+is(names[4], "4", "Enum entry 5")
+is(names[5], "5", "Enum entry 6")
+is(names[6], "something", "Enum entry 7")
+is(names[7], "item", "Enum entry 8")
+is(names[8], "namedItem", "Enum entry 9")
+is(names[9], "@@iterator", "Enum entry 10")
+is(names[10], "length", "Enum entry 11")
+
+names = Object.getOwnPropertyNames(x);
+is(names.length, 11, "Should have 11 items");
 is(names[0], "0", "Entry 1")
 is(names[1], "1", "Entry 2")
 is(names[2], "2", "Entry 3")
 is(names[3], "3", "Entry 4")
 is(names[4], "4", "Entry 5")
 is(names[5], "5", "Entry 6")
 is(names[6], "x", "Entry 7")
 is(names[7], "y", "Entry 8")
 is(names[8], "z", "Entry 9")
 is(names[9], "w", "Entry 10")
 is(names[10], "something", "Entry 11")
-is(names[11], "item", "Entry 12")
-is(names[12], "namedItem", "Entry 13")
-is(names[13], "@@iterator", "Entry 14")
-is(names[14], "length", "Entry 15")
 </script>
 </pre>
 </body>
 </html>
--- a/content/html/document/src/nsHTMLDocument.cpp
+++ b/content/html/document/src/nsHTMLDocument.cpp
@@ -2259,29 +2259,35 @@ nsHTMLDocument::NamedGetter(JSContext* c
   if (!dom::WrapObject(cx, supp, cache, nullptr, &val)) {
     rv.Throw(NS_ERROR_OUT_OF_MEMORY);
     return nullptr;
   }
   aFound = true;
   return &val.toObject();
 }
 
+bool
+nsHTMLDocument::NameIsEnumerable(const nsAString& aName)
+{
+  return true;
+}
+
 static PLDHashOperator
 IdentifierMapEntryAddNames(nsIdentifierMapEntry* aEntry, void* aArg)
 {
   nsTArray<nsString>* aNames = static_cast<nsTArray<nsString>*>(aArg);
   if (aEntry->HasNameElement() ||
       aEntry->HasIdElementExposedAsHTMLDocumentProperty()) {
     aNames->AppendElement(aEntry->GetKey());
   }
   return PL_DHASH_NEXT;
 }
 
 void
-nsHTMLDocument::GetSupportedNames(nsTArray<nsString>& aNames)
+nsHTMLDocument::GetSupportedNames(unsigned, nsTArray<nsString>& aNames)
 {
   mIdentifierMap.EnumerateEntries(IdentifierMapEntryAddNames, &aNames);
 }
 
 //----------------------------
 
 // forms related stuff
 
--- a/content/html/document/src/nsHTMLDocument.h
+++ b/content/html/document/src/nsHTMLDocument.h
@@ -169,17 +169,18 @@ public:
   virtual JSObject* WrapNode(JSContext* aCx)
     MOZ_OVERRIDE;
   void GetDomain(nsAString& aDomain, mozilla::ErrorResult& rv);
   void SetDomain(const nsAString& aDomain, mozilla::ErrorResult& rv);
   void GetCookie(nsAString& aCookie, mozilla::ErrorResult& rv);
   void SetCookie(const nsAString& aCookie, mozilla::ErrorResult& rv);
   JSObject* NamedGetter(JSContext* cx, const nsAString& aName, bool& aFound,
                         mozilla::ErrorResult& rv);
-  void GetSupportedNames(nsTArray<nsString>& aNames);
+  bool NameIsEnumerable(const nsAString& aName);
+  void GetSupportedNames(unsigned, nsTArray<nsString>& aNames);
   nsGenericHTMLElement *GetBody();
   void SetBody(nsGenericHTMLElement* aBody, mozilla::ErrorResult& rv);
   mozilla::dom::HTMLSharedElement *GetHead() {
     return static_cast<mozilla::dom::HTMLSharedElement*>(GetHeadElement());
   }
   nsIHTMLCollection* Images();
   nsIHTMLCollection* Embeds();
   nsIHTMLCollection* Plugins();
--- a/dom/base/Console.cpp
+++ b/dom/base/Console.cpp
@@ -502,19 +502,17 @@ NS_IMPL_CYCLE_COLLECTION_TRACE_BEGIN(Con
 
   for (ConsoleCallData* data = tmp->mQueuedCalls.getFirst(); data != nullptr;
        data = data->getNext()) {
     if (data->mGlobal) {
       aCallbacks.Trace(&data->mGlobal, "data->mGlobal", aClosure);
     }
 
     for (uint32_t i = 0; i < data->mArguments.Length(); ++i) {
-      if (JSVAL_IS_TRACEABLE(data->mArguments[i])) {
-        aCallbacks.Trace(&data->mArguments[i], "data->mArguments[i]", aClosure);
-      }
+      aCallbacks.Trace(&data->mArguments[i], "data->mArguments[i]", aClosure);
     }
   }
 
 NS_IMPL_CYCLE_COLLECTION_TRACE_END
 
 NS_IMPL_CYCLE_COLLECTING_ADDREF(Console)
 NS_IMPL_CYCLE_COLLECTING_RELEASE(Console)
 
--- a/dom/base/URL.h
+++ b/dom/base/URL.h
@@ -34,21 +34,16 @@ class URL MOZ_FINAL : public URLSearchPa
 {
 public:
   NS_DECL_CYCLE_COLLECTING_ISUPPORTS
   NS_DECL_CYCLE_COLLECTION_CLASS(URL)
 
   URL(nsIURI* aURI);
 
   // WebIDL methods
-  nsISupports* GetParentObject() const
-  {
-    return nullptr;
-  }
-
   JSObject*
   WrapObject(JSContext* aCx);
 
   static already_AddRefed<URL>
   Constructor(const GlobalObject& aGlobal, const nsAString& aUrl,
               URL& aBase, ErrorResult& aRv);
   static already_AddRefed<URL>
   Constructor(const GlobalObject& aGlobal, const nsAString& aUrl,
--- a/dom/base/WindowNamedPropertiesHandler.cpp
+++ b/dom/base/WindowNamedPropertiesHandler.cpp
@@ -163,35 +163,36 @@ WindowNamedPropertiesHandler::defineProp
 {
   ErrorResult rv;
   rv.ThrowTypeError(MSG_DEFINEPROPERTY_ON_GSP);
   rv.ReportTypeError(aCx);
   return false;
 }
 
 bool
-WindowNamedPropertiesHandler::getOwnPropertyNames(JSContext* aCx,
-                                                  JS::Handle<JSObject*> aProxy,
-                                                  JS::AutoIdVector& aProps)
+WindowNamedPropertiesHandler::ownPropNames(JSContext* aCx,
+                                           JS::Handle<JSObject*> aProxy,
+                                           unsigned flags,
+                                           JS::AutoIdVector& aProps)
 {
   // Grab the DOM window.
   nsGlobalWindow* win = GetWindowFromGlobal(JS_GetGlobalForObject(aCx, aProxy));
   nsTArray<nsString> names;
   win->GetSupportedNames(names);
   if (!AppendNamedPropertyIds(aCx, aProxy, names, false, aProps)) {
     return false;
   }
 
   names.Clear();
   nsCOMPtr<nsIHTMLDocument> htmlDoc = do_QueryInterface(win->GetExtantDoc());
   if (!htmlDoc) {
     return true;
   }
   nsHTMLDocument* document = static_cast<nsHTMLDocument*>(htmlDoc.get());
-  document->GetSupportedNames(names);
+  document->GetSupportedNames(flags, names);
 
   JS::AutoIdVector docProps(aCx);
   if (!AppendNamedPropertyIds(aCx, aProxy, names, false, docProps)) {
     return false;
   }
 
   return js::AppendUnique(aCx, aProps, docProps);
 }
--- a/dom/base/WindowNamedPropertiesHandler.h
+++ b/dom/base/WindowNamedPropertiesHandler.h
@@ -32,18 +32,18 @@ public:
                            JS::Handle<jsid> aId,
                            JS::MutableHandle<JSPropertyDescriptor> aDesc,
                            unsigned aFlags) MOZ_OVERRIDE;
   virtual bool
   defineProperty(JSContext* aCx, JS::Handle<JSObject*> aProxy,
                  JS::Handle<jsid> aId,
                  JS::MutableHandle<JSPropertyDescriptor> aDesc) MOZ_OVERRIDE;
   virtual bool
-  getOwnPropertyNames(JSContext* aCx, JS::Handle<JSObject*> aProxy,
-                      JS::AutoIdVector& aProps) MOZ_OVERRIDE;
+  ownPropNames(JSContext* aCx, JS::Handle<JSObject*> aProxy, unsigned flags,
+               JS::AutoIdVector& aProps) MOZ_OVERRIDE;
   virtual bool
   delete_(JSContext* aCx, JS::Handle<JSObject*> aProxy, JS::Handle<jsid> aId,
           bool* aBp) MOZ_OVERRIDE;
   virtual bool
   isExtensible(JSContext* aCx, JS::Handle<JSObject*> aProxy,
                bool* aIsExtensible) MOZ_OVERRIDE
   {
     *aIsExtensible = true;
--- a/dom/base/nsDOMWindowUtils.cpp
+++ b/dom/base/nsDOMWindowUtils.cpp
@@ -37,17 +37,16 @@
 #include "mozilla/MiscEvents.h"
 #include "mozilla/MouseEvents.h"
 #include "mozilla/TextEvents.h"
 #include "mozilla/TouchEvents.h"
 
 #include "nsViewManager.h"
 
 #include "nsIDOMHTMLCanvasElement.h"
-#include "gfxImageSurface.h"
 #include "nsLayoutUtils.h"
 #include "nsComputedDOMStyle.h"
 #include "nsIPresShell.h"
 #include "nsStyleAnimation.h"
 #include "nsCSSProps.h"
 #include "nsDOMFile.h"
 #include "nsTArrayHelpers.h"
 #include "nsIDocShell.h"
--- a/dom/base/nsMimeTypeArray.cpp
+++ b/dom/base/nsMimeTypeArray.cpp
@@ -168,26 +168,32 @@ nsMimeTypeArray::NamedGetter(const nsASt
   // We don't want navigator.mimeTypes enumeration to expose MIME types with
   // application handlers, so add them to the list of hidden MIME types.
   nsMimeType *mt = new nsMimeType(mWindow, lowerName);
   mHiddenMimeTypes.AppendElement(mt);
 
   return mt;
 }
 
+bool
+nsMimeTypeArray::NameIsEnumerable(const nsAString& aName)
+{
+  return true;
+}
+
 uint32_t
 nsMimeTypeArray::Length()
 {
   EnsurePluginMimeTypes();
 
   return mMimeTypes.Length();
 }
 
 void
-nsMimeTypeArray::GetSupportedNames(nsTArray< nsString >& aRetval)
+nsMimeTypeArray::GetSupportedNames(unsigned, nsTArray< nsString >& aRetval)
 {
   EnsurePluginMimeTypes();
 
   for (uint32_t i = 0; i < mMimeTypes.Length(); ++i) {
     aRetval.AppendElement(mMimeTypes[i]->Type());
   }
 }
 
--- a/dom/base/nsMimeTypeArray.h
+++ b/dom/base/nsMimeTypeArray.h
@@ -31,18 +31,19 @@ public:
 
   void Refresh();
 
   // MimeTypeArray WebIDL methods
   nsMimeType* Item(uint32_t index);
   nsMimeType* NamedItem(const nsAString& name);
   nsMimeType* IndexedGetter(uint32_t index, bool &found);
   nsMimeType* NamedGetter(const nsAString& name, bool &found);
+  bool NameIsEnumerable(const nsAString& name);
   uint32_t Length();
-  void GetSupportedNames(nsTArray< nsString >& retval);
+  void GetSupportedNames(unsigned, nsTArray< nsString >& retval);
 
 protected:
   void EnsurePluginMimeTypes();
   void Clear();
 
   nsCOMPtr<nsPIDOMWindow> mWindow;
 
   // mMimeTypes contains MIME types handled by non-hidden plugins, those
--- a/dom/base/nsPluginArray.cpp
+++ b/dom/base/nsPluginArray.cpp
@@ -217,30 +217,36 @@ nsPluginArray::NamedGetter(const nsAStri
   if (!plugin) {
     plugin = FindPlugin(mHiddenPlugins, aName);
   }
 
   aFound = (plugin != nullptr);
   return plugin;
 }
 
+bool
+nsPluginArray::NameIsEnumerable(const nsAString& aName)
+{
+  return true;
+}
+
 uint32_t
 nsPluginArray::Length()
 {
   if (!AllowPlugins()) {
     return 0;
   }
 
   EnsurePlugins();
 
   return mPlugins.Length();
 }
 
 void
-nsPluginArray::GetSupportedNames(nsTArray< nsString >& aRetval)
+nsPluginArray::GetSupportedNames(unsigned, nsTArray<nsString>& aRetval)
 {
   aRetval.Clear();
 
   if (!AllowPlugins()) {
     return;
   }
 
   for (uint32_t i = 0; i < mPlugins.Length(); ++i) {
@@ -435,26 +441,32 @@ nsPluginElement::NamedGetter(const nsASt
 
       return mMimeTypes[i];
     }
   }
 
   return nullptr;
 }
 
+bool
+nsPluginElement::NameIsEnumerable(const nsAString& aName)
+{
+  return true;
+}
+
 uint32_t
 nsPluginElement::Length()
 {
   EnsurePluginMimeTypes();
 
   return mMimeTypes.Length();
 }
 
 void
-nsPluginElement::GetSupportedNames(nsTArray< nsString >& retval)
+nsPluginElement::GetSupportedNames(unsigned, nsTArray<nsString>& retval)
 {
   EnsurePluginMimeTypes();
 
   for (uint32_t i = 0; i < mMimeTypes.Length(); ++i) {
     retval.AppendElement(mMimeTypes[i]->Type());
   }
 }
 
--- a/dom/base/nsPluginArray.h
+++ b/dom/base/nsPluginArray.h
@@ -47,18 +47,19 @@ public:
 
   // PluginArray WebIDL methods
 
   nsPluginElement* Item(uint32_t aIndex);
   nsPluginElement* NamedItem(const nsAString& aName);
   void Refresh(bool aReloadDocuments);
   nsPluginElement* IndexedGetter(uint32_t aIndex, bool &aFound);
   nsPluginElement* NamedGetter(const nsAString& aName, bool &aFound);
+  bool NameIsEnumerable(const nsAString& aName);
   uint32_t Length();
-  void GetSupportedNames(nsTArray< nsString >& aRetval);
+  void GetSupportedNames(unsigned, nsTArray<nsString>& aRetval);
 
 private:
   bool AllowPlugins() const;
   void EnsurePlugins();
 
   nsCOMPtr<nsPIDOMWindow> mWindow;
 
   // Many sites check whether a particular plugin is installed by enumerating
@@ -96,18 +97,19 @@ public:
   void GetDescription(nsString& retval) const;
   void GetFilename(nsString& retval) const;
   void GetVersion(nsString& retval) const;
   void GetName(nsString& retval) const;
   nsMimeType* Item(uint32_t index);
   nsMimeType* NamedItem(const nsAString& name);
   nsMimeType* IndexedGetter(uint32_t index, bool &found);
   nsMimeType* NamedGetter(const nsAString& name, bool &found);
+  bool NameIsEnumerable(const nsAString& aName);
   uint32_t Length();
-  void GetSupportedNames(nsTArray< nsString >& retval);
+  void GetSupportedNames(unsigned, nsTArray<nsString>& retval);
 
   nsTArray<nsRefPtr<nsMimeType> >& MimeTypes();
 
 protected:
   void EnsurePluginMimeTypes();
 
   nsCOMPtr<nsPIDOMWindow> mWindow;
   nsRefPtr<nsPluginTag> mPluginTag;
--- a/dom/bindings/Codegen.py
+++ b/dom/bindings/Codegen.py
@@ -774,17 +774,17 @@ class CGIfElseWrapper(CGList):
         CGList.__init__(self, kids)
 
 
 class CGTemplatedType(CGWrapper):
     def __init__(self, templateName, child, isConst=False, isReference=False):
         const = "const " if isConst else ""
         pre = "%s%s<" % (const, templateName)
         ref = "&" if isReference else ""
-        post = " >%s" % ref
+        post = ">%s" % ref
         CGWrapper.__init__(self, child, pre=pre, post=post)
 
 
 class CGNamespace(CGWrapper):
     def __init__(self, namespace, child, declareOnly=False):
         pre = "namespace %s {\n" % namespace
         post = "} // namespace %s\n" % namespace
         CGWrapper.__init__(self, child, pre=pre, post=post,
@@ -8763,17 +8763,18 @@ class CGProxyUnwrap(CGAbstractMethod):
 
 
 class CGDOMJSProxyHandler_getOwnPropertyDescriptor(ClassMethod):
     def __init__(self, descriptor):
         args = [Argument('JSContext*', 'cx'), Argument('JS::Handle<JSObject*>', 'proxy'),
                 Argument('JS::Handle<jsid>', 'id'),
                 Argument('JS::MutableHandle<JSPropertyDescriptor>', 'desc'),
                 Argument('unsigned', 'flags')]
-        ClassMethod.__init__(self, "getOwnPropertyDescriptor", "bool", args)
+        ClassMethod.__init__(self, "getOwnPropertyDescriptor", "bool", args,
+                             virtual=True, override=True)
         self.descriptor = descriptor
 
     def getBody(self):
         indexedGetter = self.descriptor.operations['IndexedGetter']
         indexedSetter = self.descriptor.operations['IndexedSetter']
 
         setOrIndexedGet = "bool isXray = xpc::WrapperFactory::IsXrayWrapper(proxy);\n"
         if self.descriptor.supportsIndexedProperties():
@@ -8842,18 +8843,27 @@ MOZ_ASSERT_IF(desc.object(), desc.object
         else:
             if indexedGetter:
                 setOrIndexedGet += ("if (!(flags & JSRESOLVE_ASSIGNING)) {\n" +
                                     CGIndenter(CGGeneric(get)).define() +
                                     "}\n\n")
             setOrIndexedGet += getUnforgeable
 
         if self.descriptor.supportsNamedProperties():
-            readonly = toStringBool(self.descriptor.operations['NamedSetter'] is None)
-            fillDescriptor = "FillPropertyDescriptor(desc, proxy, %s);\nreturn true;" % readonly
+            operations = self.descriptor.operations
+            readonly = toStringBool(operations['NamedSetter'] is None)
+            enumerable = (
+                "self->NameIsEnumerable(Constify(%s))" %
+                # First [0] means first (and only) signature, [1] means
+                # "arguments" as opposed to return type, [0] means first (and
+                # only) argument.
+                operations['NamedGetter'].signatures()[0][1][0].identifier.name)
+            fillDescriptor = (
+                "FillPropertyDescriptor(desc, proxy, %s, %s);\n"
+                "return true;" % (readonly, enumerable))
             templateValues = {'jsvalRef': 'desc.value()', 'jsvalHandle': 'desc.value()',
                               'obj': 'proxy', 'successCode': fillDescriptor}
             condition = "!HasPropertyOnPrototype(cx, proxy, id)"
             if self.descriptor.interface.getExtendedAttribute('OverrideBuiltins'):
                 condition = "(!isXray || %s)" % condition
             condition = "!(flags & JSRESOLVE_ASSIGNING) && " + condition
             if self.descriptor.supportsIndexedProperties():
                 condition = "!IsArrayIndex(index) && " + condition
@@ -8941,17 +8951,18 @@ class CGDOMJSProxyHandler_defineProperty
         return set
 
 
 class CGDOMJSProxyHandler_delete(ClassMethod):
     def __init__(self, descriptor):
         args = [Argument('JSContext*', 'cx'), Argument('JS::Handle<JSObject*>', 'proxy'),
                 Argument('JS::Handle<jsid>', 'id'),
                 Argument('bool*', 'bp')]
-        ClassMethod.__init__(self, "delete_", "bool", args)
+        ClassMethod.__init__(self, "delete_", "bool", args,
+                             virtual=True, override=True)
         self.descriptor = descriptor
 
     def getBody(self):
         def getDeleterBody(type):
             """
             type should be "Named" or "Indexed"
             """
             assert type is "Named" or type is "Indexed"
@@ -9020,22 +9031,24 @@ class CGDOMJSProxyHandler_delete(ClassMe
                                      "!HasPropertyOnPrototype(cx, proxy, id)").define()
         delete += """
 
 return dom::DOMProxyHandler::delete_(cx, proxy, id, bp);"""
 
         return delete
 
 
-class CGDOMJSProxyHandler_getOwnPropertyNames(ClassMethod):
-    def __init__(self, descriptor):
+class CGDOMJSProxyHandler_ownPropNames(ClassMethod):
+    def __init__(self, descriptor, ):
         args = [Argument('JSContext*', 'cx'),
                 Argument('JS::Handle<JSObject*>', 'proxy'),
+                Argument('unsigned', 'flags'),
                 Argument('JS::AutoIdVector&', 'props')]
-        ClassMethod.__init__(self, "getOwnPropertyNames", "bool", args)
+        ClassMethod.__init__(self, "ownPropNames", "bool", args,
+                             virtual=True, override=True)
         self.descriptor = descriptor
 
     def getBody(self):
         # Per spec, we do indices, then named props, then everything else
         if self.descriptor.supportsIndexedProperties():
             addIndices = """
 uint32_t length = UnwrapProxy(proxy)->Length();
 MOZ_ASSERT(int32_t(length) >= 0);
@@ -9050,52 +9063,53 @@ for (int32_t i = 0; i < int32_t(length);
 
         if self.descriptor.supportsNamedProperties():
             if self.descriptor.interface.getExtendedAttribute('OverrideBuiltins'):
                 shadow = "!isXray"
             else:
                 shadow = "false"
             addNames = """
 nsTArray<nsString> names;
-UnwrapProxy(proxy)->GetSupportedNames(names);
+UnwrapProxy(proxy)->GetSupportedNames(flags, names);
 if (!AppendNamedPropertyIds(cx, proxy, names, %s, props)) {
   return false;
 }
 """ % shadow
         else:
             addNames = ""
 
         if UseHolderForUnforgeable(self.descriptor):
             addUnforgeable = (
-                "if (!js::GetPropertyNames(cx, ${holder}, JSITER_OWNONLY | JSITER_HIDDEN, &props)) {\n"
+                "if (!js::GetPropertyNames(cx, ${holder}, flags, &props)) {\n"
                 "  return false;\n"
                 "}")
             addUnforgeable = CallOnUnforgeableHolder(self.descriptor,
                                                      addUnforgeable,
                                                      "isXray")
         else:
             addUnforgeable = ""
         return """bool isXray = xpc::WrapperFactory::IsXrayWrapper(proxy);
 """ + addIndices + addUnforgeable + addNames + """
 JS::Rooted<JSObject*> expando(cx);
 if (!isXray && (expando = DOMProxyHandler::GetExpandoObject(proxy)) &&
-    !js::GetPropertyNames(cx, expando, JSITER_OWNONLY | JSITER_HIDDEN, &props)) {
+    !js::GetPropertyNames(cx, expando, flags, &props)) {
   return false;
 }
 
 return true;"""
 
 
 class CGDOMJSProxyHandler_hasOwn(ClassMethod):
     def __init__(self, descriptor):
         args = [Argument('JSContext*', 'cx'),
                 Argument('JS::Handle<JSObject*>', 'proxy'),
                 Argument('JS::Handle<jsid>', 'id'),
                 Argument('bool*', 'bp')]
-        ClassMethod.__init__(self, "hasOwn", "bool", args)
+        ClassMethod.__init__(self, "hasOwn", "bool", args,
+                             virtual=True, override=True)
         self.descriptor = descriptor
 
     def getBody(self):
         if self.descriptor.supportsIndexedProperties():
             indexed = ("int32_t index = GetArrayIndexFromId(cx, id);\n" +
                        "if (IsArrayIndex(index)) {\n" +
                        CGIndenter(CGProxyIndexedPresenceChecker(self.descriptor)).define() + "\n" +
                        "  *bp = found;\n" +
@@ -9148,17 +9162,18 @@ return true;"""
 
 class CGDOMJSProxyHandler_get(ClassMethod):
     def __init__(self, descriptor):
         args = [Argument('JSContext*', 'cx'),
                 Argument('JS::Handle<JSObject*>', 'proxy'),
                 Argument('JS::Handle<JSObject*>', 'receiver'),
                 Argument('JS::Handle<jsid>', 'id'),
                 Argument('JS::MutableHandle<JS::Value>', 'vp')]
-        ClassMethod.__init__(self, "get", "bool", args)
+        ClassMethod.__init__(self, "get", "bool", args,
+                             virtual=True, override=True)
         self.descriptor = descriptor
 
     def getBody(self):
         getUnforgeableOrExpando = "JS::Rooted<JSObject*> sharedRoot(cx);\n"
         if UseHolderForUnforgeable(self.descriptor):
             hasUnforgeable = (
                 "bool hasUnforgeable;\n"
                 "if (!JS_AlreadyHasOwnPropertyById(cx, ${holder}, id, &hasUnforgeable)) {\n"
@@ -9243,27 +9258,29 @@ class CGDOMJSProxyHandler_className(Clas
 
     def getBody(self):
         return 'return "%s";' % self.descriptor.name
 
 
 class CGDOMJSProxyHandler_finalizeInBackground(ClassMethod):
     def __init__(self, descriptor):
         args = [Argument('JS::Value', 'priv')]
-        ClassMethod.__init__(self, "finalizeInBackground", "bool", args)
+        ClassMethod.__init__(self, "finalizeInBackground", "bool", args,
+                             virtual=True, override=True)
         self.descriptor = descriptor
 
     def getBody(self):
         return ("return false;")
 
 
 class CGDOMJSProxyHandler_finalize(ClassMethod):
     def __init__(self, descriptor):
         args = [Argument('JSFreeOp*', 'fop'), Argument('JSObject*', 'proxy')]
-        ClassMethod.__init__(self, "finalize", "void", args)
+        ClassMethod.__init__(self, "finalize", "void", args,
+                             virtual=True, override=True)
         self.descriptor = descriptor
 
     def getBody(self):
         return ("%s self = UnwrapProxy(proxy);\n\n" % (self.descriptor.nativeType + "*") +
                 finalizeHook(self.descriptor, FINALIZE_HOOK_NAME, self.args[0].name).define())
 
 
 class CGDOMJSProxyHandler_slice(ClassMethod):
@@ -9329,17 +9346,17 @@ return &instance;"""
 class CGDOMJSProxyHandler(CGClass):
     def __init__(self, descriptor):
         assert (descriptor.supportsIndexedProperties() or
                 descriptor.supportsNamedProperties())
         methods = [CGDOMJSProxyHandler_getOwnPropertyDescriptor(descriptor),
                    CGDOMJSProxyHandler_defineProperty(descriptor),
                    ClassUsingDeclaration("mozilla::dom::DOMProxyHandler",
                                          "defineProperty"),
-                   CGDOMJSProxyHandler_getOwnPropertyNames(descriptor),
+                   CGDOMJSProxyHandler_ownPropNames(descriptor),
                    CGDOMJSProxyHandler_hasOwn(descriptor),
                    CGDOMJSProxyHandler_get(descriptor),
                    CGDOMJSProxyHandler_className(descriptor),
                    CGDOMJSProxyHandler_finalizeInBackground(descriptor),
                    CGDOMJSProxyHandler_finalize(descriptor),
                    CGDOMJSProxyHandler_getInstance(),
                    CGDOMJSProxyHandler_delete(descriptor)]
         if descriptor.supportsIndexedProperties():
@@ -11116,26 +11133,39 @@ class CGBindingImplClass(CGClass):
             if not haveLengthAttr:
                 self.methodDecls.append(
                     CGNativeMember(descriptor, FakeMember(),
                                    "Length",
                                    (BuiltinTypes[IDLBuiltinType.Types.unsigned_long],
                                     []),
                                    {"infallible": True}))
         # And if we support named properties we need to be able to
-        # enumerate the supported names.
+        # enumerate the supported names and test whether they're enumerable.
         if descriptor.supportsNamedProperties():
             self.methodDecls.append(
                 CGNativeMember(
                     descriptor, FakeMember(),
                     "GetSupportedNames",
                     (IDLSequenceType(None,
                                      BuiltinTypes[IDLBuiltinType.Types.domstring]),
-                     []),
+                     # Let's use unsigned long for the type here, though really
+                     # it's just a C++ "unsigned"...
+                     [FakeArgument(BuiltinTypes[IDLBuiltinType.Types.unsigned_long],
+                                   FakeMember(),
+                                   name="aFlags")]),
                     {"infallible": True}))
+            self.methodDecls.append(
+                CGNativeMember(
+                    descriptor, FakeMember(),
+                    "NameIsEnumerable",
+                    (BuiltinTypes[IDLBuiltinType.Types.boolean],
+                     [FakeArgument(BuiltinTypes[IDLBuiltinType.Types.domstring],
+                                   FakeMember(),
+                                   name="aName")]),
+                    { "infallible": True }))
 
         wrapArgs = [Argument('JSContext*', 'aCx')]
         self.methodDecls.insert(0,
                                 ClassMethod("WrapObject", "JSObject*",
                                             wrapArgs, virtual=descriptor.wrapperCache,
                                             breakAfterReturnDecl=" ",
                                             override=descriptor.wrapperCache,
                                             body=self.getWrapObjectBody()))
@@ -11163,17 +11193,19 @@ class CGBindingImplClass(CGClass):
         return self._deps
 
 
 class CGExampleClass(CGBindingImplClass):
     """
     Codegen for the actual example class implementation for this descriptor
     """
     def __init__(self, descriptor):
-        CGBindingImplClass.__init__(self, descriptor, CGExampleMethod, CGExampleGetter, CGExampleSetter)
+        CGBindingImplClass.__init__(self, descriptor,
+                                    CGExampleMethod, CGExampleGetter, CGExampleSetter,
+                                    wantGetParent=descriptor.wrapperCache)
 
         self.refcounted = descriptor.nativeOwnership == "refcounted"
 
         self.parentIface = descriptor.interface.parent
         if self.parentIface:
             self.parentDesc = descriptor.getDescriptor(
                 self.parentIface.identifier.name)
             bases = [ClassBase(self.nativeLeafName(self.parentDesc))]
--- a/dom/bindings/DOMJSProxyHandler.cpp
+++ b/dom/bindings/DOMJSProxyHandler.cpp
@@ -229,17 +229,17 @@ DOMProxyHandler::delete_(JSContext* cx, 
 bool
 BaseDOMProxyHandler::enumerate(JSContext* cx, JS::Handle<JSObject*> proxy,
                                AutoIdVector& props)
 {
   JS::Rooted<JSObject*> proto(cx);
   if (!JS_GetPrototype(cx, proxy, &proto))  {
     return false;
   }
-  return getOwnPropertyNames(cx, proxy, props) &&
+  return keys(cx, proxy, props) &&
          (!proto || js::GetPropertyNames(cx, proto, 0, &props));
 }
 
 bool
 BaseDOMProxyHandler::watch(JSContext* cx, JS::Handle<JSObject*> proxy, JS::Handle<jsid> id,
                            JS::Handle<JSObject*> callable)
 {
   return js::WatchGuts(cx, proxy, id, callable);
@@ -247,16 +247,32 @@ BaseDOMProxyHandler::watch(JSContext* cx
 
 bool
 BaseDOMProxyHandler::unwatch(JSContext* cx, JS::Handle<JSObject*> proxy, JS::Handle<jsid> id)
 {
   return js::UnwatchGuts(cx, proxy, id);
 }
 
 bool
+BaseDOMProxyHandler::getOwnPropertyNames(JSContext* cx,
+                                         JS::Handle<JSObject*> proxy,
+                                         JS::AutoIdVector& props)
+{
+  return ownPropNames(cx, proxy, JSITER_OWNONLY | JSITER_HIDDEN, props);
+}
+
+bool
+BaseDOMProxyHandler::keys(JSContext* cx,
+                          JS::Handle<JSObject*> proxy,
+                          JS::AutoIdVector& props)
+{
+  return ownPropNames(cx, proxy, JSITER_OWNONLY, props);
+}
+
+bool
 DOMProxyHandler::has(JSContext* cx, JS::Handle<JSObject*> proxy, JS::Handle<jsid> id, bool* bp)
 {
   if (!hasOwn(cx, proxy, id, bp)) {
     return false;
   }
 
   if (*bp) {
     // We have the property ourselves; no need to worry about our prototype
--- a/dom/bindings/DOMJSProxyHandler.h
+++ b/dom/bindings/DOMJSProxyHandler.h
@@ -52,16 +52,32 @@ public:
                              JS::Handle<jsid> id,
                              JS::MutableHandle<JSPropertyDescriptor> desc,
                              unsigned flags) MOZ_OVERRIDE;
 
   bool watch(JSContext* cx, JS::Handle<JSObject*> proxy, JS::Handle<jsid> id,
              JS::Handle<JSObject*> callable) MOZ_OVERRIDE;
   bool unwatch(JSContext* cx, JS::Handle<JSObject*> proxy,
                JS::Handle<jsid> id) MOZ_OVERRIDE;
+  virtual bool getOwnPropertyNames(JSContext* cx, JS::Handle<JSObject*> proxy,
+                                   JS::AutoIdVector &props) MOZ_OVERRIDE;
+  // We override keys() and implement it directly instead of using the
+  // default implementation, which would getOwnPropertyNames and then
+  // filter out the non-enumerable ones.  This avoids doing
+  // unnecessary work during enumeration.
+  virtual bool keys(JSContext* cx, JS::Handle<JSObject*> proxy,
+                    JS::AutoIdVector &props) MOZ_OVERRIDE;
+
+protected:
+  // Hook for subclasses to implement shared getOwnPropertyNames()/keys()
+  // functionality.  The "flags" argument is either JSITER_OWNONLY (for keys())
+  // or JSITER_OWNONLY | JSITER_HIDDEN (for getOwnPropertyNames()).
+  virtual bool ownPropNames(JSContext* cx, JS::Handle<JSObject*> proxy,
+                            unsigned flags,
+                            JS::AutoIdVector& props) = 0;
 };
 
 class DOMProxyHandler : public BaseDOMProxyHandler
 {
 public:
   DOMProxyHandler()
     : BaseDOMProxyHandler(ProxyFamily())
   {
@@ -134,30 +150,33 @@ GetArrayIndexFromId(JSContext* cx, JS::H
 
 inline bool
 IsArrayIndex(int32_t index)
 {
   return index >= 0;
 }
 
 inline void
-FillPropertyDescriptor(JS::MutableHandle<JSPropertyDescriptor> desc, JSObject* obj, bool readonly)
+FillPropertyDescriptor(JS::MutableHandle<JSPropertyDescriptor> desc,
+                       JSObject* obj, bool readonly, bool enumerable = true)
 {
   desc.object().set(obj);
-  desc.setAttributes((readonly ? JSPROP_READONLY : 0) | JSPROP_ENUMERATE);
+  desc.setAttributes((readonly ? JSPROP_READONLY : 0) |
+                     (enumerable ? JSPROP_ENUMERATE : 0));
   desc.setGetter(nullptr);
   desc.setSetter(nullptr);
 }
 
 inline void
-FillPropertyDescriptor(JS::MutableHandle<JSPropertyDescriptor> desc, JSObject* obj, JS::Value v,
-                       bool readonly)
+FillPropertyDescriptor(JS::MutableHandle<JSPropertyDescriptor> desc,
+                       JSObject* obj, JS::Value v,
+                       bool readonly, bool enumerable = true)
 {
   desc.value().set(v);
-  FillPropertyDescriptor(desc, obj, readonly);
+  FillPropertyDescriptor(desc, obj, readonly, enumerable);
 }
 
 inline void
 FillPropertyDescriptor(JS::MutableHandle<JSPropertyDescriptor> desc,
                        JSObject* obj, unsigned attributes, JS::Value v)
 {
   desc.object().set(obj);
   desc.value().set(v);
--- a/dom/bindings/test/TestBindingHeader.h
+++ b/dom/bindings/test/TestBindingHeader.h
@@ -984,49 +984,52 @@ class TestNamedGetterInterface : public 
 {
 public:
   NS_DECL_ISUPPORTS
 
   // We need a GetParentObject to make binding codegen happy
   virtual nsISupports* GetParentObject();
 
   void NamedGetter(const nsAString&, bool&, nsAString&);
-  void GetSupportedNames(nsTArray<nsString>&);
+  bool NameIsEnumerable(const nsAString&);
+  void GetSupportedNames(unsigned, nsTArray<nsString>&);
 };
 
 class TestIndexedGetterAndSetterAndNamedGetterInterface : public nsISupports,
                                                           public nsWrapperCache
 {
 public:
   NS_DECL_ISUPPORTS
 
   // We need a GetParentObject to make binding codegen happy
   virtual nsISupports* GetParentObject();
 
   void NamedGetter(const nsAString&, bool&, nsAString&);
-  void GetSupportedNames(nsTArray<nsString>&);
+  bool NameIsEnumerable(const nsAString&);
+  void GetSupportedNames(unsigned, nsTArray<nsString>&);
   int32_t IndexedGetter(uint32_t, bool&);
   void IndexedSetter(uint32_t, int32_t);
   uint32_t Length();
 };
 
 class TestIndexedAndNamedGetterInterface : public nsISupports,
                                            public nsWrapperCache
 {
 public:
   NS_DECL_ISUPPORTS
 
   // We need a GetParentObject to make binding codegen happy
   virtual nsISupports* GetParentObject();
 
   uint32_t IndexedGetter(uint32_t, bool&);
   void NamedGetter(const nsAString&, bool&, nsAString&);
+  bool NameIsEnumerable(const nsAString&);
   void NamedItem(const nsAString&, nsAString&);
   uint32_t Length();
-  void GetSupportedNames(nsTArray<nsString>&);
+  void GetSupportedNames(unsigned, nsTArray<nsString>&);
 };
 
 class TestIndexedSetterInterface : public nsISupports,
                                    public nsWrapperCache
 {
 public:
   NS_DECL_ISUPPORTS
 
@@ -1045,50 +1048,53 @@ class TestNamedSetterInterface : public 
 public:
   NS_DECL_ISUPPORTS
 
   // We need a GetParentObject to make binding codegen happy
   virtual nsISupports* GetParentObject();
 
   void NamedSetter(const nsAString&, TestIndexedSetterInterface&);
   TestIndexedSetterInterface* NamedGetter(const nsAString&, bool&);
-  void GetSupportedNames(nsTArray<nsString>&);
+  bool NameIsEnumerable(const nsAString&);
+  void GetSupportedNames(unsigned, nsTArray<nsString>&);
 };
 
 class TestIndexedAndNamedSetterInterface : public nsISupports,
                                            public nsWrapperCache
 {
 public:
   NS_DECL_ISUPPORTS
 
   // We need a GetParentObject to make binding codegen happy
   virtual nsISupports* GetParentObject();
 
   void IndexedSetter(uint32_t, TestIndexedSetterInterface&);
   TestIndexedSetterInterface* IndexedGetter(uint32_t, bool&);
   uint32_t Length();
   void NamedSetter(const nsAString&, TestIndexedSetterInterface&);
   TestIndexedSetterInterface* NamedGetter(const nsAString&, bool&);
+  bool NameIsEnumerable(const nsAString&);
   void SetNamedItem(const nsAString&, TestIndexedSetterInterface&);
-  void GetSupportedNames(nsTArray<nsString>&);
+  void GetSupportedNames(unsigned, nsTArray<nsString>&);
 };
 
 class TestIndexedAndNamedGetterAndSetterInterface : public TestIndexedSetterInterface
 {
 public:
   uint32_t IndexedGetter(uint32_t, bool&);
   uint32_t Item(uint32_t);
   void NamedGetter(const nsAString&, bool&, nsAString&);
+  bool NameIsEnumerable(const nsAString&);
   void NamedItem(const nsAString&, nsAString&);
   void IndexedSetter(uint32_t, int32_t&);
   void IndexedSetter(uint32_t, const nsAString&) MOZ_DELETE;
   void NamedSetter(const nsAString&, const nsAString&);
   void Stringify(nsAString&);
   uint32_t Length();
-  void GetSupportedNames(nsTArray<nsString>&);
+  void GetSupportedNames(unsigned, nsTArray<nsString>&);
 };
 
 class TestCppKeywordNamedMethodsInterface : public nsISupports,
                                             public nsWrapperCache
 {
 public:
   NS_DECL_ISUPPORTS
 
@@ -1140,34 +1146,36 @@ class TestNamedDeleterInterface : public
 public:
   NS_DECL_ISUPPORTS
 
   // We need a GetParentObject to make binding codegen happy
   virtual nsISupports* GetParentObject();
 
   void NamedDeleter(const nsAString&, bool&);
   long NamedGetter(const nsAString&, bool&);
-  void GetSupportedNames(nsTArray<nsString>&);
+  bool NameIsEnumerable(const nsAString&);
+  void GetSupportedNames(unsigned, nsTArray<nsString>&);
 };
 
 class TestNamedDeleterWithRetvalInterface : public nsISupports,
                                             public nsWrapperCache
 {
 public:
   NS_DECL_ISUPPORTS
 
   // We need a GetParentObject to make binding codegen happy
   virtual nsISupports* GetParentObject();
 
   bool NamedDeleter(const nsAString&, bool&);
   bool NamedDeleter(const nsAString&) MOZ_DELETE;
   long NamedGetter(const nsAString&, bool&);
+  bool NameIsEnumerable(const nsAString&);
   bool DelNamedItem(const nsAString&);
   bool DelNamedItem(const nsAString&, bool&) MOZ_DELETE;
-  void GetSupportedNames(nsTArray<nsString>&);
+  void GetSupportedNames(unsigned, nsTArray<nsString>&);
 };
 
 class TestIndexedAndNamedDeleterInterface : public nsISupports,
                                             public nsWrapperCache
 {
 public:
   NS_DECL_ISUPPORTS
 
@@ -1176,19 +1184,20 @@ public:
 
   void IndexedDeleter(uint32_t, bool&);
   long IndexedGetter(uint32_t, bool&);
   uint32_t Length();
 
   void NamedDeleter(const nsAString&, bool&);
   void NamedDeleter(const nsAString&) MOZ_DELETE;
   long NamedGetter(const nsAString&, bool&);
+  bool NameIsEnumerable(const nsAString&);
   void DelNamedItem(const nsAString&);
   void DelNamedItem(const nsAString&, bool&) MOZ_DELETE;
-  void GetSupportedNames(nsTArray<nsString>&);
+  void GetSupportedNames(unsigned, nsTArray<nsString>&);
 };
 
 class TestParentInterface : public nsISupports,
                             public nsWrapperCache
 {
 public:
   NS_DECL_ISUPPORTS
 
--- a/dom/bindings/test/mochitest.ini
+++ b/dom/bindings/test/mochitest.ini
@@ -30,14 +30,15 @@ skip-if = true
 [test_forOf.html]
 [test_integers.html]
 [test_interfaceToString.html]
 [test_exceptions_from_jsimplemented.html]
 skip-if = (toolkit == 'gonk' && debug) #debug-only failure; bug 926547
 [test_lenientThis.html]
 [test_lookupGetter.html]
 [test_namedNoIndexed.html]
+[test_named_getter_enumerability.html]
 [test_Object.prototype_props.html]
 [test_queryInterface.html]
 [test_sequence_wrapping.html]
 [test_throwing_method_noDCE.html]
 [test_treat_non_object_as_null.html]
 [test_traceProtos.html]
new file mode 100644
--- /dev/null
+++ b/dom/bindings/test/test_named_getter_enumerability.html
@@ -0,0 +1,40 @@
+<!DOCTYPE html>
+<meta charset=utf-8>
+<title>Test for named getter enumerability</title>
+<script src="/resources/testharness.js"></script>
+<script src="/resources/testharnessreport.js"></script>
+<div id="log"></div>
+<script>
+test(function() {
+  var list = document.getElementsByTagName("div");
+  var desc = Object.getOwnPropertyDescriptor(list, "0");
+  assert_equals(typeof desc, "object", "Should have a '0' property");
+  assert_true(desc.enumerable, "'0' property should be enumerable");
+  desc = Object.getOwnPropertyDescriptor(list, "log");
+  assert_equals(typeof desc, "object", "Should have a 'log' property");
+  assert_false(desc.enumerable, "'log' property should not be enumerable");
+}, "Correct getOwnPropertyDescriptor behavior");
+test(function() {
+  var list = document.getElementsByTagName("div");
+  props = [];
+  for (var prop in list) {
+    props.push(prop);
+  }
+  assert_not_equals(props.indexOf("0"), -1, "Should enumerate '0'");
+  assert_equals(props.indexOf("log"), -1, "Should not enumerate 'log'");
+}, "Correct enumeration behavior");
+test(function() {
+  var list = document.getElementsByTagName("div");
+  props = Object.keys(list)
+  assert_not_equals(props.indexOf("0"), -1, "Keys should contain '0'");
+  assert_equals(props.indexOf("log"), -1, "Keys should not contain 'log'");
+}, "Correct keys() behavior");
+test(function() {
+  var list = document.getElementsByTagName("div");
+  props = Object.getOwnPropertyNames(list)
+  assert_not_equals(props.indexOf("0"), -1,
+                    "own prop names should contain '0'");
+  assert_not_equals(props.indexOf("log"), -1,
+                    "own prop names should contain 'log'");
+}, "Correct getOwnPropertyNames() behavior");
+</script>
--- a/dom/browser-element/BrowserElementChildPreload.js
+++ b/dom/browser-element/BrowserElementChildPreload.js
@@ -79,17 +79,16 @@ let SEC_ERROR_CERT_SIGNATURE_ALGORITHM_D
 let SSL_ERROR_BASE = Ci.nsINSSErrorsService.NSS_SSL_ERROR_BASE;
 let SSL_ERROR_BAD_CERT_DOMAIN = (SSL_ERROR_BASE + 12);
 
 function getErrorClass(errorCode) {
   let NSPRCode = -1 * NS_ERROR_GET_CODE(errorCode);
 
   switch (NSPRCode) {
     case SEC_ERROR_UNKNOWN_ISSUER:
-    case SEC_ERROR_CA_CERT_INVALID:
     case SEC_ERROR_UNTRUSTED_ISSUER:
     case SEC_ERROR_EXPIRED_ISSUER_CERTIFICATE:
     case SEC_ERROR_UNTRUSTED_CERT:
     case SSL_ERROR_BAD_CERT_DOMAIN:
     case SEC_ERROR_EXPIRED_CERTIFICATE:
     case SEC_ERROR_CERT_SIGNATURE_ALGORITHM_DISABLED:
       return Ci.nsINSSErrorsService.ERROR_CLASS_BAD_CERT;
     default:
--- a/dom/encoding/TextDecoder.h
+++ b/dom/encoding/TextDecoder.h
@@ -46,22 +46,16 @@ public:
     MOZ_COUNT_DTOR(TextDecoder);
   }
 
   JSObject* WrapObject(JSContext* aCx, bool* aTookOwnership)
   {
     return TextDecoderBinding::Wrap(aCx, this, aTookOwnership);
   }
 
-  nsISupports*
-  GetParentObject()
-  {
-    return nullptr;
-  }
-
   /**
    * Validates provided label and throws an exception if invalid label.
    *
    * @param aLabel       The encoding label (case insensitive) provided.
    * @param aFatal       indicates whether to throw an 'EncodingError'
    *                     exception or not when decoding.
    * @return aRv         EncodingError exception else null.
    */
--- a/dom/encoding/TextEncoder.h
+++ b/dom/encoding/TextEncoder.h
@@ -41,22 +41,16 @@ public:
   ~TextEncoder()
   {}
 
   JSObject* WrapObject(JSContext* aCx, bool* aTookOwnership)
   {
     return TextEncoderBinding::Wrap(aCx, this, aTookOwnership);
   }
 
-  nsISupports*
-  GetParentObject()
-  {
-    return nullptr;
-  }
-
   JSObject* Encode(JSContext* aCx,
                    JS::Handle<JSObject*> aObj,
                    const nsAString& aString,
                    const TextEncodeOptions& aOptions,
                    ErrorResult& aRv) {
     return TextEncoder::Encode(aCx, aObj, aString, aOptions.mStream, aRv);
   }
 
--- a/dom/events/DeviceMotionEvent.h
+++ b/dom/events/DeviceMotionEvent.h
@@ -16,21 +16,16 @@ class DeviceRotationRate MOZ_FINAL : pub
 {
 public:
   NS_INLINE_DECL_CYCLE_COLLECTING_NATIVE_REFCOUNTING(DeviceRotationRate)
   NS_DECL_CYCLE_COLLECTION_SCRIPT_HOLDER_NATIVE_CLASS(DeviceRotationRate)
 
   DeviceRotationRate(DeviceMotionEvent* aOwner,
                      Nullable<double> aAlpha, Nullable<double> aBeta,
                      Nullable<double> aGamma);
-  DeviceRotationRate(double aAlpha, double aBeta, double aGamma)
-  {
-    DeviceRotationRate(nullptr, Nullable<double>(aAlpha),
-                       Nullable<double>(aBeta), Nullable<double>(aGamma));
-  }
 
   DeviceMotionEvent* GetParentObject() const
   {
     return mOwner;
   }
 
   virtual JSObject* WrapObject(JSContext* aCx) MOZ_OVERRIDE
   {
@@ -53,21 +48,16 @@ class DeviceAcceleration MOZ_FINAL : pub
 {
 public:
   NS_INLINE_DECL_CYCLE_COLLECTING_NATIVE_REFCOUNTING(DeviceAcceleration)
   NS_DECL_CYCLE_COLLECTION_SCRIPT_HOLDER_NATIVE_CLASS(DeviceAcceleration)
 
   DeviceAcceleration(DeviceMotionEvent* aOwner,
                      Nullable<double> aX, Nullable<double> aY,
                      Nullable<double> aZ);
-  DeviceAcceleration(double aX, double aY, double aZ)
-  {
-    DeviceAcceleration(nullptr, Nullable<double>(aX),
-                       Nullable<double>(aY), Nullable<double>(aZ));
-  }
 
   DeviceMotionEvent* GetParentObject() const
   {
     return mOwner;
   }
 
   virtual JSObject* WrapObject(JSContext* aCx) MOZ_OVERRIDE
   {
--- a/dom/imptests/html/dom/nodes/test_Document-getElementsByTagName.html
+++ b/dom/imptests/html/dom/nodes/test_Document-getElementsByTagName.html
@@ -59,20 +59,25 @@ test(function() {
   assert_equals(pre.id, "x");
   assert_equals(list['x'], pre);
 
   assert_true('x' in list, "'x' in list");
   assert_true(list.hasOwnProperty('x'), "list.hasOwnProperty('x')");
 
   assert_array_equals(Object.getOwnPropertyNames(list).sort(), ["0", "x"]);
 
-  var desc = Object.getOwnPropertyDescriptor(list, 'x');
+  var desc = Object.getOwnPropertyDescriptor(list, '0');
   assert_equals(typeof desc, "object", "descriptor should be an object");
   assert_true(desc.enumerable, "desc.enumerable");
   assert_true(desc.configurable, "desc.configurable");
+
+  desc = Object.getOwnPropertyDescriptor(list, 'x');
+  assert_equals(typeof desc, "object", "descriptor should be an object");
+  assert_false(desc.enumerable, "desc.enumerable");
+  assert_true(desc.configurable, "desc.configurable");
 }, "hasOwnProperty, getOwnPropertyDescriptor, getOwnPropertyNames")
 
 test(function() {
   assert_equals(document.createElementNS("http://www.w3.org/1999/xhtml", "i").localName, "i") // Sanity
   var i = document.body.appendChild(document.createElementNS("http://www.w3.org/1999/xhtml", "I"))
   assert_equals(i.localName, "I")
   assert_equals(i.tagName, "I")
   assert_equals(document.getElementsByTagName("I").length, 0)
--- a/dom/imptests/html/dom/nodes/test_Element-children.html
+++ b/dom/imptests/html/dom/nodes/test_Element-children.html
@@ -15,11 +15,13 @@ test(function() {
   var container = document.getElementById("test");
   var list = container.children;
   var result = [];
   for (var p in list) {
     if (list.hasOwnProperty(p)) {
       result.push(p);
     }
   }
+  assert_array_equals(result, ['0', '1', '2']);
+  result = Object.getOwnPropertyNames(list);
   assert_array_equals(result, ['0', '1', '2', 'foo']);
 });
 </script>
--- a/dom/interfaces/base/nsIDOMWindowUtils.idl
+++ b/dom/interfaces/base/nsIDOMWindowUtils.idl
@@ -31,17 +31,16 @@ interface nsIDOMElement;
 interface nsIDOMHTMLCanvasElement;
 interface nsIDOMEvent;
 interface nsITransferable;
 interface nsIQueryContentEventResult;
 interface nsIDOMWindow;
 interface nsIDOMBlob;
 interface nsIDOMFile;
 interface nsIFile;
-interface nsIDOMTouch;
 interface nsIDOMClientRect;
 interface nsIURI;
 interface nsIDOMEventTarget;
 interface nsIRunnable;
 interface nsICompositionStringSynthesizer;
 interface nsITranslationNodeList;
 
 [scriptable, uuid(3d977df2-1c0e-4b61-bc21-c6ee757a9191)]
--- a/dom/interfaces/events/nsIDOMTouchEvent.idl
+++ b/dom/interfaces/events/nsIDOMTouchEvent.idl
@@ -5,36 +5,16 @@
 
 #include "nsIDOMUIEvent.idl"
 %{C++
 #include "nsWeakPtr.h"
 #include "nsPoint.h"
 %}
 interface nsIVariant;
 
-/**
- * @see http://dvcs.w3.org/hg/webevents/raw-file/tip/touchevents.html
- */
-
-[scriptable, builtinclass, uuid(2311671f-ff7e-43d2-adfb-d9e07006955e)]
-interface nsIDOMTouch : nsISupports {
-  readonly attribute long              identifier;
-  readonly attribute nsIDOMEventTarget target;
-  readonly attribute long              pageX;
-  readonly attribute long              pageY;
-  readonly attribute long              screenX;
-  readonly attribute long              screenY;
-  readonly attribute long              clientX;
-  readonly attribute long              clientY;
-  readonly attribute long              radiusX;
-  readonly attribute long              radiusY;
-  readonly attribute float             rotationAngle;
-  readonly attribute float             force;
-};
-
 [scriptable, uuid(6d5484f7-92ac-45f8-9388-39b5bad055ce)]
 interface nsITouchEventReceiver : nsISupports {
   [implicit_jscontext] attribute jsval           ontouchstart;
   [implicit_jscontext] attribute jsval           ontouchend;
   [implicit_jscontext] attribute jsval           ontouchmove;
   [implicit_jscontext] attribute jsval           ontouchenter;
   [implicit_jscontext] attribute jsval           ontouchleave;
   [implicit_jscontext] attribute jsval           ontouchcancel;
--- a/dom/media/GetUserMediaRequest.cpp
+++ b/dom/media/GetUserMediaRequest.cpp
@@ -11,21 +11,23 @@
 #include "nsCxPusher.h"
 
 namespace mozilla {
 namespace dom {
 
 GetUserMediaRequest::GetUserMediaRequest(
     nsPIDOMWindow* aInnerWindow,
     const nsAString& aCallID,
-    const MediaStreamConstraintsInternal& aConstraints)
+    const MediaStreamConstraintsInternal& aConstraints,
+    bool aIsSecure)
   : mInnerWindowID(aInnerWindow->WindowID())
   , mOuterWindowID(aInnerWindow->GetOuterWindow()->WindowID())
   , mCallID(aCallID)
   , mConstraints(new MediaStreamConstraintsInternal(aConstraints))
+  , mIsSecure(aIsSecure)
 {
   SetIsDOMBinding();
 }
 
 NS_IMPL_CYCLE_COLLECTION_WRAPPERCACHE_0(GetUserMediaRequest)
 NS_IMPL_CYCLE_COLLECTING_ADDREF(GetUserMediaRequest)
 NS_IMPL_CYCLE_COLLECTING_RELEASE(GetUserMediaRequest)
 NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION(GetUserMediaRequest)
@@ -54,16 +56,21 @@ uint64_t GetUserMediaRequest::WindowID()
   return mOuterWindowID;
 }
 
 uint64_t GetUserMediaRequest::InnerWindowID()
 {
   return mInnerWindowID;
 }
 
+bool GetUserMediaRequest::IsSecure()
+{
+  return mIsSecure;
+}
+
 void
 GetUserMediaRequest::GetConstraints(MediaStreamConstraintsInternal &result)
 {
   result = *mConstraints;
 }
 
 } // namespace dom
 } // namespace mozilla
--- a/dom/media/GetUserMediaRequest.h
+++ b/dom/media/GetUserMediaRequest.h
@@ -16,33 +16,36 @@ namespace mozilla {
 namespace dom {
 class MediaStreamConstraintsInternal;
 
 class GetUserMediaRequest : public nsISupports, public nsWrapperCache
 {
 public:
   GetUserMediaRequest(nsPIDOMWindow* aInnerWindow,
                       const nsAString& aCallID,
-                      const MediaStreamConstraintsInternal& aConstraints);
+                      const MediaStreamConstraintsInternal& aConstraints,
+                      bool aIsSecure);
   virtual ~GetUserMediaRequest() {};
 
   NS_DECL_CYCLE_COLLECTING_ISUPPORTS
   NS_DECL_CYCLE_COLLECTION_SCRIPT_HOLDER_CLASS(GetUserMediaRequest)
 
   virtual JSObject* WrapObject(JSContext* cx)
     MOZ_OVERRIDE;
   nsISupports* GetParentObject();
 
   uint64_t WindowID();
   uint64_t InnerWindowID();
+  bool IsSecure();
   void GetCallID(nsString& retval);
   void GetConstraints(MediaStreamConstraintsInternal &result);
 
 private:
   uint64_t mInnerWindowID, mOuterWindowID;
   const nsString mCallID;
   nsAutoPtr<MediaStreamConstraintsInternal> mConstraints;
+  bool mIsSecure;
 };
 
 } // namespace dom
 } // namespace mozilla
 
 #endif // GetUserMediaRequest_h__
--- a/dom/media/MediaManager.cpp
+++ b/dom/media/MediaManager.cpp
@@ -1454,43 +1454,60 @@ MediaManager::GetUserMedia(JSContext* aC
     return NS_OK;
   }
 #endif
   // XXX No full support for picture in Desktop yet (needs proper UI)
   if (aPrivileged ||
       (c.mFake && !Preferences::GetBool("media.navigator.permission.fake"))) {
     mMediaThread->Dispatch(runnable, NS_DISPATCH_NORMAL);
   } else {
+    bool isHTTPS = false;
+    nsIURI* docURI = aWindow->GetDocumentURI();
+    if (docURI) {
+      docURI->SchemeIs("https", &isHTTPS);
+    }
+
     // Check if this site has persistent permissions.
     nsresult rv;
     nsCOMPtr<nsIPermissionManager> permManager =
       do_GetService(NS_PERMISSIONMANAGER_CONTRACTID, &rv);
     NS_ENSURE_SUCCESS(rv, rv);
 
     uint32_t audioPerm = nsIPermissionManager::UNKNOWN_ACTION;
     if (IsOn(c.mAudio)) {
       rv = permManager->TestExactPermissionFromPrincipal(
         aWindow->GetExtantDoc()->NodePrincipal(), "microphone", &audioPerm);
       NS_ENSURE_SUCCESS(rv, rv);
       if (audioPerm == nsIPermissionManager::PROMPT_ACTION) {
         audioPerm = nsIPermissionManager::UNKNOWN_ACTION;
       }
+      if (audioPerm == nsIPermissionManager::ALLOW_ACTION) {
+        if (!isHTTPS) {
+          audioPerm = nsIPermissionManager::UNKNOWN_ACTION;
+        }
+      }
     }
 
     uint32_t videoPerm = nsIPermissionManager::UNKNOWN_ACTION;
     if (IsOn(c.mVideo)) {
       rv = permManager->TestExactPermissionFromPrincipal(
         aWindow->GetExtantDoc()->NodePrincipal(), "camera", &videoPerm);
       NS_ENSURE_SUCCESS(rv, rv);
       if (videoPerm == nsIPermissionManager::PROMPT_ACTION) {
         videoPerm = nsIPermissionManager::UNKNOWN_ACTION;
       }
+      if (videoPerm == nsIPermissionManager::ALLOW_ACTION) {
+        if (!isHTTPS) {
+          videoPerm = nsIPermissionManager::UNKNOWN_ACTION;
+        }
+      }
     }
 
-    if ((!IsOn(c.mAudio) || audioPerm) && (!IsOn(c.mVideo) || videoPerm)) {
+    if ((!IsOn(c.mAudio) || audioPerm != nsIPermissionManager::UNKNOWN_ACTION) &&
+        (!IsOn(c.mVideo) || videoPerm != nsIPermissionManager::UNKNOWN_ACTION)) {
       // All permissions we were about to request already have a saved value.
       if (IsOn(c.mAudio) && audioPerm == nsIPermissionManager::DENY_ACTION) {
         c.mAudio.SetAsBoolean() = false;
         runnable->SetContraints(c);
       }
       if (IsOn(c.mVideo) && videoPerm == nsIPermissionManager::DENY_ACTION) {
         c.mVideo.SetAsBoolean() = false;
         runnable->SetContraints(c);
@@ -1528,17 +1545,17 @@ MediaManager::GetUserMedia(JSContext* aC
       array = new nsTArray<nsString>();
       array->AppendElement(callID);
       mCallIds.Put(windowID, array);
     } else {
       array->AppendElement(callID);
     }
     nsCOMPtr<nsIObserverService> obs = services::GetObserverService();
     nsRefPtr<GetUserMediaRequest> req = new GetUserMediaRequest(aWindow,
-                                                                callID, c);
+                                                                callID, c, isHTTPS);
     obs->NotifyObservers(req, "getUserMedia:request", nullptr);
   }
 
   return NS_OK;
 }
 
 nsresult
 MediaManager::GetUserMediaDevices(nsPIDOMWindow* aWindow,
--- a/dom/plugins/ipc/PluginLibrary.h
+++ b/dom/plugins/ipc/PluginLibrary.h
@@ -10,17 +10,16 @@
 #include "prlink.h"
 #include "npapi.h"
 #include "npfunctions.h"
 #include "nscore.h"
 #include "nsTArray.h"
 #include "nsError.h"
 #include "mozilla/EventForwards.h"
 
-class gfxASurface;
 class gfxContext;
 class nsCString;
 struct nsIntRect;
 struct nsIntSize;
 class nsNPAPIPlugin;
 
 namespace mozilla {
 namespace layers {
--- a/dom/webidl/GetUserMediaRequest.webidl
+++ b/dom/webidl/GetUserMediaRequest.webidl
@@ -7,9 +7,10 @@
  */
 
 [NoInterfaceObject]
 interface GetUserMediaRequest {
   readonly attribute unsigned long long windowID;
   readonly attribute unsigned long long innerWindowID;
   readonly attribute DOMString callID;
   MediaStreamConstraintsInternal getConstraints();
+  readonly attribute boolean isSecure;
 };
--- a/dom/wifi/WifiWorker.js
+++ b/dom/wifi/WifiWorker.js
@@ -885,23 +885,23 @@ var WifiManager = (function() {
   function createWaitForDriverReadyTimer(onTimeout) {
     waitForDriverReadyTimer = Cc["@mozilla.org/timer;1"].createInstance(Ci.nsITimer);
     waitForDriverReadyTimer.initWithCallback(onTimeout,
                                              manager.driverDelay,
                                              Ci.nsITimer.TYPE_ONE_SHOT);
   };
 
   // Public interface of the wifi service.
-  manager.setWifiEnabled = function(enable, callback) {
-    if (enable === manager.enabled) {
+  manager.setWifiEnabled = function(enabled, callback) {
+    if (enabled === manager.isWifiEnabled(manager.state)) {
       callback("no change");
       return;
     }
 
-    if (enable) {
+    if (enabled) {
       manager.state = "INITIALIZING";
       // Register as network interface.
       WifiNetworkInterface.name = manager.ifname;
       if (!WifiNetworkInterface.registered) {
         gNetworkManager.registerNetworkInterface(WifiNetworkInterface);
         WifiNetworkInterface.registered = true;
       }
       WifiNetworkInterface.state = Ci.nsINetworkInterface.NETWORK_STATE_DISCONNECTED;
@@ -947,16 +947,20 @@ var WifiManager = (function() {
               cancelWaitForDriverReadyTimer();
 
               if (!manager.connectToSupplicant) {
                 startSupplicantInternal();
                 return;
               }
               wifiCommand.closeSupplicantConnection(function () {
                 manager.connectToSupplicant = false;
+                // closeSupplicantConnection() will trigger onsupplicantlost
+                // and set manager.state to "UNINITIALIZED", we have to
+                // restore it here.
+                manager.state = "INITIALIZING";
                 startSupplicantInternal();
               });
             }
             // Driver startup on certain platforms takes longer than it takes for us
             // to return from loadDriver, so wait 2 seconds before starting
             // the supplicant to give it a chance to start.
             if (manager.driverDelay > 0) {
               createWaitForDriverReadyTimer(doStartSupplicant);
@@ -989,16 +993,21 @@ var WifiManager = (function() {
       } else {
         doDisableWifi();
       }
     }
   }
 
   // Get wifi interface and load wifi driver when enable Ap mode.
   manager.setWifiApEnabled = function(enabled, configuration, callback) {
+    if (enabled === manager.isWifiTetheringEnabled(manager.tetheringState)) {
+      callback("no change");
+      return;
+    }
+
     if (enabled) {
       manager.tetheringState = "INITIALIZING";
       loadDriver(function (status) {
         if (status < 0) {
           callback();
           manager.tetheringState = "UNINITIALIZED";
           return;
         }
@@ -1253,16 +1262,36 @@ var WifiManager = (function() {
       case "SCANNING":
       case "UNINITIALIZED":
       case "INVALID":
       case "CONNECTED":
       default:
         return false;
     }
   }
+
+  manager.isWifiEnabled = function(state) {
+    switch (state) {
+      case "UNINITIALIZED":
+      case "DISABLING":
+        return false;
+      default:
+        return true;
+    }
+  }
+
+  manager.isWifiTetheringEnabled = function(state) {
+    switch (state) {
+      case "UNINITIALIZED":
+        return false;
+      default:
+        return true;
+    }
+  }
+
   manager.syncDebug = syncDebug;
   manager.stateOrdinal = function(state) {
     return supplicantStatesMap.indexOf(state);
   }
   manager.supplicantLoopDetection = function(prevState, state) {
     var isPrevStateInHandShake = manager.isHandShakeState(prevState);
     var isStateInHandShake = manager.isHandShakeState(state);
 
@@ -1797,30 +1826,34 @@ function WifiWorker() {
     } catch (e) {
       self._allowWpaEap = false;
     }
 
     // Notify everybody, even if they didn't ask us to come up.
     WifiManager.getMacAddress(function (mac) {
       self.macAddress = mac;
       debug("Got mac: " + mac);
+      self._ignoreNextWifiEnabledSetting = true;
       self._fireEvent("wifiUp", { macAddress: mac });
+      self.requestDone();
     });
 
     if (WifiManager.state === "SCANNING")
       startScanStuckTimer();
   };
 
   WifiManager.onsupplicantlost = function() {
     WifiManager.enabled = WifiManager.supplicantStarted = false;
     WifiManager.state = "UNINITIALIZED";
     debug("Supplicant died!");
 
     // Notify everybody, even if they didn't ask us to come up.
+    self._ignoreNextWifiDisabledSetting = true;
     self._fireEvent("wifiDown", {});
+    self.requestDone();
   };
 
   WifiManager.onpasswordmaybeincorrect = function() {
     WifiManager.authenticationFailuresCount++;
   };
 
   WifiManager.ondisconnected = function() {
     // We may fail to establish the connection, re-enable the
@@ -2239,16 +2272,23 @@ WifiWorker.prototype = {
   disconnectedByWifi: false,
 
   disconnectedByWifiTethering: false,
 
   _wifiTetheringSettingsToRead: [],
 
   _oldWifiTetheringEnabledState: null,
 
+  // 930355: Workaround before bug 930355 is landed.
+  // Current system app will set settings value "wifi.enabled" after receiving
+  // wifi enable/disable event, this will cause infinite loop between gaia
+  // and gecko, so now use this variable to cut the loop.
+  _ignoreNextWifiDisabledSetting: false,
+  _ignoreNextWifiEnabledSetting: false,
+
   tetheringSettings: {},
 
   initTetheringSettings: function initTetheringSettings() {
     this.tetheringSettings[SETTINGS_WIFI_TETHERING_ENABLED] = null;
     this.tetheringSettings[SETTINGS_WIFI_SSID] = DEFAULT_WIFI_SSID;
     this.tetheringSettings[SETTINGS_WIFI_SECURITY_TYPE] = DEFAULT_WIFI_SECURITY_TYPE;
     this.tetheringSettings[SETTINGS_WIFI_SECURITY_PASSWORD] = DEFAULT_WIFI_SECURITY_PASSWORD;
     this.tetheringSettings[SETTINGS_WIFI_IP] = DEFAULT_WIFI_IP;
@@ -2684,23 +2724,26 @@ WifiWorker.prototype = {
         networks.push(netToDOM(this.configuredNetworks[networkKey]));
       }
 
       this._sendMessage(message, true, networks, msg);
     }).bind(this));
   },
 
   _setWifiEnabledCallback: function(status) {
+    if (status !== 0) {
+      this.requestDone();
+      return;
+    }
+
     // If we're enabling ourselves, then wait until we've connected to the
     // supplicant to notify. If we're disabling, we take care of this in
     // supplicantlost.
     if (WifiManager.supplicantStarted)
       WifiManager.start();
-
-    this.requestDone();
   },
 
   setWifiEnabled: function(enabled, callback) {
     // Reply error to pending requests.
     if (!enabled) {
       this._clearPendingRequest();
     }
 
@@ -3102,24 +3145,21 @@ WifiWorker.prototype = {
         handleError: function(aErrorMessage) {
           self.requestDone();
         }
       },
       "fromInternalSetting");
   },
 
   handleWifiEnabled: function(enabled) {
-    if (WifiManager.enabled === enabled) {
-      return;
-    }
     // Make sure Wifi hotspot is idle before switching to Wifi mode.
     if (enabled) {
       this.queueRequest(false, function(data) {
         if (this.tetheringSettings[SETTINGS_WIFI_TETHERING_ENABLED] ||
-            WifiManager.tetheringState != "UNINITIALIZED") {
+            WifiManager.isWifiTetheringEnabled(WifiManager.tetheringState)) {
           this.disconnectedByWifi = true;
           this.setWifiApEnabled(false, this.notifyTetheringOff.bind(this));
         } else {
           this.requestDone();
         }
       }.bind(this));
     }
 
@@ -3138,27 +3178,27 @@ WifiWorker.prototype = {
       }.bind(this));
     }
   },
 
   handleWifiTetheringEnabled: function(enabled) {
     // Make sure Wifi is idle before switching to Wifi hotspot mode.
     if (enabled) {
       this.queueRequest(false, function(data) {
-        if (WifiManager.enabled || WifiManager.state != "UNINITIALIZED") {
+        if (WifiManager.isWifiEnabled(WifiManager.state)) {
           this.disconnectedByWifiTethering = true;
           this.setWifiEnabled(false, this._setWifiEnabledCallback.bind(this));
         } else {
           this.requestDone();
         }
       }.bind(this));
     }
 
     this.queueRequest(enabled, function(data) {
-      this.setWifiApEnabled(data, this.requestDone.bind(this));
+      this.setWifiApEnabled(enabled, this.requestDone.bind(this));
     }.bind(this));
 
     if (!enabled) {
       this.queueRequest(true, function(data) {
         if (this.disconnectedByWifiTethering) {
           this.setWifiEnabled(true, this._setWifiEnabledCallback.bind(this));
         } else {
           this.requestDone();
@@ -3186,16 +3226,24 @@ WifiWorker.prototype = {
     }
 
     this.handle(setting.key, setting.value);
   },
 
   handle: function handle(aName, aResult) {
     switch(aName) {
       case SETTINGS_WIFI_ENABLED:
+        if (this._ignoreNextWifiEnabledSetting && aResult) {
+          this._ignoreNextWifiEnabledSetting = false;
+          break;
+        }
+        if (this._ignoreNextWifiDisabledSetting && !aResult) {
+          this._ignoreNextWifiDisabledSetting = false;
+          break;
+        }
         this.handleWifiEnabled(aResult)
         break;
       case SETTINGS_WIFI_DEBUG_ENABLED:
         if (aResult === null)
           aResult = false;
         DEBUG = aResult;
         updateDebug();
         break;
--- a/gfx/2d/DrawTargetCairo.cpp
+++ b/gfx/2d/DrawTargetCairo.cpp
@@ -317,26 +317,27 @@ GfxPatternToCairoPattern(const Pattern& 
       pat = cairo_pattern_create_rgba(color.r, color.g, color.b, color.a * aAlpha);
       break;
     }
 
     case PatternType::SURFACE:
     {
       const SurfacePattern& pattern = static_cast<const SurfacePattern&>(aPattern);
       cairo_surface_t* surf = GetCairoSurfaceForSourceSurface(pattern.mSurface);
+      if (!surf)
+        return nullptr;
 
       pat = cairo_pattern_create_for_surface(surf);
 
       matrix = &pattern.mMatrix;
 
       cairo_pattern_set_filter(pat, GfxFilterToCairoFilter(pattern.mFilter));
       cairo_pattern_set_extend(pat, GfxExtendToCairoExtend(pattern.mExtendMode));
 
       cairo_surface_destroy(surf);
-
       break;
     }
     case PatternType::LINEAR_GRADIENT:
     {
       const LinearGradientPattern& pattern = static_cast<const LinearGradientPattern&>(aPattern);
 
       pat = cairo_pattern_create_linear(pattern.mBegin.x, pattern.mBegin.y,
                                         pattern.mEnd.x, pattern.mEnd.y);
@@ -573,17 +574,17 @@ DrawTargetCairo::DrawSurfaceWithShadow(S
                                        const Color &aColor,
                                        const Point &aOffset,
                                        Float aSigma,
                                        CompositionOp aOperator)
 {
   if (aSurface->GetType() != SurfaceType::CAIRO) {
     return;
   }
-  
+
   AutoClearDeviceOffset clear(aSurface);
 
   Float width = Float(aSurface->GetSize().width);
   Float height = Float(aSurface->GetSize().height);
 
   SourceSurfaceCairo* source = static_cast<SourceSurfaceCairo*>(aSurface);
   cairo_surface_t* sourcesurf = source->GetSurface();
   cairo_surface_t* blursurf;
@@ -645,20 +646,23 @@ DrawTargetCairo::DrawPattern(const Patte
                              const StrokeOptions& aStrokeOptions,
                              const DrawOptions& aOptions,
                              DrawPatternType aDrawType,
                              bool aPathBoundsClip)
 {
   if (!PatternIsCompatible(aPattern)) {
     return;
   }
-  
+
   AutoClearDeviceOffset clear(aPattern);
 
   cairo_pattern_t* pat = GfxPatternToCairoPattern(aPattern, aOptions.mAlpha);
+  if (!pat)
+    return;
+
   cairo_set_source(mContext, pat);
 
   cairo_set_antialias(mContext, GfxAntialiasToCairoAntialias(aOptions.mAntialiasMode));
 
   if (NeedIntermediateSurface(aPattern, aOptions) ||
       (!IsOperatorBoundByMask(aOptions.mCompositionOp) && !aPathBoundsClip)) {
     cairo_push_group_with_content(mContext, CAIRO_CONTENT_COLOR_ALPHA);
 
@@ -878,16 +882,19 @@ DrawTargetCairo::FillGlyphs(ScaledFont *
 {
   AutoPrepareForDrawing prep(this, mContext);
   AutoClearDeviceOffset clear(aPattern);
 
   ScaledFontBase* scaledFont = static_cast<ScaledFontBase*>(aFont);
   cairo_set_scaled_font(mContext, scaledFont->GetCairoScaledFont());
 
   cairo_pattern_t* pat = GfxPatternToCairoPattern(aPattern, aOptions.mAlpha);
+  if (!pat)
+    return;
+
   cairo_set_source(mContext, pat);
   cairo_pattern_destroy(pat);
 
   cairo_set_antialias(mContext, GfxAntialiasToCairoAntialias(aOptions.mAntialiasMode));
 
   // Convert our GlyphBuffer into an array of Cairo glyphs.
   std::vector<cairo_glyph_t> glyphs(aBuffer.mNumGlyphs);
   for (uint32_t i = 0; i < aBuffer.mNumGlyphs; ++i) {
@@ -906,19 +913,26 @@ DrawTargetCairo::Mask(const Pattern &aSo
 {
   AutoPrepareForDrawing prep(this, mContext);
   AutoClearDeviceOffset clearSource(aSource);
   AutoClearDeviceOffset clearMask(aMask);
 
   cairo_set_antialias(mContext, GfxAntialiasToCairoAntialias(aOptions.mAntialiasMode));
 
   cairo_pattern_t* source = GfxPatternToCairoPattern(aSource, aOptions.mAlpha);
-  cairo_set_source(mContext, source);
+  if (!source)
+    return;
 
   cairo_pattern_t* mask = GfxPatternToCairoPattern(aMask, aOptions.mAlpha);
+  if (!mask) {
+    cairo_pattern_destroy(source);
+    return;
+  }
+
+  cairo_set_source(mContext, source);
   cairo_mask(mContext, mask);
 
   cairo_pattern_destroy(mask);
   cairo_pattern_destroy(source);
 }
 
 void
 DrawTargetCairo::MaskSurface(const Pattern &aSource,
@@ -932,16 +946,19 @@ DrawTargetCairo::MaskSurface(const Patte
 
   if (!PatternIsCompatible(aSource)) {
     return;
   }
 
   cairo_set_antialias(mContext, GfxAntialiasToCairoAntialias(aOptions.mAntialiasMode));
 
   cairo_pattern_t* pat = GfxPatternToCairoPattern(aSource, aOptions.mAlpha);
+  if (!pat)
+    return;
+
   cairo_set_source(mContext, pat);
 
   if (NeedIntermediateSurface(aSource, aOptions)) {
     cairo_push_group_with_content(mContext, CAIRO_CONTENT_COLOR_ALPHA);
 
     // Don't want operators to be applied twice
     cairo_set_operator(mContext, CAIRO_OPERATOR_OVER);
 
@@ -1006,17 +1023,17 @@ DrawTargetCairo::PopClip()
   // so we'll save it now and restore it after the cairo_restore
   cairo_matrix_t mat;
   cairo_get_matrix(mContext, &mat);
 
   cairo_restore(mContext);
 
   cairo_set_matrix(mContext, &mat);
 
-  MOZ_ASSERT(GetTransform() == Matrix(mat.xx, mat.yx, mat.xy, mat.yy, mat.x0, mat.y0),
+  MOZ_ASSERT(cairo_status(mContext) || GetTransform() == Matrix(mat.xx, mat.yx, mat.xy, mat.yy, mat.x0, mat.y0),
              "Transforms are out of sync");
 }
 
 TemporaryRef<PathBuilder>
 DrawTargetCairo::CreatePathBuilder(FillRule aFillRule /* = FillRule::FILL_WINDING */) const
 {
   RefPtr<PathBuilderCairo> builder = new PathBuilderCairo(aFillRule);
 
--- a/gfx/2d/DrawTargetD2D.cpp
+++ b/gfx/2d/DrawTargetD2D.cpp
@@ -1,16 +1,19 @@
 /* -*- Mode: C++; tab-width: 20; 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/. */
 
 #include <initguid.h>
 #include "DrawTargetD2D.h"
 #include "SourceSurfaceD2D.h"
+#ifdef USE_D2D1_1
+#include "SourceSurfaceD2D1.h"
+#endif
 #include "SourceSurfaceD2DTarget.h"
 #include "ShadersD2D.h"
 #include "PathD2D.h"
 #include "GradientStopsD2D.h"
 #include "ScaledFontDWrite.h"
 #include "ImageScaling.h"
 #include "Logging.h"
 #include "Tools.h"
@@ -313,16 +316,34 @@ DrawTargetD2D::GetBitmapForSurface(Sourc
       aSource.y -= (uint32_t)aSource.y;
     }
     break;
   }
 
   return bitmap;
 }
 
+#ifdef USE_D2D1_1
+TemporaryRef<ID2D1Image>
+DrawTargetD2D::GetImageForSurface(SourceSurface *aSurface)
+{
+  RefPtr<ID2D1Image> image;
+
+  if (aSurface->GetType() == SurfaceType::D2D1_1_IMAGE) {
+    image = static_cast<SourceSurfaceD2D1*>(aSurface)->GetImage();
+    static_cast<SourceSurfaceD2D1*>(aSurface)->EnsureIndependent();
+  } else {
+    Rect r(Point(), Size(aSurface->GetSize()));
+    image = GetBitmapForSurface(aSurface, r);
+  }
+
+  return image;
+}
+#endif
+
 void
 DrawTargetD2D::DrawSurface(SourceSurface *aSurface,
                            const Rect &aDest,
                            const Rect &aSource,
                            const DrawSurfaceOptions &aSurfOptions,
                            const DrawOptions &aOptions)
 {
   RefPtr<ID2D1Bitmap> bitmap;
--- a/gfx/2d/DrawTargetD2D.h
+++ b/gfx/2d/DrawTargetD2D.h
@@ -134,16 +134,20 @@ public:
 
   bool Init(const IntSize &aSize, SurfaceFormat aFormat);
   bool Init(ID3D10Texture2D *aTexture, SurfaceFormat aFormat);
   bool InitD3D10Data();
   uint32_t GetByteSize() const;
   TemporaryRef<ID2D1Layer> GetCachedLayer();
   void PopCachedLayer(ID2D1RenderTarget *aRT);
 
+#ifdef USE_D2D1_1
+  TemporaryRef<ID2D1Image> GetImageForSurface(SourceSurface *aSurface);
+#endif
+
   static ID2D1Factory *factory();
   static void CleanupD2D();
   static IDWriteFactory *GetDWriteFactory();
   ID2D1RenderTarget *GetRT() { return mRT; }
 
   operator std::string() const {
     std::stringstream stream;
     stream << "DrawTargetD2D(" << this << ")";
--- a/gfx/2d/FilterNodeD2D1.cpp
+++ b/gfx/2d/FilterNodeD2D1.cpp
@@ -123,39 +123,25 @@ D2D1_CHANNEL_SELECTOR D2DChannelSelector
   }
 
   MOZ_CRASH("Unknown enum value!");
   return D2D1_CHANNEL_SELECTOR_R;
 }
 
 TemporaryRef<ID2D1Image> GetImageForSourceSurface(DrawTarget *aDT, SourceSurface *aSurface)
 {
-  if (aDT->GetType() == BackendType::DIRECT2D1_1) {
-    return static_cast<DrawTargetD2D1*>(aDT)->GetImageForSurface(aSurface, ExtendMode::CLAMP);
+  switch (aDT->GetType()) {
+    case BackendType::DIRECT2D1_1:
+      return static_cast<DrawTargetD2D1*>(aDT)->GetImageForSurface(aSurface, ExtendMode::CLAMP);
+    case BackendType::DIRECT2D:
+      return static_cast<DrawTargetD2D*>(aDT)->GetImageForSurface(aSurface);
+    default:
+      MOZ_CRASH("Unknown draw target type!");
+      return nullptr;
   }
-  RefPtr<ID2D1Image> image;
-  switch (aSurface->GetType()) {
-  case SurfaceType::D2D1_1_IMAGE:
-    image = static_cast<SourceSurfaceD2D1*>(aSurface)->GetImage();
-    static_cast<SourceSurfaceD2D1*>(aSurface)->EnsureIndependent();
-    break;
-  case SurfaceType::D2D1_BITMAP:
-   image = static_cast<SourceSurfaceD2D*>(aSurface)->GetBitmap();
-    break;
-  case SurfaceType::D2D1_DRAWTARGET: {
-      SourceSurfaceD2DTarget *surf = static_cast<SourceSurfaceD2DTarget*>(aSurface);
-      image = surf->GetBitmap(static_cast<DrawTargetD2D*>(aDT)->GetRT());
-    }
-    break;
-  default:
-    gfxWarning() << "Unknown input SourceSurface set on effect.";
-    MOZ_ASSERT(0);
-  }
-
-  return image;
 }
 
 uint32_t ConvertValue(FilterType aType, uint32_t aAttribute, uint32_t aValue)
 {
   switch (aType) {
   case FilterType::COLOR_MATRIX:
     if (aAttribute == ATT_COLOR_MATRIX_ALPHA_MODE) {
       aValue = D2DAlphaMode(aValue);
--- a/gfx/2d/MacIOSurface.h
+++ b/gfx/2d/MacIOSurface.h
@@ -38,17 +38,16 @@ typedef CGImageRef (*IOSurfaceContextCre
 typedef IOSurfacePtr (*IOSurfaceContextGetSurfaceFunc)(CGContextRef ref);
 
 
 
 #import <OpenGL/OpenGL.h>
 #include "2D.h"
 #include "mozilla/RefPtr.h"
 
-class gfxASurface;
 struct _CGLContextObject;
 
 typedef _CGLContextObject* CGLContextObj;
 typedef struct CGContext* CGContextRef;
 typedef struct CGImage* CGImageRef;
 typedef uint32_t IOSurfaceID;
 
 enum CGContextType {
--- a/gfx/gl/GLContext.h
+++ b/gfx/gl/GLContext.h
@@ -22,17 +22,16 @@
 #endif
 
 #ifdef GetClassName
 #undef GetClassName
 #endif
 
 #include "GLDefs.h"
 #include "GLLibraryLoader.h"
-#include "gfxImageSurface.h"
 #include "gfx3DMatrix.h"
 #include "nsISupportsImpl.h"
 #include "plstr.h"
 #include "nsDataHashtable.h"
 #include "nsHashKeys.h"
 #include "nsAutoPtr.h"
 #include "GLContextTypes.h"
 #include "GLTextureImage.h"
@@ -2519,16 +2518,18 @@ public:
         // support contexts used on multiple threads.
         NS_ASSERTION(IsOwningThreadCurrent(),
                      "MakeCurrent() called on different thread than this context was created on!");
 #endif
 #endif
         return MakeCurrentImpl(aForce);
     }
 
+    virtual bool Init() = 0;
+
     virtual bool SetupLookupFunction() = 0;
 
     virtual void ReleaseSurface() {}
 
     // Mark this context as destroyed.  This will nullptr out all
     // the GL function pointers!
     void MarkDestroyed();
 
--- a/gfx/gl/GLContextCGL.h
+++ b/gfx/gl/GLContextCGL.h
@@ -37,17 +37,17 @@ public:
 
     virtual GLContextType GetContextType() const MOZ_OVERRIDE { return GLContextType::CGL; }
 
     static GLContextCGL* Cast(GLContext* gl) {
         MOZ_ASSERT(gl->GetContextType() == GLContextType::CGL);
         return static_cast<GLContextCGL*>(gl);
     }
 
-    bool Init();
+    bool Init() MOZ_OVERRIDE;
 
     NSOpenGLContext* GetNSOpenGLContext() const { return mContext; }
     CGLContextObj GetCGLContext() const;
 
     virtual bool MakeCurrentImpl(bool aForce) MOZ_OVERRIDE;
 
     virtual bool IsCurrent() MOZ_OVERRIDE;
 
--- a/gfx/gl/GLContextEGL.h
+++ b/gfx/gl/GLContextEGL.h
@@ -41,17 +41,17 @@ public:
 
     virtual GLContextType GetContextType() const MOZ_OVERRIDE { return GLContextType::EGL; }
 
     static GLContextEGL* Cast(GLContext* gl) {
         MOZ_ASSERT(gl->GetContextType() == GLContextType::EGL);
         return static_cast<GLContextEGL*>(gl);
     }
 
-    bool Init();
+    bool Init() MOZ_OVERRIDE;
 
     virtual bool IsDoubleBuffered() const MOZ_OVERRIDE {
         return mIsDoubleBuffered;
     }
 
     void SetIsDoubleBuffered(bool aIsDB) {
         mIsDoubleBuffered = aIsDB;
     }
@@ -112,16 +112,17 @@ protected:
 
     bool mIsPBuffer;
     bool mIsDoubleBuffered;
     bool mCanBindToTexture;
     bool mShareWithEGLImage;
 #ifdef MOZ_WIDGET_GONK
     nsRefPtr<HwcComposer2D> mHwc;
 #endif
+    bool mOwnsContext;
 
     static EGLSurface CreatePBufferSurfaceTryingPowerOfTwo(EGLConfig config,
                                                            EGLenum bindToTextureFormat,
                                                            gfxIntSize& pbsize);
 };
 
 }
 }
--- a/gfx/gl/GLContextGLX.h
+++ b/gfx/gl/GLContextGLX.h
@@ -31,17 +31,17 @@ public:
 
     virtual GLContextType GetContextType() const MOZ_OVERRIDE { return GLContextType::GLX; }
 
     static GLContextGLX* Cast(GLContext* gl) {
         MOZ_ASSERT(gl->GetContextType() == GLContextType::GLX);
         return static_cast<GLContextGLX*>(gl);
     }
 
-    bool Init();
+    bool Init() MOZ_OVERRIDE;
 
     virtual bool MakeCurrentImpl(bool aForce) MOZ_OVERRIDE;
 
     virtual bool IsCurrent() MOZ_OVERRIDE;
 
     virtual bool SetupLookupFunction() MOZ_OVERRIDE;
 
     virtual bool IsDoubleBuffered() const MOZ_OVERRIDE;
@@ -67,14 +67,15 @@ private:
     Display *mDisplay;
     GLXDrawable mDrawable;
     bool mDeleteDrawable;
     bool mDoubleBuffered;
 
     GLXLibrary* mGLX;
 
     nsRefPtr<gfxXlibSurface> mPixmap;
+    bool mOwnsContext;
 };
 
 }
 }
 
 #endif // GLCONTEXTGLX_H_
--- a/gfx/gl/GLContextProvider.h
+++ b/gfx/gl/GLContextProvider.h
@@ -2,23 +2,22 @@
  * 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 GLCONTEXTPROVIDER_H_
 #define GLCONTEXTPROVIDER_H_
 
 #include "GLContextTypes.h"
-#include "gfxTypes.h"
-#include "gfxPoint.h"
 #include "nsAutoPtr.h"
 #include "SurfaceTypes.h"
 
+#include "nsSize.h" // for gfxIntSize (needed by GLContextProviderImpl.h below)
+
 class nsIWidget;
-class gfxASurface;
 
 namespace mozilla {
 namespace gl {
 
 #define IN_GL_CONTEXT_PROVIDER_H
 
 // Null is always there
 #define GL_CONTEXT_PROVIDER_NAME GLContextProviderNull
--- a/gfx/gl/GLContextProviderCGL.mm
+++ b/gfx/gl/GLContextProviderCGL.mm
@@ -4,19 +4,16 @@
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #include "GLContextProvider.h"
 #include "GLContextCGL.h"
 #include "TextureImageCGL.h"
 #include "nsDebug.h"
 #include "nsIWidget.h"
 #include <OpenGL/gl.h>
-#include "gfxASurface.h"
-#include "gfxImageSurface.h"
-#include "gfxQuartzSurface.h"
 #include "gfxPrefs.h"
 #include "gfxFailure.h"
 #include "prenv.h"
 #include "mozilla/Preferences.h"
 #include "GeckoProfiler.h"
 #include "mozilla/gfx/MacIOSurface.h"
 
 using namespace mozilla::gfx;
@@ -185,22 +182,24 @@ GLContextCGL::SwapBuffers()
 
 static GLContextCGL *
 GetGlobalContextCGL()
 {
     return static_cast<GLContextCGL*>(GLContextProviderCGL::GetGlobalContext());
 }
 
 already_AddRefed<GLContext>
+GLContextProviderCGL::CreateWrappingExisting(void*, void*)
+{
+    return nullptr;
+}
+
+already_AddRefed<GLContext>
 GLContextProviderCGL::CreateForWindow(nsIWidget *aWidget)
 {
-    if (!sCGLLibrary.EnsureInitialized()) {
-        return nullptr;
-    }
-
     GLContextCGL *shareContext = GetGlobalContextCGL();
 
     NSOpenGLContext *context = [[NSOpenGLContext alloc]
                                 initWithFormat:sCGLLibrary.PixelFormat()
                                 shareContext:(shareContext ? shareContext->mContext : NULL)];
     if (!context) {
         return nullptr;
     }
--- a/gfx/gl/GLContextProviderEGL.cpp
+++ b/gfx/gl/GLContextProviderEGL.cpp
@@ -95,17 +95,16 @@ public:
 #error "Platform not recognized"
 
 #endif
 
 #include "mozilla/Preferences.h"
 #include "gfxUtils.h"
 #include "gfxFailure.h"
 #include "gfxASurface.h"
-#include "gfxImageSurface.h"
 #include "gfxPlatform.h"
 #include "GLContextProvider.h"
 #include "GLLibraryEGL.h"
 #include "TextureImageEGL.h"
 #include "nsDebug.h"
 #include "nsThreadUtils.h"
 
 #include "nsIWidget.h"
@@ -229,16 +228,17 @@ GLContextEGL::GLContextEGL(
     , mSurfaceOverride(EGL_NO_SURFACE)
     , mContext(context)
     , mThebesSurface(nullptr)
     , mBound(false)
     , mIsPBuffer(false)
     , mIsDoubleBuffered(false)
     , mCanBindToTexture(false)
     , mShareWithEGLImage(false)
+    , mOwnsContext(true)
 {
     // any EGL contexts will always be GLESv2
     SetProfileVersion(ContextProfile::OpenGLES, 200);
 
 #ifdef DEBUG
     printf_stderr("Initializing context %p surface %p on display %p\n", mContext, mSurface, EGL_DISPLAY());
 #endif
 #if defined(MOZ_WIDGET_GONK)
@@ -253,16 +253,21 @@ GLContextEGL::GLContextEGL(
     }
 #endif
 }
 
 GLContextEGL::~GLContextEGL()
 {
     MarkDestroyed();
 
+    // Wrapped context should not destroy eglContext/Surface
+    if (!mOwnsContext) {
+        return;
+    }
+
 #ifdef DEBUG
     printf_stderr("Destroying context %p surface %p on display %p\n", mContext, mSurface, EGL_DISPLAY());
 #endif
 
     sEGLLibrary.fDestroyContext(EGL_DISPLAY(), mContext);
 
 #if defined(MOZ_WIDGET_GONK) && ANDROID_VERSION < 17
     if (!mIsOffscreen) {
@@ -405,16 +410,19 @@ GLContextEGL::MakeCurrentImpl(bool aForc
 
 bool
 GLContextEGL::IsCurrent() {
     return sEGLLibrary.fGetCurrentContext() == mContext;
 }
 
 bool
 GLContextEGL::RenewSurface() {
+    if (!mOwnsContext) {
+        return false;
+    }
 #ifndef MOZ_WIDGET_ANDROID
     MOZ_CRASH("unimplemented");
     // to support this on non-Android platforms, need to keep track of the nsIWidget that
     // this GLContext was created for (with CreateForWindow) so that we know what to
     // pass again to CreateSurfaceForWindow below.
     // The reason why Android doesn't need this is that it delegates EGLSurface creation to
     // Java code which is the only thing that knows about our actual widget.
 #endif
@@ -425,17 +433,19 @@ GLContextEGL::RenewSurface() {
     if (mSurface == EGL_NO_SURFACE) {
         return false;
     }
     return MakeCurrent(true);
 }
 
 void
 GLContextEGL::ReleaseSurface() {
-    DestroySurface(mSurface);
+    if (mOwnsContext) {
+        DestroySurface(mSurface);
+    }
     mSurface = EGL_NO_SURFACE;
 }
 
 bool
 GLContextEGL::SetupLookupFunction()
 {
     mLookupFunc = (PlatformLookupFunction)sEGLLibrary.mSymbols.fGetProcAddress;
     return true;
@@ -678,16 +688,41 @@ CreateConfig(EGLConfig* aConfig)
 #endif
         return false;
     } else {
         return true;
     }
 }
 
 already_AddRefed<GLContext>
+GLContextProviderEGL::CreateWrappingExisting(void* aContext, void* aSurface)
+{
+    if (!sEGLLibrary.EnsureInitialized()) {
+        MOZ_CRASH("Failed to load EGL library!\n");
+        return nullptr;
+    }
+
+    if (aContext && aSurface) {
+        SurfaceCaps caps = SurfaceCaps::Any();
+        EGLConfig config = EGL_NO_CONFIG;
+        nsRefPtr<GLContextEGL> glContext =
+            new GLContextEGL(caps,
+                             nullptr, false,
+                             config, (EGLSurface)aSurface, (EGLContext)aContext);
+
+        glContext->SetIsDoubleBuffered(true);
+        glContext->mOwnsContext = false;
+
+        return glContext.forget();
+    }
+
+    return nullptr;
+}
+
+already_AddRefed<GLContext>
 GLContextProviderEGL::CreateForWindow(nsIWidget *aWidget)
 {
     if (!sEGLLibrary.EnsureInitialized()) {
         MOZ_CRASH("Failed to load EGL library!\n");
         return nullptr;
     }
 
     bool doubleBuffered = true;
--- a/gfx/gl/GLContextProviderGLX.cpp
+++ b/gfx/gl/GLContextProviderGLX.cpp
@@ -21,17 +21,16 @@
 #include "prenv.h"
 #include "GLContextProvider.h"
 #include "GLLibraryLoader.h"
 #include "nsDebug.h"
 #include "nsIWidget.h"
 #include "GLXLibrary.h"
 #include "gfxXlibSurface.h"
 #include "gfxContext.h"
-#include "gfxImageSurface.h"
 #include "gfxPlatform.h"
 #include "GLContextGLX.h"
 #include "gfxUtils.h"
 #include "gfx2DGlue.h"
 
 #include "gfxCrashReporterUtils.h"
 
 #ifdef MOZ_WIDGET_GTK
@@ -820,16 +819,21 @@ TRY_AGAIN_NO_SHARING:
 
     return glContext.forget();
 }
 
 GLContextGLX::~GLContextGLX()
 {
     MarkDestroyed();
 
+    // Wrapped context should not destroy glxContext/Surface
+    if (!mOwnsContext) {
+        return;
+    }
+
     // see bug 659842 comment 76
 #ifdef DEBUG
     bool success =
 #endif
     mGLX->xMakeCurrent(mDisplay, None, nullptr);
     NS_ABORT_IF_FALSE(success,
         "glXMakeCurrent failed to release GL context before we call glXDestroyContext!");
 
@@ -919,17 +923,18 @@ GLContextGLX::GLContextGLX(
                   gfxXlibSurface *aPixmap)
     : GLContext(caps, shareContext, isOffscreen),//aDeleteDrawable ? true : false, aShareContext, ),
       mContext(aContext),
       mDisplay(aDisplay),
       mDrawable(aDrawable),
       mDeleteDrawable(aDeleteDrawable),
       mDoubleBuffered(aDoubleBuffered),
       mGLX(&sGLXLibrary),
-      mPixmap(aPixmap)
+      mPixmap(aPixmap),
+      mOwnsContext(true)
 {
     MOZ_ASSERT(mGLX);
     // See 899855
     SetProfileVersion(ContextProfile::OpenGLCompatibility, 200);
 }
 
 
 static GLContextGLX *
@@ -953,31 +958,66 @@ AreCompatibleVisuals(Visual *one, Visual
 
     if (one->bits_per_rgb != two->bits_per_rgb) {
         return false;
     }
 
     return true;
 }
 
+static StaticRefPtr<GLContext> gGlobalContext;
+
+already_AddRefed<GLContext>
+GLContextProviderGLX::CreateWrappingExisting(void* aContext, void* aSurface)
+{
+    if (!sGLXLibrary.EnsureInitialized()) {
+        return nullptr;
+    }
+
+    if (aContext && aSurface) {
+        SurfaceCaps caps = SurfaceCaps::Any();
+        nsRefPtr<GLContextGLX> glContext =
+            new GLContextGLX(caps,
+                             nullptr, // SharedContext
+                             false, // Offscreen
+                             (Display*)DefaultXDisplay(), // Display
+                             (GLXDrawable)aSurface, (GLXContext)aContext,
+                             false, // aDeleteDrawable,
+                             true,
+                             (gfxXlibSurface*)nullptr);
+
+        glContext->mOwnsContext = false;
+        gGlobalContext = glContext;
+
+        return glContext.forget();
+    }
+
+    return nullptr;
+}
+
 already_AddRefed<GLContext>
 GLContextProviderGLX::CreateForWindow(nsIWidget *aWidget)
 {
     if (!sGLXLibrary.EnsureInitialized()) {
         return nullptr;
     }
 
     // Currently, we take whatever Visual the window already has, and
     // try to create an fbconfig for that visual.  This isn't
     // necessarily what we want in the long run; an fbconfig may not
     // be available for the existing visual, or if it is, the GL
     // performance might be suboptimal.  But using the existing visual
     // is a relatively safe intermediate step.
 
     Display *display = (Display*)aWidget->GetNativeData(NS_NATIVE_DISPLAY);
+    if (!display) {
+        NS_ERROR("X Display required for GLX Context provider");
+        return nullptr;
+    }
+
     int xscreen = DefaultScreen(display);
     Window window = GET_NATIVE_WINDOW(aWidget);
 
     int numConfigs;
     ScopedXFree<GLXFBConfig> cfgs;
     if (sGLXLibrary.IsATI() ||
         !sGLXLibrary.GLXVersionCheck(1, 3)) {
         const int attribs[] = {
@@ -1184,18 +1224,16 @@ GLContextProviderGLX::CreateOffscreen(co
         return nullptr;
 
     if (!glContext->InitOffscreen(ToIntSize(size), caps))
         return nullptr;
 
     return glContext.forget();
 }
 
-static StaticRefPtr<GLContext> gGlobalContext;
-
 GLContext*
 GLContextProviderGLX::GetGlobalContext()
 {
     static bool checkedContextSharing = false;
     static bool useContextSharing = false;
 
     if (!checkedContextSharing) {
         useContextSharing = getenv("MOZ_DISABLE_CONTEXT_SHARING_GLX") == 0;
--- a/gfx/gl/GLContextProviderImpl.h
+++ b/gfx/gl/GLContextProviderImpl.h
@@ -57,16 +57,27 @@ public:
      *
      * @return Context to use for offscreen rendering
      */
     static already_AddRefed<GLContext>
     CreateOffscreen(const gfxIntSize& size,
                     const SurfaceCaps& caps);
 
     /**
+     * Create wrapping Gecko GLContext for external gl context.
+     *
+     * @param aContext External context which will be wrapped by Gecko GLContext.
+     * @param aSurface External surface which is used for external context.
+     *
+     * @return Wrapping Context to use for rendering
+     */
+    static already_AddRefed<GLContext>
+    CreateWrappingExisting(void* aContext, void* aSurface);
+
+    /**
      * Get a pointer to the global context, creating it if it doesn't exist.
      */
     static GLContext*
     GetGlobalContext();
 
     /**
      * Free any resources held by this Context Provider.
      */
--- a/gfx/gl/GLContextProviderNull.cpp
+++ b/gfx/gl/GLContextProviderNull.cpp
@@ -10,16 +10,22 @@ namespace gl {
 
 already_AddRefed<GLContext>
 GLContextProviderNull::CreateForWindow(nsIWidget*)
 {
     return nullptr;
 }
 
 already_AddRefed<GLContext>
+GLContextProviderNull::CreateWrappingExisting(void*, void*)
+{
+    return nullptr;
+}
+
+already_AddRefed<GLContext>
 GLContextProviderNull::CreateOffscreen(const gfxIntSize&,
                                        const SurfaceCaps&,
                                        ContextFlags)
 {
     return nullptr;
 }
 
 GLContext*
--- a/gfx/gl/GLContextProviderWGL.cpp
+++ b/gfx/gl/GLContextProviderWGL.cpp
@@ -3,18 +3,16 @@
  * 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 "GLContextProvider.h"
 #include "GLContextWGL.h"
 #include "GLLibraryLoader.h"
 #include "nsDebug.h"
 #include "nsIWidget.h"
-#include "gfxASurface.h"
-#include "gfxImageSurface.h"
 #include "gfxPlatform.h"
 #include "gfxWindowsSurface.h"
 
 #include "gfxCrashReporterUtils.h"
 
 #include "prenv.h"
 
 #include "mozilla/Preferences.h"
@@ -396,16 +394,22 @@ IsValidSizeForFormat(HDC hDC, int format
 
 static GLContextWGL *
 GetGlobalContextWGL()
 {
     return static_cast<GLContextWGL*>(GLContextProviderWGL::GetGlobalContext());
 }
 
 already_AddRefed<GLContext>
+GLContextProviderWGL::CreateWrappingExisting(void*, void*)
+{
+    return nullptr;
+}
+
+already_AddRefed<GLContext>
 GLContextProviderWGL::CreateForWindow(nsIWidget *aWidget)
 {
     if (!sWGLLib.EnsureInitialized()) {
         return nullptr;
     }
 
     /**
        * We need to make sure we call SetPixelFormat -after- calling
--- a/gfx/gl/GLContextWGL.h
+++ b/gfx/gl/GLContextWGL.h
@@ -38,17 +38,17 @@ public:
 
     virtual GLContextType GetContextType() const MOZ_OVERRIDE { return GLContextType::WGL; }
 
     static GLContextWGL* Cast(GLContext* gl) {
         MOZ_ASSERT(gl->GetContextType() == GLContextType::WGL);
         return static_cast<GLContextWGL*>(gl);
     }
 
-    bool Init();
+    bool Init() MOZ_OVERRIDE;
 
     virtual bool MakeCurrentImpl(bool aForce) MOZ_OVERRIDE;
 
     virtual bool IsCurrent() MOZ_OVERRIDE;
 
     void SetIsDoubleBuffered(bool aIsDB);
 
     virtual bool IsDoubleBuffered() const MOZ_OVERRIDE;
--- a/gfx/gl/GLReadTexImageHelper.cpp
+++ b/gfx/gl/GLReadTexImageHelper.cpp
@@ -4,16 +4,17 @@
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #include "GLReadTexImageHelper.h"
 #include "GLContext.h"
 #include "OGLShaderProgram.h"
 #include "gfxTypes.h"
 #include "gfxContext.h"
+#include "gfxImageSurface.h"
 #include "ScopedGLHelpers.h"
 #include "mozilla/gfx/2D.h"
 #include "gfx2DGlue.h"
 
 using namespace mozilla::gfx;
 
 namespace mozilla {
 namespace gl {
--- a/gfx/gl/SharedSurfaceGL.h
+++ b/gfx/gl/SharedSurfaceGL.h
@@ -13,17 +13,16 @@
 #include "GLContextTypes.h"
 #include "nsAutoPtr.h"
 #include "gfxTypes.h"
 #include "mozilla/Mutex.h"
 
 #include <queue>
 
 // Forwards:
-class gfxImageSurface;
 namespace mozilla {
     namespace gl {
         class GLContext;
     }
     namespace gfx {
         class DataSourceSurface;
     }
 }
--- a/gfx/gl/SharedSurfaceIO.cpp
+++ b/gfx/gl/SharedSurfaceIO.cpp
@@ -1,16 +1,15 @@
 /* -*- Mode: c++; c-basic-offset: 4; indent-tabs-mode: nil; tab-width: 40; -*- */
 /* 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 "SharedSurfaceIO.h"
 #include "GLContextCGL.h"
-#include "gfxImageSurface.h"
 #include "mozilla/gfx/MacIOSurface.h"
 #include "mozilla/DebugOnly.h"
 #include "ScopedGLHelpers.h"
 
 namespace mozilla {
 namespace gl {
 
 using namespace gfx;
--- a/gfx/gl/SharedSurfaceIO.h
+++ b/gfx/gl/SharedSurfaceIO.h
@@ -1,16 +1,17 @@
 /* -*- Mode: c++; c-basic-offset: 4; indent-tabs-mode: nil; tab-width: 40; -*- */
 /* 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 SHARED_SURFACEIO_H_
 #define SHARED_SURFACEIO_H_
 
+#include "gfxImageSurface.h"
 #include "SharedSurfaceGL.h"
 #include "mozilla/RefPtr.h"
 
 class MacIOSurface;
 
 namespace mozilla {
 namespace gl {
 
--- a/gfx/layers/CopyableCanvasLayer.cpp
+++ b/gfx/layers/CopyableCanvasLayer.cpp
@@ -5,17 +5,16 @@
 
 #include "BasicLayersImpl.h"            // for FillWithMask, etc
 #include "CopyableCanvasLayer.h"
 #include "GLContext.h"                  // for GLContext
 #include "GLScreenBuffer.h"             // for GLScreenBuffer
 #include "SharedSurface.h"              // for SharedSurface
 #include "SharedSurfaceGL.h"            // for SharedSurface_GL, etc
 #include "SurfaceTypes.h"               // for APITypeT, APITypeT::OpenGL, etc
-#include "gfxImageSurface.h"            // for gfxImageSurface
 #include "gfxMatrix.h"                  // for gfxMatrix
 #include "gfxPattern.h"                 // for gfxPattern, etc
 #include "gfxPlatform.h"                // for gfxPlatform, gfxImageFormat
 #include "gfxRect.h"                    // for gfxRect
 #include "gfxUtils.h"                   // for gfxUtils
 #include "gfx2DGlue.h"                  // for thebes --> moz2d transition
 #include "mozilla/gfx/BaseSize.h"       // for BaseSize
 #include "nsDebug.h"                    // for NS_ASSERTION, NS_WARNING, etc
--- a/gfx/layers/CopyableCanvasLayer.h
+++ b/gfx/layers/CopyableCanvasLayer.h
@@ -4,17 +4,16 @@
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #ifndef GFX_COPYABLECANVASLAYER_H
 #define GFX_COPYABLECANVASLAYER_H
 
 #include <stdint.h>                     // for uint32_t
 #include "GLContextTypes.h"             // for GLContext
 #include "Layers.h"                     // for CanvasLayer, etc
-#include "gfxASurface.h"                // for gfxASurface
 #include "gfxContext.h"                 // for gfxContext, etc
 #include "gfxTypes.h"
 #include "gfxPlatform.h"                // for gfxImageFormat
 #include "mozilla/Assertions.h"         // for MOZ_ASSERT, etc
 #include "mozilla/Preferences.h"        // for Preferences
 #include "mozilla/RefPtr.h"             // for RefPtr
 #include "mozilla/gfx/2D.h"             // for DrawTarget
 #include "mozilla/mozalloc.h"           // for operator delete, etc
--- a/gfx/layers/D3D9SurfaceImage.cpp
+++ b/gfx/layers/D3D9SurfaceImage.cpp
@@ -1,15 +1,14 @@
 /* -*- Mode: C++; tab-width: 20; 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/. */
 
 #include "D3D9SurfaceImage.h"
-#include "gfxImageSurface.h"
 #include "gfx2DGlue.h"
 #include "mozilla/layers/TextureD3D9.h"
 #include "mozilla/gfx/Types.h"
 
 namespace mozilla {
 namespace layers {
 
 
--- a/gfx/layers/GrallocImages.cpp
+++ b/gfx/layers/GrallocImages.cpp
@@ -6,17 +6,16 @@
 
 #include "GrallocImages.h"
 #include <stddef.h>                     // for size_t
 #include <stdint.h>                     // for int8_t, uint8_t, uint32_t, etc
 #include "nsDebug.h"                    // for NS_WARNING, NS_PRECONDITION
 #include "mozilla/layers/ImageBridgeChild.h"
 #include "mozilla/layers/GrallocTextureClient.h"
 #include "gfx2DGlue.h"
-#include "gfxImageSurface.h"
 #include "YCbCrUtils.h"                 // for YCbCr conversions
 
 #include <ColorConverter.h>
 #include <OMX_IVCommon.h>
 
 
 using namespace mozilla::ipc;
 using namespace android;
--- a/gfx/layers/ImageContainer.cpp
+++ b/gfx/layers/ImageContainer.cpp
@@ -3,17 +3,16 @@
  * 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 "ImageContainer.h"
 #include <string.h>                     // for memcpy, memset
 #include "SharedTextureImage.h"         // for SharedTextureImage
 #include "gfx2DGlue.h"
-#include "gfxImageSurface.h"            // for gfxImageSurface
 #include "gfxPlatform.h"                // for gfxPlatform
 #include "gfxUtils.h"                   // for gfxUtils
 #include "mozilla/RefPtr.h"             // for TemporaryRef
 #include "mozilla/ipc/CrossProcessMutex.h"  // for CrossProcessMutex, etc
 #include "mozilla/layers/CompositorTypes.h"
 #include "mozilla/layers/ImageBridgeChild.h"  // for ImageBridgeChild
 #include "mozilla/layers/ImageClient.h"  // for ImageClient
 #include "nsISupportsUtils.h"           // for NS_IF_ADDREF
--- a/gfx/layers/ImageContainer.h
+++ b/gfx/layers/ImageContainer.h
@@ -3,18 +3,18 @@
  * 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 GFX_IMAGECONTAINER_H
 #define GFX_IMAGECONTAINER_H
 
 #include <stdint.h>                     // for uint32_t, uint8_t, uint64_t
 #include <sys/types.h>                  // for int32_t
+#include "gfxTypes.h"
 #include "ImageTypes.h"                 // for ImageFormat, etc
-#include "gfxASurface.h"                // for gfxASurface, etc
 #include "mozilla/Assertions.h"         // for MOZ_ASSERT_HELPER2
 #include "mozilla/Mutex.h"              // for Mutex
 #include "mozilla/ReentrantMonitor.h"   // for ReentrantMonitorAutoEnter, etc
 #include "mozilla/TimeStamp.h"          // for TimeStamp
 #include "mozilla/gfx/Point.h"          // For IntSize
 #include "mozilla/layers/LayersTypes.h"  // for LayersBackend, etc
 #include "mozilla/mozalloc.h"           // for operator delete, etc
 #include "nsAutoPtr.h"                  // for nsRefPtr, nsAutoArrayPtr, etc
--- a/gfx/layers/ImageDataSerializer.cpp
+++ b/gfx/layers/ImageDataSerializer.cpp
@@ -1,16 +1,15 @@
 /* -*- Mode: C++; tab-width: 20; 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/. */
 
 #include "ImageDataSerializer.h"
 #include "gfx2DGlue.h"                  // for SurfaceFormatToImageFormat
-#include "gfxASurface.h"                // for gfxASurface
 #include "gfxImageSurface.h"            // for gfxImageSurface
 #include "gfxPoint.h"                   // for gfxIntSize
 #include "mozilla/Assertions.h"         // for MOZ_ASSERT, etc
 #include "mozilla/gfx/2D.h"             // for DataSourceSurface, Factory
 #include "mozilla/gfx/Tools.h"          // for GetAlignedStride, etc
 #include "mozilla/mozalloc.h"           // for operator delete, etc
 
 namespace mozilla {
--- a/gfx/layers/LayerSorter.cpp
+++ b/gfx/layers/LayerSorter.cpp
@@ -148,35 +148,35 @@ static LayerSortOrder CompareDepth(Layer
   } else {
     return BBeforeA;
   }
 }
 
 #ifdef DEBUG
 static bool gDumpLayerSortList = getenv("MOZ_DUMP_LAYER_SORT_LIST") != 0;
 
-#define BLACK       0
-#define RED         1
-#define GREEN       2
-#define YELLOW      3
-#define BLUE        4
-#define MAGENTA     5
-#define CYAN        6
-#define WHITE       7
+static const int BLACK = 0;
+static const int RED = 1;
+static const int GREEN = 2;
+static const int YELLOW = 3;
+static const int BLUE = 4;
+static const int MAGENTA = 5;
+static const int CYAN = 6;
+static const int WHITE = 7;
 
 //#define USE_XTERM_COLORING
 #ifdef USE_XTERM_COLORING
 
-#define RESET       0
-#define BRIGHT      1
-#define DIM         2
-#define UNDERLINE   3
-#define BLINK       4
-#define REVERSE     7
-#define HIDDEN      8
+static const int RESET = 0;
+static const int BRIGHT = 1;
+static const int DIM = 2;
+static const int UNDERLINE = 3;
+static const int BLINK = 4;
+static const int REVERSE = 7;
+static const int HIDDEN = 8;
 
 static void SetTextColor(uint32_t aColor)
 {
   char command[13];
 
   /* Command is the control command to the terminal */
   sprintf(command, "%c[%d;%d;%dm", 0x1B, RESET, aColor + 30, BLACK + 40);
   printf("%s", command);
--- a/gfx/layers/Layers.h
+++ b/gfx/layers/Layers.h
@@ -42,17 +42,16 @@
 #include "nsString.h"                   // for nsCString
 #include "nsStyleAnimation.h"           // for nsStyleAnimation::Value, etc
 #include "nsTArray.h"                   // for nsTArray
 #include "nsTArrayForwardDeclare.h"     // for InfallibleTArray
 #include "nscore.h"                     // for nsACString, nsAString
 #include "prlog.h"                      // for PRLogModuleInfo
 #include "gfx2DGlue.h"
 
-class gfxASurface;
 class gfxContext;
 
 extern uint8_t gLayerManagerLayerBuilder;
 
 namespace mozilla {
 
 class FrameLayerBuilder;
 class WebGLContext;
--- a/gfx/layers/MacIOSurfaceImage.h
+++ b/gfx/layers/MacIOSurfaceImage.h
@@ -5,17 +5,16 @@
 
 #ifndef GFX_MACIOSURFACEIMAGE_H
 #define GFX_MACIOSURFACEIMAGE_H
 
 #include "ImageContainer.h"
 #include "mozilla/gfx/MacIOSurface.h"
 #include "mozilla/gfx/Point.h"
 #include "mozilla/layers/TextureClient.h"
-#include "gfxImageSurface.h"
 
 namespace mozilla {
 
 namespace layers {
 
 class MacIOSurfaceImage : public Image,
                           public ISharedImage {
 public:
--- a/gfx/layers/RotatedBuffer.h
+++ b/gfx/layers/RotatedBuffer.h
@@ -1,18 +1,18 @@
 /* -*- Mode: C++; tab-width: 20; 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/. */
 
 #ifndef ROTATEDBUFFER_H_
 #define ROTATEDBUFFER_H_
 
+#include "gfxTypes.h"
 #include <stdint.h>                     // for uint32_t
-#include "gfxASurface.h"                // for gfxASurface, etc
 #include "mozilla/Assertions.h"         // for MOZ_ASSERT, etc
 #include "mozilla/RefPtr.h"             // for RefPtr, TemporaryRef
 #include "mozilla/gfx/2D.h"             // for DrawTarget, etc
 #include "mozilla/mozalloc.h"           // for operator delete
 #include "nsAutoPtr.h"                  // for nsRefPtr
 #include "nsCOMPtr.h"                   // for already_AddRefed
 #include "nsDebug.h"                    // for NS_RUNTIMEABORT
 #include "nsISupportsImpl.h"            // for MOZ_COUNT_CTOR, etc
--- a/gfx/layers/SharedTextureImage.h
+++ b/gfx/layers/SharedTextureImage.h
@@ -7,18 +7,16 @@
 #define GFX_SHAREDTEXTUREIMAGE_H
 
 #include "GLContextProvider.h"          // for GLContextProvider
 #include "ImageContainer.h"             // for Image
 #include "ImageTypes.h"                 // for ImageFormat::SHARED_TEXTURE
 #include "nsCOMPtr.h"                   // for already_AddRefed
 #include "mozilla/gfx/Point.h"          // for IntSize
 
-class gfxASurface;
-
 // Split into a separate header from ImageLayers.h due to GLContext.h dependence
 // Implementation remains in ImageLayers.cpp
 
 namespace mozilla {
 
 namespace layers {
 
 class SharedTextureImage : public Image {
--- a/gfx/layers/basic/AutoMaskData.h
+++ b/gfx/layers/basic/AutoMaskData.h
@@ -1,27 +1,25 @@
 /* -*- Mode: C++; 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/. */
 
 #ifndef GFX_AUTOMASKDATA_H_
 #define GFX_AUTOMASKDATA_H_
 
-#include "gfxASurface.h"
 #include "mozilla/layers/LayersSurfaces.h"  // for SurfaceDescriptor
 
 namespace mozilla {
 namespace layers {
 
 /**
  * Drawing with a mask requires a mask surface and a transform.
  *
- * This helper class manages the gfxASurface
- * logic.
+ * This helper class manages the SourceSurface logic.
  */
 class MOZ_STACK_CLASS AutoMoz2DMaskData {
 public:
   AutoMoz2DMaskData() { }
   ~AutoMoz2DMaskData() { }
 
   void Construct(const gfx::Matrix& aTransform,
                  gfx::SourceSurface* aSurface)
--- a/gfx/layers/basic/BasicImageLayer.cpp
+++ b/gfx/layers/basic/BasicImageLayer.cpp
@@ -4,23 +4,16 @@
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #include "BasicLayersImpl.h"            // for FillRectWithMask, etc
 #include "ImageContainer.h"             // for AutoLockImage, etc
 #include "ImageLayers.h"                // for ImageLayer
 #include "Layers.h"                     // for Layer (ptr only), etc
 #include "basic/BasicImplData.h"        // for BasicImplData
 #include "basic/BasicLayers.h"          // for BasicLayerManager
-#include "gfxASurface.h"                // for gfxASurface, etc
-#include "gfxContext.h"                 // for gfxContext
-#include "gfxPattern.h"                 // for gfxPattern, etc
-#include "gfxUtils.h"                   // for gfxUtils
-#ifdef MOZ_X11
-#include "gfxXlibSurface.h"             // for gfxXlibSurface
-#endif
 #include "mozilla/mozalloc.h"           // for operator new
 #include "nsAutoPtr.h"                  // for nsRefPtr, getter_AddRefs, etc
 #include "nsCOMPtr.h"                   // for already_AddRefed
 #include "nsDebug.h"                    // for NS_ASSERTION
 #include "nsISupportsImpl.h"            // for gfxPattern::Release, etc
 #include "nsRect.h"                     // for nsIntRect
 #include "nsRegion.h"                   // for nsIntRegion
 #include "mozilla/gfx/Point.h"          // for IntSize
--- a/gfx/layers/basic/BasicImages.cpp
+++ b/gfx/layers/basic/BasicImages.cpp
@@ -4,17 +4,16 @@
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #include <stdint.h>                     // for uint8_t, uint32_t
 #include "BasicLayers.h"                // for BasicLayerManager
 #include "ImageContainer.h"             // for PlanarYCbCrImage, etc
 #include "ImageTypes.h"                 // for ImageFormat, etc
 #include "cairo.h"                      // for cairo_user_data_key_t
 #include "gfxASurface.h"                // for gfxASurface, etc
-#include "gfxImageSurface.h"            // for gfxImageSurface
 #include "gfxPlatform.h"                // for gfxPlatform, gfxImageFormat
 #include "gfxUtils.h"                   // for gfxUtils
 #include "mozilla/mozalloc.h"           // for operator delete[], etc
 #include "nsAutoPtr.h"                  // for nsRefPtr, nsAutoArrayPtr
 #include "nsAutoRef.h"                  // for nsCountedRef
 #include "nsCOMPtr.h"                   // for already_AddRefed
 #include "nsDebug.h"                    // for NS_ERROR, NS_ASSERTION
 #include "nsISupportsImpl.h"            // for Image::Release, etc
--- a/gfx/layers/basic/BasicImplData.h
+++ b/gfx/layers/basic/BasicImplData.h
@@ -6,18 +6,16 @@
 #define GFX_BASICIMPLDATA_H
 
 #include "Layers.h"                     // for Layer (ptr only), etc
 #include "gfxContext.h"                 // for gfxContext, etc
 #include "nsDebug.h"                    // for NS_ASSERTION
 #include "nsISupportsImpl.h"            // for MOZ_COUNT_CTOR, etc
 #include "mozilla/gfx/Types.h"
 
-class gfxASurface;
-
 namespace mozilla {
 namespace layers {
 
 class ReadbackProcessor;
 class SurfaceDescriptor;
 
 /**
  * This is the ImplData for all Basic layers. It also exposes methods
--- a/gfx/layers/basic/BasicLayersImpl.h
+++ b/gfx/layers/basic/BasicLayersImpl.h
@@ -4,17 +4,16 @@
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #ifndef GFX_BASICLAYERSIMPL_H
 #define GFX_BASICLAYERSIMPL_H
 
 #include "BasicImplData.h"              // for BasicImplData
 #include "BasicLayers.h"                // for BasicLayerManager
 #include "ReadbackLayer.h"              // for ReadbackLayer
-#include "gfxASurface.h"                // for gfxASurface
 #include "gfxContext.h"                 // for gfxContext, etc
 #include "mozilla/Attributes.h"         // for MOZ_DELETE, MOZ_STACK_CLASS
 #include "mozilla/Maybe.h"              // for Maybe
 #include "nsAutoPtr.h"                  // for nsRefPtr
 #include "nsDebug.h"                    // for NS_ASSERTION
 #include "nsISupportsImpl.h"            // for gfxContext::Release, etc
 #include "nsRegion.h"                   // for nsIntRegion
 
--- a/gfx/layers/basic/BasicThebesLayer.cpp
+++ b/gfx/layers/basic/BasicThebesLayer.cpp
@@ -5,17 +5,16 @@
 
 #include "BasicThebesLayer.h"
 #include <stdint.h>                     // for uint32_t
 #include "GeckoProfiler.h"              // for PROFILER_LABEL
 #include "ReadbackLayer.h"              // for ReadbackLayer, ReadbackSink
 #include "ReadbackProcessor.h"          // for ReadbackProcessor::Update, etc
 #include "RenderTrace.h"                // for RenderTraceInvalidateEnd, etc
 #include "BasicLayersImpl.h"            // for AutoMaskData, etc
-#include "gfxASurface.h"                // for gfxASurface, etc
 #include "gfxContext.h"                 // for gfxContext, etc
 #include "gfxRect.h"                    // for gfxRect
 #include "gfxUtils.h"                   // for gfxUtils
 #include "mozilla/gfx/2D.h"             // for DrawTarget
 #include "mozilla/gfx/BaseRect.h"       // for BaseRect
 #include "mozilla/gfx/Matrix.h"         // for Matrix
 #include "mozilla/gfx/Rect.h"           // for Rect, IntRect
 #include "mozilla/gfx/Types.h"          // for Float, etc
--- a/gfx/layers/client/CanvasClient.cpp
+++ b/gfx/layers/client/CanvasClient.cpp
@@ -5,17 +5,16 @@
 
 #include "mozilla/layers/CanvasClient.h"
 #include "ClientCanvasLayer.h"          // for ClientCanvasLayer
 #include "GLContext.h"                  // for GLContext
 #include "GLScreenBuffer.h"             // for GLScreenBuffer
 #include "SurfaceStream.h"              // for SurfaceStream
 #include "SurfaceTypes.h"               // for SurfaceStreamHandle
 #include "gfx2DGlue.h"                  // for ImageFormatToSurfaceFormat
-#include "gfxASurface.h"                // for gfxASurface, etc
 #include "gfxPlatform.h"                // for gfxPlatform
 #include "mozilla/gfx/BaseSize.h"       // for BaseSize
 #include "mozilla/layers/CompositableForwarder.h"
 #include "mozilla/layers/GrallocTextureClient.h"
 #include "mozilla/layers/LayersTypes.h"
 #include "mozilla/layers/TextureClient.h"  // for TextureClient, etc
 #include "mozilla/layers/TextureClientOGL.h"
 #include "nsAutoPtr.h"                  // for nsRefPtr
--- a/gfx/layers/client/ClientImageLayer.cpp
+++ b/gfx/layers/client/ClientImageLayer.cpp
@@ -1,17 +1,16 @@
 /* -*- Mode: C++; 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/. */
 
 #include "ClientLayerManager.h"         // for ClientLayerManager, etc
 #include "ImageContainer.h"             // for AutoLockImage, etc
 #include "ImageLayers.h"                // for ImageLayer
-#include "gfxASurface.h"                // for gfxASurface
 #include "mozilla/Attributes.h"         // for MOZ_OVERRIDE
 #include "mozilla/RefPtr.h"             // for RefPtr
 #include "mozilla/layers/CompositorTypes.h"
 #include "mozilla/layers/ImageClient.h"  // for ImageClient, etc
 #include "mozilla/layers/LayersMessages.h"  // for ImageLayerAttributes, etc
 #include "mozilla/mozalloc.h"           // for operator delete, etc
 #include "nsAutoPtr.h"                  // for nsRefPtr, getter_AddRefs, etc
 #include "nsCOMPtr.h"                   // for already_AddRefed
--- a/gfx/layers/client/ClientLayerManager.cpp
+++ b/gfx/layers/client/ClientLayerManager.cpp
@@ -1,17 +1,16 @@
 /* -*- Mode: C++; 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/. */
 
 #include "ClientLayerManager.h"
 #include "CompositorChild.h"            // for CompositorChild
 #include "GeckoProfiler.h"              // for PROFILER_LABEL
-#include "gfxASurface.h"                // for gfxASurface, etc
 #include "gfxPrefs.h"                   // for gfxPrefs::LayersTileWidth/Height
 #include "mozilla/Assertions.h"         // for MOZ_ASSERT, etc
 #include "mozilla/Hal.h"
 #include "mozilla/dom/ScreenOrientation.h"  // for ScreenOrientation
 #include "mozilla/dom/TabChild.h"       // for TabChild
 #include "mozilla/hal_sandbox/PHal.h"   // for ScreenConfiguration
 #include "mozilla/layers/CompositableClient.h"  // for CompositableChild, etc
 #include "mozilla/layers/ContentClient.h"  // for ContentClientRemote
--- a/gfx/layers/client/ClientThebesLayer.cpp
+++ b/gfx/layers/client/ClientThebesLayer.cpp
@@ -4,17 +4,16 @@
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #include "ClientThebesLayer.h"
 #include "ClientTiledThebesLayer.h"     // for ClientTiledThebesLayer
 #include "SimpleTiledContentClient.h"
 #include <stdint.h>                     // for uint32_t
 #include "GeckoProfiler.h"              // for PROFILER_LABEL
 #include "client/ClientLayerManager.h"  // for ClientLayerManager, etc
-#include "gfxASurface.h"                // for gfxASurface, etc
 #include "gfxContext.h"                 // for gfxContext
 #include "gfxRect.h"                    // for gfxRect
 #include "gfxPrefs.h"                   // for gfxPrefs
 #include "mozilla/Assertions.h"         // for MOZ_ASSERT, etc
 #include "mozilla/gfx/2D.h"             // for DrawTarget
 #include "mozilla/gfx/Matrix.h"         // for Matrix
 #include "mozilla/gfx/Rect.h"           // for Rect, IntRect
 #include "mozilla/gfx/Types.h"          // for Float, etc
--- a/gfx/layers/client/CompositableClient.cpp
+++ b/gfx/layers/client/CompositableClient.cpp
@@ -5,17 +5,16 @@
 
 #include "mozilla/layers/CompositableClient.h"
 #include <stdint.h>                     // for uint64_t, uint32_t
 #include "gfxPlatform.h"                // for gfxPlatform
 #include "mozilla/layers/CompositableForwarder.h"
 #include "mozilla/layers/TextureClient.h"  // for TextureClient, etc
 #include "mozilla/layers/TextureClientOGL.h"
 #include "mozilla/mozalloc.h"           // for operator delete, etc
-#include "gfxASurface.h"                // for gfxContentType
 #ifdef XP_WIN
 #include "gfxWindowsPlatform.h"         // for gfxWindowsPlatform
 #include "mozilla/layers/TextureD3D11.h"
 #include "mozilla/layers/TextureD3D9.h"
 #endif
 
 using namespace mozilla::gfx;
 
--- a/gfx/layers/client/CompositableClient.h
+++ b/gfx/layers/client/CompositableClient.h
@@ -11,17 +11,16 @@
 #include <map>                          // for map
 #include "mozilla/Assertions.h"         // for MOZ_CRASH
 #include "mozilla/RefPtr.h"             // for TemporaryRef, RefCounted
 #include "mozilla/gfx/Types.h"          // for SurfaceFormat
 #include "mozilla/layers/CompositorTypes.h"
 #include "mozilla/layers/LayersTypes.h"  // for LayersBackend
 #include "mozilla/layers/PCompositableChild.h"  // for PCompositableChild
 #include "nsISupportsImpl.h"            // for MOZ_COUNT_CTOR, etc
-#include "gfxASurface.h"                // for gfxContentType
 
 namespace mozilla {
 namespace layers {
 
 class CompositableClient;
 class TextureClient;
 class BufferTextureClient;
 class ImageBridgeChild;
--- a/gfx/layers/client/ContentClient.h
+++ b/gfx/layers/client/ContentClient.h
@@ -23,17 +23,16 @@
 #include "mozilla/mozalloc.h"           // for operator delete
 #include "nsCOMPtr.h"                   // for already_AddRefed
 #include "nsPoint.h"                    // for nsIntPoint
 #include "nsRect.h"                     // for nsIntRect
 #include "nsRegion.h"                   // for nsIntRegion
 #include "nsTArray.h"                   // for nsTArray
 
 class gfxContext;
-class gfxASurface;
 
 namespace mozilla {
 namespace gfx {
 class DrawTarget;
 }
 
 namespace layers {
 
--- a/gfx/layers/client/ImageClient.cpp
+++ b/gfx/layers/client/ImageClient.cpp
@@ -4,17 +4,16 @@
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #include "ImageClient.h"
 #include <stdint.h>                     // for uint32_t
 #include "ImageContainer.h"             // for Image, PlanarYCbCrImage, etc
 #include "ImageTypes.h"                 // for ImageFormat::PLANAR_YCBCR, etc
 #include "SharedTextureImage.h"         // for SharedTextureImage::Data, etc
 #include "gfx2DGlue.h"                  // for ImageFormatToSurfaceFormat
-#include "gfxASurface.h"                // for gfxASurface, etc
 #include "gfxPlatform.h"                // for gfxPlatform
 #include "mozilla/Assertions.h"         // for MOZ_ASSERT, etc
 #include "mozilla/RefPtr.h"             // for RefPtr, TemporaryRef
 #include "mozilla/gfx/BaseSize.h"       // for BaseSize
 #include "mozilla/gfx/Point.h"          // for IntSize
 #include "mozilla/gfx/Types.h"          // for SurfaceFormat, etc
 #include "mozilla/layers/CompositableClient.h"  // for CompositableClient
 #include "mozilla/layers/CompositableForwarder.h"
--- a/gfx/layers/client/TextureClient.cpp
+++ b/gfx/layers/client/TextureClient.cpp
@@ -41,17 +41,16 @@
 
 #ifdef MOZ_WIDGET_GONK
 #include <cutils/properties.h>
 #include "mozilla/layers/GrallocTextureClient.h"
 #endif
 
 #ifdef MOZ_ANDROID_OMTC
 #  include "gfxReusableImageSurfaceWrapper.h"
-#  include "gfxImageSurface.h"
 #else
 #  include "gfxReusableSharedImageSurfaceWrapper.h"
 #  include "gfxSharedImageSurface.h"
 #endif
 
 #if 0
 #define RECYCLE_LOG(...) printf_stderr(__VA_ARGS__)
 #else
--- a/gfx/layers/client/TextureClient.h
+++ b/gfx/layers/client/TextureClient.h
@@ -24,17 +24,16 @@
 #include "mozilla/layers/LayersSurfaces.h"  // for SurfaceDescriptor
 #include "mozilla/layers/PTextureChild.h" // for PTextureChild
 #include "mozilla/mozalloc.h"           // for operator delete
 #include "nsAutoPtr.h"                  // for nsRefPtr
 #include "nsCOMPtr.h"                   // for already_AddRefed
 #include "nsISupportsImpl.h"            // for TextureImage::AddRef, etc
 
 class gfxReusableSurfaceWrapper;
-class gfxASurface;
 class gfxImageSurface;
 
 namespace mozilla {
 namespace layers {
 
 class ContentClient;
 class CompositableForwarder;
 class ISurfaceAllocator;
--- a/gfx/layers/client/TiledContentClient.h
+++ b/gfx/layers/client/TiledContentClient.h
@@ -31,18 +31,16 @@
 #include "nsRect.h"                     // for nsIntRect
 #include "nsRegion.h"                   // for nsIntRegion
 #include "nsTArray.h"                   // for nsTArray, nsTArray_Impl, etc
 #include "mozilla/layers/ISurfaceAllocator.h"
 #include "gfxReusableSurfaceWrapper.h"
 #include "pratom.h"                     // For PR_ATOMIC_INCREMENT/DECREMENT
 #include "gfxPrefs.h"
 
-class gfxImageSurface;
-
 namespace mozilla {
 namespace layers {
 
 class BasicTileDescriptor;
 class ClientTiledThebesLayer;
 class ClientLayerManager;
 
 
--- a/gfx/layers/composite/CompositableHost.cpp
+++ b/gfx/layers/composite/CompositableHost.cpp
@@ -15,17 +15,16 @@
 #include "nsAutoPtr.h"                  // for nsRefPtr
 #include "nsDebug.h"                    // for NS_WARNING
 #include "nsISupportsImpl.h"            // for MOZ_COUNT_CTOR, etc
 #include "gfxPlatform.h"                // for gfxPlatform
 
 namespace mozilla {
 namespace layers {
 
-class Matrix4x4;
 class Compositor;
 
 CompositableHost::CompositableHost(const TextureInfo& aTextureInfo)
   : mTextureInfo(aTextureInfo)
   , mCompositor(nullptr)
   , mLayer(nullptr)
   , mFlashCounter(0)
   , mAttached(false)
--- a/gfx/layers/composite/ContainerLayerComposite.cpp
+++ b/gfx/layers/composite/ContainerLayerComposite.cpp
@@ -4,17 +4,16 @@
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #include "ContainerLayerComposite.h"
 #include <algorithm>                    // for min
 #include "FrameMetrics.h"               // for FrameMetrics
 #include "Units.h"                      // for LayerRect, LayerPixel, etc
 #include "gfx2DGlue.h"                  // for ToMatrix4x4
 #include "gfx3DMatrix.h"                // for gfx3DMatrix
-#include "gfxImageSurface.h"            // for gfxImageSurface
 #include "gfxPrefs.h"                   // for gfxPrefs
 #include "gfxUtils.h"                   // for gfxUtils, etc
 #include "mozilla/Assertions.h"         // for MOZ_ASSERT, etc
 #include "mozilla/RefPtr.h"             // for RefPtr
 #include "mozilla/gfx/BaseRect.h"       // for BaseRect
 #include "mozilla/gfx/Matrix.h"         // for Matrix4x4
 #include "mozilla/gfx/Point.h"          // for Point, IntPoint
 #include "mozilla/gfx/Rect.h"           // for IntRect, Rect
--- a/gfx/layers/composite/LayerManagerComposite.cpp
+++ b/gfx/layers/composite/LayerManagerComposite.cpp
@@ -48,17 +48,16 @@
 #include "nsRect.h"                     // for nsIntRect
 #include "nsRegion.h"                   // for nsIntRegion, etc
 #ifdef MOZ_WIDGET_ANDROID
 #include <android/log.h>
 #endif
 #include "GeckoProfiler.h"
 #include "TextRenderer.h"               // for TextRenderer
 
-class gfxASurface;
 class gfxContext;
 struct nsIntSize;
 
 
 namespace mozilla {
 namespace layers {
 
 class ImageLayer;
--- a/gfx/layers/composite/LayerManagerComposite.h
+++ b/gfx/layers/composite/LayerManagerComposite.h
@@ -24,17 +24,16 @@
 #include "nsCOMPtr.h"                   // for already_AddRefed
 #include "nsDebug.h"                    // for NS_ASSERTION
 #include "nsISupportsImpl.h"            // for Layer::AddRef, etc
 #include "nsRect.h"                     // for nsIntRect
 #include "nsRegion.h"                   // for nsIntRegion
 #include "nscore.h"                     // for nsAString, etc
 #include "LayerTreeInvalidation.h"
 
-class gfxASurface;
 class gfxContext;
 struct nsIntPoint;
 struct nsIntSize;
 
 #ifdef XP_WIN
 #include <windows.h>
 #endif
 
--- a/gfx/layers/composite/TextureHost.cpp
+++ b/gfx/layers/composite/TextureHost.cpp
@@ -2,17 +2,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/. */
 
 #include "mozilla/layers/TextureHost.h"
 #include "CompositableHost.h"           // for CompositableHost
 #include "LayersLogging.h"              // for AppendToString
 #include "gfx2DGlue.h"                  // for ToIntSize
-#include "gfxImageSurface.h"            // for gfxImageSurface
 #include "mozilla/gfx/2D.h"             // for DataSourceSurface, Factory
 #include "mozilla/ipc/Shmem.h"          // for Shmem
 #include "mozilla/layers/Compositor.h"  // for Compositor
 #include "mozilla/layers/ISurfaceAllocator.h"  // for ISurfaceAllocator
 #include "mozilla/layers/ImageDataSerializer.h"
 #include "mozilla/layers/LayersSurfaces.h"  // for SurfaceDescriptor, etc
 #include "mozilla/layers/TextureHostOGL.h"  // for TextureHostOGL
 #ifdef MOZ_X11
--- a/gfx/layers/composite/TextureHost.h
+++ b/gfx/layers/composite/TextureHost.h
@@ -21,17 +21,16 @@
 #include "nsCOMPtr.h"                   // for already_AddRefed
 #include "nsDebug.h"                    // for NS_RUNTIMEABORT
 #include "nsISupportsImpl.h"            // for MOZ_COUNT_CTOR, etc
 #include "nsRegion.h"                   // for nsIntRegion
 #include "nsTraceRefcnt.h"              // for MOZ_COUNT_CTOR, etc
 #include "nscore.h"                     // for nsACString
 #include "mozilla/layers/AtomicRefCountedWithFinalize.h"
 
-class gfxImageSurface;
 class gfxReusableSurfaceWrapper;
 struct nsIntPoint;
 struct nsIntSize;
 struct nsIntRect;
 
 namespace mozilla {
 namespace ipc {
 class Shmem;
--- a/gfx/layers/d3d10/CanvasLayerD3D10.cpp
+++ b/gfx/layers/d3d10/CanvasLayerD3D10.cpp
@@ -1,17 +1,16 @@
 /* -*- Mode: C++; tab-width: 20; 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/. */
 
 #include "CanvasLayerD3D10.h"
 
 #include "../d3d9/Nv3DVUtils.h"
-#include "gfxImageSurface.h"
 #include "gfxWindowsSurface.h"
 #include "gfxWindowsPlatform.h"
 #include "SurfaceStream.h"
 #include "SharedSurfaceANGLE.h"
 #include "SharedSurfaceGL.h"
 #include "gfxContext.h"
 #include "GLContext.h"
 #include "gfxPrefs.h"
--- a/gfx/layers/d3d10/CanvasLayerD3D10.h
+++ b/gfx/layers/d3d10/CanvasLayerD3D10.h
@@ -5,18 +5,16 @@
 
 #ifndef GFX_CANVASLAYERD3D10_H
 #define GFX_CANVASLAYERD3D10_H
 
 #include "LayerManagerD3D10.h"
 
 #include "mozilla/Preferences.h"
 
-class gfxASurface;
-
 namespace mozilla {
 
 namespace gl {
 class GLContext;
 }
 
 namespace layers {
 
--- a/gfx/layers/d3d10/ImageLayerD3D10.cpp
+++ b/gfx/layers/d3d10/ImageLayerD3D10.cpp
@@ -1,15 +1,14 @@
 /* -*- Mode: C++; tab-width: 20; 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/. */
 
 #include "ImageLayerD3D10.h"
-#include "gfxImageSurface.h"
 #include "gfxD2DSurface.h"
 #include "gfxWindowsSurface.h"
 #include "yuv_convert.h"
 #include "../d3d9/Nv3DVUtils.h"
 #include "D3D9SurfaceImage.h"
 #include "mozilla/gfx/Point.h"
 #include "gfx2DGlue.h"
 
--- a/gfx/layers/d3d11/TextureD3D11.cpp
+++ b/gfx/layers/d3d11/TextureD3D11.cpp
@@ -1,17 +1,16 @@
 /* -*- Mode: C++; tab-width: 20; indent-tabs-mode: nil; c-basic-offset: 4 -*-
  * 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 "TextureD3D11.h"
 #include "CompositorD3D11.h"
 #include "gfxContext.h"
-#include "gfxImageSurface.h"
 #include "Effects.h"
 #include "mozilla/layers/YCbCrImageDataSerializer.h"
 #include "gfxWindowsPlatform.h"
 #include "gfxD2DSurface.h"
 #include "gfx2DGlue.h"
 
 namespace mozilla {
 
--- a/gfx/layers/d3d9/CanvasLayerD3D9.cpp
+++ b/gfx/layers/d3d9/CanvasLayerD3D9.cpp
@@ -1,17 +1,16 @@
 /* -*- Mode: C++; tab-width: 20; 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/. */
 
 
 #include "mozilla/layers/PLayerTransaction.h"
 
-#include "gfxImageSurface.h"
 #include "gfxWindowsSurface.h"
 #include "gfxWindowsPlatform.h"
 #include "SurfaceStream.h"
 #include "SharedSurfaceGL.h"
 #include "GLContext.h"
 #include "CanvasLayerD3D9.h"
 
 using namespace mozilla::gfx;
--- a/gfx/layers/d3d9/CanvasLayerD3D9.h
+++ b/gfx/layers/d3d9/CanvasLayerD3D9.h
@@ -4,18 +4,16 @@
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #ifndef GFX_CANVASLAYERD3D9_H
 #define GFX_CANVASLAYERD3D9_H
 
 #include "LayerManagerD3D9.h"
 #include "GLContextTypes.h"
 
-class gfxASurface;
-
 namespace mozilla {
 namespace layers {
 
 
 class CanvasLayerD3D9 :
   public CanvasLayer,
   public LayerD3D9
 {
--- a/gfx/layers/d3d9/ImageLayerD3D9.cpp
+++ b/gfx/layers/d3d9/ImageLayerD3D9.cpp
@@ -7,17 +7,16 @@
 #include "mozilla/gfx/Point.h"
 #include "mozilla/RefPtr.h"
 #include "mozilla/layers/PLayerTransaction.h"
 #include "gfxSharedImageSurface.h"
 
 #include "ImageLayerD3D9.h"
 #include "ThebesLayerD3D9.h"
 #include "gfxPlatform.h"
-#include "gfxImageSurface.h"
 #include "gfx2DGlue.h"
 #include "yuv_convert.h"
 #include "nsIServiceManager.h"
 #include "nsIConsoleService.h"
 #include "Nv3DVUtils.h"
 #include "D3D9SurfaceImage.h"
 
 namespace mozilla {
--- a/gfx/layers/d3d9/ThebesLayerD3D9.h
+++ b/gfx/layers/d3d9/ThebesLayerD3D9.h
@@ -3,17 +3,16 @@
  * 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 GFX_THEBESLAYERD3D9_H
 #define GFX_THEBESLAYERD3D9_H
 
 #include "Layers.h"
 #include "LayerManagerD3D9.h"
-#include "gfxImageSurface.h"
 #include "ReadbackProcessor.h"
 
 namespace mozilla {
 namespace layers {
 
 class ReadbackProcessor;
 
 class ThebesLayerD3D9 : public ThebesLayer,
--- a/gfx/layers/ipc/ISurfaceAllocator.cpp
+++ b/gfx/layers/ipc/ISurfaceAllocator.cpp
@@ -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/. */
 
 #include "ISurfaceAllocator.h"
 #include <sys/types.h>                  // for int32_t
 #include "gfx2DGlue.h"                  // for IntSize
-#include "gfxASurface.h"                // for gfxASurface, etc
 #include "gfxPlatform.h"                // for gfxPlatform, gfxImageFormat
 #include "gfxSharedImageSurface.h"      // for gfxSharedImageSurface
 #include "mozilla/Assertions.h"         // for MOZ_ASSERT, etc
 #include "mozilla/Atomics.h"            // for PrimitiveIntrinsics
 #include "mozilla/ipc/SharedMemory.h"   // for SharedMemory, etc
 #include "mozilla/layers/LayersSurfaces.h"  // for SurfaceDescriptor, etc
 #include "ShadowLayerUtils.h"
 #include "mozilla/mozalloc.h"           // for operator delete[], etc
--- a/gfx/layers/ipc/ShadowLayerUtilsGralloc.cpp
+++ b/gfx/layers/ipc/ShadowLayerUtilsGralloc.cpp
@@ -17,17 +17,16 @@
 #include "mozilla/layers/TextureHost.h"
 #include "mozilla/unused.h"
 #include "nsXULAppAPI.h"
 
 #include "ShadowLayerUtilsGralloc.h"
 
 #include "nsIMemoryReporter.h"
 
-#include "gfxImageSurface.h"
 #include "gfxPlatform.h"
 #include "gfx2DGlue.h"
 #include "GLContext.h"
 
 #include "GeckoProfiler.h"
 
 #include "cutils/properties.h"
 
@@ -361,16 +360,19 @@ GrallocBufferActor::InitFromHandle(const
 }
 
 PGrallocBufferChild*
 ShadowLayerForwarder::AllocGrallocBuffer(const gfx::IntSize& aSize,
                                          uint32_t aFormat,
                                          uint32_t aUsage,
                                          MaybeMagicGrallocBufferHandle* aHandle)
 {
+  if (!mShadowManager->IPCOpen()) {
+    return nullptr;
+  }
   return mShadowManager->SendPGrallocBufferConstructor(aSize, aFormat, aUsage, aHandle);
 }
 
 void
 ShadowLayerForwarder::DeallocGrallocBuffer(PGrallocBufferChild* aChild)
 {
   MOZ_ASSERT(aChild);
   PGrallocBufferChild::Send__delete__(aChild);
--- a/gfx/layers/ipc/ShadowLayerUtilsGralloc.h
+++ b/gfx/layers/ipc/ShadowLayerUtilsGralloc.h
@@ -13,18 +13,16 @@
 
 #include "ipc/IPCMessageUtils.h"
 #include "mozilla/layers/PGrallocBufferChild.h"
 #include "mozilla/layers/PGrallocBufferParent.h"
 
 #define MOZ_HAVE_SURFACEDESCRIPTORGRALLOC
 #define MOZ_HAVE_PLATFORM_SPECIFIC_LAYER_BUFFERS
 
-class gfxASurface;
-
 namespace mozilla {
 namespace layers {
 
 class MaybeMagicGrallocBufferHandle;
 class TextureHost;
 
 /**
  * This class exists to share the underlying GraphicBuffer resources
--- a/gfx/layers/ipc/ShadowLayerUtilsX11.cpp
+++ b/gfx/layers/ipc/ShadowLayerUtilsX11.cpp
@@ -8,17 +8,16 @@
 #include "ShadowLayerUtilsX11.h"
 #include <X11/X.h>                      // for Drawable, XID
 #include <X11/Xlib.h>                   // for Display, Visual, etc
 #include <X11/extensions/Xrender.h>     // for XRenderPictFormat, etc
 #include <X11/extensions/render.h>      // for PictFormat
 #include "cairo-xlib.h"
 #include <stdint.h>                     // for uint32_t
 #include "GLDefs.h"                     // for GLenum
-#include "gfxASurface.h"                // for gfxASurface, etc
 #include "gfxPlatform.h"                // for gfxPlatform
 #include "gfxXlibSurface.h"             // for gfxXlibSurface
 #include "gfx2DGlue.h"                  // for Moz2D transistion helpers
 #include "mozilla/X11Util.h"            // for DefaultXDisplay, FinishX, etc
 #include "mozilla/gfx/Point.h"          // for IntSize
 #include "mozilla/layers/CompositableForwarder.h"
 #include "mozilla/layers/CompositorTypes.h"  // for OpenMode
 #include "mozilla/layers/ISurfaceAllocator.h"  // for ISurfaceAllocator, etc
--- a/gfx/layers/ipc/ShadowLayers.cpp
+++ b/gfx/layers/ipc/ShadowLayers.cpp
@@ -9,17 +9,16 @@
 #include <set>                          // for _Rb_tree_const_iterator, etc
 #include <vector>                       // for vector
 #include "GeckoProfiler.h"              // for PROFILER_LABEL
 #include "ISurfaceAllocator.h"          // for IsSurfaceDescriptorValid
 #include "Layers.h"                     // for Layer
 #include "RenderTrace.h"                // for RenderTraceScope
 #include "ShadowLayerChild.h"           // for ShadowLayerChild
 #include "gfx2DGlue.h"                  // for Moz2D transition helpers
-#include "gfxImageSurface.h"            // for gfxImageSurface
 #include "gfxPlatform.h"                // for gfxImageFormat, gfxPlatform
 #include "gfxSharedImageSurface.h"      // for gfxSharedImageSurface
 #include "ipc/IPCMessageUtils.h"        // for gfxContentType, null_t
 #include "mozilla/Assertions.h"         // for MOZ_ASSERT, etc
 #include "mozilla/gfx/Point.h"          // for IntSize
 #include "mozilla/layers/CompositableClient.h"  // for CompositableClient, etc
 #include "mozilla/layers/LayersMessages.h"  // for Edit, etc
 #include "mozilla/layers/LayersSurfaces.h"  // for SurfaceDescriptor, etc
@@ -537,27 +536,29 @@ ShadowLayerForwarder::EndTransaction(Inf
   MOZ_LAYERS_LOG(("[LayersForwarder] syncing before send..."));
   PlatformSyncBeforeUpdate();
 
   profiler_tracing("Paint", "Rasterize", TRACING_INTERVAL_END);
   if (mTxn->mSwapRequired) {
     MOZ_LAYERS_LOG(("[LayersForwarder] sending transaction..."));
     RenderTraceScope rendertrace3("Forward Transaction", "000093");
     if (!HasShadowManager() ||
+        !mShadowManager->IPCOpen() ||
         !mShadowManager->SendUpdate(cset, targetConfig, mIsFirstPaint,
                                     aScheduleComposite, aReplies)) {
       MOZ_LAYERS_LOG(("[LayersForwarder] WARNING: sending transaction failed!"));
       return false;
     }
   } else {
     // If we don't require a swap we can call SendUpdateNoSwap which
     // assumes that aReplies is empty (DEBUG assertion)
     MOZ_LAYERS_LOG(("[LayersForwarder] sending no swap transaction..."));
     RenderTraceScope rendertrace3("Forward NoSwap Transaction", "000093");
     if (!HasShadowManager() ||
+        !mShadowManager->IPCOpen() ||
         !mShadowManager->SendUpdateNoSwap(cset, targetConfig, mIsFirstPaint, aScheduleComposite)) {
       MOZ_LAYERS_LOG(("[LayersForwarder] WARNING: sending transaction failed!"));
       return false;
     }
   }
 
   *aSent = true;
   mIsFirstPaint = false;
@@ -566,54 +567,69 @@ ShadowLayerForwarder::EndTransaction(Inf
 }
 
 bool
 ShadowLayerForwarder::AllocShmem(size_t aSize,
                                  ipc::SharedMemory::SharedMemoryType aType,
                                  ipc::Shmem* aShmem)
 {
   NS_ABORT_IF_FALSE(HasShadowManager(), "no shadow manager");
+  if (!mShadowManager->IPCOpen()) {
+    return false;
+  }
   return mShadowManager->AllocShmem(aSize, aType, aShmem);
 }
 bool
 ShadowLayerForwarder::AllocUnsafeShmem(size_t aSize,
                                           ipc::SharedMemory::SharedMemoryType aType,
                                           ipc::Shmem* aShmem)
 {
   NS_ABORT_IF_FALSE(HasShadowManager(), "no shadow manager");
+  if (!mShadowManager->IPCOpen()) {
+    return false;
+  }
   return mShadowManager->AllocUnsafeShmem(aSize, aType, aShmem);
 }
 void
 ShadowLayerForwarder::DeallocShmem(ipc::Shmem& aShmem)
 {
   NS_ABORT_IF_FALSE(HasShadowManager(), "no shadow manager");
+  if (!mShadowManager->IPCOpen()) {
+    return;
+  }
   mShadowManager->DeallocShmem(aShmem);
 }
 
 bool
 ShadowLayerForwarder::IPCOpen() const
 {
   return mShadowManager->IPCOpen();
 }
 
 bool
 ShadowLayerForwarder::IsSameProcess() const
 {
+  if (!mShadowManager->IPCOpen()) {
+    return false;
+  }
   return mShadowManager->OtherProcess() == kInvalidProcessHandle;
 }
 
 /**
   * We bail out when we have no shadow manager. That can happen when the
   * layer manager is created by the preallocated process.
   * See bug 914843 for details.
   */
 PLayerChild*
 ShadowLayerForwarder::ConstructShadowFor(ShadowableLayer* aLayer)
 {
   NS_ABORT_IF_FALSE(HasShadowManager(), "no manager to forward to");
+  if (!mShadowManager->IPCOpen()) {
+    return nullptr;
+  }
   return mShadowManager->SendPLayerConstructor(new ShadowLayerChild(aLayer));
 }
 
 #if !defined(MOZ_HAVE_PLATFORM_SPECIFIC_LAYER_BUFFERS)
 
 /*static*/ void
 ShadowLayerForwarder::PlatformSyncBeforeUpdate()
 {
@@ -624,16 +640,19 @@ ShadowLayerForwarder::PlatformSyncBefore
 void
 ShadowLayerForwarder::Connect(CompositableClient* aCompositable)
 {
 #ifdef GFX_COMPOSITOR_LOGGING
   printf("ShadowLayerForwarder::Connect(Compositable)\n");
 #endif
   MOZ_ASSERT(aCompositable);
   MOZ_ASSERT(mShadowManager);
+  if (!mShadowManager->IPCOpen()) {
+    return;
+  }
   CompositableChild* child = static_cast<CompositableChild*>(
     mShadowManager->SendPCompositableConstructor(aCompositable->GetTextureInfo()));
   MOZ_ASSERT(child);
   aCompositable->SetIPDLActor(child);
   child->SetClient(aCompositable);
 }
 
 void
@@ -664,16 +683,19 @@ void ShadowLayerForwarder::AttachAsyncCo
   mTxn->AddEdit(OpAttachAsyncCompositable(nullptr, Shadow(aLayer),
                                           aCompositableID));
 }
 
 PTextureChild*
 ShadowLayerForwarder::CreateTexture(const SurfaceDescriptor& aSharedData,
                                     TextureFlags aFlags)
 {
+  if (!mShadowManager->IPCOpen()) {
+    return nullptr;
+  }
   return mShadowManager->SendPTextureConstructor(aSharedData, aFlags);
 }
 
 
 void ShadowLayerForwarder::SetShadowManager(PLayerTransactionChild* aShadowManager)
 {
   mShadowManager = static_cast<LayerTransactionChild*>(aShadowManager);
 }
--- a/gfx/layers/ipc/ShadowLayers.h
+++ b/gfx/layers/ipc/ShadowLayers.h
@@ -18,17 +18,16 @@
 #include "mozilla/layers/CompositableForwarder.h"
 #include "mozilla/layers/CompositorTypes.h"  // for OpenMode, etc
 #include "nsCOMPtr.h"                   // for already_AddRefed
 #include "nsRegion.h"                   // for nsIntRegion
 #include "nsTArrayForwardDeclare.h"     // for InfallibleTArray
  
 struct nsIntPoint;
 struct nsIntRect;
-class gfxASurface;
 
 namespace mozilla {
 namespace layers {
 
 class ClientTiledLayerBuffer;
 class CanvasClient;
 class CanvasLayerComposite;
 class CanvasSurface;
--- a/gfx/layers/ipc/SharedPlanarYCbCrImage.cpp
+++ b/gfx/layers/ipc/SharedPlanarYCbCrImage.cpp
@@ -15,18 +15,16 @@
 #include "mozilla/layers/LayersSurfaces.h"  // for SurfaceDescriptor, etc
 #include "mozilla/layers/TextureClient.h"  // for BufferTextureClient, etc
 #include "mozilla/layers/YCbCrImageDataSerializer.h"
 #include "mozilla/layers/ImageBridgeChild.h"  // for ImageBridgeChild
 #include "mozilla/mozalloc.h"           // for operator delete
 #include "nsISupportsImpl.h"            // for Image::AddRef
 #include "mozilla/ipc/Shmem.h"
 
-class gfxASurface;
-
 namespace mozilla {
 namespace layers {
 
 using namespace mozilla::ipc;
 
 SharedPlanarYCbCrImage::SharedPlanarYCbCrImage(ImageClient* aCompositable)
 : PlanarYCbCrImage(nullptr)
 , mCompositable(aCompositable)
--- a/gfx/layers/ipc/SharedPlanarYCbCrImage.h
+++ b/gfx/layers/ipc/SharedPlanarYCbCrImage.h
@@ -7,18 +7,16 @@
 #include "ImageContainer.h"             // for PlanarYCbCrImage, etc
 #include "mozilla/Attributes.h"         // for MOZ_OVERRIDE
 #include "mozilla/RefPtr.h"             // for RefPtr
 #include "mozilla/ipc/Shmem.h"          // for Shmem
 #include "nsCOMPtr.h"                   // for already_AddRefed
 #include "nsDebug.h"                    // for NS_WARNING
 #include "nsISupportsImpl.h"            // for MOZ_COUNT_CTOR
 
-class gfxASurface;
-
 #ifndef MOZILLA_LAYERS_SHAREDPLANARYCBCRIMAGE_H
 #define MOZILLA_LAYERS_SHAREDPLANARYCBCRIMAGE_H
 
 namespace mozilla {
 namespace layers {
 
 class BufferTextureClient;
 class ImageClient;
--- a/gfx/layers/ipc/SharedRGBImage.h
+++ b/gfx/layers/ipc/SharedRGBImage.h
@@ -10,18 +10,16 @@
 #include "ImageContainer.h"             // for ISharedImage, Image, etc
 #include "gfxTypes.h"
 #include "mozilla/Attributes.h"         // for MOZ_OVERRIDE
 #include "mozilla/RefPtr.h"             // for RefPtr
 #include "mozilla/gfx/Point.h"          // for IntSize
 #include "mozilla/gfx/Types.h"          // for SurfaceFormat
 #include "nsCOMPtr.h"                   // for already_AddRefed
 
-class gfxASurface;
-
 namespace mozilla {
 namespace ipc {
 class Shmem;
 }
 
 namespace layers {
 
 class BufferTextureClient;
--- a/gfx/layers/opengl/CompositingRenderTargetOGL.h
+++ b/gfx/layers/opengl/CompositingRenderTargetOGL.h
@@ -17,17 +17,16 @@
 #include "mozilla/layers/TextureHost.h" // for CompositingRenderTarget
 #include "mozilla/layers/CompositorOGL.h"  // for CompositorOGL
 #include "mozilla/mozalloc.h"           // for operator new
 #include "nsAString.h"
 #include "nsCOMPtr.h"                   // for already_AddRefed
 #include "nsDebug.h"                    // for NS_ERROR, NS_WARNING
 #include "nsString.h"                   // for nsAutoCString
 
-class gfxImageSurface;
 
 namespace mozilla {
 namespace gl {
   class BindableTexture;
 }
 namespace gfx {
   class DataSourceSurface;
 }
--- a/gfx/layers/opengl/CompositorOGL.cpp
+++ b/gfx/layers/opengl/CompositorOGL.cpp
@@ -9,17 +9,16 @@
 #include <stdlib.h>                     // for free, malloc
 #include "GLContextProvider.h"          // for GLContextProvider
 #include "GLContext.h"                  // for GLContext
 #include "GLUploadHelpers.h"
 #include "Layers.h"                     // for WriteSnapshotToDumpFile
 #include "LayerScope.h"                 // for LayerScope
 #include "gfx2DGlue.h"                  // for ThebesFilter
 #include "gfx3DMatrix.h"                // for gfx3DMatrix
-#include "gfxASurface.h"                // for gfxASurface, etc
 #include "gfxCrashReporterUtils.h"      // for ScopedGfxFeatureReporter
 #include "gfxImageSurface.h"            // for gfxImageSurface
 #include "gfxMatrix.h"                  // for gfxMatrix
 #include "GraphicsFilter.h"             // for GraphicsFilter
 #include "gfxPlatform.h"                // for gfxPlatform
 #include "gfxPrefs.h"                   // for gfxPrefs
 #include "gfxRect.h"                    // for gfxRect
 #include "gfxUtils.h"                   // for NextPowerOfTwo, gfxUtils, etc
--- a/gfx/layers/opengl/GrallocTextureClient.cpp
+++ b/gfx/layers/opengl/GrallocTextureClient.cpp
@@ -6,18 +6,16 @@
 #ifdef MOZ_WIDGET_GONK
 
 #include "mozilla/gfx/2D.h"
 #include "mozilla/layers/GrallocTextureClient.h"
 #include "mozilla/layers/CompositableForwarder.h"
 #include "mozilla/layers/ISurfaceAllocator.h"
 #include "mozilla/layers/ShadowLayerUtilsGralloc.h"
 #include "gfx2DGlue.h"
-#include "gfxASurface.h"
-#include "gfxImageSurface.h"            // for gfxImageSurface
 
 namespace mozilla {
 namespace layers {
 
 using namespace mozilla::gfx;
 using namespace android;
 
 class GrallocTextureClientData : public TextureClientData {
--- a/gfx/layers/opengl/GrallocTextureHost.cpp
+++ b/gfx/layers/opengl/GrallocTextureHost.cpp
@@ -1,15 +1,14 @@
 /* -*- Mode: C++; tab-width: 20; 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/. */
 
 #include "GLContext.h"
-#include "gfxImageSurface.h"
 #include "gfx2DGlue.h"
 #include <ui/GraphicBuffer.h>
 #include "GrallocImages.h"  // for GrallocImage
 #include "mozilla/layers/GrallocTextureHost.h"
 #include "mozilla/layers/CompositorOGL.h"
 #include "EGLImageHelpers.h"
 #include "GLReadTexImageHelper.h"
 
--- a/gfx/layers/opengl/TextureHostOGL.cpp
+++ b/gfx/layers/opengl/TextureHostOGL.cpp
@@ -9,17 +9,16 @@
 #include "GLUploadHelpers.h"
 #include "GLReadTexImageHelper.h"
 #include "SharedSurface.h"              // for SharedSurface
 #include "SharedSurfaceEGL.h"           // for SharedSurface_EGLImage
 #include "SharedSurfaceGL.h"            // for SharedSurface_GLTexture, etc
 #include "SurfaceStream.h"              // for SurfaceStream
 #include "SurfaceTypes.h"               // for SharedSurfaceType, etc
 #include "gfx2DGlue.h"                  // for ContentForFormat, etc
-#include "gfxImageSurface.h"            // for gfxImageSurface
 #include "gfxReusableSurfaceWrapper.h"  // for gfxReusableSurfaceWrapper
 #include "mozilla/gfx/2D.h"             // for DataSourceSurface
 #include "mozilla/gfx/BaseSize.h"       // for BaseSize
 #include "mozilla/layers/CompositorOGL.h"  // for CompositorOGL
 #ifdef MOZ_WIDGET_GONK
 # include "GrallocImages.h"  // for GrallocImage
 # include "EGLImageHelpers.h"
 #endif
--- a/gfx/layers/opengl/TextureHostOGL.h
+++ b/gfx/layers/opengl/TextureHostOGL.h
@@ -31,17 +31,16 @@
 #include "OGLShaderProgram.h"           // for ShaderProgramType, etc
 #ifdef MOZ_WIDGET_GONK
 #include <ui/GraphicBuffer.h>
 #if ANDROID_VERSION >= 17
 #include <ui/Fence.h>
 #endif
 #endif
 
-class gfxImageSurface;
 class gfxReusableSurfaceWrapper;
 class nsIntRegion;
 struct nsIntPoint;
 struct nsIntRect;
 struct nsIntSize;
 
 namespace mozilla {
 namespace gfx {
--- a/gfx/thebes/gfxBlur.h
+++ b/gfx/thebes/gfxBlur.h
@@ -8,17 +8,16 @@
 
 #include "gfxTypes.h"
 #include "nsSize.h"
 #include "nsAutoPtr.h"
 #include "gfxPoint.h"
 #include "mozilla/RefPtr.h"
 
 class gfxContext;
-class gfxImageSurface;
 struct gfxRect;
 struct gfxRGBA;
 class gfxCornerSizes;
 class gfxMatrix;
 
 namespace mozilla {
   namespace gfx {
     class AlphaBoxBlur;
--- a/gfx/thebes/gfxDrawable.cpp
+++ b/gfx/thebes/gfxDrawable.cpp
@@ -1,16 +1,17 @@
 /* -*- Mode: C++; tab-width: 20; indent-tabs-mode: nil; c-basic-offset: 4 -*-
  * 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 "gfxDrawable.h"
 #include "gfxASurface.h"
 #include "gfxContext.h"
+#include "gfxImageSurface.h"
 #include "gfxPlatform.h"
 #include "gfxColor.h"
 #ifdef MOZ_X11
 #include "cairo.h"
 #include "gfxXlibSurface.h"
 #endif
 
 using namespace mozilla;
@@ -190,24 +191,28 @@ gfxCallbackDrawable::gfxCallbackDrawable
  : gfxDrawable(aSize)
  , mCallback(aCallback)
 {
 }
 
 already_AddRefed<gfxSurfaceDrawable>
 gfxCallbackDrawable::MakeSurfaceDrawable(const GraphicsFilter aFilter)
 {
-    nsRefPtr<gfxASurface> surface =
-        gfxPlatform::GetPlatform()->CreateOffscreenSurface(mSize.ToIntSize(),
-                                                           gfxContentType::COLOR_ALPHA);
-    if (!surface || surface->CairoStatus() != 0)
+    SurfaceFormat format =
+        gfxPlatform::GetPlatform()->Optimal2DFormatForContent(gfxContentType::COLOR_ALPHA);
+    RefPtr<DrawTarget> dt =
+        gfxPlatform::GetPlatform()->CreateOffscreenContentDrawTarget(mSize.ToIntSize(),
+                                                                     format);
+    if (!dt)
         return nullptr;
 
-    nsRefPtr<gfxContext> ctx = new gfxContext(surface);
+    nsRefPtr<gfxContext> ctx = new gfxContext(dt);
     Draw(ctx, gfxRect(0, 0, mSize.width, mSize.height), false, aFilter);
+
+    RefPtr<SourceSurface> surface = dt->Snapshot();
     nsRefPtr<gfxSurfaceDrawable> drawable = new gfxSurfaceDrawable(surface, mSize);
     return drawable.forget();
 }
 
 bool
 gfxCallbackDrawable::Draw(gfxContext* aContext,
                           const gfxRect& aFillRect,
                           bool aRepeat,
--- a/gfx/thebes/gfxGdkNativeRenderer.h
+++ b/gfx/thebes/gfxGdkNativeRenderer.h
@@ -7,17 +7,16 @@
 #define GFXGDKNATIVERENDER_H_
 
 #include <gdk/gdk.h>
 #include "nsSize.h"
 #ifdef MOZ_X11
 #include "gfxXlibNativeRenderer.h"
 #endif
 
-class gfxASurface;
 class gfxContext;
 
 /**
  * This class lets us take code that draws into an GDK drawable and lets us
  * use it to draw into any Thebes context. The user should subclass this class,
  * override DrawWithGDK, and then call Draw(). The drawing will be subjected
  * to all Thebes transformations, clipping etc.
  */
--- a/gfx/thebes/gfxQtNativeRenderer.h
+++ b/gfx/thebes/gfxQtNativeRenderer.h
@@ -2,17 +2,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 GFXQTNATIVERENDER_H_
 #define GFXQTNATIVERENDER_H_
 
 #include "gfxColor.h"
-#include "gfxASurface.h"
 #include "gfxContext.h"
 #include "gfxXlibSurface.h"
 
 class QRect;
 struct nsIntRect;
 
 /**
  * This class lets us take code that draws into an Xlib surface drawable and lets us
--- a/gfx/thebes/gfxQtPlatform.h
+++ b/gfx/thebes/gfxQtPlatform.h
@@ -9,16 +9,17 @@
 #include "gfxPlatform.h"
 #include "nsAutoRef.h"
 #include "nsDataHashtable.h"
 #include "nsTArray.h"
 #ifdef MOZ_X11
 #include "X11/Xlib.h"
 #endif
 
+class gfxImageSurface;
 class gfxFontconfigUtils;
 class QWindow;
 
 class gfxQtPlatform : public gfxPlatform {
 public:
     gfxQtPlatform();
     virtual ~gfxQtPlatform();
 
--- a/gfx/thebes/nsSurfaceTexture.cpp
+++ b/gfx/thebes/nsSurfaceTexture.cpp
@@ -5,17 +5,16 @@
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #ifdef MOZ_WIDGET_ANDROID
 
 #include <set>
 #include <map>
 #include <android/log.h>
 #include "nsSurfaceTexture.h"
-#include "gfxImageSurface.h"
 #include "AndroidBridge.h"
 #include "nsThreadUtils.h"
 #include "mozilla/gfx/Matrix.h"
 
 using namespace mozilla;
 
 // UGH
 static std::map<int, nsSurfaceTexture*> sInstances;
--- a/gfx/thebes/nsSurfaceTexture.h
+++ b/gfx/thebes/nsSurfaceTexture.h
@@ -8,18 +8,16 @@
 #define nsSurfaceTexture_h__
 #ifdef MOZ_WIDGET_ANDROID
 
 #include <jni.h>
 #include "nsIRunnable.h"
 #include "gfxPlatform.h"
 #include "GLDefs.h"
 
-class gfxASurface;
-
 namespace mozilla {
 namespace gfx {
 class Matrix4x4;
 }
 }
 
 /**
  * This class is a wrapper around Android's SurfaceTexture class.
--- a/js/public/Class.h
+++ b/js/public/Class.h
@@ -474,16 +474,20 @@ struct Class
     bool isCallable() const {
         return this == js::FunctionClassPtr || call;
     }
 
     bool isProxy() const {
         return flags & JSCLASS_IS_PROXY;
     }
 
+    bool isDOMClass() const {
+        return flags & JSCLASS_IS_DOMJSCLASS;
+    }
+
     static size_t offsetOfFlags() { return offsetof(Class, flags); }
 };
 
 JS_STATIC_ASSERT(offsetof(JSClass, name) == offsetof(Class, name));
 JS_STATIC_ASSERT(offsetof(JSClass, flags) == offsetof(Class, flags));
 JS_STATIC_ASSERT(offsetof(JSClass, addProperty) == offsetof(Class, addProperty));
 JS_STATIC_ASSERT(offsetof(JSClass, delProperty) == offsetof(Class, delProperty));
 JS_STATIC_ASSERT(offsetof(JSClass, getProperty) == offsetof(Class, getProperty));
--- a/js/src/jit/MIR.cpp
+++ b/js/src/jit/MIR.cpp
@@ -3091,19 +3091,24 @@ PropertyReadNeedsTypeBarrier(types::Comp
                              types::TypeObjectKey *object, PropertyName *name,
                              types::TypeSet *observed)
 {
     // If the object being read from has types for the property which haven't
     // been observed at this access site, the read could produce a new type and
     // a barrier is needed. Note that this only covers reads from properties
     // which are accounted for by type information, i.e. native data properties
     // and elements.
-
-    if (object->unknownProperties() || observed->empty())
+    //
+    // We also need a barrier if the object is a proxy, because then all bets
+    // are off, just as if it has unknown properties.
+    if (object->unknownProperties() || observed->empty() ||
+        object->clasp()->isProxy())
+    {
         return true;
+    }
 
     jsid id = name ? NameToId(name) : JSID_VOID;
     types::HeapTypeSetKey property = object->property(id);
     if (property.maybeTypes() && !TypeSetIncludes(observed, MIRType_Value, property.maybeTypes()))
         return true;
 
     // Type information for global objects is not required to reflect the
     // initial 'undefined' value for properties, in particular global
--- a/js/src/jsinfer.cpp
+++ b/js/src/jsinfer.cpp
@@ -1758,17 +1758,17 @@ bool
 TemporaryTypeSet::isDOMClass()
 {
     if (unknownObject())
         return false;
 
     unsigned count = getObjectCount();
     for (unsigned i = 0; i < count; i++) {
         const Class *clasp = getObjectClass(i);
-        if (clasp && (!(clasp->flags & JSCLASS_IS_DOMJSCLASS) || clasp->isProxy()))
+        if (clasp && !clasp->isDOMClass())
             return false;
     }
 
     return count > 0;
 }
 
 bool
 TemporaryTypeSet::maybeCallable()
--- a/js/src/vm/ProxyObject.cpp
+++ b/js/src/vm/ProxyObject.cpp
@@ -24,19 +24,21 @@ ProxyObject::New(JSContext *cx, BaseProx
 
     JS_ASSERT(isValidProxyClass(clasp));
     JS_ASSERT_IF(proto.isObject(), cx->compartment() == proto.toObject()->compartment());
     JS_ASSERT_IF(parent, cx->compartment() == parent->compartment());
 
     /*
      * Eagerly mark properties unknown for proxies, so we don't try to track
      * their properties and so that we don't need to walk the compartment if
-     * their prototype changes later.
+     * their prototype changes later.  But don't do this for DOM proxies,
+     * because we want to be able to keep track of them in typesets in useful
+     * ways.
      */
-    if (proto.isObject() && !options.singleton()) {
+    if (proto.isObject() && !options.singleton() && !clasp->isDOMClass()) {
         RootedObject protoObj(cx, proto.toObject());
         if (!JSObject::setNewTypeUnknown(cx, clasp, protoObj))
             return nullptr;
     }
 
     NewObjectKind newKind = options.singleton() ? SingletonObject : GenericObject;
     gc::AllocKind allocKind = gc::GetGCObjectKind(clasp);
     if (handler->finalizeInBackground(priv))
@@ -44,18 +46,18 @@ ProxyObject::New(JSContext *cx, BaseProx
     RootedObject obj(cx, NewObjectWithGivenProto(cx, clasp, proto, parent, allocKind, newKind));
     if (!obj)
         return nullptr;
 
     Rooted<ProxyObject*> proxy(cx, &obj->as<ProxyObject>());
     proxy->initHandler(handler);
     proxy->initCrossCompartmentPrivate(priv);
 
-    /* Don't track types of properties of proxies. */
-    if (newKind != SingletonObject)
+    /* Don't track types of properties of non-DOM and non-singleton proxies. */
+    if (newKind != SingletonObject && !clasp->isDOMClass())
         MarkTypeObjectUnknownProperties(cx, proxy->type());
 
     return proxy;
 }
 
 void
 ProxyObject::initCrossCompartmentPrivate(HandleValue priv)
 {
--- a/layout/base/nsIPresShell.h
+++ b/layout/base/nsIPresShell.h
@@ -62,17 +62,16 @@ class nsIReflowCallback;
 class nsIDOMNode;
 class nsIntRegion;
 class nsIStyleSheet;
 class nsCSSFrameConstructor;
 class nsISelection;
 template<class E> class nsCOMArray;
 class nsWeakFrame;
 class nsIScrollableFrame;
-class gfxASurface;
 class gfxContext;
 class nsIDOMEvent;
 class nsDisplayList;
 class nsDisplayListBuilder;
 class nsPIDOMWindow;
 struct nsPoint;
 struct nsIntPoint;
 struct nsIntRect;
--- a/layout/base/nsLayoutUtils.cpp
+++ b/layout/base/nsLayoutUtils.cpp
@@ -5399,16 +5399,27 @@ nsLayoutUtils::SurfaceFromElement(nsIIma
   if (!noRasterize || imgContainer->GetType() == imgIContainer::TYPE_RASTER) {
     if (aSurfaceFlags & SFE_WANT_IMAGE_SURFACE) {
       frameFlags |= imgIContainer::FLAG_WANT_DATA_SURFACE;
     }
     result.mSourceSurface = imgContainer->GetFrame(whichFrame, frameFlags);
     if (!result.mSourceSurface) {
       return result;
     }
+    // The surface we return is likely to be cached. We don't want to have to
+    // convert to a surface that's compatible with aTarget each time it's used
+    // (that would result in terrible performance), so we convert once here
+    // upfront if aTarget is specified.
+    if (aTarget) {
+      RefPtr<SourceSurface> optSurface =
+        aTarget->OptimizeSourceSurface(result.mSourceSurface);
+      if (optSurface) {
+        result.mSourceSurface = optSurface;
+      }
+    }
   } else {
     result.mDrawInfo.mImgContainer = imgContainer;
     result.mDrawInfo.mWhichFrame = whichFrame;
     result.mDrawInfo.mDrawingFlags = frameFlags;
   }
 
   int32_t corsmode;
   if (NS_SUCCEEDED(imgRequest->GetCORSMode(&corsmode))) {
--- a/layout/svg/nsSVGFilterFrame.cpp
+++ b/layout/svg/nsSVGFilterFrame.cpp
@@ -2,17 +2,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/. */
 
 // Main header first:
 #include "nsSVGFilterFrame.h"
 
 // Keep others in (case-insensitive) order:
-#include "gfxASurface.h"
 #include "gfxUtils.h"
 #include "nsGkAtoms.h"
 #include "nsRenderingContext.h"
 #include "nsSVGEffects.h"
 #include "nsSVGElement.h"
 #include "mozilla/dom/SVGFilterElement.h"
 #include "nsSVGFilterInstance.h"
 #include "nsSVGFilterPaintCallback.h"
--- a/layout/svg/nsSVGUtils.cpp
+++ b/layout/svg/nsSVGUtils.cpp
@@ -6,17 +6,16 @@
 // Main header first:
 // This is also necessary to ensure our definition of M_SQRT1_2 is picked up
 #include "nsSVGUtils.h"
 #include <algorithm>
 
 // Keep others in (case-insensitive) order:
 #include "gfx2DGlue.h"
 #include "gfxContext.h"
-#include "gfxImageSurface.h"
 #include "gfxMatrix.h"
 #include "gfxPlatform.h"
 #include "gfxRect.h"
 #include "gfxUtils.h"
 #include "mozilla/gfx/2D.h"
 #include "mozilla/Preferences.h"
 #include "nsCSSFrameConstructor.h"
 #include "nsDisplayList.h"
--- a/layout/svg/nsSVGUtils.h
+++ b/layout/svg/nsSVGUtils.h
@@ -22,19 +22,17 @@
 #include "nsCOMPtr.h"
 #include "nsID.h"
 #include "nsISupportsBase.h"
 #include "nsMathUtils.h"
 #include "nsStyleStruct.h"
 #include "mozilla/Constants.h"
 #include <algorithm>
 
-class gfxASurface;
 class gfxContext;
-class gfxImageSurface;
 class gfxPattern;
 class nsFrameList;
 class nsIContent;
 class nsIDocument;
 class nsIFrame;
 class nsPresContext;
 class nsRenderingContext;
 class nsStyleContext;
--- a/layout/xul/tree/nsTreeColumns.cpp
+++ b/layout/xul/tree/nsTreeColumns.cpp
@@ -554,32 +554,38 @@ nsTreeColumns::NamedGetter(const nsAStri
       aFound = true;
       return currCol;
     }
   }
   aFound = false;
   return nullptr;
 }
 
+bool
+nsTreeColumns::NameIsEnumerable(const nsAString& aName)
+{
+  return true;
+}
+
 nsTreeColumn*
 nsTreeColumns::GetNamedColumn(const nsAString& aId)
 {
   bool dummy;
   return NamedGetter(aId, dummy);
 }
 
 NS_IMETHODIMP
 nsTreeColumns::GetNamedColumn(const nsAString& aId, nsITreeColumn** _retval)
 {
   NS_IF_ADDREF(*_retval = GetNamedColumn(aId));
   return NS_OK;
 }
 
 void
-nsTreeColumns::GetSupportedNames(nsTArray<nsString>& aNames)
+nsTreeColumns::GetSupportedNames(unsigned, nsTArray<nsString>& aNames)
 {
   for (nsTreeColumn* currCol = mFirstColumn; currCol; currCol = currCol->GetNext()) {
     aNames.AppendElement(currCol->GetId());
   }
 }
 
 
 nsTreeColumn*
--- a/layout/xul/tree/nsTreeColumns.h
+++ b/layout/xul/tree/nsTreeColumns.h
@@ -152,18 +152,19 @@ public:
   nsTreeColumn* GetSortedColumn();
   nsTreeColumn* GetKeyColumn();
 
   nsTreeColumn* GetColumnFor(mozilla::dom::Element* aElement);
 
   nsTreeColumn* IndexedGetter(uint32_t aIndex, bool& aFound);
   nsTreeColumn* GetColumnAt(uint32_t aIndex);
   nsTreeColumn* NamedGetter(const nsAString& aId, bool& aFound);
+  bool NameIsEnumerable(const nsAString& aName);
   nsTreeColumn* GetNamedColumn(const nsAString& aId);
-  void GetSupportedNames(nsTArray<nsString>& aNames);
+  void GetSupportedNames(unsigned, nsTArray<nsString>& aNames);
 
   // Uses XPCOM InvalidateColumns().
   // Uses XPCOM RestoreNaturalOrder().
 
   friend class nsTreeBodyFrame;
 protected:
   void SetTree(nsTreeBodyFrame* aTree) { mTree = aTree; }
 
--- a/media/libvorbis/moz.build
+++ b/media/libvorbis/moz.build
@@ -46,8 +46,12 @@ if CONFIG['OS_ARCH'] == 'SunOS':
     DEFINES['HAVE_ALLOCA_H'] = True
 
 MSVC_ENABLE_PGO = True
 
 if CONFIG['GKMEDIAS_SHARED_LIBRARY']:
     NO_VISIBILITY_FLAGS = True
 
 FINAL_LIBRARY = 'gkmedias'
+
+# Suppress warnings in third-party code.
+if CONFIG['GNU_CC']:
+    CFLAGS += ['-Wno-uninitialized']
--- a/media/webrtc/signaling/src/mediapipeline/MediaPipeline.cpp
+++ b/media/webrtc/signaling/src/mediapipeline/MediaPipeline.cpp
@@ -33,17 +33,16 @@
 #include "AudioSegment.h"
 #include "MediaSegment.h"
 #include "databuffer.h"
 #include "transportflow.h"
 #include "transportlayer.h"
 #include "transportlayerdtls.h"
 #include "transportlayerice.h"
 #include "runnable_utils.h"
-#include "gfxImageSurface.h"
 #include "libyuv/convert.h"
 #include "mozilla/gfx/Point.h"
 #include "mozilla/gfx/Types.h"
 
 #include "webrtc/modules/interface/module_common_types.h"
 #include "webrtc/modules/rtp_rtcp/interface/rtp_header_parser.h"
 
 using namespace mozilla;
new file mode 100644
--- /dev/null
+++ b/mfbt/double-conversion/fix-gcc-warnings.patch
@@ -0,0 +1,24 @@
+diff --git a/a/mfbt/double-conversion/strtod.cc b/inbound/mfbt/double-conversion/strtod.cc
+index 9758989..97fa4a5 100644
+--- a/a/mfbt/double-conversion/strtod.cc
++++ b/inbound/mfbt/double-conversion/strtod.cc
+@@ -501,17 +501,19 @@ float Strtof(Vector<const char> buffer, int exponent) {
+   // if they would round to the same float. If the guess is not correct we have
+   // to look at four values (since two different doubles could be the correct
+   // double).
+ 
+   double double_next = Double(double_guess).NextDouble();
+   double double_previous = Double(double_guess).PreviousDouble();
+ 
+   float f1 = static_cast<float>(double_previous);
++#if defined(DEBUG)
+   float f2 = float_guess;
++#endif
+   float f3 = static_cast<float>(double_next);
+   float f4;
+   if (is_correct) {
+     f4 = f3;
+   } else {
+     double double_next2 = Double(double_next).NextDouble();
+     f4 = static_cast<float>(double_next2);
+   }
--- a/mfbt/double-conversion/strtod.cc
+++ b/mfbt/double-conversion/strtod.cc
@@ -501,17 +501,19 @@ float Strtof(Vector<const char> buffer, 
   // if they would round to the same float. If the guess is not correct we have
   // to look at four values (since two different doubles could be the correct
   // double).
 
   double double_next = Double(double_guess).NextDouble();
   double double_previous = Double(double_guess).PreviousDouble();
 
   float f1 = static_cast<float>(double_previous);
+#if defined(DEBUG)
   float f2 = float_guess;
+#endif
   float f3 = static_cast<float>(double_next);
   float f4;
   if (is_correct) {
     f4 = f3;
   } else {
     double double_next2 = Double(double_next).NextDouble();
     f4 = static_cast<float>(double_next2);
   }
--- a/mfbt/double-conversion/update.sh
+++ b/mfbt/double-conversion/update.sh
@@ -16,11 +16,12 @@ cp $1/src/*.h ./
 # Source
 cp $1/src/*.cc ./
 
 patch -p3 < add-mfbt-api-markers.patch
 patch -p3 < use-StandardInteger.patch
 patch -p3 < use-mozilla-assertions.patch
 patch -p3 < use-static_assert.patch
 patch -p3 < ToPrecision-exponential.patch
+patch -p3 < fix-gcc-warnings.patch
 
 # Merged upstream, part of 2.0.1 version
 patch -p3 < fix-aarch64-macro.patch
--- a/mfbt/moz.build
+++ b/mfbt/moz.build
@@ -88,8 +88,13 @@ DEFINES['IMPL_MFBT'] = True
 # Compression.cpp cannot be built in unified mode because it pulls in Windows system headers.
 # Decimal.cpp doesn't build in unified mode with gcc.
 SOURCES += [
     'Compression.cpp',
     'decimal/Decimal.cpp',
 ]
 
 DISABLE_STL_WRAPPING = True
+
+# Suppress warnings in third-party code.
+if CONFIG['GNU_CXX']:
+    # TODO: Remove this LZ4 warning suppression after bug 993267 is fixed.
+    SOURCES['Compression.cpp'].flags += ['-Wno-unused-function']
--- a/mobile/android/base/tests/helpers/JavascriptBridge.java
+++ b/mobile/android/base/tests/helpers/JavascriptBridge.java
@@ -13,19 +13,51 @@ import org.json.JSONArray;
 import org.json.JSONException;
 import org.json.JSONObject;
 
 import org.mozilla.gecko.Actions;
 import org.mozilla.gecko.Actions.EventExpecter;
 import org.mozilla.gecko.Assert;
 import org.mozilla.gecko.tests.UITestContext;
 
-
 /**
- * Javascript bridge allows calls to and from Javascript.
+ * Javascript bridge allows calls to and from JavaScript.
+ *
+ * To establish communication, create an instance of JavascriptBridge in Java and pass in
+ * an object that will receive calls from JavaScript. For example:
+ *
+ *  {@code final JavascriptBridge js = new JavascriptBridge(javaObj);}
+ *
+ * Next, create an instance of JavaBridge in JavaScript and pass in another object
+ * that will receive calls from Java. For example:
+ *
+ *  {@code let java = new JavaBridge(jsObj);}
+ *
+ * Once a link is established, calls can be made using the methods syncCall and asyncCall.
+ * syncCall waits for the call to finish before returning. For example:
+ *
+ *  {@code js.syncCall("abc", 1, 2, 3);} will synchronously call the JavaScript method
+ *    jsObj.abc and pass in arguments 1, 2, and 3.
+ *
+ *  {@code java.asyncCall("def", 4, 5, 6);} will asynchronously call the Java method
+ *    javaObj.def and pass in arguments 4, 5, and 6.
+ *
+ * Supported argument types include int, double, boolean, String, and JSONObject. Note
+ * that only implicit conversion is done, meaning if a floating point argument is passed
+ * from JavaScript to Java, the call will fail if the Java method has an int argument.
+ *
+ * Because JavascriptBridge and JavaBridge use one underlying communication channel,
+ * creating multiple instances of them will not create independent links.
+ *
+ * Note also that because Robocop tests finish as soon as the Java test method returns,
+ * the last call to JavaScript from Java must be a synchronous call. Otherwise, the test
+ * will finish before the JavaScript method is run. Calls to Java from JavaScript do not
+ * have this requirement. Because of these considerations, calls from Java to JavaScript
+ * are usually synchronous and calls from JavaScript to Java are usually asynchronous.
+ * See testJavascriptBridge.java for examples.
  */
 public final class JavascriptBridge {
 
     private static enum MessageStatus {
         QUEUE_EMPTY, // Did not process a message; queue was empty.
         PROCESSED,   // A message other than sync was processed.
         REPLIED,     // A sync message was processed.
         SAVED,       // An async message was saved; see processMessage().
@@ -62,16 +94,18 @@ public final class JavascriptBridge {
     // Parser for handling xpcshell assertions
     private final JavascriptMessageParser mLogParser;
     // Expecter of our internal Robocop event
     private final EventExpecter mExpecter;
     // Saved async message; see processMessage() for its purpose.
     private JSONObject mSavedAsyncMessage;
     // Number of levels in the synchronous call stack
     private int mCallStackDepth;
+    // If JavaBridge has been loaded
+    private boolean mJavaBridgeLoaded;
 
     /* package */ static void init(final UITestContext context) {
         sActions = context.getActions();
         sAsserter = context.getAsserter();
     }
 
     public JavascriptBridge(final Object target) {
         mTarget = target;
@@ -176,17 +210,25 @@ public final class JavascriptBridge {
         do {
             result = maybeProcessPendingMessage();
             if (result == MessageStatus.REPLIED) {
                 throw new IllegalStateException("Sync reply was unexpected");
             }
         } while (result != MessageStatus.QUEUE_EMPTY);
     }
 
+    private void ensureJavaBridgeLoaded() {
+        while (!mJavaBridgeLoaded) {
+            processPendingMessage();
+        }
+    }
+
     private void sendMessage(final String innerType, final String method, final Object[] args) {
+        ensureJavaBridgeLoaded();
+
         // Call from Java to Javascript
         final JSONObject message = new JSONObject();
         final JSONArray jsonArgs = new JSONArray();
         try {
             if (args != null) {
                 for (final Object arg : args) {
                     jsonArgs.put(convertToJSONValue(arg));
                 }
@@ -212,16 +254,20 @@ public final class JavascriptBridge {
             }
             type = message.getString("innerType");
 
             if ("progress".equals(type)) {
                 // Javascript harness message
                 mLogParser.logMessage(message.getString("message"));
                 return MessageStatus.PROCESSED;
 
+            } else if ("notify-loaded".equals(type)) {
+                mJavaBridgeLoaded = true;
+                return MessageStatus.PROCESSED;
+
             } else if ("sync-reply".equals(type)) {
                 // Reply to Java-to-Javascript sync call
                 return MessageStatus.REPLIED;
 
             } else if ("sync-call".equals(type) || "async-call".equals(type)) {
 
                 if ("async-call".equals(type)) {
                     // Save this async message until another async message arrives, then we
--- a/mobile/android/base/tests/robocop_head.js
+++ b/mobile/android/base/tests/robocop_head.js
@@ -1152,16 +1152,18 @@ function run_next_test()
 
 function JavaBridge(obj) {
 
   this._EVENT_TYPE = "Robocop:JS";
   this._target = obj;
   // The number of replies needed to answer all outstanding sync calls.
   this._repliesNeeded = 0;
   this._Services.obs.addObserver(this, this._EVENT_TYPE, false);
+
+  this._sendMessage("notify-loaded", []);
 };
 
 JavaBridge.prototype = {
 
   _Services: Components.utils.import(
     "resource://gre/modules/Services.jsm", {}).Services,
 
   _sendMessageToJava: Components.utils.import(
--- a/modules/libmar/tool/mar.c
+++ b/modules/libmar/tool/mar.c
@@ -32,27 +32,33 @@ static void print_version() {
   printf("Version: %s\n", MOZ_APP_VERSION);
   printf("Default Channel ID: %s\n", MAR_CHANNEL_ID);
 }
 
 static void print_usage() {
   printf("usage:\n");
   printf("Create a MAR file:\n");
   printf("  mar [-H MARChannelID] [-V ProductVersion] [-C workingDir] "
-         "{-c|-x|-t|-T} archive.mar [files...]\n");
+         "-c archive.mar [files...]\n");
+
+  printf("Extract a MAR file:\n");
+  printf("  mar [-C workingDir] -x archive.mar\n");
 #ifndef NO_SIGN_VERIFY
   printf("Sign a MAR file:\n");
   printf("  mar [-C workingDir] -d NSSConfigDir -n certname -s "
          "archive.mar out_signed_archive.mar\n");
+
   printf("Strip a MAR signature:\n");
   printf("  mar [-C workingDir] -r "
          "signed_input_archive.mar output_archive.mar\n");
+
   printf("Extract a MAR signature:\n");
   printf("  mar [-C workingDir] -n(i) -X "
          "signed_input_archive.mar base_64_encoded_signature_file\n");
+
   printf("Import a MAR signature:\n");
   printf("  mar [-C workingDir] -n(i) -I "
          "signed_input_archive.mar base_64_encoded_signature_file "
          "changed_signed_output.mar\n");
   printf("(i) is the index of the certificate to extract\n");
 #if defined(XP_WIN) && !defined(MAR_NSS)
   printf("Verify a MAR file:\n");
   printf("  mar [-C workingDir] -D DERFilePath -v signed_archive.mar\n");
@@ -72,18 +78,25 @@ static void print_usage() {
          "-v signed_archive.mar\n");
   printf("At most %d signature certificate names are specified by "
          "-n0 certName -n1 certName2, ...\n", MAX_SIGNATURES);
 #endif
   printf("At most %d verification certificate names are specified by "
          "-n0 certName -n1 certName2, ...\n", MAX_SIGNATURES);
 #endif
   printf("Print information on a MAR file:\n");
+  printf("  mar -t archive.mar\n");
+
+  printf("Print detailed information on a MAR file including signatures:\n");
+  printf("  mar -T archive.mar\n");
+
+  printf("Refresh the product information block of a MAR file:\n");
   printf("  mar [-H MARChannelID] [-V ProductVersion] [-C workingDir] "
          "-i unsigned_archive_to_refresh.mar\n");
+
   printf("Print executable version:\n");
   printf("  mar --version\n");
   printf("This program does not handle unicode file paths properly\n");
 }
 
 static int mar_test_callback(MarFile *mar, 
                              const MarItem *item, 
                              void *unused) {
@@ -183,17 +196,17 @@ int main(int argc, char **argv) {
       NSSConfigDir = argv[2];
       argv += 2;
       argc -= 2;
      /* -n certName, also matches -n[index] certName
         We allow an index for verifying to be symmetric
         with the import and export command line arguments. */
     } else if (argv[1][0] == '-' &&
                argv[1][1] == 'n' &&
-               (argv[1][2] == '0' + certCount ||
+               (argv[1][2] == (char)('0' + certCount) ||
                 argv[1][2] == '\0' ||
                 !strcmp(argv[2], "-X") ||
                 !strcmp(argv[2], "-I"))) {
       if (certCount >= MAX_SIGNATURES) {
         print_usage();
         return -1;
       }
       certNames[certCount++] = argv[2];
--- a/netwerk/dns/nsDNSService2.cpp
+++ b/netwerk/dns/nsDNSService2.cpp
@@ -25,34 +25,34 @@
 #include "prnetdb.h"
 #include "prmon.h"
 #include "prio.h"
 #include "plstr.h"
 #include "nsIOService.h"
 #include "nsCharSeparatedTokenizer.h"
 #include "nsNetAddr.h"
 #include "nsProxyRelease.h"
-#include "nsIObserverService.h"
 
 #include "mozilla/Attributes.h"
 #include "mozilla/VisualEventTracer.h"
 #include "mozilla/net/NeckoCommon.h"
 #include "mozilla/net/ChildDNSService.h"
 #include "mozilla/net/DNSListenerProxy.h"
 
 using namespace mozilla;
 using namespace mozilla::net;
 
-static const char kPrefDnsCacheEntries[]    = "network.dnsCacheEntries";
-static const char kPrefDnsCacheExpiration[] = "network.dnsCacheExpiration";
-static const char kPrefDnsCacheGrace[]      = "network.dnsCacheExpirationGracePeriod";
-static const char kPrefIPv4OnlyDomains[]    = "network.dns.ipv4OnlyDomains";
-static const char kPrefDisableIPv6[]        = "network.dns.disableIPv6";
-static const char kPrefDisablePrefetch[]    = "network.dns.disablePrefetch";
-static const char kPrefDnsLocalDomains[]    = "network.dns.localDomains";
+static const char kPrefDnsCacheEntries[]     = "network.dnsCacheEntries";
+static const char kPrefDnsCacheExpiration[]  = "network.dnsCacheExpiration";
+static const char kPrefDnsCacheGrace[]       = "network.dnsCacheExpirationGracePeriod";
+static const char kPrefIPv4OnlyDomains[]     = "network.dns.ipv4OnlyDomains";
+static const char kPrefDisableIPv6[]         = "network.dns.disableIPv6";
+static const char kPrefDisablePrefetch[]     = "network.dns.disablePrefetch";
+static const char kPrefDnsLocalDomains[]     = "network.dns.localDomains";
+static const char kPrefDnsNotifyResolution[] = "network.dns.notifyResolution";
 
 //-----------------------------------------------------------------------------
 
 class nsDNSRecord : public nsIDNSRecord
 {
 public:
     NS_DECL_THREADSAFE_ISUPPORTS
     NS_DECL_NSIDNSRECORD
@@ -390,16 +390,41 @@ nsDNSSyncRequest::SizeOfIncludingThis(Ma
 
     // Measurement of the following members may be added later if DMD finds it
     // is worthwhile:
     // - mMonitor
 
     return n;
 }
 
+class NotifyDNSResolution: public nsRunnable
+{
+public:
+    NotifyDNSResolution(nsMainThreadPtrHandle<nsIObserverService> &aObs,
+                        const nsACString &aHostname)
+        : mObs(aObs)
+        , mHostname(aHostname)
+    {
+        MOZ_ASSERT(mObs);
+    }
+
+    NS_IMETHOD Run()
+    {
+        MOZ_ASSERT(NS_IsMainThread());
+        mObs->NotifyObservers(nullptr,
+                              "dns-resolution-request",
+                              NS_ConvertUTF8toUTF16(mHostname).get());
+        return NS_OK;
+    }
+
+private:
+    nsMainThreadPtrHandle<nsIObserverService> mObs;
+    nsCString                                 mHostname;
+};
+
 //-----------------------------------------------------------------------------
 
 nsDNSService::nsDNSService()
     : mLock("nsDNSServer.mLock")
     , mFirstTime(true)
     , mOffline(false)
 {
 }
@@ -457,16 +482,17 @@ nsDNSService::Init()
 
     // prefs
     uint32_t maxCacheEntries  = 400;
     uint32_t maxCacheLifetime = 120; // seconds
     uint32_t lifetimeGracePeriod = 60; // seconds
     bool     disableIPv6      = false;
     bool     disablePrefetch  = false;
     int      proxyType        = nsIProtocolProxyService::PROXYCONFIG_DIRECT;
+    bool     notifyResolution = false;
 
     nsAdoptingCString ipv4OnlyDomains;
     nsAdoptingCString localDomains;
 
     // read prefs
     nsCOMPtr<nsIPrefBranch> prefs = do_GetService(NS_PREFSERVICE_CONTRACTID);
     if (prefs) {
         int32_t val;
@@ -480,30 +506,32 @@ nsDNSService::Init()
         // ASSUMPTION: pref branch does not modify out params on failure
         prefs->GetBoolPref(kPrefDisableIPv6, &disableIPv6);
         prefs->GetCharPref(kPrefIPv4OnlyDomains, getter_Copies(ipv4OnlyDomains));
         prefs->GetCharPref(kPrefDnsLocalDomains, getter_Copies(localDomains));
         prefs->GetBoolPref(kPrefDisablePrefetch, &disablePrefetch);
 
         // If a manual proxy is in use, disable prefetch implicitly
         prefs->GetIntPref("network.proxy.type", &proxyType);
+        prefs->GetBoolPref(kPrefDnsNotifyResolution, &notifyResolution);
     }
 
     if (mFirstTime) {
         mFirstTime = false;
 
         // register as prefs observer
         if (prefs) {
             prefs->AddObserver(kPrefDnsCacheEntries, this, false);
             prefs->AddObserver(kPrefDnsCacheExpiration, this, false);
             prefs->AddObserver(kPrefDnsCacheGrace, this, false);
             prefs->AddObserver(kPrefIPv4OnlyDomains, this, false);
             prefs->AddObserver(kPrefDnsLocalDomains, this, false);
             prefs->AddObserver(kPrefDisableIPv6, this, false);
             prefs->AddObserver(kPrefDisablePrefetch, this, false);
+            prefs->AddObserver(kPrefDnsNotifyResolution, this, false);
 
             // Monitor these to see if there is a change in proxy configuration
             // If a manual proxy is in use, disable prefetch implicitly
             prefs->AddObserver("network.proxy.type", this, false);
         }
 
         nsresult rv;
         nsCOMPtr<nsIObserverService> observerService =
@@ -517,16 +545,19 @@ nsDNSService::Init()
 
     // Don't initialize the resolver if we're in offline mode.
     // Later on, the IO service will reinitialize us when going online.
     if (gIOService->IsOffline() && !gIOService->IsComingOnline())
         return NS_OK;
 
     nsCOMPtr<nsIIDNService> idn = do_GetService(NS_IDNSERVICE_CONTRACTID);
 
+    nsCOMPtr<nsIObserverService> obs =
+        do_GetService(NS_OBSERVERSERVICE_CONTRACTID);
+
     nsRefPtr<nsHostResolver> res;
     nsresult rv = nsHostResolver::Create(maxCacheEntries,
                                          maxCacheLifetime,
                                          lifetimeGracePeriod,
                                          getter_AddRefs(res));
     if (NS_SUCCEEDED(rv)) {
         // now, set all of our member variables while holding the lock
         MutexAutoLock lock(mLock);
@@ -545,16 +576,21 @@ nsDNSService::Init()
             nsCharSeparatedTokenizer tokenizer(domains, ',',
                                                nsCharSeparatedTokenizerTemplate<>::SEPARATOR_OPTIONAL);
 
             while (tokenizer.hasMoreTokens()) {
                 const nsSubstring& domain = tokenizer.nextToken();
                 mLocalDomains.PutEntry(nsDependentCString(NS_ConvertUTF16toUTF8(domain).get()));
             }
         }
+        mNotifyResolution = notifyResolution;
+        if (mNotifyResolution) {
+            mObserverService =
+              new nsMainThreadPtrHolder<nsIObserverService>(obs);
+        }
     }
 
     RegisterWeakMemoryReporter(this);
 
     return rv;
 }
 
 NS_IMETHODIMP
@@ -620,16 +656,22 @@ nsDNSService::AsyncResolve(const nsACStr
 
         if (mDisablePrefetch && (flags & RESOLVE_SPECULATE))
             return NS_ERROR_DNS_LOOKUP_QUEUE_FULL;
 
         res = mResolver;
         idn = mIDN;
         localDomain = mLocalDomains.GetEntry(hostname);
     }
+
+    if (mNotifyResolution) {
+        NS_DispatchToMainThread(new NotifyDNSResolution(mObserverService,
+                                                        hostname));
+    }
+
     if (!res)
         return NS_ERROR_OFFLINE;
 
     if (mOffline)
         flags |= RESOLVE_OFFLINE;
 
     const nsACString *hostPtr = &hostname;
 
@@ -724,16 +766,22 @@ nsDNSService::Resolve(const nsACString &
     nsCOMPtr<nsIIDNService> idn;
     bool localDomain = false;
     {
         MutexAutoLock lock(mLock);
         res = mResolver;
         idn = mIDN;
         localDomain = mLocalDomains.GetEntry(hostname);
     }
+
+    if (mNotifyResolution) {
+        NS_DispatchToMainThread(new NotifyDNSResolution(mObserverService,
+                                                        hostname));
+    }
+
     NS_ENSURE_TRUE(res, NS_ERROR_OFFLINE);
 
     if (mOffline)
         flags |= RESOLVE_OFFLINE;
 
     const nsACString *hostPtr = &hostname;
 
     if (localDomain) {
--- a/netwerk/dns/nsDNSService2.h
+++ b/netwerk/dns/nsDNSService2.h
@@ -11,16 +11,18 @@
 #include "nsIIDNService.h"
 #include "nsIMemoryReporter.h"
 #include "nsIObserver.h"
 #include "nsHostResolver.h"
 #include "nsAutoPtr.h"
 #include "nsString.h"
 #include "nsTHashtable.h"
 #include "nsHashKeys.h"
+#include "nsIObserverService.h"
+#include "nsProxyRelease.h"
 #include "mozilla/Mutex.h"
 #include "mozilla/Attributes.h"
 
 class nsDNSService MOZ_FINAL : public nsPIDNSService
                              , public nsIObserver
                              , public nsIMemoryReporter
 {
 public:
@@ -46,17 +48,19 @@ private:
     nsCOMPtr<nsIIDNService>   mIDN;
 
     // mLock protects access to mResolver and mIPv4OnlyDomains
     mozilla::Mutex            mLock;
 
     // mIPv4OnlyDomains is a comma-separated list of domains for which only
     // IPv4 DNS lookups are performed. This allows the user to disable IPv6 on
     // a per-domain basis and work around broken DNS servers. See bug 68796.
-    nsAdoptingCString         mIPv4OnlyDomains;
-    bool                      mDisableIPv6;
-    bool                      mDisablePrefetch;
-    bool                      mFirstTime;
-    bool                      mOffline;
-    nsTHashtable<nsCStringHashKey> mLocalDomains;
+    nsAdoptingCString                         mIPv4OnlyDomains;
+    bool                                      mDisableIPv6;
+    bool                                      mDisablePrefetch;
+    bool                                      mFirstTime;
+    bool                                      mOffline;
+    bool                                      mNotifyResolution;
+    nsMainThreadPtrHandle<nsIObserverService> mObserverService;
+    nsTHashtable<nsCStringHashKey>            mLocalDomains;
 };
 
 #endif //nsDNSService2_h__
new file mode 100644
--- /dev/null
+++ b/netwerk/test/unit/test_dns_proxy_bypass.js
@@ -0,0 +1,68 @@
+/* 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/. */
+
+var ioService = Cc["@mozilla.org/network/io-service;1"].
+  getService(Ci.nsIIOService);
+
+var prefs = Cc["@mozilla.org/preferences-service;1"].
+  getService(Ci.nsIPrefBranch);
+
+var url = "ws://dnsleak.example.com";
+
+var dnsRequestObserver = {
+  register: function() {
+    this.obs = Cc["@mozilla.org/observer-service;1"].
+      getService(Ci.nsIObserverService);
+    this.obs.addObserver(this, "dns-resolution-request", false);
+  },
+
+  unregister: function() {
+    if (this.obs) {
+      this.obs.removeObserver(this, "dns-resolution-request");
+    }
+  },
+
+  observe: function(subject, topic, data) {
+    if (topic == "dns-resolution-request") {
+      do_print(data);
+      if (data.indexOf("dnsleak.example.com") > -1) {
+        try {
+          do_check_true(false);
+        } catch (e) {}
+      }
+    }
+  }
+};
+
+var listener = {
+  onAcknowledge: function(aContext, aSize) {},
+  onBinaryMessageAvailable: function(aContext, aMsg) {},
+  onMessageAvailable: function(aContext, aMsg) {},
+  onServerClose: function(aContext, aCode, aReason) {},
+  onStart: function(aContext) {},
+  onStop: function(aContext, aStatusCode) {
+    prefs.clearUserPref("network.proxy.socks");
+    prefs.clearUserPref("network.proxy.socks_port");
+    prefs.clearUserPref("network.proxy.type");
+    prefs.clearUserPref("network.proxy.socks_remote_dns");
+    prefs.clearUserPref("network.dns.notifyResolution");
+    dnsRequestObserver.unregister();
+    do_test_finished();
+  }
+};
+
+function run_test() {
+  dnsRequestObserver.register();
+  prefs.setBoolPref("network.dns.notifyResolution", true);
+  prefs.setCharPref("network.proxy.socks", "127.0.0.1");
+  prefs.setIntPref("network.proxy.socks_port", 9000);
+  prefs.setIntPref("network.proxy.type", 1);
+  prefs.setBoolPref("network.proxy.socks_remote_dns", true);
+  var chan = Cc["@mozilla.org/network/protocol;1?name=ws"].
+    createInstance(Components.interfaces.nsIWebSocketChannel);
+  var uri = ioService.newURI(url, null, null);
+  chan.asyncOpen(uri, url, listener, null);
+  do_test_pending();
+}
+
--- a/netwerk/test/unit/xpcshell.ini
+++ b/netwerk/test/unit/xpcshell.ini
@@ -186,16 +186,17 @@ skip-if = os == "android"
 [test_content_encoding_gzip.js]
 [test_content_sniffer.js]
 [test_cookie_header.js]
 [test_cookiejars.js]
 [test_cookiejars_safebrowsing.js]
 [test_data_protocol.js]
 [test_dns_service.js]
 [test_dns_localredirect.js]
+[test_dns_proxy_bypass.js]
 [test_duplicate_headers.js]
 [test_chunked_responses.js]
 [test_event_sink.js]
 [test_extract_charset_from_content_type.js]
 [test_force_sniffing.js]
 [test_fallback_no-cache-entry_canceled.js]
 [test_fallback_no-cache-entry_passing.js]
 [test_fallback_redirect-to-different-origin_canceled.js]
--- a/parser/html/moz.build
+++ b/parser/html/moz.build
@@ -30,18 +30,20 @@ EXPORTS += [
     'nsHtml5Module.h',
     'nsHtml5NamedCharacters.h',
     'nsHtml5NamedCharactersAccel.h',
     'nsHtml5OplessBuilder.h',
     'nsHtml5OwningUTF16Buffer.h',
     'nsHtml5Parser.h',
     'nsHtml5PendingNotification.h',
     'nsHtml5PlainTextUtils.h',
+    'nsHtml5RefPtr.h',
     'nsHtml5Speculation.h',
     'nsHtml5SpeculativeLoad.h',
+    'nsHtml5StreamListener.h',
     'nsHtml5StreamParser.h',
     'nsHtml5StringParser.h',
     'nsHtml5SVGLoadDispatcher.h',
     'nsHtml5TreeOperation.h',
     'nsHtml5TreeOpExecutor.h',
     'nsHtml5TreeOpStage.h',
     'nsHtml5UTF16Buffer.h',
     'nsHtml5UTF16BufferHSupplement.h',
@@ -70,16 +72,17 @@ UNIFIED_SOURCES += [
     'nsHtml5PlainTextUtils.cpp',
     'nsHtml5Portability.cpp',
     'nsHtml5ReleasableAttributeName.cpp',
     'nsHtml5ReleasableElementName.cpp',
     'nsHtml5Speculation.cpp',
     'nsHtml5SpeculativeLoad.cpp',
     'nsHtml5StackNode.cpp',
     'nsHtml5StateSnapshot.cpp',
+    'nsHtml5StreamListener.cpp',
     'nsHtml5StreamParser.cpp',
     'nsHtml5StringParser.cpp',
     'nsHtml5SVGLoadDispatcher.cpp',
     'nsHtml5Tokenizer.cpp',
     'nsHtml5TreeBuilder.cpp',
     'nsHtml5TreeOperation.cpp',
     'nsHtml5TreeOpExecutor.cpp',
     'nsHtml5TreeOpStage.cpp',
--- a/parser/html/nsHtml5Parser.cpp
+++ b/parser/html/nsHtml5Parser.cpp
@@ -21,17 +21,17 @@ NS_INTERFACE_MAP_END
 
 NS_IMPL_CYCLE_COLLECTING_ADDREF(nsHtml5Parser)
 NS_IMPL_CYCLE_COLLECTING_RELEASE(nsHtml5Parser)
 
 NS_IMPL_CYCLE_COLLECTION_CLASS(nsHtml5Parser)
 
 NS_IMPL_CYCLE_COLLECTION_TRAVERSE_BEGIN(nsHtml5Parser)
   NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mExecutor)
-  NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mStreamParser)
+  NS_IMPL_CYCLE_COLLECTION_TRAVERSE_RAWPTR(GetStreamParser())
 NS_IMPL_CYCLE_COLLECTION_TRAVERSE_END
 
 NS_IMPL_CYCLE_COLLECTION_UNLINK_BEGIN(nsHtml5Parser)
   NS_IMPL_CYCLE_COLLECTION_UNLINK(mExecutor)
   tmp->DropStreamParser();
 NS_IMPL_CYCLE_COLLECTION_UNLINK_END
 
 nsHtml5Parser::nsHtml5Parser()
@@ -91,46 +91,46 @@ nsHtml5Parser::SetCommand(eParserCommand
 }
 
 NS_IMETHODIMP_(void)
 nsHtml5Parser::SetDocumentCharset(const nsACString& aCharset,
                                   int32_t aCharsetSource)
 {
   NS_PRECONDITION(!mExecutor->HasStarted(),
                   "Document charset set too late.");
-  NS_PRECONDITION(mStreamParser, "Setting charset on a script-only parser.");
+  NS_PRECONDITION(GetStreamParser(), "Setting charset on a script-only parser.");
   nsAutoCString trimmed;
   trimmed.Assign(aCharset);
   trimmed.Trim(" \t\r\n\f");
-  mStreamParser->SetDocumentCharset(trimmed, aCharsetSource);
+  GetStreamParser()->SetDocumentCharset(trimmed, aCharsetSource);
   mExecutor->SetDocumentCharsetAndSource(trimmed,
                                          aCharsetSource);
 }
 
 NS_IMETHODIMP
 nsHtml5Parser::GetChannel(nsIChannel** aChannel)
 {
-  if (mStreamParser) {
-    return mStreamParser->GetChannel(aChannel);
+  if (GetStreamParser()) {
+    return GetStreamParser()->GetChannel(aChannel);
   } else {
     return NS_ERROR_NOT_AVAILABLE;
   }
 }
 
 NS_IMETHODIMP
 nsHtml5Parser::GetDTD(nsIDTD** aDTD)
 {
   *aDTD = nullptr;
   return NS_OK;
 }
 
 nsIStreamListener*
 nsHtml5Parser::GetStreamListener()
 {
-  return mStreamParser;
+  return mStreamListener;
 }
 
 NS_IMETHODIMP
 nsHtml5Parser::ContinueInterruptedParsing()
 {
   NS_NOTREACHED("Don't call. For interface compat only.");
   return NS_ERROR_NOT_IMPLEMENTED;
 }
@@ -173,21 +173,21 @@ nsHtml5Parser::Parse(nsIURI* aURL,
                      nsDTDMode aMode) // legacy; ignored
 {
   /*
    * Do NOT cause WillBuildModel to be called synchronously from here!
    * The document won't be ready for it until OnStartRequest!
    */
   NS_PRECONDITION(!mExecutor->HasStarted(), 
                   "Tried to start parse without initializing the parser.");
-  NS_PRECONDITION(mStreamParser, 
+  NS_PRECONDITION(GetStreamParser(),
                   "Can't call this Parse() variant on script-created parser");
-  mStreamParser->SetObserver(aObserver);
-  mStreamParser->SetViewSourceTitle(aURL); // In case we're viewing source
-  mExecutor->SetStreamParser(mStreamParser);
+  GetStreamParser()->SetObserver(aObserver);
+  GetStreamParser()->SetViewSourceTitle(aURL); // In case we're viewing source
+  mExecutor->SetStreamParser(GetStreamParser());
   mExecutor->SetParser(this);
   return NS_OK;
 }
 
 NS_IMETHODIMP
 nsHtml5Parser::Parse(const nsAString& aSourceBuffer,
                      void* aKey,
                      const nsACString& aContentType,
@@ -203,21 +203,21 @@ nsHtml5Parser::Parse(const nsAString& aS
   }
 
   // Maintain a reference to ourselves so we don't go away
   // till we're completely done. The old parser grips itself in this method.
   nsCOMPtr<nsIParser> kungFuDeathGrip(this);
   
   // Gripping the other objects just in case, since the other old grip
   // required grips to these, too.
-  nsRefPtr<nsHtml5StreamParser> streamKungFuDeathGrip(mStreamParser);
+  nsRefPtr<nsHtml5StreamParser> streamKungFuDeathGrip(GetStreamParser());
   nsRefPtr<nsHtml5TreeOpExecutor> treeOpKungFuDeathGrip(mExecutor);
 
   if (!mExecutor->HasStarted()) {
-    NS_ASSERTION(!mStreamParser,
+    NS_ASSERTION(!GetStreamParser(),
                  "Had stream parser but document.write started life cycle.");
     // This is the first document.write() on a document.open()ed document
     mExecutor->SetParser(this);
     mTreeBuilder->setScriptingEnabled(mExecutor->IsScriptEnabled());
 
     bool isSrcdoc = false;
     nsCOMPtr<nsIChannel> channel;
     rv = GetChannel(getter_AddRefs(channel));
@@ -242,17 +242,17 @@ nsHtml5Parser::Parse(const nsAString& aS
 
   // Return early if the parser has processed EOF
   if (mExecutor->IsComplete()) {
     return NS_OK;
   }
 
   if (aLastCall && aSourceBuffer.IsEmpty() && !aKey) {
     // document.close()
-    NS_ASSERTION(!mStreamParser,
+    NS_ASSERTION(!GetStreamParser(),
                  "Had stream parser but got document.close().");
     if (mDocumentClosed) {
       // already closed
       return NS_OK;
     }
     mDocumentClosed = true;
     if (!mBlocked && !mInDocumentWrite) {
       ParseUntilBlocked();
@@ -261,17 +261,17 @@ nsHtml5Parser::Parse(const nsAString& aS
   }
 
   // If we got this far, we are dealing with a document.write or
   // document.writeln call--not document.close().
 
   NS_ASSERTION(IsInsertionPointDefined(),
                "Doc.write reached parser with undefined insertion point.");
 
-  NS_ASSERTION(!(mStreamParser && !aKey),
+  NS_ASSERTION(!(GetStreamParser() && !aKey),
                "Got a null key in a non-script-created parser");
 
   // XXX is this optimization bogus?
   if (aSourceBuffer.IsEmpty()) {
     return NS_OK;
   }
 
   // This guard is here to prevent document.close from tokenizing synchronously
@@ -354,17 +354,17 @@ nsHtml5Parser::Parse(const nsAString& aS
 
   nsHtml5DependentUTF16Buffer stackBuffer(aSourceBuffer);
 
   while (!mBlocked && stackBuffer.hasMore()) {
     stackBuffer.adjust(mLastWasCR);
     mLastWasCR = false;
     if (stackBuffer.hasMore()) {
       int32_t lineNumberSave;
-      bool inRootContext = (!mStreamParser && !aKey);
+      bool inRootContext = (!GetStreamParser() && !aKey);
       if (inRootContext) {
         mTokenizer->setLineNumber(mRootContextLineNumber);
       } else {
         // we aren't the root context, so save the line number on the
         // *stack* so that we can restore it.
         lineNumberSave = mTokenizer->getLineNumber();
       }
 
@@ -491,20 +491,20 @@ nsHtml5Parser::Terminate()
   // We should only call DidBuildModel once, so don't do anything if this is
   // the second time that Terminate has been called.
   if (mExecutor->IsComplete()) {
     return NS_OK;
   }
   // XXX - [ until we figure out a way to break parser-sink circularity ]
   // Hack - Hold a reference until we are completely done...
   nsCOMPtr<nsIParser> kungFuDeathGrip(this);
-  nsRefPtr<nsHtml5StreamParser> streamKungFuDeathGrip(mStreamParser);
+  nsRefPtr<nsHtml5StreamParser> streamKungFuDeathGrip(GetStreamParser());
   nsRefPtr<nsHtml5TreeOpExecutor> treeOpKungFuDeathGrip(mExecutor);
-  if (mStreamParser) {
-    mStreamParser->Terminate();
+  if (GetStreamParser()) {
+    GetStreamParser()->Terminate();
   }
   return mExecutor->DidBuildModel(true);
 }
 
 NS_IMETHODIMP
 nsHtml5Parser::ParseFragment(const nsAString& aSourceBuffer,
                              nsTArray<nsString>& aTagStack)
 {
@@ -538,17 +538,17 @@ nsHtml5Parser::CanInterrupt()
   // interrupt.
   return true;
 }
 
 bool
 nsHtml5Parser::IsInsertionPointDefined()
 {
   return !mExecutor->IsFlushing() &&
-    (!mStreamParser || mParserInsertedScriptsBeingEvaluated);
+    (!GetStreamParser() || mParserInsertedScriptsBeingEvaluated);
 }
 
 void
 nsHtml5Parser::BeginEvaluatingParserInsertedScript()
 {
   ++mParserInsertedScriptsBeingEvaluated;
 }
 
@@ -556,17 +556,17 @@ void
 nsHtml5Parser::EndEvaluatingParserInsertedScript()
 {
   --mParserInsertedScriptsBeingEvaluated;
 }
 
 void
 nsHtml5Parser::MarkAsNotScriptCreated(const char* aCommand)
 {
-  NS_PRECONDITION(!mStreamParser, "Must not call this twice.");
+  NS_PRECONDITION(!mStreamListener, "Must not call this twice.");
   eParserMode mode = NORMAL;
   if (!nsCRT::strcmp(aCommand, "view-source")) {
     mode = VIEW_SOURCE_HTML;
   } else if (!nsCRT::strcmp(aCommand, "view-source-xml")) {
     mode = VIEW_SOURCE_XML;
   } else if (!nsCRT::strcmp(aCommand, "view-source-plain")) {
     mode = VIEW_SOURCE_PLAIN;
   } else if (!nsCRT::strcmp(aCommand, "plain-text")) {
@@ -576,23 +576,24 @@ nsHtml5Parser::MarkAsNotScriptCreated(co
   }
 #ifdef DEBUG
   else {
     NS_ASSERTION(!nsCRT::strcmp(aCommand, "view") ||
                  !nsCRT::strcmp(aCommand, "external-resource"),
                  "Unsupported parser command!");
   }
 #endif
-  mStreamParser = new nsHtml5StreamParser(mExecutor, this, mode);
+  mStreamListener =
+    new nsHtml5StreamListener(new nsHtml5StreamParser(mExecutor, this, mode));
 }
 
 bool
 nsHtml5Parser::IsScriptCreated()
 {
-  return !mStreamParser;
+  return !GetStreamParser();
 }
 
 /* End nsIParser  */
 
 // not from interface
 void
 nsHtml5Parser::ParseUntilBlocked()
 {
@@ -608,34 +609,34 @@ nsHtml5Parser::ParseUntilBlocked()
   for (;;) {
     if (!mFirstBuffer->hasMore()) {
       if (mFirstBuffer == mLastBuffer) {
         if (mExecutor->IsComplete()) {
           // something like cache manisfests stopped the parse in mid-flight
           return;
         }
         if (mDocumentClosed) {
-          NS_ASSERTION(!mStreamParser,
+          NS_ASSERTION(!GetStreamParser(),
                        "This should only happen with script-created parser.");
           mTokenizer->eof();
           mTreeBuilder->StreamEnded();
           mTreeBuilder->Flush();
           mExecutor->FlushDocumentWrite();
           mTokenizer->end();
           return;            
         }
         // never release the last buffer.
         NS_ASSERTION(!mLastBuffer->getStart() && !mLastBuffer->getEnd(),
                      "Sentinel buffer had its indeces changed.");
-        if (mStreamParser) {
+        if (GetStreamParser()) {
           if (mReturnToStreamParserPermitted &&
               !mExecutor->IsScriptExecuting()) {
             mTreeBuilder->Flush();
             mReturnToStreamParserPermitted = false;
-            mStreamParser->ContinueAfterScripts(mTokenizer,
+            GetStreamParser()->ContinueAfterScripts(mTokenizer,
                                                 mTreeBuilder,
                                                 mLastWasCR);
           }
         } else {
           // Script-created parser
           mTreeBuilder->Flush();
           // No need to flush the executor, because the executor is already
           // in a flush
@@ -651,17 +652,17 @@ nsHtml5Parser::ParseUntilBlocked()
     if (mBlocked || mExecutor->IsComplete()) {
       return;
     }
 
     // now we have a non-empty buffer
     mFirstBuffer->adjust(mLastWasCR);
     mLastWasCR = false;
     if (mFirstBuffer->hasMore()) {
-      bool inRootContext = (!mStreamParser && !mFirstBuffer->key);
+      bool inRootContext = (!GetStreamParser() && !mFirstBuffer->key);
       if (inRootContext) {
         mTokenizer->setLineNumber(mRootContextLineNumber);
       }
       mLastWasCR = mTokenizer->tokenizeBuffer(mFirstBuffer);
       if (inRootContext) {
         mRootContextLineNumber = mTokenizer->getLineNumber();
       }
       if (mTreeBuilder->HasScript()) {
@@ -710,13 +711,13 @@ nsHtml5Parser::InitializeDocWriteParserS
   mTreeBuilder->loadState(aState, &mAtomTable);
   mLastWasCR = false;
   mReturnToStreamParserPermitted = true;
 }
 
 void
 nsHtml5Parser::ContinueAfterFailedCharsetSwitch()
 {
-  NS_PRECONDITION(mStreamParser, 
+  NS_PRECONDITION(GetStreamParser(),
     "Tried to continue after failed charset switch without a stream parser");
-  mStreamParser->ContinueAfterFailedCharsetSwitch();
+  GetStreamParser()->ContinueAfterFailedCharsetSwitch();
 }
 
--- a/parser/html/nsHtml5Parser.h
+++ b/parser/html/nsHtml5Parser.h
@@ -20,16 +20,17 @@
 #include "nsCycleCollectionParticipant.h"
 #include "nsIInputStream.h"
 #include "nsDetectionConfident.h"
 #include "nsHtml5OwningUTF16Buffer.h"
 #include "nsHtml5TreeOpExecutor.h"
 #include "nsHtml5StreamParser.h"
 #include "nsHtml5AtomTable.h"
 #include "nsWeakReference.h"
+#include "nsHtml5StreamListener.h"
 
 class nsHtml5Parser : public nsIParser,
                       public nsSupportsWeakReference
 {
   public:
     NS_DECL_AND_IMPL_ZEROING_OPERATOR_NEW
     NS_DECL_CYCLE_COLLECTING_ISUPPORTS
 
@@ -234,29 +235,33 @@ class nsHtml5Parser : public nsIParser,
     inline nsHtml5Tokenizer* GetTokenizer() {
       return mTokenizer;
     }
 
     void InitializeDocWriteParserState(nsAHtml5TreeBuilderState* aState, int32_t aLine);
 
     void DropStreamParser()
     {
-      if (mStreamParser) {
-        mStreamParser->DropTimer();
-        mStreamParser = nullptr;
+      if (GetStreamParser()) {
+        GetStreamParser()->DropTimer();
+        mStreamListener->DropDelegate();
+        mStreamListener = nullptr;
       }
     }
     
     void StartTokenizer(bool aScriptingEnabled);
     
     void ContinueAfterFailedCharsetSwitch();
 
     nsHtml5StreamParser* GetStreamParser()
     {
-      return mStreamParser;
+      if (!mStreamListener) {
+        return nullptr;
+      }
+      return mStreamListener->GetDelegate();
     }
 
     /**
      * Parse until pending data is exhausted or a script blocks the parser
      */
     void ParseUntilBlocked();
 
   private:
@@ -329,19 +334,19 @@ class nsHtml5Parser : public nsIParser,
     nsAutoPtr<nsHtml5TreeBuilder> mDocWriteSpeculativeTreeBuilder;
 
     /**
      * Another HTML5 tokenizer for preloading document.written content.
      */
     nsAutoPtr<nsHtml5Tokenizer>   mDocWriteSpeculativeTokenizer;
 
     /**
-     * The stream parser.
+     * The stream listener holding the stream parser.
      */
-    nsRefPtr<nsHtml5StreamParser>       mStreamParser;
+    nsRefPtr<nsHtml5StreamListener>     mStreamListener;
 
     /**
      *
      */
     int32_t                             mRootContextLineNumber;
     
     /**
      * Whether it's OK to transfer parsing back to the stream parser
--- a/parser/html/nsHtml5RefPtr.h
+++ b/parser/html/nsHtml5RefPtr.h
@@ -1,17 +1,17 @@
 /* -*- Mode: C++; 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/. */
 
 #ifndef nsHtml5RefPtr_h
 #define nsHtml5RefPtr_h
 
-#include "nsIThread.h"
+#include "nsThreadUtils.h"
 
 template <class T>
 class nsHtml5RefPtrReleaser : public nsRunnable
   {
     private:
       T* mPtr;
     public:
       nsHtml5RefPtrReleaser(T* aPtr)
new file mode 100644
--- /dev/null
+++ b/parser/html/nsHtml5StreamListener.cpp
@@ -0,0 +1,82 @@
+/* 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 "nsHtml5StreamListener.h"
+
+NS_IMPL_ADDREF(nsHtml5StreamListener)
+NS_IMPL_RELEASE(nsHtml5StreamListener)
+
+NS_INTERFACE_MAP_BEGIN(nsHtml5StreamListener)
+  NS_INTERFACE_MAP_ENTRY_AMBIGUOUS(nsISupports, nsIRequestObserver)
+  NS_INTERFACE_MAP_ENTRY(nsIRequestObserver)
+  NS_INTERFACE_MAP_ENTRY(nsIStreamListener)
+  NS_INTERFACE_MAP_ENTRY(nsIThreadRetargetableStreamListener)
+NS_INTERFACE_MAP_END_THREADSAFE
+
+nsHtml5StreamListener::nsHtml5StreamListener(nsHtml5StreamParser* aDelegate)
+ : mDelegate(aDelegate)
+{
+}
+
+nsHtml5StreamListener::~nsHtml5StreamListener()
+{
+}
+
+void
+nsHtml5StreamListener::DropDelegate()
+{
+  MOZ_ASSERT(NS_IsMainThread(),
+             "Must not call DropDelegate from non-main threads.");
+  mDelegate = nullptr;
+}
+
+NS_IMETHODIMP
+nsHtml5StreamListener::CheckListenerChain()
+{
+  if (MOZ_UNLIKELY(!mDelegate)) {
+    return NS_ERROR_NOT_AVAILABLE;
+  }
+  return mDelegate->CheckListenerChain();
+}
+
+NS_IMETHODIMP
+nsHtml5StreamListener::OnStartRequest(nsIRequest* aRequest,
+                                      nsISupports* aContext)
+{
+  if (MOZ_UNLIKELY(!mDelegate)) {
+    return NS_ERROR_NOT_AVAILABLE;
+  }
+  return mDelegate->OnStartRequest(aRequest, aContext);
+}
+
+NS_IMETHODIMP
+nsHtml5StreamListener::OnStopRequest(nsIRequest* aRequest,
+                                     nsISupports* aContext,
+                                     nsresult aStatus)
+{
+  if (MOZ_UNLIKELY(!mDelegate)) {
+    return NS_ERROR_NOT_AVAILABLE;
+  }
+  return mDelegate->OnStopRequest(aRequest,
+                                  aContext,
+                                  aStatus);
+}
+
+NS_IMETHODIMP
+nsHtml5StreamListener::OnDataAvailable(nsIRequest* aRequest,
+                                       nsISupports* aContext,
+                                       nsIInputStream* aInStream,
+                                       uint64_t aSourceOffset,
+                                       uint32_t aLength)
+{
+  if (MOZ_UNLIKELY(!mDelegate)) {
+    return NS_ERROR_NOT_AVAILABLE;
+  }
+  return mDelegate->OnDataAvailable(aRequest,
+                                    aContext,
+                                    aInStream,
+                                    aSourceOffset,
+                                    aLength);
+}
+
new file mode 100644
--- /dev/null
+++ b/parser/html/nsHtml5StreamListener.h
@@ -0,0 +1,54 @@
+/* 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 nsHtml5StreamListener_h
+#define nsHtml5StreamListener_h
+
+#include "nsIStreamListener.h"
+#include "nsIThreadRetargetableStreamListener.h"
+#include "nsHtml5RefPtr.h"
+#include "nsHtml5StreamParser.h"
+
+/**
+ * The purpose of this class is to reconcile the problem that
+ * nsHtml5StreamParser is a cycle collection participant, which means that it
+ * can only be refcounted on the main thread, but
+ * nsIThreadRetargetableStreamListener can be refcounted from another thread,
+ * so nsHtml5StreamParser being an nsIThreadRetargetableStreamListener was
+ * a memory corruption problem.
+ *
+ * mDelegate is an nsHtml5RefPtr, which releases the object that it points
+ * to from a runnable on the main thread. DropDelegate() is only called on
+ * the main thread. This call will finish before the main-thread derefs the
+ * nsHtml5StreamListener itself, so there is no risk of another thread making
+ * the refcount of nsHtml5StreamListener go to zero and running the destructor
+ * concurrently. Other than that, the thread-safe nsISupports implementation
+ * takes care of the destructor not running concurrently from different
+ * threads, so there is no need to have a mutex around nsHtml5RefPtr to
+ * prevent it from double-releasing nsHtml5StreamParser.
+ */
+class nsHtml5StreamListener : public nsIStreamListener,
+                              public nsIThreadRetargetableStreamListener
+{
+public:
+  nsHtml5StreamListener(nsHtml5StreamParser* aDelegate);
+  virtual ~nsHtml5StreamListener();
+
+  NS_DECL_THREADSAFE_ISUPPORTS
+  NS_DECL_NSIREQUESTOBSERVER
+  NS_DECL_NSISTREAMLISTENER
+  NS_DECL_NSITHREADRETARGETABLESTREAMLISTENER
+
+  inline nsHtml5StreamParser* GetDelegate()
+  {
+    return mDelegate;
+  }
+
+  void DropDelegate();
+
+private:
+  nsHtml5RefPtr<nsHtml5StreamParser> mDelegate;
+};
+
+#endif // nsHtml5StreamListener_h
--- a/parser/html/nsHtml5StreamParser.cpp
+++ b/parser/html/nsHtml5StreamParser.cpp
@@ -68,20 +68,18 @@ nsHtml5StreamParser::InitializeStatics()
  * posted from the parser thread to main thread don't need to wrap any
  * runnable-specific data. (In the other direction, the runnables most notably
  * wrap the byte data of the stream.)
  */
 NS_IMPL_CYCLE_COLLECTING_ADDREF(nsHtml5StreamParser)
 NS_IMPL_CYCLE_COLLECTING_RELEASE(nsHtml5StreamParser)
 
 NS_INTERFACE_TABLE_HEAD(nsHtml5StreamParser)
-  NS_INTERFACE_TABLE3(nsHtml5StreamParser,
-                      nsIStreamListener, 
-                      nsICharsetDetectionObserver,
-                      nsIThreadRetargetableStreamListener)
+  NS_INTERFACE_TABLE1(nsHtml5StreamParser,
+                      nsICharsetDetectionObserver)
   NS_INTERFACE_TABLE_TO_MAP_SEGUE_CYCLE_COLLECTION(nsHtml5StreamParser)
 NS_INTERFACE_MAP_END
 
 NS_IMPL_CYCLE_COLLECTION_CLASS(nsHtml5StreamParser)
 
 NS_IMPL_CYCLE_COLLECTION_UNLINK_BEGIN(nsHtml5StreamParser)
   tmp->DropTimer();
   NS_IMPL_CYCLE_COLLECTION_UNLINK(mObserver)
@@ -105,17 +103,17 @@ NS_IMPL_CYCLE_COLLECTION_TRAVERSE_BEGIN(
   // hack: count the strongly owned edge wrapped in the runnable
   if (tmp->mLoadFlusher) {
     NS_CYCLE_COLLECTION_NOTE_EDGE_NAME(cb, "mLoadFlusher->mExecutor");
     cb.NoteXPCOMChild(static_cast<nsIContentSink*> (tmp->mExecutor));
   }
   // hack: count self if held by mChardet
   if (tmp->mChardet) {
     NS_CYCLE_COLLECTION_NOTE_EDGE_NAME(cb, "mChardet->mObserver");
-    cb.NoteXPCOMChild(static_cast<nsIStreamListener*>(tmp));
+    cb.NoteXPCOMChild(static_cast<nsICharsetDetectionObserver*>(tmp));
   }
 NS_IMPL_CYCLE_COLLECTION_TRAVERSE_END
 
 class nsHtml5ExecutorFlusher : public nsRunnable
 {
   private:
     nsRefPtr<nsHtml5TreeOpExecutor> mExecutor;
   public:
@@ -847,17 +845,16 @@ nsHtml5StreamParser::WriteStreamBytes(co
       NS_ASSERTION(totalByteCount == (int32_t)aCount,
           "The Unicode decoder consumed the wrong number of bytes.");
       *aWriteCount = (uint32_t)totalByteCount;
       return NS_OK;
     }
   }
 }
 
-// nsIRequestObserver methods:
 nsresult
 nsHtml5StreamParser::OnStartRequest(nsIRequest* aRequest, nsISupports* aContext)
 {
   NS_PRECONDITION(STREAM_NOT_STARTED == mStreamState,
                   "Got OnStartRequest when the stream had already started.");
   NS_PRECONDITION(!mExecutor->HasStarted(), 
                   "Got OnStartRequest at the wrong stage in the executor life cycle.");
   NS_ASSERTION(NS_IsMainThread(), "Wrong thread!");
@@ -969,17 +966,17 @@ nsHtml5StreamParser::OnStartRequest(nsIR
   mReparseForbidden = true;
   mFeedChardet = false;
 
   // Instantiate the converter here to avoid BOM sniffing.
   mUnicodeDecoder = EncodingUtils::DecoderForEncoding(mCharset);
   return NS_OK;
 }
 
-NS_IMETHODIMP
+nsresult
 nsHtml5StreamParser::CheckListenerChain()
 {
   NS_ASSERTION(NS_IsMainThread(), "Should be on the main thread!");
   if (!mObserver) {
     return NS_OK;
   }
   nsresult rv;
   nsCOMPtr<nsIThreadRetargetableStreamListener> retargetable =
@@ -1120,23 +1117,22 @@ class nsHtml5DataAvailable : public nsRu
     NS_IMETHODIMP Run()
     {
       mozilla::MutexAutoLock autoLock(mStreamParser->mTokenizerMutex);
       mStreamParser->DoDataAvailable(mData, mLength);
       return NS_OK;
     }
 };
 
-// nsIStreamListener method:
 nsresult
 nsHtml5StreamParser::OnDataAvailable(nsIRequest* aRequest,
-                               nsISupports* aContext,
-                               nsIInputStream* aInStream,
-                               uint64_t aSourceOffset,
-                               uint32_t aLength)
+                                     nsISupports* aContext,
+                                     nsIInputStream* aInStream,
+                                     uint64_t aSourceOffset,
+                                     uint32_t aLength)
 {
   nsresult rv;
   if (NS_FAILED(rv = mExecutor->IsBroken())) {
     return rv;
   }
 
   NS_ASSERTION(mRequest == aRequest, "Got data on wrong stream.");
   uint32_t totalRead;
--- a/parser/html/nsHtml5StreamParser.h
+++ b/parser/html/nsHtml5StreamParser.h
@@ -3,29 +3,27 @@
  * 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 nsHtml5StreamParser_h
 #define nsHtml5StreamParser_h
 
 #include "nsAutoPtr.h"
 #include "nsCOMPtr.h"
-#include "nsIStreamListener.h"
 #include "nsICharsetDetectionObserver.h"
 #include "nsHtml5MetaScanner.h"
 #include "nsIUnicodeDecoder.h"
 #include "nsHtml5TreeOpExecutor.h"
 #include "nsHtml5OwningUTF16Buffer.h"
 #include "nsIInputStream.h"
 #include "mozilla/Mutex.h"
 #include "nsHtml5AtomTable.h"
 #include "nsHtml5Speculation.h"
 #include "nsITimer.h"
 #include "nsICharsetDetector.h"
-#include "nsIThreadRetargetableStreamListener.h"
 
 class nsHtml5Parser;
 
 #define NS_HTML5_STREAM_PARSER_READ_BUFFER_SIZE 1024
 #define NS_HTML5_STREAM_PARSER_SNIFFING_BUFFER_SIZE 1024
 
 enum eParserMode {
   /**
@@ -96,45 +94,52 @@ enum eBomState {
 };
 
 enum eHtml5StreamState {
   STREAM_NOT_STARTED = 0,
   STREAM_BEING_READ = 1,
   STREAM_ENDED = 2
 };
 
-class nsHtml5StreamParser : public nsIStreamListener,
-                            public nsIThreadRetargetableStreamListener,
-                            public nsICharsetDetectionObserver {
+class nsHtml5StreamParser : public nsICharsetDetectionObserver {
 
   friend class nsHtml5RequestStopper;
   friend class nsHtml5DataAvailable;
   friend class nsHtml5StreamParserContinuation;
   friend class nsHtml5TimerKungFu;
 
   public:
     NS_DECL_AND_IMPL_ZEROING_OPERATOR_NEW
     NS_DECL_CYCLE_COLLECTING_ISUPPORTS
-    NS_DECL_CYCLE_COLLECTION_CLASS_AMBIGUOUS(nsHtml5StreamParser, nsIStreamListener)
+    NS_DECL_CYCLE_COLLECTION_CLASS_AMBIGUOUS(nsHtml5StreamParser,
+                                             nsICharsetDetectionObserver)
 
     static void InitializeStatics();
 
     nsHtml5StreamParser(nsHtml5TreeOpExecutor* aExecutor,
                         nsHtml5Parser* aOwner,
                         eParserMode aMode);
                         
     virtual ~nsHtml5StreamParser();
 
-    // nsIRequestObserver methods:
-    NS_DECL_NSIREQUESTOBSERVER
-    // nsIStreamListener methods:
-    NS_DECL_NSISTREAMLISTENER
-    // nsIThreadRetargetableStreamListener methods:
-    NS_DECL_NSITHREADRETARGETABLESTREAMLISTENER
-    
+    // Methods that nsHtml5StreamListener calls
+    nsresult CheckListenerChain();
+
+    nsresult OnStartRequest(nsIRequest* aRequest, nsISupports* aContext);
+
+    nsresult OnDataAvailable(nsIRequest* aRequest,
+                             nsISupports* aContext,
+                             nsIInputStream* aInStream,
+                             uint64_t aSourceOffset,
+                             uint32_t aLength);
+
+    nsresult OnStopRequest(nsIRequest* aRequest,
+                           nsISupports* aContext,
+                           nsresult status);
+
     // nsICharsetDetectionObserver
     /**
      * Chardet calls this to report the detection result
      */
     NS_IMETHOD Notify(const char* aCharset, nsDetectionConfident aConf);
 
     // EncodingDeclarationHandler
     // http://hg.mozilla.org/projects/htmlparser/file/tip/src/nu/validator/htmlparser/common/EncodingDeclarationHandler.java
--- a/security/manager/ssl/src/NSSErrorsService.cpp
+++ b/security/manager/ssl/src/NSSErrorsService.cpp
@@ -90,26 +90,27 @@ NSSErrorsService::GetErrorClass(nsresult
   
   int32_t aNSPRCode = -1 * NS_ERROR_GET_CODE(aXPCOMErrorCode);
 
   if (!IS_SEC_ERROR(aNSPRCode) && !IS_SSL_ERROR(aNSPRCode))
     return NS_ERROR_FAILURE;
 
   switch (aNSPRCode)
   {
+    // Overridable errors.
     case SEC_ERROR_UNKNOWN_ISSUER:
-    case SEC_ERROR_CA_CERT_INVALID:
     case SEC_ERROR_UNTRUSTED_ISSUER:
     case SEC_ERROR_EXPIRED_ISSUER_CERTIFICATE:
     case SEC_ERROR_UNTRUSTED_CERT:
     case SSL_ERROR_BAD_CERT_DOMAIN:
     case SEC_ERROR_EXPIRED_CERTIFICATE:
     case SEC_ERROR_CERT_SIGNATURE_ALGORITHM_DISABLED:
       *aErrorClass = ERROR_CLASS_BAD_CERT;
       break;
+    // Non-overridable errors.
     default:
       *aErrorClass = ERROR_CLASS_SSL_PROTOCOL;
       break;
   }
   return NS_OK;
 }
 
 NS_IMETHODIMP
--- a/security/manager/ssl/src/SSLServerCertVerification.cpp
+++ b/security/manager/ssl/src/SSLServerCertVerification.cpp
@@ -294,17 +294,16 @@ private:
 
 // A probe value of 1 means "no error".
 uint32_t
 MapCertErrorToProbeValue(PRErrorCode errorCode)
 {
   switch (errorCode)
   {
     case SEC_ERROR_UNKNOWN_ISSUER:                     return  2;
-    case SEC_ERROR_CA_CERT_INVALID:                    return  3;
     case SEC_ERROR_UNTRUSTED_ISSUER:                   return  4;
     case SEC_ERROR_EXPIRED_ISSUER_CERTIFICATE:         return  5;
     case SEC_ERROR_UNTRUSTED_CERT:                     return  6;
     case SEC_ERROR_INADEQUATE_KEY_USAGE:               return  7;
     case SEC_ERROR_CERT_SIGNATURE_ALGORITHM_DISABLED:  return  8;
     case SSL_ERROR_BAD_CERT_DOMAIN:                    return  9;
     case SEC_ERROR_EXPIRED_CERTIFICATE:                return 10;
   }
@@ -558,17 +557,16 @@ CertErrorRunnable::RunOnTargetThread()
 // if the given error code is an overridable error.
 // If it is not, then 0 is returned.
 uint32_t
 PRErrorCodeToOverrideType(PRErrorCode errorCode)
 {
   switch (errorCode)
   {
     case SEC_ERROR_UNKNOWN_ISSUER:
-    case SEC_ERROR_CA_CERT_INVALID:
     case SEC_ERROR_UNTRUSTED_ISSUER:
     case SEC_ERROR_EXPIRED_ISSUER_CERTIFICATE:
     case SEC_ERROR_UNTRUSTED_CERT:
     case SEC_ERROR_INADEQUATE_KEY_USAGE:
     case SEC_ERROR_CERT_SIGNATURE_ALGORITHM_DISABLED:
       // We group all these errors as "cert not trusted"
       return nsICertOverrideService::ERROR_UNTRUSTED;
     case SSL_ERROR_BAD_CERT_DOMAIN:
--- a/security/manager/ssl/src/nsNSSIOLayer.cpp
+++ b/security/manager/ssl/src/nsNSSIOLayer.cpp
@@ -1870,17 +1870,16 @@ ClientAuthDataRunnable::RunOnTargetThrea
 {
   PLArenaPool* arena = nullptr;
   char** caNameStrings;
   mozilla::pkix::ScopedCERTCertificate cert;
   ScopedSECKEYPrivateKey privKey;
   mozilla::pkix::ScopedCERTCertList certList;
   CERTCertListNode* node;
   ScopedCERTCertNicknames nicknames;
-  char* extracted = nullptr;
   int keyError = 0; // used for private key retrieval error
   SSM_UserCertChoice certChoice;
   int32_t NumberOfCerts = 0;
   void* wincx = mSocketInfo;
   nsresult rv;
 
   // create caNameStrings
   arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE);
@@ -2208,19 +2207,16 @@ ClientAuthDataRunnable::RunOnTargetThrea
 noCert:
 loser:
   if (mRV == SECSuccess) {
     mRV = SECFailure;
   }
 done:
   int error = PR_GetError();
 
-  if (extracted) {
-    PR_Free(extracted);
-  }
   if (arena) {
     PORT_FreeArena(arena, false);
   }
 
   *mPRetCert = cert.release();
   *mPRetKey = privKey.forget();
 
   if (mRV == SECFailure) {
--- a/security/manager/ssl/tests/unit/test_cert_overrides.js
+++ b/security/manager/ssl/tests/unit/test_cert_overrides.js
@@ -29,32 +29,43 @@ function add_cert_override(aHost, aExpec
 }
 
 function add_cert_override_test(aHost, aExpectedBits, aExpectedError) {
   add_connection_test(aHost, aExpectedError, null,
                       add_cert_override.bind(this, aHost, aExpectedBits));
   add_connection_test(aHost, Cr.NS_OK);
 }
 
+function add_non_overridable_test(aHost, aExpectedError) {
+  add_connection_test(
+    aHost, getXPCOMStatusFromNSS(aExpectedError), null,
+    function (securityInfo) {
+      // bug 754369 - no SSLStatus probably means this is a non-overridable
+      // error, which is what we're testing (although it would be best to test
+      // this directly).
+      securityInfo.QueryInterface(Ci.nsISSLStatusProvider);
+      do_check_eq(securityInfo.SSLStatus, null);
+    });
+}
+
 function check_telemetry() {
   let histogram = Cc["@mozilla.org/base/telemetry;1"]
                     .getService(Ci.nsITelemetry)
                     .getHistogramById("SSL_CERT_ERROR_OVERRIDES")
                     .snapshot();
   do_check_eq(histogram.counts[ 0], 0);
   do_check_eq(histogram.counts[ 2], 8 + 1); // SEC_ERROR_UNKNOWN_ISSUER
-  do_check_eq(histogram.counts[ 3], 0 + 2); // SEC_ERROR_CA_CERT_INVALID
+  do_check_eq(histogram.counts[ 3], 0);     // SEC_ERROR_CA_CERT_INVALID
   do_check_eq(histogram.counts[ 4], 0 + 5); // SEC_ERROR_UNTRUSTED_ISSUER
   do_check_eq(histogram.counts[ 5], 0 + 1); // SEC_ERROR_EXPIRED_ISSUER_CERTIFICATE
   do_check_eq(histogram.counts[ 6], 0 + 1); // SEC_ERROR_UNTRUSTED_CERT
   do_check_eq(histogram.counts[ 7], 0 + 1); // SEC_ERROR_INADEQUATE_KEY_USAGE
   do_check_eq(histogram.counts[ 8], 2 + 2); // SEC_ERROR_CERT_SIGNATURE_ALGORITHM_DISABLED
   do_check_eq(histogram.counts[ 9], 4 + 4); // SSL_ERROR_BAD_CERT_DOMAIN
   do_check_eq(histogram.counts[10], 5 + 5); // SEC_ERROR_EXPIRED_CERTIFICATE
-
   run_next_test();
 }
 
 function run_test() {
   add_tls_server_setup("BadCertServer");
 
   let fakeOCSPResponder = new HttpServer();
   fakeOCSPResponder.registerPrefixHandler("/", function (request, response) {
@@ -88,21 +99,24 @@ function add_tests_in_mode(useMozillaPKI
     run_next_test();
   });
 }
 
 function add_simple_tests(useMozillaPKIX) {
   add_cert_override_test("expired.example.com",
                          Ci.nsICertOverrideService.ERROR_TIME,
                          getXPCOMStatusFromNSS(SEC_ERROR_EXPIRED_CERTIFICATE));
-  add_cert_override_test("selfsigned.example.com",
-                         Ci.nsICertOverrideService.ERROR_UNTRUSTED,
-                         getXPCOMStatusFromNSS(
-                            useMozillaPKIX ? SEC_ERROR_UNKNOWN_ISSUER
-                                           : SEC_ERROR_CA_CERT_INVALID));
+  if (useMozillaPKIX) {
+    add_cert_override_test("selfsigned.example.com",
+                           Ci.nsICertOverrideService.ERROR_UNTRUSTED,
+                           getXPCOMStatusFromNSS(SEC_ERROR_UNKNOWN_ISSUER));
+  } else {
+    add_non_overridable_test("selfsigned.example.com",
+                             SEC_ERROR_CA_CERT_INVALID);
+  }
   add_cert_override_test("unknownissuer.example.com",
                          Ci.nsICertOverrideService.ERROR_UNTRUSTED,
                          getXPCOMStatusFromNSS(SEC_ERROR_UNKNOWN_ISSUER));
   add_cert_override_test("expiredissuer.example.com",
                          Ci.nsICertOverrideService.ERROR_UNTRUSTED,
                          getXPCOMStatusFromNSS(
                             useMozillaPKIX ? SEC_ERROR_UNKNOWN_ISSUER
                                            : SEC_ERROR_EXPIRED_ISSUER_CERTIFICATE));
@@ -118,35 +132,30 @@ function add_simple_tests(useMozillaPKIX
   // properties similar to the one this "host" will present (see
   // tlsserver/generate_certs.sh).
   // One of the errors classic verification collects is that this
   // certificate has an inadequate key usage to sign a certificate
   // (i.e. itself). As a result, to be able to override this,
   // SEC_ERROR_INADEQUATE_KEY_USAGE must be overridable (although,
   // confusingly, this isn't the main error reported).
   // mozilla::pkix just says this certificate's issuer is unknown.
-  add_cert_override_test("selfsigned-inadequateEKU.example.com",
-                         Ci.nsICertOverrideService.ERROR_UNTRUSTED,
-                         getXPCOMStatusFromNSS(
-                            useMozillaPKIX ? SEC_ERROR_UNKNOWN_ISSUER
-                                           : SEC_ERROR_CA_CERT_INVALID));
+  if (useMozillaPKIX) {
+    add_cert_override_test("selfsigned-inadequateEKU.example.com",
+                           Ci.nsICertOverrideService.ERROR_UNTRUSTED,
+                           getXPCOMStatusFromNSS(SEC_ERROR_UNKNOWN_ISSUER));
+  } else {
+    add_non_overridable_test("selfsigned-inadequateEKU.example.com",
+                             SEC_ERROR_CA_CERT_INVALID);
+  }
 
   // SEC_ERROR_INADEQUATE_KEY_USAGE is overridable in general for
   // classic verification, but not for mozilla::pkix verification.
   if (useMozillaPKIX) {
-    add_connection_test("inadequatekeyusage.example.com",
-                        getXPCOMStatusFromNSS(SEC_ERROR_INADEQUATE_KEY_USAGE),
-                        null,
-                        function (securityInfo) {
-                          // bug 754369 - no SSLStatus probably means this is
-                          // a non-overridable error, which is what we're testing
-                          // (although it would be best to test this directly).
-                          securityInfo.QueryInterface(Ci.nsISSLStatusProvider);
-                          do_check_eq(securityInfo.SSLStatus, null);
-                        });
+    add_non_overridable_test("inadequatekeyusage.example.com",
+                             SEC_ERROR_INADEQUATE_KEY_USAGE);
   } else {
     add_cert_override_test("inadequatekeyusage.example.com",
                            Ci.nsICertOverrideService.ERROR_UNTRUSTED,
                            getXPCOMStatusFromNSS(SEC_ERROR_INADEQUATE_KEY_USAGE));
   }
 
   // Bug 990603: Apache documentation has recommended generating a self-signed
   // test certificate with basic constraints: CA:true. For compatibility, this
--- a/toolkit/components/places/PlacesBackups.jsm
+++ b/toolkit/components/places/PlacesBackups.jsm
@@ -8,21 +8,22 @@ this.EXPORTED_SYMBOLS = ["PlacesBackups"
 
 const Ci = Components.interfaces;
 const Cu = Components.utils;
 const Cc = Components.classes;
 
 Cu.import("resource://gre/modules/XPCOMUtils.jsm");
 Cu.import("resource://gre/modules/Services.jsm");
 Cu.import("resource://gre/modules/PlacesUtils.jsm");
-Cu.import("resource://gre/modules/BookmarkJSONUtils.jsm");
 Cu.import("resource://gre/modules/Task.jsm");
 Cu.import("resource://gre/modules/osfile.jsm");
 Cu.import("resource://gre/modules/NetUtil.jsm");
 
+XPCOMUtils.defineLazyModuleGetter(this, "BookmarkJSONUtils",
+  "resource://gre/modules/BookmarkJSONUtils.jsm");
 XPCOMUtils.defineLazyModuleGetter(this, "Deprecated",
   "resource://gre/modules/Deprecated.jsm");
 XPCOMUtils.defineLazyModuleGetter(this, "OS",
   "resource://gre/modules/osfile.jsm");
 XPCOMUtils.defineLazyModuleGetter(this, "Sqlite",
   "resource://gre/modules/Sqlite.jsm");
 
 XPCOMUtils.defineLazyGetter(this, "localFileCtor",
--- a/widget/cocoa/nsDeviceContextSpecX.mm
+++ b/widget/cocoa/nsDeviceContextSpecX.mm
@@ -3,22 +3,22 @@
  * 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 "nsDeviceContextSpecX.h"
 
 #include "nsCRT.h"
 #include <unistd.h>
 
+#include "nsAutoPtr.h"
 #include "nsIServiceManager.h"
 #include "nsIPrintOptions.h"
 #include "nsPrintSettingsX.h"
 
 #include "gfxQuartzSurface.h"
-#include "gfxImageSurface.h"
 
 // This must be the last include:
 #include "nsObjCExceptions.h"
 
 nsDeviceContextSpecX::nsDeviceContextSpecX()
 : mPrintSession(NULL)
 , mPageFormat(kPMNoPageFormat)
 , mPrintSettings(kPMNoPrintSettings)
--- a/widget/cocoa/nsDragService.mm
+++ b/widget/cocoa/nsDragService.mm
@@ -22,17 +22,16 @@
 #include "nsIDOMNode.h"
 #include "nsRect.h"
 #include "nsPoint.h"
 #include "nsIIOService.h"
 #include "nsNetUtil.h"
 #include "nsIDocument.h"
 #include "nsIContent.h"
 #include "nsView.h"
-#include "gfxASurface.h"
 #include "gfxContext.h"
 #include "nsCocoaUtils.h"
 #include "mozilla/gfx/2D.h"
 #include "gfxPlatform.h"
 
 using namespace mozilla;
 using namespace mozilla::gfx;
 
--- a/widget/cocoa/nsMenuItemIconX.mm
+++ b/widget/cocoa/nsMenuItemIconX.mm
@@ -31,17 +31,16 @@
 #include "nsIDOMCSSPrimitiveValue.h"
 #include "nsIDOMRect.h"
 #include "nsThreadUtils.h"
 #include "nsToolkit.h"
 #include "nsNetUtil.h"
 #include "imgLoader.h"
 #include "imgRequestProxy.h"
 #include "nsMenuItemX.h"
-#include "gfxImageSurface.h"
 #include "gfxPlatform.h"
 #include "imgIContainer.h"
 #include "nsCocoaUtils.h"
 #include "nsContentUtils.h"
 
 using mozilla::gfx::SourceSurface;
 using mozilla::RefPtr;
 
--- a/widget/gtk/nsDragService.h
+++ b/widget/gtk/nsDragService.h
@@ -2,16 +2,17 @@
 /* vim: set ts=4 et sw=4 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 nsDragService_h__
 #define nsDragService_h__
 
+#include "nsAutoPtr.h"
 #include "nsBaseDragService.h"
 #include "nsIObserver.h"
 #include "nsAutoRef.h"
 #include <gtk/gtk.h>
 
 class nsWindow;
 
 namespace mozilla {
--- a/widget/gtk/nsImageToPixbuf.cpp
+++ b/widget/gtk/nsImageToPixbuf.cpp
@@ -1,28 +1,22 @@
 /* vim:set sw=4 sts=4 et cin: */
 /* 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 <gdk-pixbuf/gdk-pixbuf.h>
 
-#include "gfxASurface.h"
-#include "gfxImageSurface.h"
-#include "gfxContext.h"
-#include "gfxPlatform.h"
+#include "nsImageToPixbuf.h"
+
+#include "imgIContainer.h"
 #include "mozilla/gfx/2D.h"
 #include "mozilla/RefPtr.h"
-
-#include "imgIContainer.h"
-
 #include "nsAutoPtr.h"
 
-#include "nsImageToPixbuf.h"
-
 using mozilla::gfx::DataSourceSurface;
 using mozilla::gfx::SurfaceFormat;
 using mozilla::RefPtr;
 
 NS_IMPL_ISUPPORTS1(nsImageToPixbuf, nsIImageToPixbuf)
 
 inline unsigned char
 unpremultiply (unsigned char color,
--- a/widget/gtk/nsImageToPixbuf.h
+++ b/widget/gtk/nsImageToPixbuf.h
@@ -4,20 +4,16 @@
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #ifndef NSIMAGETOPIXBUF_H_
 #define NSIMAGETOPIXBUF_H_
 
 #include "nsIImageToPixbuf.h"
 #include "mozilla/Attributes.h"
 
-class gfxASurface;
-class gfxPattern;
-class gfxImageSurface;
-
 namespace mozilla {
 namespace gfx {
 class SourceSurface;
 }
 }
 
 class nsImageToPixbuf MOZ_FINAL : public nsIImageToPixbuf {
     typedef mozilla::gfx::SourceSurface SourceSurface;
--- a/widget/qt/nsWindow.cpp
+++ b/widget/qt/nsWindow.cpp
@@ -55,28 +55,25 @@
 #include "nsGfxCIID.h"
 
 #include "imgIContainer.h"
 #include "nsGfxCIID.h"
 #include "nsIInterfaceRequestorUtils.h"
 #include "nsAutoPtr.h"
 
 #include "gfxQtPlatform.h"
-#include "gfxContext.h"
-#include "gfxImageSurface.h"
 
 #include "nsIDOMWheelEvent.h"
 
 #include "GLContext.h"
 
 #ifdef MOZ_X11
 #include "keysym2ucs.h"
 #endif
 
-#include "gfxUtils.h"
 #include "Layers.h"
 #include "GLContextProvider.h"
 
 using namespace mozilla;
 using namespace mozilla::gl;
 using namespace mozilla::widget;
 using namespace mozilla::gfx;
 using namespace mozilla::layers;
--- a/widget/windows/nsDragService.cpp
+++ b/widget/windows/nsDragService.cpp
@@ -30,17 +30,16 @@
 #include "nsISupportsPrimitives.h"
 #include "nsNetUtil.h"
 #include "nsIURL.h"
 #include "nsCWebBrowserPersist.h"
 #include "nsToolkit.h"
 #include "nsCRT.h"
 #include "nsDirectoryServiceDefs.h"
 #include "nsUnicharUtils.h"
-#include "gfxASurface.h"
 #include "gfxContext.h"
 #include "nsRect.h"
 #include "nsMathUtils.h"
 #include "gfxWindowsPlatform.h"
 #include "mozilla/gfx/2D.h"
 #include "mozilla/gfx/DataSurfaceHelpers.h"
 #include "mozilla/gfx/Tools.h"
 
--- a/widget/xpwidgets/nsBaseDragService.h
+++ b/widget/xpwidgets/nsBaseDragService.h
@@ -7,21 +7,20 @@
 #define nsBaseDragService_h__
 
 #include "nsIDragService.h"
 #include "nsIDragSession.h"
 #include "nsITransferable.h"
 #include "nsIDOMDocument.h"
 #include "nsIDOMDataTransfer.h"
 #include "nsCOMPtr.h"
+#include "nsRect.h"
 #include "nsPoint.h"
 #include "mozilla/RefPtr.h"
 
-#include "gfxImageSurface.h"
-
 // translucency level for drag images
 #define DRAG_TRANSLUCENCY 0.65
 
 class nsIContent;
 class nsIDOMNode;
 class nsIFrame;
 class nsPresContext;
 class nsIImageLoadingContent;
--- a/xpcom/base/nsCycleCollector.cpp
+++ b/xpcom/base/nsCycleCollector.cpp
@@ -2406,19 +2406,21 @@ public:
     bool HasSnowWhiteObjects() const
     {
       return mObjects.Length() > 0;
     }
 
     virtual void Trace(JS::Heap<JS::Value>* aValue, const char* aName,
                        void* aClosure) const
     {
-        void* thing = JSVAL_TO_TRACEABLE(aValue->get());
-        if (thing && xpc_GCThingIsGrayCCThing(thing)) {
-            mCollector->GetJSPurpleBuffer()->mValues.AppendElement(*aValue);
+        if (aValue->isMarkable()) {
+            void* thing = aValue->toGCThing();
+            if (thing && xpc_GCThingIsGrayCCThing(thing)) {
+                mCollector->GetJSPurpleBuffer()->mValues.AppendElement(*aValue);
+            }
         }
     }
 
     virtual void Trace(JS::Heap<jsid>* aId, const char* aName,
                        void* aClosure) const
     {
     }
 
--- a/xpcom/build/nsXPComInit.cpp
+++ b/xpcom/build/nsXPComInit.cpp
@@ -11,16 +11,19 @@
 #include "mozilla/XPCOM.h"
 #include "nsXULAppAPI.h"
 
 #include "nsXPCOMPrivate.h"
 #include "nsXPCOMCIDInternal.h"
 
 #include "prlink.h"
 
+#include "mozilla/layers/ImageBridgeChild.h"
+#include "mozilla/layers/CompositorParent.h"
+
 #include "nsCycleCollector.h"
 #include "nsObserverList.h"
 #include "nsObserverService.h"
 #include "nsProperties.h"
 #include "nsPersistentProperties.h"
 #include "nsScriptableInputStream.h"
 #include "nsBinaryStream.h"
 #include "nsStorageStream.h"
--- a/xpcom/glue/nsCycleCollectionParticipant.cpp
+++ b/xpcom/glue/nsCycleCollectionParticipant.cpp
@@ -64,17 +64,19 @@ CycleCollectionNoteEdgeNameImpl(nsCycleC
     arrayEdgeName.AppendLiteral("[i]");
   }
   aCallback.NoteNextEdgeName(arrayEdgeName.get());
 }
 
 void
 TraceCallbackFunc::Trace(JS::Heap<JS::Value>* p, const char* name, void* closure) const
 {
-  mCallback(JSVAL_TO_TRACEABLE(p->get()), name, closure);
+  if (p->isMarkable()) {
+    mCallback(p->toGCThing(), name, closure);
+  }
 }
 
 void
 TraceCallbackFunc::Trace(JS::Heap<jsid>* p, const char* name, void* closure) const
 {
   void *thing = JSID_TO_GCTHING(*p);
   if (thing) {
     mCallback(thing, name, closure);
--- a/xpcom/glue/nsCycleCollectionParticipant.h
+++ b/xpcom/glue/nsCycleCollectionParticipant.h
@@ -424,19 +424,17 @@ T* DowncastCCParticipant(void *p)
     nsISupports *s = static_cast<nsISupports*>(p);                             \
     NS_CYCLE_COLLECTION_CLASSNAME(_base_class)::Trace(s, aCallbacks, aClosure);
 
 #define NS_IMPL_CYCLE_COLLECTION_TRACE_JS_MEMBER_CALLBACK(_field)              \
   if (tmp->_field)                                                             \
     aCallbacks.Trace(&tmp->_field, #_field, aClosure);
 
 #define NS_IMPL_CYCLE_COLLECTION_TRACE_JSVAL_MEMBER_CALLBACK(_field)           \
-  if (JSVAL_IS_TRACEABLE(tmp->_field)) {                                       \
-    aCallbacks.Trace(&tmp->_field, #_field, aClosure);                         \
-  }
+  aCallbacks.Trace(&tmp->_field, #_field, aClosure);
 
 // NB: The (void)tmp; hack in the TRACE_END macro exists to support
 // implementations that don't need to do anything in their Trace method.
 // Without this hack, some compilers warn about the unused tmp local.
 #define NS_IMPL_CYCLE_COLLECTION_TRACE_END                                     \
       (void)tmp;                                                               \
   }