Merge m-c to fx-team, a=merge
authorWes Kocher <wkocher@mozilla.com>
Wed, 10 Jun 2015 18:40:51 -0700
changeset 248140 af9a8b7899756891fc1cd332c03b443db253e1de
parent 248139 9cc8ad860e4b181a1019b27a5525b59acf2318aa (current diff)
parent 248113 54942e3f878087156d18983dd119af1640e50354 (diff)
child 248141 a10852989627e8b13f0525d42418e552447f0402
push id28892
push usercbook@mozilla.com
push dateThu, 11 Jun 2015 12:41:51 +0000
treeherdermozilla-central@9ebd530c5843 [default view] [failures only]
perfherder[talos] [build metrics] [platform microbench] (compared to previous push)
reviewersmerge
milestone41.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=merge
browser/base/content/browser.js
dom/base/test/TestCSPParser.cpp
dom/base/test/csp/browser.ini
dom/base/test/csp/browser_test_web_manifest.js
dom/base/test/csp/browser_test_web_manifest_mixed_content.js
dom/base/test/csp/chrome.ini
dom/base/test/csp/file_CSP.css
dom/base/test/csp/file_CSP.sjs
dom/base/test/csp/file_CSP_bug663567.xsl
dom/base/test/csp/file_CSP_bug663567_allows.xml
dom/base/test/csp/file_CSP_bug663567_allows.xml^headers^
dom/base/test/csp/file_CSP_bug663567_blocks.xml
dom/base/test/csp/file_CSP_bug663567_blocks.xml^headers^
dom/base/test/csp/file_CSP_bug802872.html
dom/base/test/csp/file_CSP_bug802872.html^headers^
dom/base/test/csp/file_CSP_bug802872.js
dom/base/test/csp/file_CSP_bug802872.sjs
dom/base/test/csp/file_CSP_bug885433_allows.html
dom/base/test/csp/file_CSP_bug885433_allows.html^headers^
dom/base/test/csp/file_CSP_bug885433_blocks.html
dom/base/test/csp/file_CSP_bug885433_blocks.html^headers^
dom/base/test/csp/file_CSP_bug888172.html
dom/base/test/csp/file_CSP_bug888172.sjs
dom/base/test/csp/file_CSP_bug909029_none.html
dom/base/test/csp/file_CSP_bug909029_none.html^headers^
dom/base/test/csp/file_CSP_bug909029_star.html
dom/base/test/csp/file_CSP_bug909029_star.html^headers^
dom/base/test/csp/file_CSP_bug910139.sjs
dom/base/test/csp/file_CSP_bug910139.xml
dom/base/test/csp/file_CSP_bug910139.xsl
dom/base/test/csp/file_CSP_bug941404.html
dom/base/test/csp/file_CSP_bug941404_xhr.html
dom/base/test/csp/file_CSP_bug941404_xhr.html^headers^
dom/base/test/csp/file_CSP_evalscript_main.html
dom/base/test/csp/file_CSP_evalscript_main.html^headers^
dom/base/test/csp/file_CSP_evalscript_main.js
dom/base/test/csp/file_CSP_evalscript_main_allowed.html
dom/base/test/csp/file_CSP_evalscript_main_allowed.html^headers^
dom/base/test/csp/file_CSP_evalscript_main_allowed.js
dom/base/test/csp/file_CSP_frameancestors.sjs
dom/base/test/csp/file_CSP_frameancestors_main.html
dom/base/test/csp/file_CSP_frameancestors_main.js
dom/base/test/csp/file_CSP_inlinescript_main.html
dom/base/test/csp/file_CSP_inlinescript_main.html^headers^
dom/base/test/csp/file_CSP_inlinescript_main_allowed.html
dom/base/test/csp/file_CSP_inlinescript_main_allowed.html^headers^
dom/base/test/csp/file_CSP_inlinestyle_main.html
dom/base/test/csp/file_CSP_inlinestyle_main.html^headers^
dom/base/test/csp/file_CSP_inlinestyle_main_allowed.html
dom/base/test/csp/file_CSP_inlinestyle_main_allowed.html^headers^
dom/base/test/csp/file_CSP_main.html
dom/base/test/csp/file_CSP_main.html^headers^
dom/base/test/csp/file_CSP_main.js
dom/base/test/csp/file_CSP_web_manifest.html
dom/base/test/csp/file_CSP_web_manifest.json
dom/base/test/csp/file_CSP_web_manifest.json^headers^
dom/base/test/csp/file_CSP_web_manifest_https.html
dom/base/test/csp/file_CSP_web_manifest_https.json
dom/base/test/csp/file_CSP_web_manifest_mixed_content.html
dom/base/test/csp/file_CSP_web_manifest_remote.html
dom/base/test/csp/file_base-uri.html
dom/base/test/csp/file_blob_data_schemes.html
dom/base/test/csp/file_bug836922_npolicies.html
dom/base/test/csp/file_bug836922_npolicies.html^headers^
dom/base/test/csp/file_bug836922_npolicies_ro_violation.sjs
dom/base/test/csp/file_bug836922_npolicies_violation.sjs
dom/base/test/csp/file_bug886164.html
dom/base/test/csp/file_bug886164.html^headers^
dom/base/test/csp/file_bug886164_2.html
dom/base/test/csp/file_bug886164_2.html^headers^
dom/base/test/csp/file_bug886164_3.html
dom/base/test/csp/file_bug886164_3.html^headers^
dom/base/test/csp/file_bug886164_4.html
dom/base/test/csp/file_bug886164_4.html^headers^
dom/base/test/csp/file_bug886164_5.html
dom/base/test/csp/file_bug886164_5.html^headers^
dom/base/test/csp/file_bug886164_6.html
dom/base/test/csp/file_bug886164_6.html^headers^
dom/base/test/csp/file_connect-src-fetch.html
dom/base/test/csp/file_connect-src.html
dom/base/test/csp/file_csp_allow_https_schemes.html
dom/base/test/csp/file_csp_bug768029.html
dom/base/test/csp/file_csp_bug768029.sjs
dom/base/test/csp/file_csp_bug773891.html
dom/base/test/csp/file_csp_bug773891.sjs
dom/base/test/csp/file_csp_invalid_source_expression.html
dom/base/test/csp/file_csp_path_matching.html
dom/base/test/csp/file_csp_path_matching.js
dom/base/test/csp/file_csp_path_matching_incl_query.html
dom/base/test/csp/file_csp_path_matching_redirect.html
dom/base/test/csp/file_csp_path_matching_redirect_server.sjs
dom/base/test/csp/file_csp_redirects_main.html
dom/base/test/csp/file_csp_redirects_page.sjs
dom/base/test/csp/file_csp_redirects_resource.sjs
dom/base/test/csp/file_csp_referrerdirective.html
dom/base/test/csp/file_csp_report.html
dom/base/test/csp/file_csp_testserver.sjs
dom/base/test/csp/file_dual_header_testserver.sjs
dom/base/test/csp/file_form-action.html
dom/base/test/csp/file_hash_source.html
dom/base/test/csp/file_hash_source.html^headers^
dom/base/test/csp/file_ignore_unsafe_inline.html
dom/base/test/csp/file_leading_wildcard.html
dom/base/test/csp/file_multi_policy_injection_bypass.html
dom/base/test/csp/file_multi_policy_injection_bypass.html^headers^
dom/base/test/csp/file_multi_policy_injection_bypass_2.html
dom/base/test/csp/file_multi_policy_injection_bypass_2.html^headers^
dom/base/test/csp/file_nonce_source.html
dom/base/test/csp/file_nonce_source.html^headers^
dom/base/test/csp/file_null_baseuri.html
dom/base/test/csp/file_policyuri_regression_from_multipolicy.html
dom/base/test/csp/file_policyuri_regression_from_multipolicy.html^headers^
dom/base/test/csp/file_policyuri_regression_from_multipolicy_policy
dom/base/test/csp/file_redirect_content.sjs
dom/base/test/csp/file_redirect_report.sjs
dom/base/test/csp/file_report_uri_missing_in_report_only_header.html
dom/base/test/csp/file_report_uri_missing_in_report_only_header.html^headers^
dom/base/test/csp/file_scheme_relative_sources.js
dom/base/test/csp/file_scheme_relative_sources.sjs
dom/base/test/csp/file_self_none_as_hostname_confusion.html
dom/base/test/csp/file_self_none_as_hostname_confusion.html^headers^
dom/base/test/csp/file_subframe_run_js_if_allowed.html
dom/base/test/csp/file_subframe_run_js_if_allowed.html^headers^
dom/base/test/csp/file_worker_redirect.html
dom/base/test/csp/file_worker_redirect.sjs
dom/base/test/csp/mochitest.ini
dom/base/test/csp/referrerdirective.sjs
dom/base/test/csp/test_301_redirect.html
dom/base/test/csp/test_302_redirect.html
dom/base/test/csp/test_303_redirect.html
dom/base/test/csp/test_307_redirect.html
dom/base/test/csp/test_CSP.html
dom/base/test/csp/test_CSP_bug663567.html
dom/base/test/csp/test_CSP_bug802872.html
dom/base/test/csp/test_CSP_bug885433.html
dom/base/test/csp/test_CSP_bug888172.html
dom/base/test/csp/test_CSP_bug909029.html
dom/base/test/csp/test_CSP_bug910139.html
dom/base/test/csp/test_CSP_bug941404.html
dom/base/test/csp/test_CSP_evalscript.html
dom/base/test/csp/test_CSP_frameancestors.html
dom/base/test/csp/test_CSP_inlinescript.html
dom/base/test/csp/test_CSP_inlinestyle.html
dom/base/test/csp/test_CSP_referrerdirective.html
dom/base/test/csp/test_base-uri.html
dom/base/test/csp/test_blob_data_schemes.html
dom/base/test/csp/test_bug836922_npolicies.html
dom/base/test/csp/test_bug886164.html
dom/base/test/csp/test_bug949549.html
dom/base/test/csp/test_connect-src.html
dom/base/test/csp/test_csp_allow_https_schemes.html
dom/base/test/csp/test_csp_bug768029.html
dom/base/test/csp/test_csp_bug773891.html
dom/base/test/csp/test_csp_invalid_source_expression.html
dom/base/test/csp/test_csp_path_matching.html
dom/base/test/csp/test_csp_path_matching_redirect.html
dom/base/test/csp/test_csp_redirects.html
dom/base/test/csp/test_csp_report.html
dom/base/test/csp/test_dual_header.html
dom/base/test/csp/test_form-action.html
dom/base/test/csp/test_hash_source.html
dom/base/test/csp/test_ignore_unsafe_inline.html
dom/base/test/csp/test_leading_wildcard.html
dom/base/test/csp/test_multi_policy_injection_bypass.html
dom/base/test/csp/test_nonce_source.html
dom/base/test/csp/test_null_baseuri.html
dom/base/test/csp/test_policyuri_regression_from_multipolicy.html
dom/base/test/csp/test_report_uri_missing_in_report_only_header.html
dom/base/test/csp/test_scheme_relative_sources.html
dom/base/test/csp/test_self_none_as_hostname_confusion.html
dom/base/test/csp/test_subframe_run_js_if_allowed.html
dom/base/test/csp/test_worker_redirect.html
dom/base/test/file_CrossSiteXHR_cache_server.sjs
dom/base/test/file_CrossSiteXHR_inner.html
dom/base/test/file_CrossSiteXHR_inner.jar
dom/base/test/file_CrossSiteXHR_inner_data.sjs
dom/base/test/file_CrossSiteXHR_server.sjs
dom/base/test/mixedcontentblocker/bug803225_test_mailto.html
dom/base/test/mixedcontentblocker/file_mixed_content_frameNavigation.html
dom/base/test/mixedcontentblocker/file_mixed_content_frameNavigation_blankTarget.html
dom/base/test/mixedcontentblocker/file_mixed_content_frameNavigation_grandchild.html
dom/base/test/mixedcontentblocker/file_mixed_content_frameNavigation_innermost.html
dom/base/test/mixedcontentblocker/file_mixed_content_frameNavigation_secure.html
dom/base/test/mixedcontentblocker/file_mixed_content_frameNavigation_secure_grandchild.html
dom/base/test/mixedcontentblocker/file_mixed_content_main.html
dom/base/test/mixedcontentblocker/file_mixed_content_main_bug803225.html
dom/base/test/mixedcontentblocker/file_mixed_content_main_bug803225_websocket_wsh.py
dom/base/test/mixedcontentblocker/file_mixed_content_server.sjs
dom/base/test/mixedcontentblocker/mochitest.ini
dom/base/test/mixedcontentblocker/test_mixed_content_blocker.html
dom/base/test/mixedcontentblocker/test_mixed_content_blocker_bug803225.html
dom/base/test/mixedcontentblocker/test_mixed_content_blocker_frameNavigation.html
dom/base/test/test_CrossSiteXHR.html
dom/base/test/test_CrossSiteXHR_cache.html
dom/base/test/test_CrossSiteXHR_origin.html
dom/base/test/unit/test_cspreports.js
dom/tests/mochitest/chrome/fullscreen_preventdefault.xul
dom/tests/mochitest/chrome/test_fullscreen_preventdefault.xul
mobile/android/chrome/content/browser.js
--- a/b2g/app/b2g.js
+++ b/b2g/app/b2g.js
@@ -347,20 +347,20 @@ pref("image.onload.decode.limit", 24); /
 // we don't really have a better one at the moment.
 // enable touch events interfaces
 pref("dom.w3c_touch_events.enabled", 1);
 pref("dom.w3c_touch_events.safetyX", 0); // escape borders in units of 1/240"
 pref("dom.w3c_touch_events.safetyY", 120); // escape borders in units of 1/240"
 
 #ifdef MOZ_SAFE_BROWSING
 // Safe browsing does nothing unless this pref is set
-pref("browser.safebrowsing.enabled", false);
+pref("browser.safebrowsing.enabled", true);
 
 // Prevent loading of pages identified as malware
-pref("browser.safebrowsing.malware.enabled", false);
+pref("browser.safebrowsing.malware.enabled", true);
 
 pref("browser.safebrowsing.debug", false);
 pref("browser.safebrowsing.updateURL", "https://safebrowsing.google.com/safebrowsing/downloads?client=SAFEBROWSING_ID&appver=%VERSION%&pver=2.2&key=%GOOGLE_API_KEY%");
 pref("browser.safebrowsing.gethashURL", "https://safebrowsing.google.com/safebrowsing/gethash?client=SAFEBROWSING_ID&appver=%VERSION%&pver=2.2");
 pref("browser.safebrowsing.reportURL", "https://safebrowsing.google.com/safebrowsing/report?");
 pref("browser.safebrowsing.reportGenericURL", "http://%LOCALE%.phish-generic.mozilla.com/?hl=%LOCALE%");
 pref("browser.safebrowsing.reportErrorURL", "http://%LOCALE%.phish-error.mozilla.com/?hl=%LOCALE%");
 pref("browser.safebrowsing.reportPhishURL", "http://%LOCALE%.phish-report.mozilla.com/?hl=%LOCALE%");
@@ -400,16 +400,21 @@ pref("urlclassifier.gethash.timeout_ms",
 
 // If an urlclassifier table has not been updated in this number of seconds,
 // a gethash request will be forced to check that the result is still in
 // the database.
 pref("urlclassifier.max-complete-age", 2700);
 
 // URL for checking the reason for a malware warning.
 pref("browser.safebrowsing.malware.reportURL", "https://safebrowsing.google.com/safebrowsing/diagnostic?client=%NAME%&hl=%LOCALE%&site=");
+
+// Tracking protection
+pref("privacy.trackingprotection.enabled", true);
+pref("privacy.trackingprotection.pbmode.enabled", false);
+
 #endif
 
 // True if this is the first time we are showing about:firstrun
 pref("browser.firstrun.show.uidiscovery", true);
 pref("browser.firstrun.show.localepicker", true);
 
 // initiated by a user
 pref("content.ime.strict_policy", true);
--- a/b2g/app/nsBrowserApp.cpp
+++ b/b2g/app/nsBrowserApp.cpp
@@ -29,17 +29,17 @@
 #include "nsWindowsWMain.cpp"
 #if defined(_MSC_VER) && (_MSC_VER < 1900)
 #define snprintf _snprintf
 #endif
 #define strcasecmp _stricmp
 #endif
 
 #ifdef MOZ_WIDGET_GONK
-#include "GonkDisplay.h"
+#include "BootAnimation.h"
 #endif
 
 #include "BinaryPath.h"
 
 #include "nsXPCOMPrivate.h" // for MAXPATHLEN and XPCOM_DLL
 
 #ifdef MOZ_WIDGET_GONK
 # include <binder/ProcessState.h>
@@ -143,18 +143,18 @@ static int do_main(int argc, char* argv[
       return 255;
     }
     argv[2] = argv[0];
     argv += 2;
     argc -= 2;
   }
 
 #ifdef MOZ_WIDGET_GONK
-  /* Called to start the boot animation */
-  (void) mozilla::GetGonkDisplay();
+  /* Start boot animation */
+  mozilla::StartBootAnimation();
 #endif
 
   if (appini) {
     nsXREAppData *appData;
     rv = XRE_CreateAppData(appini, &appData);
     if (NS_FAILED(rv)) {
       Output("Couldn't read application.ini");
       return 255;
--- a/b2g/components/AboutServiceWorkers.jsm
+++ b/b2g/components/AboutServiceWorkers.jsm
@@ -125,17 +125,26 @@ this.AboutServiceWorkers = {
         });
         break;
 
       case "update":
         if (!message.scope) {
           self.sendError(message.id, "MissingScope");
           return;
         }
-        gServiceWorkerManager.softUpdate(message.scope);
+
+        if (!message.principal ||
+            !message.principal.originAttributes) {
+          // XXX This will always error until bug 1171915 is fixed.
+          self.sendError(message.id, "MissingOriginAttributes");
+          return;
+        }
+
+        gServiceWorkerManager.propagateSoftUpdate({},
+                                                  message.scope);
         self.sendResult(message.id, true);
         break;
 
       case "unregister":
         if (!message.principal ||
             !message.principal.origin ||
             !message.principal.appId) {
           self.sendError("MissingPrincipal");
@@ -161,17 +170,17 @@ this.AboutServiceWorkers = {
           unregisterFailed: function() {
             self.sendError(message.id, "UnregisterError");
           },
 
           QueryInterface: XPCOMUtils.generateQI([
             Ci.nsIServiceWorkerUnregisterCallback
           ])
         };
-        gServiceWorkerManager.unregister(principal,
-                                         serviceWorkerUnregisterCallback,
-                                         message.scope);
+        gServiceWorkerManager.propagateUnregister(principal,
+                                                  serviceWorkerUnregisterCallback,
+                                                  message.scope);
         break;
     }
   }
 };
 
 AboutServiceWorkers.init();
--- a/b2g/components/test/unit/test_aboutserviceworkers.js
+++ b/b2g/components/test/unit/test_aboutserviceworkers.js
@@ -123,17 +123,20 @@ function run_test() {
 // registrations are not allowed.
 // All we can do for now is to test the interface of the swm.
 add_test(function test_swm() {
   do_check_true(gServiceWorkerManager, "SWM exists");
   do_check_true(gServiceWorkerManager.getAllRegistrations,
                 "SWM.getAllRegistrations exists");
   do_check_true(typeof gServiceWorkerManager.getAllRegistrations == "function",
                 "SWM.getAllRegistrations is a function");
-  do_check_true(gServiceWorkerManager.softUpdate, "SWM.softUpdate exists");
-  do_check_true(typeof gServiceWorkerManager.softUpdate == "function",
-                "SWM.softUpdate is a function");
-  do_check_true(gServiceWorkerManager.unregister, "SWM.unregister exists");
-  do_check_true(typeof gServiceWorkerManager.unregister == "function",
-                "SWM.unregister exists");
+  do_check_true(gServiceWorkerManager.propagateSoftUpdate,
+                "SWM.propagateSoftUpdate exists");
+  do_check_true(typeof gServiceWorkerManager.propagateSoftUpdate == "function",
+
+                "SWM.propagateSoftUpdate is a function");
+  do_check_true(gServiceWorkerManager.propagateUnregister,
+                "SWM.propagateUnregister exists");
+  do_check_true(typeof gServiceWorkerManager.propagateUnregister == "function",
+                "SWM.propagateUnregister exists");
 
   run_next_test();
 });
--- a/b2g/config/aries/sources.xml
+++ b/b2g/config/aries/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="e862ab9177af664f00b4522e2350f4cb13866d73">
     <copyfile dest="Makefile" src="core/root.mk"/>
   </project>
-  <project name="gaia" path="gaia" remote="mozillaorg" revision="e3eaf72ccd1bfe6d60d37efde6d3b92c1dbc5ff9"/>
+  <project name="gaia" path="gaia" remote="mozillaorg" revision="d2f31eb85837aae6eca04d022d1f5b2023bc778c"/>
   <project name="fake-libdvm" path="dalvik" remote="b2g" revision="d50ae982b19f42f0b66d08b9eb306be81687869f"/>
   <project name="gonk-misc" path="gonk-misc" remote="b2g" revision="3477513bcd385571aa01c0d074849e35bd5e2376"/>
   <project name="librecovery" path="librecovery" remote="b2g" revision="1b3591a50ed352fc6ddb77462b7b35d0bfa555a3"/>
   <project name="moztt" path="external/moztt" remote="b2g" revision="46da1a05ac04157669685246d70ac59d48699c9e"/>
   <project name="rilproxy" path="rilproxy" remote="b2g" revision="5ef30994f4778b4052e58a4383dbe7890048c87e"/>
   <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="70b7fcbf7ff0ef38d04f82d68a56f2bb44ec694a"/>
--- a/b2g/config/dolphin/sources.xml
+++ b/b2g/config/dolphin/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="e862ab9177af664f00b4522e2350f4cb13866d73">
     <copyfile dest="Makefile" src="core/root.mk"/>
   </project>
-  <project name="gaia" path="gaia" remote="mozillaorg" revision="e3eaf72ccd1bfe6d60d37efde6d3b92c1dbc5ff9"/>
+  <project name="gaia" path="gaia" remote="mozillaorg" revision="d2f31eb85837aae6eca04d022d1f5b2023bc778c"/>
   <project name="fake-libdvm" path="dalvik" remote="b2g" revision="d50ae982b19f42f0b66d08b9eb306be81687869f"/>
   <project name="gonk-misc" path="gonk-misc" remote="b2g" revision="3477513bcd385571aa01c0d074849e35bd5e2376"/>
   <project name="librecovery" path="librecovery" remote="b2g" revision="1b3591a50ed352fc6ddb77462b7b35d0bfa555a3"/>
   <project name="moztt" path="external/moztt" remote="b2g" revision="46da1a05ac04157669685246d70ac59d48699c9e"/>
   <project name="rilproxy" path="rilproxy" remote="b2g" revision="5ef30994f4778b4052e58a4383dbe7890048c87e"/>
   <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="70b7fcbf7ff0ef38d04f82d68a56f2bb44ec694a"/>
--- a/b2g/config/emulator-ics/sources.xml
+++ b/b2g/config/emulator-ics/sources.xml
@@ -14,20 +14,20 @@
   <!--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="173b3104bfcbd23fc9dccd4b0035fc49aae3d444">
     <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="e3eaf72ccd1bfe6d60d37efde6d3b92c1dbc5ff9"/>
+  <project name="gaia.git" path="gaia" remote="mozillaorg" revision="d2f31eb85837aae6eca04d022d1f5b2023bc778c"/>
   <project name="gonk-misc" path="gonk-misc" remote="b2g" revision="3477513bcd385571aa01c0d074849e35bd5e2376"/>
   <project name="rilproxy" path="rilproxy" remote="b2g" revision="5ef30994f4778b4052e58a4383dbe7890048c87e"/>
-  <project name="platform_hardware_ril" path="hardware/ril" remote="b2g" revision="aac9cc4bb94cf720baf8f7ee419b4d76ac86b1ac"/>
+  <project name="platform_hardware_ril" path="hardware/ril" remote="b2g" revision="87a2d8ab9248540910e56921654367b78a587095"/>
   <project name="platform_external_qemu" path="external/qemu" remote="b2g" revision="9d0e5057ee5404a31ec1bf76131cb11336a7c3b6"/>
   <project name="moztt" path="external/moztt" remote="b2g" revision="46da1a05ac04157669685246d70ac59d48699c9e"/>
   <project name="apitrace" path="external/apitrace" remote="apitrace" revision="34ea6163f9f0e0122fb0bb03607eccdca31ced7a"/>
   <!-- Stock Android things -->
   <project name="platform/abi/cpp" path="abi/cpp" revision="dd924f92906085b831bf1cbbc7484d3c043d613c"/>
   <project name="platform_bionic" path="bionic" remote="b2g" revision="e2b3733ba3fa5e3f404e983d2e4142b1f6b1b846"/>
   <project name="platform/bootable/recovery" path="bootable/recovery" revision="425f8b5fadf5889834c5acd27d23c9e0b2129c28"/>
   <project name="device/common" path="device/common" revision="42b808b7e93d0619286ae8e59110b176b7732389"/>
--- 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="4efd19d199ae52656604f794c5a77518400220fd">
     <copyfile dest="Makefile" src="core/root.mk"/>
   </project>
   <project name="rilproxy" path="rilproxy" remote="b2g" revision="5ef30994f4778b4052e58a4383dbe7890048c87e"/>
   <project name="fake-libdvm" path="dalvik" remote="b2g" revision="d50ae982b19f42f0b66d08b9eb306be81687869f"/>
-  <project name="gaia" path="gaia" remote="mozillaorg" revision="e3eaf72ccd1bfe6d60d37efde6d3b92c1dbc5ff9"/>
+  <project name="gaia" path="gaia" remote="mozillaorg" revision="d2f31eb85837aae6eca04d022d1f5b2023bc778c"/>
   <project name="gonk-misc" path="gonk-misc" remote="b2g" revision="3477513bcd385571aa01c0d074849e35bd5e2376"/>
   <project name="moztt" path="external/moztt" remote="b2g" revision="46da1a05ac04157669685246d70ac59d48699c9e"/>
   <project name="apitrace" path="external/apitrace" remote="apitrace" revision="70b7fcbf7ff0ef38d04f82d68a56f2bb44ec694a"/>
   <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="e862ab9177af664f00b4522e2350f4cb13866d73">
     <copyfile dest="Makefile" src="core/root.mk"/>
   </project>
-  <project name="gaia" path="gaia" remote="mozillaorg" revision="e3eaf72ccd1bfe6d60d37efde6d3b92c1dbc5ff9"/>
+  <project name="gaia" path="gaia" remote="mozillaorg" revision="d2f31eb85837aae6eca04d022d1f5b2023bc778c"/>
   <project name="fake-libdvm" path="dalvik" remote="b2g" revision="d50ae982b19f42f0b66d08b9eb306be81687869f"/>
   <project name="gonk-misc" path="gonk-misc" remote="b2g" revision="3477513bcd385571aa01c0d074849e35bd5e2376"/>
   <project name="librecovery" path="librecovery" remote="b2g" revision="1b3591a50ed352fc6ddb77462b7b35d0bfa555a3"/>
   <project name="moztt" path="external/moztt" remote="b2g" revision="46da1a05ac04157669685246d70ac59d48699c9e"/>
   <project name="rilproxy" path="rilproxy" remote="b2g" revision="5ef30994f4778b4052e58a4383dbe7890048c87e"/>
   <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="70b7fcbf7ff0ef38d04f82d68a56f2bb44ec694a"/>
@@ -127,14 +127,14 @@
   <project name="platform_system_core" path="system/core" remote="b2g" revision="9395eb5aa885cf6d305a202de6e9694a58a89717"/>
   <default remote="caf" revision="refs/tags/android-4.4.2_r1" sync-j="4"/>
   <!-- Emulator specific things -->
   <project name="device/generic/armv7-a-neon" path="device/generic/armv7-a-neon" revision="72ffdf71c68a96309212eb13d63560d66db14c9e"/>
   <project name="device_generic_goldfish" path="device/generic/goldfish" remote="b2g" revision="f390788a00706c06e5248edfd8d27b365387e84a"/>
   <project name="platform_external_qemu" path="external/qemu" remote="b2g" revision="4bebbe8d92368befc31e8b4a99da2d29cc26bfbc"/>
   <project name="platform/external/libnfc-nci" path="external/libnfc-nci" revision="f37bd545063039e30a92f2550ae78c0e6e4e2d08"/>
   <project name="platform_external_wpa_supplicant_8" path="external/wpa_supplicant_8" remote="b2g" revision="0c6a6547cd1fd302fa2b0f6e375654df36bf0ec4"/>
-  <project name="platform_hardware_ril" path="hardware/ril" remote="b2g" revision="de4bfffbbc2aabe5b5eca485e459da75e49097e2"/>
+  <project name="platform_hardware_ril" path="hardware/ril" remote="b2g" revision="2b62676f02abb7633aac619e0f92c7fd70216860"/>
   <project name="platform_system_nfcd" path="system/nfcd" remote="b2g" revision="d82e00fb6380b4f6cea7a96213913ee9eb441239"/>
   <project name="platform/development" path="development" revision="5968ff4e13e0d696ad8d972281fc27ae5a12829b"/>
   <project name="android-sdk" path="sdk" remote="b2g" revision="0951179277915335251c5e11d242e4e1a8c2236f"/>
   <project name="darwinstreamingserver" path="system/darwinstreamingserver" remote="b2g" revision="cf85968c7f85e0ec36e72c87ceb4837a943b8af6"/>
 </manifest>
--- a/b2g/config/emulator-l/sources.xml
+++ b/b2g/config/emulator-l/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="61e82f99bb8bc78d52b5717e9a2481ec7267fa33">
     <copyfile dest="Makefile" src="core/root.mk"/>
   </project>
-  <project name="gaia" path="gaia" remote="mozillaorg" revision="e3eaf72ccd1bfe6d60d37efde6d3b92c1dbc5ff9"/>
+  <project name="gaia" path="gaia" remote="mozillaorg" revision="d2f31eb85837aae6eca04d022d1f5b2023bc778c"/>
   <project name="fake-libdvm" path="dalvik" remote="b2g" revision="d50ae982b19f42f0b66d08b9eb306be81687869f"/>
   <project name="gonk-misc" path="gonk-misc" remote="b2g" revision="3477513bcd385571aa01c0d074849e35bd5e2376"/>
   <project name="librecovery" path="librecovery" remote="b2g" revision="1b3591a50ed352fc6ddb77462b7b35d0bfa555a3"/>
   <project name="moztt" path="external/moztt" remote="b2g" revision="46da1a05ac04157669685246d70ac59d48699c9e"/>
   <project name="rilproxy" path="rilproxy" remote="b2g" revision="5ef30994f4778b4052e58a4383dbe7890048c87e"/>
   <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="70b7fcbf7ff0ef38d04f82d68a56f2bb44ec694a"/>
--- a/b2g/config/emulator/sources.xml
+++ b/b2g/config/emulator/sources.xml
@@ -14,20 +14,20 @@
   <!--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="173b3104bfcbd23fc9dccd4b0035fc49aae3d444">
     <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="e3eaf72ccd1bfe6d60d37efde6d3b92c1dbc5ff9"/>
+  <project name="gaia.git" path="gaia" remote="mozillaorg" revision="d2f31eb85837aae6eca04d022d1f5b2023bc778c"/>
   <project name="gonk-misc" path="gonk-misc" remote="b2g" revision="3477513bcd385571aa01c0d074849e35bd5e2376"/>
   <project name="rilproxy" path="rilproxy" remote="b2g" revision="5ef30994f4778b4052e58a4383dbe7890048c87e"/>
-  <project name="platform_hardware_ril" path="hardware/ril" remote="b2g" revision="aac9cc4bb94cf720baf8f7ee419b4d76ac86b1ac"/>
+  <project name="platform_hardware_ril" path="hardware/ril" remote="b2g" revision="87a2d8ab9248540910e56921654367b78a587095"/>
   <project name="platform_external_qemu" path="external/qemu" remote="b2g" revision="9d0e5057ee5404a31ec1bf76131cb11336a7c3b6"/>
   <project name="moztt" path="external/moztt" remote="b2g" revision="46da1a05ac04157669685246d70ac59d48699c9e"/>
   <project name="apitrace" path="external/apitrace" remote="apitrace" revision="34ea6163f9f0e0122fb0bb03607eccdca31ced7a"/>
   <!-- Stock Android things -->
   <project name="platform/abi/cpp" path="abi/cpp" revision="dd924f92906085b831bf1cbbc7484d3c043d613c"/>
   <project name="platform_bionic" path="bionic" remote="b2g" revision="e2b3733ba3fa5e3f404e983d2e4142b1f6b1b846"/>
   <project name="platform/bootable/recovery" path="bootable/recovery" revision="425f8b5fadf5889834c5acd27d23c9e0b2129c28"/>
   <project name="device/common" path="device/common" revision="42b808b7e93d0619286ae8e59110b176b7732389"/>
--- a/b2g/config/flame-kk/sources.xml
+++ b/b2g/config/flame-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="e862ab9177af664f00b4522e2350f4cb13866d73">
     <copyfile dest="Makefile" src="core/root.mk"/>
   </project>
-  <project name="gaia" path="gaia" remote="mozillaorg" revision="e3eaf72ccd1bfe6d60d37efde6d3b92c1dbc5ff9"/>
+  <project name="gaia" path="gaia" remote="mozillaorg" revision="d2f31eb85837aae6eca04d022d1f5b2023bc778c"/>
   <project name="fake-libdvm" path="dalvik" remote="b2g" revision="d50ae982b19f42f0b66d08b9eb306be81687869f"/>
   <project name="gonk-misc" path="gonk-misc" remote="b2g" revision="3477513bcd385571aa01c0d074849e35bd5e2376"/>
   <project name="librecovery" path="librecovery" remote="b2g" revision="1b3591a50ed352fc6ddb77462b7b35d0bfa555a3"/>
   <project name="moztt" path="external/moztt" remote="b2g" revision="46da1a05ac04157669685246d70ac59d48699c9e"/>
   <project name="rilproxy" path="rilproxy" remote="b2g" revision="5ef30994f4778b4052e58a4383dbe7890048c87e"/>
   <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="70b7fcbf7ff0ef38d04f82d68a56f2bb44ec694a"/>
--- a/b2g/config/gaia.json
+++ b/b2g/config/gaia.json
@@ -1,9 +1,9 @@
 {
     "git": {
-        "git_revision": "e3eaf72ccd1bfe6d60d37efde6d3b92c1dbc5ff9", 
+        "git_revision": "d2f31eb85837aae6eca04d022d1f5b2023bc778c", 
         "remote": "https://git.mozilla.org/releases/gaia.git", 
         "branch": ""
     }, 
-    "revision": "c33bf7766d1b19c407c3bbab943403ddee172915", 
+    "revision": "2e9a1e5808b983fe4aa50a169b0e36fb3f0b43a3", 
     "repo_path": "integration/gaia-central"
 }
--- a/b2g/config/nexus-4/sources.xml
+++ b/b2g/config/nexus-4/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="4efd19d199ae52656604f794c5a77518400220fd">
     <copyfile dest="Makefile" src="core/root.mk"/>
   </project>
   <project name="rilproxy" path="rilproxy" remote="b2g" revision="5ef30994f4778b4052e58a4383dbe7890048c87e"/>
   <project name="fake-libdvm" path="dalvik" remote="b2g" revision="d50ae982b19f42f0b66d08b9eb306be81687869f"/>
-  <project name="gaia" path="gaia" remote="mozillaorg" revision="e3eaf72ccd1bfe6d60d37efde6d3b92c1dbc5ff9"/>
+  <project name="gaia" path="gaia" remote="mozillaorg" revision="d2f31eb85837aae6eca04d022d1f5b2023bc778c"/>
   <project name="gonk-misc" path="gonk-misc" remote="b2g" revision="3477513bcd385571aa01c0d074849e35bd5e2376"/>
   <project name="moztt" path="external/moztt" remote="b2g" revision="46da1a05ac04157669685246d70ac59d48699c9e"/>
   <project name="apitrace" path="external/apitrace" remote="apitrace" revision="70b7fcbf7ff0ef38d04f82d68a56f2bb44ec694a"/>
   <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/nexus-5-l/sources.xml
+++ b/b2g/config/nexus-5-l/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="61e82f99bb8bc78d52b5717e9a2481ec7267fa33">
     <copyfile dest="Makefile" src="core/root.mk"/>
   </project>
-  <project name="gaia" path="gaia" remote="mozillaorg" revision="e3eaf72ccd1bfe6d60d37efde6d3b92c1dbc5ff9"/>
+  <project name="gaia" path="gaia" remote="mozillaorg" revision="d2f31eb85837aae6eca04d022d1f5b2023bc778c"/>
   <project name="fake-libdvm" path="dalvik" remote="b2g" revision="d50ae982b19f42f0b66d08b9eb306be81687869f"/>
   <project name="gonk-misc" path="gonk-misc" remote="b2g" revision="3477513bcd385571aa01c0d074849e35bd5e2376"/>
   <project name="librecovery" path="librecovery" remote="b2g" revision="1b3591a50ed352fc6ddb77462b7b35d0bfa555a3"/>
   <project name="moztt" path="external/moztt" remote="b2g" revision="46da1a05ac04157669685246d70ac59d48699c9e"/>
   <project name="rilproxy" path="rilproxy" remote="b2g" revision="5ef30994f4778b4052e58a4383dbe7890048c87e"/>
   <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="70b7fcbf7ff0ef38d04f82d68a56f2bb44ec694a"/>
--- a/browser/base/content/aboutNetError.xhtml
+++ b/browser/base/content/aboutNetError.xhtml
@@ -107,16 +107,22 @@
         // Get the hostname and add it to the panel
         document.getElementById('hostname').textContent = document.location.hostname;
 
         // Register click handler for the certificateErrorReportingPanel
         document.getElementById('showCertificateErrorReportingPanel')
                 .addEventListener('click', function togglePanelVisibility() {
           var panel = document.getElementById('certificateErrorReportingPanel');
           toggleDisplay(panel);
+
+          if (panel.style.display == "block") {
+            // send event to trigger telemetry ping
+            var event = new CustomEvent("AboutNetErrorUIExpanded", {bubbles:true});
+            document.dispatchEvent(event);
+          }
         });
       }
 
 
       function sendErrorReport() {
         var event = new CustomEvent("AboutNetErrorSendReport", {bubbles:true});
 
         document.dispatchEvent(event);
--- a/browser/base/content/browser-fullScreen.js
+++ b/browser/base/content/browser-fullScreen.js
@@ -2,24 +2,27 @@
 # 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 FullScreen = {
   _XULNS: "http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul",
 
   _MESSAGES: [
-    "DOMFullscreen:Entered",
+    "DOMFullscreen:Request",
     "DOMFullscreen:NewOrigin",
-    "DOMFullscreen:Exited"
+    "DOMFullscreen:Exited",
   ],
 
   init: function() {
     // called when we go into full screen, even if initiated by a web page script
     window.addEventListener("fullscreen", this, true);
+    window.addEventListener("MozDOMFullscreen:Entered", this,
+                            /* useCapture */ true,
+                            /* wantsUntrusted */ false);
     window.addEventListener("MozDOMFullscreen:Exited", this,
                             /* useCapture */ true,
                             /* wantsUntrusted */ false);
     for (let type of this._MESSAGES) {
       window.messageManager.addMessageListener(type, this);
     }
 
     if (window.fullScreen)
@@ -28,23 +31,19 @@ var FullScreen = {
 
   uninit: function() {
     for (let type of this._MESSAGES) {
       window.messageManager.removeMessageListener(type, this);
     }
     this.cleanup();
   },
 
-  toggle: function (event) {
+  toggle: function () {
     var enterFS = window.fullScreen;
 
-    // We get the fullscreen event _before_ the window transitions into or out of FS mode.
-    if (event && event.type == "fullscreen")
-      enterFS = !enterFS;
-
     // Toggle the View:FullScreen command, which controls elements like the
     // fullscreen menuitem, and menubars.
     let fullscreenCommand = document.getElementById("View:FullScreen");
     if (enterFS) {
       fullscreenCommand.setAttribute("checked", enterFS);
     } else {
       fullscreenCommand.removeAttribute("checked");
     }
@@ -101,41 +100,62 @@ var FullScreen = {
   handleEvent: function (event) {
     switch (event.type) {
       case "activate":
         if (document.mozFullScreen) {
           this.showWarning(this.fullscreenOrigin);
         }
         break;
       case "fullscreen":
-        this.toggle(event);
+        this.toggle();
         break;
       case "transitionend":
         if (event.propertyName == "opacity")
           this.cancelWarning();
         break;
+      case "MozDOMFullscreen:Entered": {
+        // The original target is the element which requested the DOM
+        // fullscreen. If we were entering DOM fullscreen for a remote
+        // browser, this element would be that browser element, which
+        // was the parameter of `remoteFrameFullscreenChanged` call.
+        // If the fullscreen request was initiated from an in-process
+        // browser, we need to get its corresponding browser element.
+        let originalTarget = event.originalTarget;
+        let browser;
+        if (this._isBrowser(originalTarget)) {
+          browser = originalTarget;
+        } else {
+          let topWin = originalTarget.ownerDocument.defaultView.top;
+          browser = gBrowser.getBrowserForContentWindow(topWin);
+          if (!browser) {
+            document.mozCancelFullScreen();
+            break;
+          }
+        }
+        this.enterDomFullscreen(browser);
+        // If it is a remote browser, send a message to ask the content
+        // to enter fullscreen state. We don't need to do so if it is an
+        // in-process browser, since all related document should have
+        // entered fullscreen state at this point.
+        if (this._isRemoteBrowser(browser)) {
+          browser.messageManager.sendAsyncMessage("DOMFullscreen:Entered");
+        }
+        break;
+      }
       case "MozDOMFullscreen:Exited":
         this.cleanupDomFullscreen();
         break;
     }
   },
 
   receiveMessage: function(aMessage) {
     let browser = aMessage.target;
     switch (aMessage.name) {
-      case "DOMFullscreen:Entered": {
-        // If we're a multiprocess browser, then the request to enter
-        // fullscreen did not bubble up to the root browser document -
-        // it stopped at the root of the content document. That means
-        // we have to kick off the switch to fullscreen here at the
-        // operating system level in the parent process ourselves.
-        if (this._isRemoteBrowser(browser)) {
-          this._windowUtils.remoteFrameFullscreenChanged(browser);
-        }
-        this.enterDomFullscreen(browser);
+      case "DOMFullscreen:Request": {
+        this._windowUtils.remoteFrameFullscreenChanged(browser);
         break;
       }
       case "DOMFullscreen:NewOrigin": {
         this.showWarning(aMessage.data.originNoSuffix);
         break;
       }
       case "DOMFullscreen:Exited": {
         // Like entering DOM fullscreen, we also need to exit fullscreen
@@ -187,17 +207,17 @@ var FullScreen = {
 
     // Cancel any "hide the toolbar" animation which is in progress, and make
     // the toolbar hide immediately.
     this.hideNavToolbox(true);
     this._fullScrToggler.hidden = true;
   },
 
   cleanup: function () {
-    if (window.fullScreen) {
+    if (!window.fullScreen) {
       MousePosTracker.removeListener(this);
       document.removeEventListener("keypress", this._keyToggleCallback, false);
       document.removeEventListener("popupshown", this._setPopupOpen, false);
       document.removeEventListener("popuphidden", this._setPopupOpen, false);
     }
   },
 
   cleanupDomFullscreen: function () {
@@ -215,16 +235,23 @@ var FullScreen = {
       this._shouldAnimate = true;
       this.hideNavToolbox();
     }
 
     window.messageManager
           .broadcastAsyncMessage("DOMFullscreen:CleanUp");
   },
 
+  _isBrowser: function (aNode) {
+    if (aNode.tagName != "xul:browser") {
+      return false;
+    }
+    let systemPrincipal = Services.scriptSecurityManager.getSystemPrincipal();
+    return aNode.nodePrincipal == systemPrincipal;
+  },
   _isRemoteBrowser: function (aBrowser) {
     return gMultiProcessBrowser && aBrowser.getAttribute("remote") == "true";
   },
 
   get _windowUtils() {
     return window.QueryInterface(Ci.nsIInterfaceRequestor)
                  .getInterface(Ci.nsIDOMWindowUtils);
   },
--- a/browser/base/content/browser.js
+++ b/browser/base/content/browser.js
@@ -2669,38 +2669,46 @@ let gMenuButtonUpdateBadge = {
   handleEvent: function(e) {
     if (e.type === "popupshowing") {
       PanelUI.menuButton.removeAttribute("badge");
       PanelUI.panel.removeEventListener("popupshowing", this, true);
     }
   }
 };
 
+// Values for telemtery bins: see TLS_ERROR_REPORT_UI in Histograms.json
+const TLS_ERROR_REPORT_TELEMETRY_AUTO_CHECKED   = 2;
+const TLS_ERROR_REPORT_TELEMETRY_AUTO_UNCHECKED = 3;
+const TLS_ERROR_REPORT_TELEMETRY_MANUAL_SEND    = 4;
+const TLS_ERROR_REPORT_TELEMETRY_AUTO_SEND      = 5;
+
 /**
  * Handle command events bubbling up from error page content
  * or from about:newtab or from remote error pages that invoke
  * us via async messaging.
  */
 let BrowserOnClick = {
   init: function () {
     let mm = window.messageManager;
     mm.addMessageListener("Browser:CertExceptionError", this);
     mm.addMessageListener("Browser:SiteBlockedError", this);
     mm.addMessageListener("Browser:EnableOnlineMode", this);
     mm.addMessageListener("Browser:SendSSLErrorReport", this);
     mm.addMessageListener("Browser:SetSSLErrorReportAuto", this);
+    mm.addMessageListener("Browser:SSLErrorReportTelemetry", this);
   },
 
   uninit: function () {
     let mm = window.messageManager;
     mm.removeMessageListener("Browser:CertExceptionError", this);
     mm.removeMessageListener("Browser:SiteBlockedError", this);
     mm.removeMessageListener("Browser:EnableOnlineMode", this);
     mm.removeMessageListener("Browser:SendSSLErrorReport", this);
     mm.removeMessageListener("Browser:SetSSLErrorReportAuto", this);
+    mm.removeMessageListener("Browser:SSLErrorReportTelemetry", this);
   },
 
   handleEvent: function (event) {
     if (!event.isTrusted || // Don't trust synthetic events
         event.button == 2) {
       return;
     }
 
@@ -2737,16 +2745,26 @@ let BrowserOnClick = {
       case "Browser:SendSSLErrorReport":
         this.onSSLErrorReport(msg.target, msg.data.elementId,
                               msg.data.documentURI,
                               msg.data.location,
                               msg.data.securityInfo);
       break;
       case "Browser:SetSSLErrorReportAuto":
         Services.prefs.setBoolPref("security.ssl.errorReporting.automatic", msg.json.automatic);
+        let bin = TLS_ERROR_REPORT_TELEMETRY_AUTO_UNCHECKED;
+        if (msg.json.automatic) {
+          bin = TLS_ERROR_REPORT_TELEMETRY_AUTO_CHECKED;
+        }
+        Services.telemetry.getHistogramById("TLS_ERROR_REPORT_UI").add(bin);
+      break;
+      case "Browser:SSLErrorReportTelemetry":
+        let reportStatus = msg.data.reportStatus;
+        Services.telemetry.getHistogramById("TLS_ERROR_REPORT_UI")
+          .add(reportStatus);
       break;
     }
   },
 
   onSSLErrorReport: function(browser, elementId, documentURI, location, securityInfo) {
     function showReportStatus(reportStatus) {
       gBrowser.selectedBrowser
           .messageManager
@@ -2758,16 +2776,22 @@ let BrowserOnClick = {
     }
 
     if (!Services.prefs.getBoolPref("security.ssl.errorReporting.enabled")) {
       showReportStatus("error");
       Cu.reportError("User requested certificate error report sending, but certificate error reporting is disabled");
       return;
     }
 
+    let bin = TLS_ERROR_REPORT_TELEMETRY_MANUAL_SEND;
+    if (Services.prefs.getBoolPref("security.ssl.errorReporting.automatic")) {
+      bin = TLS_ERROR_REPORT_TELEMETRY_AUTO_SEND;
+    }
+    Services.telemetry.getHistogramById("TLS_ERROR_REPORT_UI").add(bin);
+
     let serhelper = Cc["@mozilla.org/network/serialization-helper;1"]
                            .getService(Ci.nsISerializationHelper);
     let transportSecurityInfo = serhelper.deserializeObject(securityInfo);
     transportSecurityInfo.QueryInterface(Ci.nsITransportSecurityInfo)
 
     showReportStatus("activity");
 
     /*
--- a/browser/base/content/content.js
+++ b/browser/base/content/content.js
@@ -172,21 +172,28 @@ let handleContentContextMenu = function 
     };
   }
 }
 
 Cc["@mozilla.org/eventlistenerservice;1"]
   .getService(Ci.nsIEventListenerService)
   .addSystemEventListener(global, "contextmenu", handleContentContextMenu, false);
 
+// Values for telemtery bins: see TLS_ERROR_REPORT_UI in Histograms.json
+const TLS_ERROR_REPORT_TELEMETRY_UI_SHOWN = 0;
+const TLS_ERROR_REPORT_TELEMETRY_EXPANDED = 1;
+const TLS_ERROR_REPORT_TELEMETRY_SUCCESS  = 6;
+const TLS_ERROR_REPORT_TELEMETRY_FAILURE  = 7;
+
 let AboutNetErrorListener = {
   init: function(chromeGlobal) {
     chromeGlobal.addEventListener('AboutNetErrorLoad', this, false, true);
     chromeGlobal.addEventListener('AboutNetErrorSetAutomatic', this, false, true);
     chromeGlobal.addEventListener('AboutNetErrorSendReport', this, false, true);
+    chromeGlobal.addEventListener('AboutNetErrorUIExpanded', this, false, true);
   },
 
   get isAboutNetError() {
     return content.document.documentURI.startsWith("about:neterror");
   },
 
   handleEvent: function(aEvent) {
     if (!this.isAboutNetError) {
@@ -198,28 +205,36 @@ let AboutNetErrorListener = {
       this.onPageLoad(aEvent);
       break;
     case "AboutNetErrorSetAutomatic":
       this.onSetAutomatic(aEvent);
       break;
     case "AboutNetErrorSendReport":
       this.onSendReport(aEvent);
       break;
+    case "AboutNetErrorUIExpanded":
+      sendAsyncMessage("Browser:SSLErrorReportTelemetry",
+                       {reportStatus: TLS_ERROR_REPORT_TELEMETRY_EXPANDED});
+      break;
     }
   },
 
   onPageLoad: function(evt) {
     let automatic = Services.prefs.getBoolPref("security.ssl.errorReporting.automatic");
     content.dispatchEvent(new content.CustomEvent("AboutNetErrorOptions", {
             detail: JSON.stringify({
               enabled: Services.prefs.getBoolPref("security.ssl.errorReporting.enabled"),
             automatic: automatic
             })
           }
     ));
+
+    sendAsyncMessage("Browser:SSLErrorReportTelemetry",
+                     {reportStatus: TLS_ERROR_REPORT_TELEMETRY_UI_SHOWN});
+
     if (automatic) {
       this.onSendReport(evt);
     }
     // hide parts of the UI we don't need yet
     let contentDoc = content.document;
 
     let reportSendingMsg = contentDoc.getElementById("reportSendingMessage");
     let reportSentMsg = contentDoc.getElementById("reportSentMessage");
@@ -254,21 +269,25 @@ let AboutNetErrorListener = {
           retryBtn.style.display = "none";
           reportSentMsg.style.display = "none";
           reportSendingMsg.style.removeProperty("display");
           break;
         case "error":
           // show the retry button
           retryBtn.style.removeProperty("display");
           reportSendingMsg.style.display = "none";
+          sendAsyncMessage("Browser:SSLErrorReportTelemetry",
+                           {reportStatus: TLS_ERROR_REPORT_TELEMETRY_FAILURE});
           break;
         case "complete":
           // Show a success indicator
           reportSentMsg.style.removeProperty("display");
           reportSendingMsg.style.display = "none";
+          sendAsyncMessage("Browser:SSLErrorReportTelemetry",
+                           {reportStatus: TLS_ERROR_REPORT_TELEMETRY_SUCCESS});
           break;
         }
       }
     });
 
     let failedChannel = docShell.failedChannel;
     let location = contentDoc.location.href;
 
@@ -279,17 +298,17 @@ let AboutNetErrorListener = {
                                 .QueryInterface(Ci.nsITransportSecurityInfo)
                                 .QueryInterface(Ci.nsISerializable);
 
     let serializedSecurityInfo = serhelper.serializeToString(serializable);
 
     sendAsyncMessage("Browser:SendSSLErrorReport", {
         elementId: evt.target.id,
         documentURI: contentDoc.documentURI,
-        location: contentDoc.location,
+        location: {hostname: contentDoc.location.hostname, port: contentDoc.location.port},
         securityInfo: serializedSecurityInfo
       });
   }
 }
 
 AboutNetErrorListener.init(this);
 
 // An event listener for custom "WebChannelMessageToChrome" events on pages
--- a/browser/base/content/sanitize.js
+++ b/browser/base/content/sanitize.js
@@ -568,46 +568,29 @@ Sanitizer.prototype = {
 
         // First create a new window. We do this first so that on non-mac, we don't
         // accidentally close the app by closing all the windows.
         let handler = Cc["@mozilla.org/browser/clh;1"].getService(Ci.nsIBrowserHandler);
         let defaultArgs = handler.defaultArgs;
         let features = "chrome,all,dialog=no," + this.privateStateForNewWindow;
         let newWindow = existingWindow.openDialog("chrome://browser/content/", "_blank",
                                                   features, defaultArgs);
-#ifdef XP_MACOSX
-        function onFullScreen(e) {
-          newWindow.removeEventListener("fullscreen", onFullScreen);
-          let docEl = newWindow.document.documentElement;
-          let sizemode = docEl.getAttribute("sizemode");
-          if (!newWindow.fullScreen && sizemode == "fullscreen") {
-            docEl.setAttribute("sizemode", "normal");
-            e.preventDefault();
-            e.stopPropagation();
-            return false;
-          }
-        }
-        newWindow.addEventListener("fullscreen", onFullScreen);
-#endif
 
         // Window creation and destruction is asynchronous. We need to wait
         // until all existing windows are fully closed, and the new window is
         // fully open, before continuing. Otherwise the rest of the sanitizer
         // could run too early (and miss new cookies being set when a page
         // closes) and/or run too late (and not have a fully-formed window yet
         // in existence). See bug 1088137.
         let newWindowOpened = false;
         function onWindowOpened(subject, topic, data) {
           if (subject != newWindow)
             return;
 
           Services.obs.removeObserver(onWindowOpened, "browser-delayed-startup-finished");
-#ifdef XP_MACOSX
-          newWindow.removeEventListener("fullscreen", onFullScreen);
-#endif
           newWindowOpened = true;
           // If we're the last thing to happen, invoke callback.
           if (numWindowsClosing == 0) {
             TelemetryStopwatch.finish("FX_SANITIZE_OPENWINDOWS");
             aCallback();
           }
         }
 
--- a/browser/base/content/tab-content.js
+++ b/browser/base/content/tab-content.js
@@ -584,47 +584,61 @@ if (Services.appinfo.processType == Serv
   tabchild.webBrowserChrome = WebBrowserChrome;
 }
 
 
 let DOMFullscreenHandler = {
   _fullscreenDoc: null,
 
   init: function() {
+    addMessageListener("DOMFullscreen:Entered", this);
     addMessageListener("DOMFullscreen:Approved", this);
     addMessageListener("DOMFullscreen:CleanUp", this);
-    addEventListener("MozDOMFullscreen:Entered", this);
+    addEventListener("MozDOMFullscreen:Request", this);
     addEventListener("MozDOMFullscreen:NewOrigin", this);
     addEventListener("MozDOMFullscreen:Exited", this);
   },
 
+  get _windowUtils() {
+    return content.QueryInterface(Ci.nsIInterfaceRequestor)
+                  .getInterface(Ci.nsIDOMWindowUtils);
+  },
+
   receiveMessage: function(aMessage) {
     switch(aMessage.name) {
+      case "DOMFullscreen:Entered": {
+        if (!this._windowUtils.handleFullscreenRequests() &&
+            !content.document.mozFullScreen) {
+          // If we don't actually have any pending fullscreen request
+          // to handle, neither we have been in fullscreen, tell the
+          // parent to just exit.
+          sendAsyncMessage("DOMFullscreen:Exited");
+        }
+        break;
+      }
       case "DOMFullscreen:Approved": {
         if (this._fullscreenDoc) {
           Services.obs.notifyObservers(this._fullscreenDoc,
                                        "fullscreen-approved",
                                        "");
         }
         break;
       }
       case "DOMFullscreen:CleanUp": {
-        let utils = content.QueryInterface(Ci.nsIInterfaceRequestor)
-                           .getInterface(Ci.nsIDOMWindowUtils);
-        utils.exitFullscreen();
+        this._windowUtils.exitFullscreen();
         this._fullscreenDoc = null;
         break;
       }
     }
   },
 
   handleEvent: function(aEvent) {
     switch (aEvent.type) {
-      case "MozDOMFullscreen:Entered": {
-        sendAsyncMessage("DOMFullscreen:Entered");
+      case "MozDOMFullscreen:Request": {
+        sendAsyncMessage("DOMFullscreen:Request");
         break;
       }
       case "MozDOMFullscreen:NewOrigin": {
         this._fullscreenDoc = aEvent.target;
         sendAsyncMessage("DOMFullscreen:NewOrigin", {
           originNoSuffix: this._fullscreenDoc.nodePrincipal.originNoSuffix,
         });
         break;
--- a/caps/BasePrincipal.cpp
+++ b/caps/BasePrincipal.cpp
@@ -12,54 +12,119 @@
 
 #include "nsPrincipal.h"
 #include "nsNetUtil.h"
 #include "nsNullPrincipal.h"
 #include "nsScriptSecurityManager.h"
 
 #include "mozilla/dom/CSPDictionariesBinding.h"
 #include "mozilla/dom/ToJSValue.h"
+#include "mozilla/dom/URLSearchParams.h"
 
 namespace mozilla {
 
+using dom::URLSearchParams;
+
 void
 OriginAttributes::CreateSuffix(nsACString& aStr) const
 {
-  aStr.Truncate();
   MOZ_RELEASE_ASSERT(mAppId != nsIScriptSecurityManager::UNKNOWN_APP_ID);
-  int attrCount = 0;
+
+  nsRefPtr<URLSearchParams> usp = new URLSearchParams();
+  nsAutoString value;
 
   if (mAppId != nsIScriptSecurityManager::NO_APP_ID) {
-    aStr.Append(attrCount++ ? "&appId=" : "!appId=");
-    aStr.AppendInt(mAppId);
+    value.AppendInt(mAppId);
+    usp->Set(NS_LITERAL_STRING("appId"), value);
   }
 
   if (mInBrowser) {
-    aStr.Append(attrCount++ ? "&inBrowser=1" : "!inBrowser=1");
+    usp->Set(NS_LITERAL_STRING("inBrowser"), NS_LITERAL_STRING("1"));
+  }
+
+  aStr.Truncate();
+
+  usp->Serialize(value);
+  if (!value.IsEmpty()) {
+    aStr.AppendLiteral("!");
+    aStr.Append(NS_ConvertUTF16toUTF8(value));
   }
 }
 
-void
-OriginAttributes::Serialize(nsIObjectOutputStream* aStream) const
+namespace {
+
+class MOZ_STACK_CLASS PopulateFromSuffixIterator final
+  : public URLSearchParams::ForEachIterator
 {
-  aStream->Write32(mAppId);
-  aStream->WriteBoolean(mInBrowser);
+public:
+  explicit PopulateFromSuffixIterator(OriginAttributes* aOriginAttributes)
+    : mOriginAttributes(aOriginAttributes)
+  {
+    MOZ_ASSERT(aOriginAttributes);
+  }
+
+  bool URLSearchParamsIterator(const nsString& aName,
+                               const nsString& aValue) override
+  {
+    if (aName.EqualsLiteral("appId")) {
+      nsresult rv;
+      mOriginAttributes->mAppId = aValue.ToInteger(&rv);
+      if (NS_WARN_IF(NS_FAILED(rv))) {
+        return false;
+      }
+
+      if (mOriginAttributes->mAppId == nsIScriptSecurityManager::UNKNOWN_APP_ID) {
+        return false;
+      }
+
+      return true;
+    }
+
+    if (aName.EqualsLiteral("inBrowser")) {
+      if (!aValue.EqualsLiteral("1")) {
+        return false;
+      }
+
+      mOriginAttributes->mInBrowser = true;
+      return true;
+    }
+
+    // No other attributes are supported.
+    return false;
+  }
+
+private:
+  OriginAttributes* mOriginAttributes;
+};
+
+} // anonymous namespace
+
+bool
+OriginAttributes::PopulateFromSuffix(const nsACString& aStr)
+{
+  if (aStr.IsEmpty()) {
+    return true;
+  }
+
+  if (aStr[0] != '!') {
+    return false;
+  }
+
+  nsRefPtr<URLSearchParams> usp = new URLSearchParams();
+  usp->ParseInput(Substring(aStr, 1, aStr.Length() - 1), nullptr);
+
+  PopulateFromSuffixIterator iterator(this);
+  return usp->ForEach(iterator);
 }
 
-nsresult
-OriginAttributes::Deserialize(nsIObjectInputStream* aStream)
-{
-  nsresult rv = aStream->Read32(&mAppId);
-  NS_ENSURE_SUCCESS(rv, rv);
+BasePrincipal::BasePrincipal()
+{}
 
-  rv = aStream->ReadBoolean(&mInBrowser);
-  NS_ENSURE_SUCCESS(rv, rv);
-
-  return NS_OK;
-}
+BasePrincipal::~BasePrincipal()
+{}
 
 NS_IMETHODIMP
 BasePrincipal::GetOrigin(nsACString& aOrigin)
 {
   nsresult rv = GetOriginInternal(aOrigin);
   NS_ENSURE_SUCCESS(rv, rv);
   nsAutoCString suffix;
   mOriginAttributes.CreateSuffix(suffix);
--- a/caps/BasePrincipal.h
+++ b/caps/BasePrincipal.h
@@ -8,16 +8,17 @@
 #define mozilla_BasePrincipal_h
 
 #include "nsIPrincipal.h"
 #include "nsIScriptSecurityManager.h"
 #include "nsJSPrincipals.h"
 
 #include "mozilla/dom/SystemDictionariesBinding.h"
 
+class nsIContentSecurityPolicy;
 class nsIObjectOutputStream;
 class nsIObjectInputStream;
 
 namespace mozilla {
 
 class OriginAttributes : public dom::OriginAttributesDictionary
 {
 public:
@@ -33,36 +34,34 @@ public:
     return mAppId == aOther.mAppId &&
            mInBrowser == aOther.mInBrowser;
   }
   bool operator!=(const OriginAttributes& aOther) const
   {
     return !(*this == aOther);
   }
 
-  // Serializes non-default values into the suffix format, i.e.
+  // Serializes/Deserializes non-default values into the suffix format, i.e.
   // |!key1=value1&key2=value2|. If there are no non-default attributes, this
   // returns an empty string.
   void CreateSuffix(nsACString& aStr) const;
-
-  void Serialize(nsIObjectOutputStream* aStream) const;
-  nsresult Deserialize(nsIObjectInputStream* aStream);
+  bool PopulateFromSuffix(const nsACString& aStr);
 };
 
 /*
  * Base class from which all nsIPrincipal implementations inherit. Use this for
  * default implementations and other commonalities between principal
  * implementations.
  *
  * We should merge nsJSPrincipals into this class at some point.
  */
 class BasePrincipal : public nsJSPrincipals
 {
 public:
-  BasePrincipal() {}
+  BasePrincipal();
 
   enum DocumentDomainConsideration { DontConsiderDocumentDomain, ConsiderDocumentDomain};
   bool Subsumes(nsIPrincipal* aOther, DocumentDomainConsideration aConsideration);
 
   NS_IMETHOD GetOrigin(nsACString& aOrigin) final;
   NS_IMETHOD GetOriginNoSuffix(nsACString& aOrigin) final;
   NS_IMETHOD Equals(nsIPrincipal* other, bool* _retval) final;
   NS_IMETHOD EqualsConsideringDomain(nsIPrincipal* other, bool* _retval) final;
@@ -88,17 +87,17 @@ public:
   static BasePrincipal* Cast(nsIPrincipal* aPrin) { return static_cast<BasePrincipal*>(aPrin); }
   static already_AddRefed<BasePrincipal> CreateCodebasePrincipal(nsIURI* aURI, OriginAttributes& aAttrs);
 
   const OriginAttributes& OriginAttributesRef() { return mOriginAttributes; }
   uint32_t AppId() const { return mOriginAttributes.mAppId; }
   bool IsInBrowserElement() const { return mOriginAttributes.mInBrowser; }
 
 protected:
-  virtual ~BasePrincipal() {}
+  virtual ~BasePrincipal();
 
   virtual nsresult GetOriginInternal(nsACString& aOrigin) = 0;
   virtual bool SubsumesInternal(nsIPrincipal* aOther, DocumentDomainConsideration aConsider) = 0;
 
   nsCOMPtr<nsIContentSecurityPolicy> mCSP;
   OriginAttributes mOriginAttributes;
 };
 
--- a/caps/nsNullPrincipal.cpp
+++ b/caps/nsNullPrincipal.cpp
@@ -77,17 +77,17 @@ nsNullPrincipal::GetScriptLocation(nsACS
 
 NS_IMETHODIMP
 nsNullPrincipal::GetHashValue(uint32_t *aResult)
 {
   *aResult = (NS_PTR_TO_INT32(this) >> 2);
   return NS_OK;
 }
 
-NS_IMETHODIMP 
+NS_IMETHODIMP
 nsNullPrincipal::GetURI(nsIURI** aURI)
 {
   return NS_EnsureSafeToReturn(mURI, aURI);
 }
 
 NS_IMETHODIMP
 nsNullPrincipal::GetDomain(nsIURI** aDomain)
 {
@@ -155,18 +155,30 @@ nsNullPrincipal::GetBaseDomain(nsACStrin
  */
 NS_IMETHODIMP
 nsNullPrincipal::Read(nsIObjectInputStream* aStream)
 {
   // Note - nsNullPrincipal use NS_GENERIC_FACTORY_CONSTRUCTOR_INIT, which means
   // that the Init() method has already been invoked by the time we deserialize.
   // This is in contrast to nsPrincipal, which uses NS_GENERIC_FACTORY_CONSTRUCTOR,
   // in which case ::Read needs to invoke Init().
-  return mOriginAttributes.Deserialize(aStream);
+  nsAutoCString suffix;
+  nsresult rv = aStream->ReadCString(suffix);
+  NS_ENSURE_SUCCESS(rv, rv);
+
+  bool ok = mOriginAttributes.PopulateFromSuffix(suffix);
+  NS_ENSURE_TRUE(ok, NS_ERROR_FAILURE);
+
+  return NS_OK;
 }
 
 NS_IMETHODIMP
 nsNullPrincipal::Write(nsIObjectOutputStream* aStream)
 {
-  OriginAttributesRef().Serialize(aStream);
+  nsAutoCString suffix;
+  OriginAttributesRef().CreateSuffix(suffix);
+
+  nsresult rv = aStream->WriteStringZ(suffix.get());
+  NS_ENSURE_SUCCESS(rv, rv);
+
   return NS_OK;
 }
 
--- a/caps/nsNullPrincipal.h
+++ b/caps/nsNullPrincipal.h
@@ -18,18 +18,18 @@
 #include "nsCOMPtr.h"
 #include "nsIContentSecurityPolicy.h"
 
 #include "mozilla/BasePrincipal.h"
 
 class nsIURI;
 
 #define NS_NULLPRINCIPAL_CID \
-{ 0xa0bd8b42, 0xf6bf, 0x4fb9, \
-  { 0x93, 0x42, 0x90, 0xbf, 0xc9, 0xb7, 0xa1, 0xab } }
+{ 0xe502ffb8, 0x5d95, 0x48e8, \
+  { 0x82, 0x3c, 0x0d, 0x29, 0xd8, 0x3a, 0x59, 0x33 } }
 #define NS_NULLPRINCIPAL_CONTRACTID "@mozilla.org/nullprincipal;1"
 
 #define NS_NULLPRINCIPAL_SCHEME "moz-nullprincipal"
 
 class nsNullPrincipal final : public mozilla::BasePrincipal
 {
 public:
   // This should only be used by deserialization, and the factory constructor.
--- a/caps/nsPrincipal.cpp
+++ b/caps/nsPrincipal.cpp
@@ -355,19 +355,23 @@ nsPrincipal::Read(nsIObjectInputStream* 
   nsCOMPtr<nsIURI> domain;
   rv = NS_ReadOptionalObject(aStream, true, getter_AddRefs(supports));
   if (NS_FAILED(rv)) {
     return rv;
   }
 
   domain = do_QueryInterface(supports);
 
+  nsAutoCString suffix;
+  rv = aStream->ReadCString(suffix);
+  NS_ENSURE_SUCCESS(rv, rv);
+
   OriginAttributes attrs;
-  rv = attrs.Deserialize(aStream);
-  NS_ENSURE_SUCCESS(rv, rv);
+  bool ok = attrs.PopulateFromSuffix(suffix);
+  NS_ENSURE_TRUE(ok, NS_ERROR_FAILURE);
 
   rv = NS_ReadOptionalObject(aStream, true, getter_AddRefs(supports));
   NS_ENSURE_SUCCESS(rv, rv);
 
   // This may be null.
   nsCOMPtr<nsIContentSecurityPolicy> csp = do_QueryInterface(supports, &rv);
 
   rv = Init(codebase, attrs);
@@ -399,17 +403,21 @@ nsPrincipal::Write(nsIObjectOutputStream
   }
 
   rv = NS_WriteOptionalCompoundObject(aStream, mDomain, NS_GET_IID(nsIURI),
                                       true);
   if (NS_FAILED(rv)) {
     return rv;
   }
 
-  OriginAttributesRef().Serialize(aStream);
+  nsAutoCString suffix;
+  OriginAttributesRef().CreateSuffix(suffix);
+
+  rv = aStream->WriteStringZ(suffix.get());
+  NS_ENSURE_SUCCESS(rv, rv);
 
   rv = NS_WriteOptionalCompoundObject(aStream, mCSP,
                                       NS_GET_IID(nsIContentSecurityPolicy),
                                       true);
   if (NS_FAILED(rv)) {
     return rv;
   }
 
--- a/caps/nsPrincipal.h
+++ b/caps/nsPrincipal.h
@@ -107,17 +107,17 @@ protected:
   bool SubsumesInternal(nsIPrincipal* aOther, DocumentDomainConsideration aConsideration) override;
 
 private:
   nsTArray< nsCOMPtr<nsIPrincipal> > mPrincipals;
 };
 
 #define NS_PRINCIPAL_CONTRACTID "@mozilla.org/principal;1"
 #define NS_PRINCIPAL_CID \
-  { 0x09b7e598, 0x490d, 0x423f, \
-    { 0xa8, 0xa6, 0x2e, 0x6c, 0x4e, 0xc8, 0x77, 0x50 }}
+  { 0xb7c8505e, 0xc56d, 0x4191, \
+    { 0xa1, 0x5e, 0x5d, 0xcb, 0x88, 0x9b, 0xa0, 0x94 }}
 
 #define NS_EXPANDEDPRINCIPAL_CONTRACTID "@mozilla.org/expandedprincipal;1"
 #define NS_EXPANDEDPRINCIPAL_CID \
-  { 0xb33a3807, 0xb76c, 0x44e5, \
-    { 0xb9, 0x9d, 0x95, 0x7e, 0xe9, 0xba, 0x6e, 0x39 }}
+  { 0x38539471, 0x68cc, 0x4a6f, \
+    { 0x81, 0x20, 0xdb, 0xd5, 0x4a, 0x22, 0x0a, 0x13 }}
 
 #endif // nsPrincipal_h__
--- a/docshell/base/nsAboutRedirector.cpp
+++ b/docshell/base/nsAboutRedirector.cpp
@@ -100,16 +100,17 @@ static RedirEntry kRedirMap[] = {
     nsIAboutModule::ALLOW_SCRIPT
   },
   {
     "webrtc", "chrome://global/content/aboutwebrtc/aboutWebrtc.xhtml",
     nsIAboutModule::ALLOW_SCRIPT
   },
   {
     "serviceworkers", "chrome://global/content/aboutServiceWorkers.xhtml",
+    nsIAboutModule::URI_CAN_LOAD_IN_CHILD |
     nsIAboutModule::ALLOW_SCRIPT
   },
   // about:srcdoc is unresolvable by specification.  It is included here
   // because the security manager would disallow srcdoc iframes otherwise.
   {
     "srcdoc", "about:blank",
     nsIAboutModule::URI_SAFE_FOR_UNTRUSTED_CONTENT |
       nsIAboutModule::HIDE_FROM_ABOUTABOUT
--- a/dom/base/Element.cpp
+++ b/dom/base/Element.cpp
@@ -3146,18 +3146,19 @@ Element::MozRequestFullScreen(JSContext*
                                NS_LITERAL_STRING("mozfullscreenerror"),
                                true,
                                false);
     asyncDispatcher->PostDOMEvent();
     return;
   }
 
   FullScreenOptions opts;
+  opts.mIsCallerChrome = nsContentUtils::IsCallerChrome();
+
   RequestFullscreenOptions fsOptions;
-
   // We need to check if options is convertible to a dict first before
   // trying to init fsOptions; otherwise Init() would throw, and we want to
   // silently ignore non-dictionary values
   if (aCx && IsConvertibleToDictionary(aCx, aOptions)) {
     if (!fsOptions.Init(aCx, aOptions)) {
       aError.Throw(NS_ERROR_FAILURE);
       return;
     }
--- a/dom/base/URLSearchParams.h
+++ b/dom/base/URLSearchParams.h
@@ -22,16 +22,20 @@ class URLSearchParams;
 class URLSearchParamsObserver : public nsISupports
 {
 public:
   virtual ~URLSearchParamsObserver() {}
 
   virtual void URLSearchParamsUpdated(URLSearchParams* aFromThis) = 0;
 };
 
+// This class is used in BasePrincipal and it's _extremely_ important that the
+// attributes are kept in the correct order. If this changes, please, update
+// BasePrincipal code.
+
 class URLSearchParams final : public nsISupports,
                               public nsWrapperCache
 {
   ~URLSearchParams();
 
 public:
   NS_DECL_CYCLE_COLLECTING_ISUPPORTS
   NS_DECL_CYCLE_COLLECTION_SCRIPT_HOLDER_CLASS(URLSearchParams)
@@ -76,25 +80,34 @@ public:
 
   void Delete(const nsAString& aName);
 
   void Stringify(nsString& aRetval) const
   {
     Serialize(aRetval);
   }
 
-  typedef void (*ParamFunc)(const nsString& aName, const nsString& aValue,
-                            void* aClosure);
+  class ForEachIterator
+  {
+  public:
+    virtual bool
+    URLSearchParamsIterator(const nsString& aName, const nsString& aValue) = 0;
+  };
 
-  void
-  ForEach(ParamFunc aFunc, void* aClosure)
+  bool
+  ForEach(ForEachIterator& aIterator)
   {
     for (uint32_t i = 0; i < mSearchParams.Length(); ++i) {
-      aFunc(mSearchParams[i].mKey, mSearchParams[i].mValue, aClosure);
+      if (!aIterator.URLSearchParamsIterator(mSearchParams[i].mKey,
+                                             mSearchParams[i].mValue)) {
+        return false;
+      }
     }
+
+    return true;
   }
 
 private:
   void AppendInternal(const nsAString& aName, const nsAString& aValue);
 
   void DeleteAll();
 
   void DecodeString(const nsACString& aInput, nsAString& aOutput);
--- a/dom/base/nsContentUtils.cpp
+++ b/dom/base/nsContentUtils.cpp
@@ -7782,21 +7782,8 @@ nsContentUtils::FirePageShowEvent(nsIDoc
   }
 
   nsCOMPtr<nsIDocument> doc = aItem->GetDocument();
   NS_ASSERTION(doc, "What happened here?");
   if (doc->IsShowing() == aFireIfShowing) {
     doc->OnPageShow(true, aChromeEventHandler);
   }
 }
-
-/* static */
-already_AddRefed<nsPIWindowRoot>
-nsContentUtils::GetWindowRoot(nsIDocument* aDoc)
-{
-  if (aDoc) {
-    nsPIDOMWindow* win = aDoc->GetWindow();
-    if (win) {
-      return win->GetTopWindowRoot();
-    }
-  }
-  return nullptr;
-}
--- a/dom/base/nsContentUtils.h
+++ b/dom/base/nsContentUtils.h
@@ -94,17 +94,16 @@ class nsPresContext;
 class nsStringBuffer;
 class nsStringHashKey;
 class nsTextFragment;
 class nsView;
 class nsViewportInfo;
 class nsWrapperCache;
 class nsAttrValue;
 class nsITransferable;
-class nsPIWindowRoot;
 
 struct JSPropertyDescriptor;
 struct JSRuntime;
 struct nsIntMargin;
 
 template<class E> class nsCOMArray;
 template<class K, class V> class nsDataHashtable;
 template<class K, class V> class nsRefPtrHashtable;
@@ -2359,18 +2358,16 @@ public:
 
   static void FirePageShowEvent(nsIDocShellTreeItem* aItem,
                                 mozilla::dom::EventTarget* aChromeEventHandler,
                                 bool aFireIfShowing);
 
   static void FirePageHideEvent(nsIDocShellTreeItem* aItem,
                                 mozilla::dom::EventTarget* aChromeEventHandler);
 
-  static already_AddRefed<nsPIWindowRoot> GetWindowRoot(nsIDocument* aDoc);
-
 private:
   static bool InitializeEventTable();
 
   static nsresult EnsureStringBundle(PropertiesFile aFile);
 
   static bool CanCallerAccess(nsIPrincipal* aSubjectPrincipal,
                                 nsIPrincipal* aPrincipal);
 
--- a/dom/base/nsDOMWindowUtils.cpp
+++ b/dom/base/nsDOMWindowUtils.cpp
@@ -3122,16 +3122,28 @@ nsDOMWindowUtils::RemoteFrameFullscreenR
 
   nsCOMPtr<nsIDocument> doc = GetDocument();
   NS_ENSURE_STATE(doc);
 
   doc->RemoteFrameFullscreenReverted();
   return NS_OK;
 }
 
+NS_IMETHODIMP
+nsDOMWindowUtils::HandleFullscreenRequests(bool* aRetVal)
+{
+  MOZ_RELEASE_ASSERT(nsContentUtils::IsCallerChrome());
+
+  nsCOMPtr<nsIDocument> doc = GetDocument();
+  NS_ENSURE_STATE(doc);
+
+  *aRetVal = nsIDocument::HandlePendingFullscreenRequests(doc);
+  return NS_OK;
+}
+
 nsresult
 nsDOMWindowUtils::ExitFullscreen()
 {
   MOZ_RELEASE_ASSERT(nsContentUtils::IsCallerChrome());
 
   nsIDocument::ExitFullscreen(nullptr, /* async */ false);
   return NS_OK;
 }
--- a/dom/base/nsDocument.cpp
+++ b/dom/base/nsDocument.cpp
@@ -11,16 +11,18 @@
 #include "nsDocument.h"
 
 #include "mozilla/ArrayUtils.h"
 #include "mozilla/AutoRestore.h"
 #include "mozilla/BinarySearch.h"
 #include "mozilla/DebugOnly.h"
 #include "mozilla/MemoryReporting.h"
 #include "mozilla/Likely.h"
+#include "mozilla/LinkedList.h"
+#include "mozilla/UniquePtr.h"
 #include <algorithm>
 
 #include "mozilla/Logging.h"
 #include "plstr.h"
 #include "prprf.h"
 
 #include "mozilla/Telemetry.h"
 #include "nsIInterfaceRequestor.h"
@@ -10880,29 +10882,29 @@ nsIDocument::ChildElementCount()
 namespace mozilla {
 
 // Singleton class to manage the list of fullscreen documents which are the
 // root of a branch which contains fullscreen documents. We maintain this list
 // so that we can easily exit all windows from fullscreen when the user
 // presses the escape key.
 class FullscreenRoots {
 public:
-  // Adds a root to the manager. Adding a root multiple times does not result
-  // in duplicate entries for that item, only one.
-  static void Add(nsIDocument* aRoot);
+  // Adds the root of given document to the manager. Calling this method
+  // with a document whose root is already contained has no effect.
+  static void Add(nsIDocument* aDoc);
 
   // Iterates over every root in the root list, and calls aFunction, passing
   // each root once to aFunction. It is safe to call Add() and Remove() while
   // iterating over the list (i.e. in aFunction). Documents that are removed
   // from the manager during traversal are not traversed, and documents that
   // are added to the manager during traversal are also not traversed.
   static void ForEach(void(*aFunction)(nsIDocument* aDoc));
 
-  // Removes a specific root from the manager.
-  static void Remove(nsIDocument* aRoot);
+  // Removes the root of a specific document from the manager.
+  static void Remove(nsIDocument* aDoc);
 
   // Returns true if all roots added to the list have been removed.
   static bool IsEmpty();
 
 private:
 
   FullscreenRoots() {
     MOZ_COUNT_CTOR(FullscreenRoots);
@@ -10955,23 +10957,24 @@ FullscreenRoots::ForEach(void(*aFunction
 bool
 FullscreenRoots::Contains(nsIDocument* aRoot)
 {
   return FullscreenRoots::Find(aRoot) != NotFound;
 }
 
 /* static */
 void
-FullscreenRoots::Add(nsIDocument* aRoot)
-{
-  if (!FullscreenRoots::Contains(aRoot)) {
+FullscreenRoots::Add(nsIDocument* aDoc)
+{
+  nsCOMPtr<nsIDocument> root = nsContentUtils::GetRootDocument(aDoc);
+  if (!FullscreenRoots::Contains(root)) {
     if (!sInstance) {
       sInstance = new FullscreenRoots();
     }
-    sInstance->mRoots.AppendElement(do_GetWeakReference(aRoot));
+    sInstance->mRoots.AppendElement(do_GetWeakReference(root));
   }
 }
 
 /* static */
 uint32_t
 FullscreenRoots::Find(nsIDocument* aRoot)
 {
   if (!sInstance) {
@@ -10984,19 +10987,20 @@ FullscreenRoots::Find(nsIDocument* aRoot
       return i;
     }
   }
   return NotFound;
 }
 
 /* static */
 void
-FullscreenRoots::Remove(nsIDocument* aRoot)
-{
-  uint32_t index = Find(aRoot);
+FullscreenRoots::Remove(nsIDocument* aDoc)
+{
+  nsCOMPtr<nsIDocument> root = nsContentUtils::GetRootDocument(aDoc);
+  uint32_t index = Find(root);
   NS_ASSERTION(index != NotFound,
     "Should only try to remove roots which are still added!");
   if (index == NotFound || !sInstance) {
     return;
   }
   sInstance->mRoots.RemoveElementAt(index);
   if (sInstance->mRoots.IsEmpty()) {
     delete sInstance;
@@ -11062,23 +11066,16 @@ private:
   nsCOMPtr<nsIDocument> mDoc;
   bool mValue;
   nsRefPtr<gfx::VRHMDInfo> mHMD;
 };
 
 static void
 SetWindowFullScreen(nsIDocument* aDoc, bool aValue, gfx::VRHMDInfo *aVRHMD = nullptr)
 {
-  // Maintain list of fullscreen root documents.
-  nsCOMPtr<nsIDocument> root = nsContentUtils::GetRootDocument(aDoc);
-  if (aValue) {
-    FullscreenRoots::Add(root);
-  } else {
-    FullscreenRoots::Remove(root);
-  }
   nsContentUtils::AddScriptRunner(new nsSetWindowFullScreen(aDoc, aValue, aVRHMD));
 }
 
 class nsCallExitFullscreen : public nsRunnable {
 public:
   explicit nsCallExitFullscreen(nsIDocument* aDoc)
     : mDoc(aDoc) {}
   NS_IMETHOD Run()
@@ -11184,16 +11181,17 @@ ExitFullscreenInDocTree(nsIDocument* aMa
   // the list since we want this event to follow the same path
   // MozDOMFullscreen:Entered dispatched.
   nsRefPtr<AsyncEventDispatcher> asyncDispatcher =
     new AsyncEventDispatcher(changed.LastElement(),
                              NS_LITERAL_STRING("MozDOMFullscreen:Exited"),
                              true, true);
   asyncDispatcher->PostDOMEvent();
   // Move the top-level window out of fullscreen mode.
+  FullscreenRoots::Remove(root);
   SetWindowFullScreen(root, false);
 }
 
 /* static */
 void
 nsDocument::ExitFullscreen(nsIDocument* aDoc)
 {
   // Unlock the pointer
@@ -11303,16 +11301,17 @@ nsDocument::RestorePreviousFullScreenSta
   if (doc == nullptr) {
     // We moved all documents in this doctree out of fullscreen mode,
     // move the top-level window out of fullscreen mode.
     NS_ASSERTION(!nsContentUtils::GetRootDocument(this)->IsFullScreenDoc(),
                  "Should have cleared all docs' stacks");
     nsRefPtr<AsyncEventDispatcher> asyncDispatcher = new AsyncEventDispatcher(
       this, NS_LITERAL_STRING("MozDOMFullscreen:Exited"), true, true);
     asyncDispatcher->PostDOMEvent();
+    FullscreenRoots::Remove(this);
     SetWindowFullScreen(this, false);
   }
 }
 
 bool
 nsDocument::IsFullScreenDoc()
 {
   return GetFullScreenElement() != nullptr;
@@ -11320,45 +11319,41 @@ nsDocument::IsFullScreenDoc()
 
 FullScreenOptions::FullScreenOptions()
 {
 }
 
 class nsCallRequestFullScreen : public nsRunnable
 {
 public:
-  explicit nsCallRequestFullScreen(Element* aElement, FullScreenOptions& aOptions)
+  explicit nsCallRequestFullScreen(Element* aElement,
+                                   const FullScreenOptions& aOptions)
     : mElement(aElement),
       mDoc(aElement->OwnerDoc()),
-      mWasCallerChrome(nsContentUtils::IsCallerChrome()),
+      mOptions(aOptions),
       mHadRequestPending(static_cast<nsDocument*>(mDoc.get())->
-                         mAsyncFullscreenPending),
-      mOptions(aOptions)
+                         mAsyncFullscreenPending)
   {
     static_cast<nsDocument*>(mDoc.get())->
       mAsyncFullscreenPending = true;
   }
 
   NS_IMETHOD Run()
   {
     static_cast<nsDocument*>(mDoc.get())->
       mAsyncFullscreenPending = mHadRequestPending;
     nsDocument* doc = static_cast<nsDocument*>(mDoc.get());
-    doc->RequestFullScreen(mElement,
-                           mOptions,
-                           mWasCallerChrome,
-                           /* aNotifyOnOriginChange */ true);
+    doc->RequestFullScreen(mElement, mOptions);
     return NS_OK;
   }
 
   nsRefPtr<Element> mElement;
   nsCOMPtr<nsIDocument> mDoc;
-  bool mWasCallerChrome;
+  FullScreenOptions mOptions;
   bool mHadRequestPending;
-  FullScreenOptions mOptions;
 };
 
 void
 nsDocument::AsyncRequestFullScreen(Element* aElement,
                                    FullScreenOptions& aOptions)
 {
   NS_ASSERTION(aElement,
     "Must pass non-null element to nsDocument::AsyncRequestFullScreen");
@@ -11560,19 +11555,19 @@ IsInActiveTab(nsIDocument* aDoc)
 
 nsresult nsDocument::RemoteFrameFullscreenChanged(nsIDOMElement* aFrameElement)
 {
   // Ensure the frame element is the fullscreen element in this document.
   // If the frame element is already the fullscreen element in this document,
   // this has no effect.
   nsCOMPtr<nsIContent> content(do_QueryInterface(aFrameElement));
   FullScreenOptions opts;
-  RequestFullScreen(content->AsElement(), opts,
-                    /* aWasCallerChrome */ false,
-                    /* aNotifyOnOriginChange */ false);
+  opts.mIsCallerChrome = false;
+  opts.mShouldNotifyNewOrigin = false;
+  RequestFullScreen(content->AsElement(), opts);
 
   return NS_OK;
 }
 
 nsresult nsDocument::RemoteFrameFullscreenReverted()
 {
   RestorePreviousFullScreenState();
   return NS_OK;
@@ -11581,68 +11576,194 @@ nsresult nsDocument::RemoteFrameFullscre
 static void
 ReleaseHMDInfoRef(void *, nsIAtom*, void *aPropertyValue, void *)
 {
   if (aPropertyValue) {
     static_cast<gfx::VRHMDInfo*>(aPropertyValue)->Release();
   }
 }
 
-void
-nsDocument::RequestFullScreen(Element* aElement,
-                              FullScreenOptions& aOptions,
-                              bool aWasCallerChrome,
-                              bool aNotifyOnOriginChange)
+bool
+nsDocument::FullscreenElementReadyCheck(Element* aElement,
+                                        bool aWasCallerChrome)
 {
   NS_ASSERTION(aElement,
     "Must pass non-null element to nsDocument::RequestFullScreen");
   if (!aElement || aElement == GetFullScreenElement()) {
-    return;
+    return false;
   }
   if (!aElement->IsInDoc()) {
     LogFullScreenDenied(true, "FullScreenDeniedNotInDocument", this);
-    return;
+    return false;
   }
   if (aElement->OwnerDoc() != this) {
     LogFullScreenDenied(true, "FullScreenDeniedMovedDocument", this);
-    return;
+    return false;
   }
   if (!GetWindow()) {
     LogFullScreenDenied(true, "FullScreenDeniedLostWindow", this);
-    return;
+    return false;
   }
   if (!IsFullScreenEnabled(aWasCallerChrome, true)) {
     // IsFullScreenEnabled calls LogFullScreenDenied, no need to log.
-    return;
+    return false;
   }
   if (GetFullScreenElement() &&
       !nsContentUtils::ContentIsDescendantOf(aElement, GetFullScreenElement())) {
     // If this document is full-screen, only grant full-screen requests from
     // a descendant of the current full-screen element.
     LogFullScreenDenied(true, "FullScreenDeniedNotDescendant", this);
-    return;
+    return false;
   }
   if (!nsContentUtils::IsChromeDoc(this) && !IsInActiveTab(this)) {
     LogFullScreenDenied(true, "FullScreenDeniedNotFocusedTab", this);
-    return;
+    return false;
   }
   // Deny requests when a windowed plugin is focused.
   nsIFocusManager* fm = nsFocusManager::GetFocusManager();
   if (!fm) {
     NS_WARNING("Failed to retrieve focus manager in full-screen request.");
-    return;
+    return false;
   }
   nsCOMPtr<nsIDOMElement> focusedElement;
   fm->GetFocusedElement(getter_AddRefs(focusedElement));
   if (focusedElement) {
     nsCOMPtr<nsIContent> content = do_QueryInterface(focusedElement);
     if (nsContentUtils::HasPluginWithUncontrolledEventDispatch(content)) {
       LogFullScreenDenied(true, "FullScreenDeniedFocusedPlugin", this);
-      return;
-    }
+      return false;
+    }
+  }
+  return true;
+}
+
+struct FullscreenRequest : public LinkedListElement<FullscreenRequest>
+{
+  FullscreenRequest(Element* aElement, const FullScreenOptions& aOptions)
+    : mElement(aElement), mOptions(aOptions)
+    { MOZ_COUNT_CTOR(FullscreenRequest); }
+  ~FullscreenRequest() { MOZ_COUNT_DTOR(FullscreenRequest); }
+
+  nsRefPtr<Element> mElement;
+  FullScreenOptions mOptions;
+};
+
+// Any fullscreen request waiting for the widget to finish being full-
+// screen is queued here. This is declared static instead of a member
+// of nsDocument because in the majority of time, there would be at most
+// one document requesting fullscreen. We shouldn't waste the space to
+// hold for it in every document.
+static LinkedList<FullscreenRequest> sPendingFullscreenRequests;
+
+static nsCOMPtr<nsPIDOMWindow>
+GetRootWindow(nsIDocument* aDoc)
+{
+  nsIDocShell* docShell = aDoc->GetDocShell();
+  if (!docShell) {
+    return nullptr;
+  }
+  nsCOMPtr<nsIDocShellTreeItem> rootItem;
+  docShell->GetRootTreeItem(getter_AddRefs(rootItem));
+  return rootItem ? rootItem->GetWindow() : nullptr;
+}
+
+void
+nsDocument::RequestFullScreen(Element* aElement,
+                              const FullScreenOptions& aOptions)
+{
+  nsCOMPtr<nsPIDOMWindow> rootWin = GetRootWindow(this);
+  if (!rootWin) {
+    return;
+  }
+
+  // If we have been in fullscreen, apply the new state directly.
+  // Note that we should check both condition, because if we are in
+  // child process, our window may not report to be in fullscreen.
+  if (static_cast<nsGlobalWindow*>(rootWin.get())->FullScreen() ||
+      nsContentUtils::GetRootDocument(this)->IsFullScreenDoc()) {
+    ApplyFullscreen(aElement, aOptions);
+    return;
+  }
+
+  // We don't need to check element ready before this point, because
+  // if we called ApplyFullscreen, it would check that for us.
+  if (!FullscreenElementReadyCheck(aElement, aOptions.mIsCallerChrome)) {
+    return;
+  }
+
+  sPendingFullscreenRequests.insertBack(
+    new FullscreenRequest(aElement, aOptions));
+  if (XRE_GetProcessType() == GeckoProcessType_Content) {
+    // If we are not the top level process, dispatch an event to make
+    // our parent process go fullscreen first.
+    (new AsyncEventDispatcher(
+       this, NS_LITERAL_STRING("MozDOMFullscreen:Request"),
+       /* Bubbles */ true, /* ChromeOnly */ true))->PostDOMEvent();
+  } else {
+    // Make the window fullscreen.
+    SetWindowFullScreen(this, true, aOptions.mVRHMDDevice);
+  }
+}
+
+/* static */ bool
+nsIDocument::HandlePendingFullscreenRequest(const FullscreenRequest& aRequest,
+                                            nsIDocShellTreeItem* aRootShell,
+                                            bool* aHandled)
+{
+  nsRefPtr<nsDocument> doc =
+    static_cast<nsDocument*>(aRequest.mElement->OwnerDoc());
+  nsIDocShellTreeItem* shell = doc->GetDocShell();
+  if (!shell) {
+    return true;
+  }
+  nsCOMPtr<nsIDocShellTreeItem> rootShell;
+  shell->GetRootTreeItem(getter_AddRefs(rootShell));
+  if (rootShell != aRootShell) {
+    return false;
+  }
+
+  doc->ApplyFullscreen(aRequest.mElement, aRequest.mOptions);
+  *aHandled = true;
+  return true;
+}
+
+/* static */ bool
+nsIDocument::HandlePendingFullscreenRequests(nsIDocument* aDoc)
+{
+  if (sPendingFullscreenRequests.isEmpty()) {
+    return false;
+  }
+
+  bool handled = false;
+  nsIDocShellTreeItem* shell = aDoc->GetDocShell();
+  nsCOMPtr<nsIDocShellTreeItem> rootShell;
+  if (shell) {
+    shell->GetRootTreeItem(getter_AddRefs(rootShell));
+  }
+  FullscreenRequest* request = sPendingFullscreenRequests.getFirst();
+  while (request) {
+    if (HandlePendingFullscreenRequest(*request, rootShell, &handled)) {
+      // Drop requests, which either have been detached from document/
+      // document shell, or are handled by HandleFullscreenRequest.
+      FullscreenRequest* thisRequest = request;
+      request = request->getNext();
+      delete thisRequest;
+    } else {
+      request = request->getNext();
+    }
+  }
+  return handled;
+}
+
+void
+nsDocument::ApplyFullscreen(Element* aElement,
+                            const FullScreenOptions& aOptions)
+{
+  if (!FullscreenElementReadyCheck(aElement, aOptions.mIsCallerChrome)) {
+    return;
   }
 
   // Stash a reference to any existing fullscreen doc, we'll use this later
   // to detect if the origin which is fullscreen has changed.
   nsCOMPtr<nsIDocument> previousFullscreenDoc = GetFullscreenLeaf(this);
 
   AddFullscreenApprovedObserver();
 
@@ -11725,58 +11846,38 @@ nsDocument::RequestFullScreen(Element* a
   // If it is the first entry of the fullscreen, trigger an event so
   // that the UI can response to this change, e.g. hide chrome, or
   // notifying parent process to enter fullscreen. Note that chrome
   // code may also want to listen to MozDOMFullscreen:NewOrigin event
   // to pop up warning/approval UI.
   if (!previousFullscreenDoc) {
     nsRefPtr<AsyncEventDispatcher> asyncDispatcher =
       new AsyncEventDispatcher(
-        this, NS_LITERAL_STRING("MozDOMFullscreen:Entered"),
+        aElement, NS_LITERAL_STRING("MozDOMFullscreen:Entered"),
         /* Bubbles */ true, /* ChromeOnly */ true);
     asyncDispatcher->PostDOMEvent();
   }
 
   // The origin which is fullscreen gets changed. Trigger an event so
   // that the chrome knows to pop up a warning/approval UI. Note that
   // previousFullscreenDoc == nullptr upon first entry, so we always
   // take this path on the first entry. Also note that, in a multi-
   // process browser, the code in content process is responsible for
   // sending message with the origin to its parent, and the parent
   // shouldn't rely on this event itself.
-  if (aNotifyOnOriginChange &&
+  if (aOptions.mShouldNotifyNewOrigin &&
       !nsContentUtils::HaveEqualPrincipals(previousFullscreenDoc, this)) {
     nsRefPtr<AsyncEventDispatcher> asyncDispatcher =
       new AsyncEventDispatcher(
         this, NS_LITERAL_STRING("MozDOMFullscreen:NewOrigin"),
         /* Bubbles */ true, /* ChromeOnly */ true);
     asyncDispatcher->PostDOMEvent();
   }
 
-#ifdef DEBUG
-  // Note assertions must run before SetWindowFullScreen() as that does
-  // synchronous event dispatch which can run script which exits full-screen!
-  NS_ASSERTION(GetFullScreenElement() == aElement,
-               "Full-screen element should be the requested element!");
-  NS_ASSERTION(IsFullScreenDoc(), "Should be full-screen doc");
-  nsCOMPtr<nsIDOMElement> fse;
-  GetMozFullScreenElement(getter_AddRefs(fse));
-  nsCOMPtr<nsIContent> c(do_QueryInterface(fse));
-  NS_ASSERTION(c->AsElement() == aElement,
-    "GetMozFullScreenElement should match GetFullScreenElement()");
-#endif
-
-  // Make the window full-screen. Note we must make the state changes above
-  // before making the window full-screen, as then the document reports as
-  // being in full-screen mode when the chrome "fullscreen" event fires,
-  // enabling chrome to distinguish between browser and dom full-screen
-  // modes. Also note that nsGlobalWindow::SetFullScreen() (which
-  // SetWindowFullScreen() calls) proxies to the root window in its hierarchy,
-  // and does not operate on the a per-nsIDOMWindow basis.
-  SetWindowFullScreen(this, true, aOptions.mVRHMDDevice);
+  FullscreenRoots::Add(this);
 }
 
 NS_IMETHODIMP
 nsDocument::GetMozFullScreenElement(nsIDOMElement **aFullScreenElement)
 {
   ErrorResult rv;
   Element* el = GetMozFullScreenElement(rv);
   if (rv.Failed()) {
--- a/dom/base/nsDocument.h
+++ b/dom/base/nsDocument.h
@@ -1211,30 +1211,24 @@ public:
   // This array contains nodes that have been blocked to prevent
   // user tracking. They most likely have had their nsIChannel
   // canceled by the URL classifier (Safebrowsing).
   //
   already_AddRefed<nsSimpleContentList> BlockedTrackingNodes() const;
 
   static void ExitFullscreen(nsIDocument* aDoc);
 
+  // Do the "fullscreen element ready check" from the fullscreen spec.
+  // It returns true if the given element is allowed to go into fullscreen.
+  bool FullscreenElementReadyCheck(Element* aElement, bool aWasCallerChrome);
+
   // This is called asynchronously by nsIDocument::AsyncRequestFullScreen()
-  // to move this document into full-screen mode if allowed. aWasCallerChrome
-  // should be true when nsIDocument::AsyncRequestFullScreen() was called
-  // by chrome code. aNotifyOnOriginChange denotes whether we should trigger
-  // a MozFullscreenOriginChanged event if requesting fullscreen in this
-  // document causes the origin which is fullscreen to change. We may want to
-  // *not* send this notification if we're calling RequestFullScreen() as part
-  // of a continuation of a request in a subdocument, whereupon the caller will
-  // need to send some notification itself with the origin of the document
-  // which originally requested fullscreen, not *this* document's origin.
+  // to move this document into full-screen mode if allowed.
   void RequestFullScreen(Element* aElement,
-                         mozilla::dom::FullScreenOptions& aOptions,
-                         bool aWasCallerChrome,
-                         bool aNotifyOnOriginChange);
+                         const mozilla::dom::FullScreenOptions& aOptions);
 
   // Removes all elements from the full-screen stack, removing full-scren
   // styles from the top element in the stack.
   void CleanupFullscreenState();
 
   // Add/remove "fullscreen-approved" observer service notification listener.
   // Chrome sends us a notification when fullscreen is approved for a
   // document, with the notification subject as the document that was approved.
@@ -1513,16 +1507,20 @@ protected:
 
   explicit nsDocument(const char* aContentType);
   virtual ~nsDocument();
 
   void EnsureOnloadBlocker();
 
   void NotifyStyleSheetApplicableStateChanged();
 
+  // Apply the fullscreen state to the document, and trigger related events.
+  void ApplyFullscreen(Element* aElement,
+                       const mozilla::dom::FullScreenOptions& aOptions);
+
   nsTArray<nsIObserver*> mCharSetObservers;
 
   PLDHashTable *mSubDocuments;
 
   // Array of owning references to all children
   nsAttrAndChildArray mChildren;
 
   // Pointer to our parser if we're currently in the process of being
--- a/dom/base/nsFrameLoader.cpp
+++ b/dom/base/nsFrameLoader.cpp
@@ -131,35 +131,34 @@ NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION(
   NS_INTERFACE_MAP_ENTRY(nsIFrameLoader)
   NS_INTERFACE_MAP_ENTRY_AMBIGUOUS(nsISupports, nsIFrameLoader)
 NS_INTERFACE_MAP_END
 
 nsFrameLoader::nsFrameLoader(Element* aOwner, bool aNetworkCreated)
   : mOwnerContent(aOwner)
   , mAppIdSentToPermissionManager(nsIScriptSecurityManager::NO_APP_ID)
   , mDetachedSubdocViews(nullptr)
+  , mRemoteBrowser(nullptr)
+  , mChildID(0)
+  , mEventMode(EVENT_MODE_NORMAL_DISPATCH)
   , mIsPrerendered(false)
   , mDepthTooGreat(false)
   , mIsTopLevelContent(false)
   , mDestroyCalled(false)
   , mNeedsAsyncDestroy(false)
   , mInSwap(false)
   , mInShow(false)
   , mHideCalled(false)
   , mNetworkCreated(aNetworkCreated)
   , mRemoteBrowserShown(false)
   , mRemoteFrame(false)
   , mClipSubdocument(true)
   , mClampScrollPosition(true)
   , mObservingOwnerContent(false)
   , mVisible(true)
-  , mCurrentRemoteFrame(nullptr)
-  , mRemoteBrowser(nullptr)
-  , mChildID(0)
-  , mEventMode(EVENT_MODE_NORMAL_DISPATCH)
 {
   ResetPermissionManagerStatus();
 }
 
 nsFrameLoader::~nsFrameLoader()
 {
   if (mMessageManager) {
     mMessageManager->Disconnect();
@@ -1484,17 +1483,17 @@ nsFrameLoader::GetDepthTooGreat(bool* aD
 void
 nsFrameLoader::SetOwnerContent(Element* aContent)
 {
   if (mObservingOwnerContent) {
     mObservingOwnerContent = false;
     mOwnerContent->RemoveMutationObserver(this);
   }
   mOwnerContent = aContent;
-  if (RenderFrameParent* rfp = GetCurrentRemoteFrame()) {
+  if (RenderFrameParent* rfp = GetCurrentRenderFrame()) {
     rfp->OwnerContentChanged(aContent);
   }
 
   ResetPermissionManagerStatus();
 }
 
 bool
 nsFrameLoader::OwnerIsBrowserOrAppFrame()
@@ -2194,17 +2193,16 @@ nsFrameLoader::TryRemoteBrowser()
   NS_ENSURE_TRUE(rv, false);
 
   nsCOMPtr<Element> ownerElement = mOwnerContent;
   mRemoteBrowser = ContentParent::CreateBrowserOrApp(context, ownerElement, openerContentParent);
   if (!mRemoteBrowser) {
     return false;
   }
 
-  mContentParent = mRemoteBrowser->Manager();
   mChildID = mRemoteBrowser->Manager()->ChildID();
 
   nsCOMPtr<nsIDocShellTreeItem> rootItem;
   parentDocShell->GetRootTreeItem(getter_AddRefs(rootItem));
   nsCOMPtr<nsIDOMWindow> rootWin = rootItem->GetWindow();
   nsCOMPtr<nsIDOMChromeWindow> rootChromeWin = do_QueryInterface(rootWin);
 
   if (rootChromeWin) {
@@ -2219,21 +2217,30 @@ nsFrameLoader::TryRemoteBrowser()
                                  eCaseMatters)) {
     unused << mRemoteBrowser->SendSetUpdateHitRegion(true);
   }
 
   return true;
 }
 
 mozilla::dom::PBrowserParent*
-nsFrameLoader::GetRemoteBrowser()
+nsFrameLoader::GetRemoteBrowser() const
 {
   return mRemoteBrowser;
 }
 
+RenderFrameParent*
+nsFrameLoader::GetCurrentRenderFrame() const
+{
+  if (mRemoteBrowser) {
+    return mRemoteBrowser->GetRenderFrame();
+  }
+  return nullptr;
+}
+
 NS_IMETHODIMP
 nsFrameLoader::ActivateRemoteFrame() {
   if (mRemoteBrowser) {
     mRemoteBrowser->Activate();
     return NS_OK;
   }
   return NS_ERROR_UNEXPECTED;
 }
@@ -2526,17 +2533,16 @@ nsFrameLoader::GetChildID(uint64_t* aChi
   *aChildID = mChildID;
   return NS_OK;
 }
 
 void
 nsFrameLoader::SetRemoteBrowser(nsITabParent* aTabParent)
 {
   MOZ_ASSERT(!mRemoteBrowser);
-  MOZ_ASSERT(!mCurrentRemoteFrame);
   mRemoteFrame = true;
   mRemoteBrowser = TabParent::GetFrom(aTabParent);
   mChildID = mRemoteBrowser ? mRemoteBrowser->Manager()->ChildID() : 0;
   ShowRemoteFrame(ScreenIntSize(0, 0));
 }
 
 void
 nsFrameLoader::SetDetachedSubdocView(nsView* aDetachedViews,
--- a/dom/base/nsFrameLoader.h
+++ b/dom/base/nsFrameLoader.h
@@ -56,21 +56,16 @@ class nsFrameLoader final : public nsIFr
                             public nsStubMutationObserver,
                             public mozilla::dom::ipc::MessageManagerCallback
 {
   friend class AutoResetInShow;
   typedef mozilla::dom::PBrowserParent PBrowserParent;
   typedef mozilla::dom::TabParent TabParent;
   typedef mozilla::layout::RenderFrameParent RenderFrameParent;
 
-protected:
-  nsFrameLoader(mozilla::dom::Element* aOwner, bool aNetworkCreated);
-
-  ~nsFrameLoader();
-
 public:
   static nsFrameLoader* Create(mozilla::dom::Element* aOwner,
                                bool aNetworkCreated);
 
   NS_DECL_CYCLE_COLLECTING_ISUPPORTS
   NS_DECL_CYCLE_COLLECTION_CLASS_AMBIGUOUS(nsFrameLoader, nsIFrameLoader)
   NS_DECL_NSIFRAMELOADER
   NS_DECL_NSIMUTATIONOBSERVER_ATTRIBUTECHANGED
@@ -125,79 +120,64 @@ public:
   nsresult SwapWithOtherLoader(nsFrameLoader* aOther,
                                nsRefPtr<nsFrameLoader>& aFirstToSwap,
                                nsRefPtr<nsFrameLoader>& aSecondToSwap);
 
   nsresult SwapWithOtherRemoteLoader(nsFrameLoader* aOther,
                                      nsRefPtr<nsFrameLoader>& aFirstToSwap,
                                      nsRefPtr<nsFrameLoader>& aSecondToSwap);
 
-  // When IPC is enabled, destroy any associated child process.
-  void DestroyChild();
-
   /**
    * Return the primary frame for our owning content, or null if it
    * can't be found.
    */
   nsIFrame* GetPrimaryFrameOfOwningContent() const
   {
     return mOwnerContent ? mOwnerContent->GetPrimaryFrame() : nullptr;
   }
 
   /** 
    * Return the document that owns this, or null if we don't have
    * an owner.
    */
   nsIDocument* GetOwnerDoc() const
   { return mOwnerContent ? mOwnerContent->OwnerDoc() : nullptr; }
 
-  PBrowserParent* GetRemoteBrowser();
+  PBrowserParent* GetRemoteBrowser() const;
 
   /**
    * The "current" render frame is the one on which the most recent
    * remote layer-tree transaction was executed.  If no content has
    * been drawn yet, or the remote browser doesn't have any drawn
    * content for whatever reason, return nullptr.  The returned render
    * frame has an associated shadow layer tree.
    *
    * Note that the returned render frame might not be a frame
    * constructed for this->GetURL().  This can happen, e.g., if the
    * <browser> was just navigated to a new URL, but hasn't painted the
    * new page yet.  A render frame for the previous page may be
    * returned.  (In-process <browser> behaves similarly, and this
    * behavior seems desirable.)
    */
-  RenderFrameParent* GetCurrentRemoteFrame() const
-  {
-    return mCurrentRemoteFrame;
-  }
+  RenderFrameParent* GetCurrentRenderFrame() const;
 
-  /**
-   * |aFrame| can be null.  If non-null, it must be the remote frame
-   * on which the most recent layer transaction completed for this's
-   * <browser>.
-   */
-  void SetCurrentRemoteFrame(RenderFrameParent* aFrame)
-  {
-    mCurrentRemoteFrame = aFrame;
-  }
   nsFrameMessageManager* GetFrameMessageManager() { return mMessageManager; }
 
   mozilla::dom::Element* GetOwnerContent() { return mOwnerContent; }
   bool ShouldClipSubdocument() { return mClipSubdocument; }
 
   bool ShouldClampScrollPosition() { return mClampScrollPosition; }
 
   /**
    * Tell this FrameLoader to use a particular remote browser.
    *
-   * This will assert if mRemoteBrowser or mCurrentRemoteFrame is non-null.  In
-   * practice, this means you can't have successfully run TryRemoteBrowser() on
-   * this object, which means you can't have called ShowRemoteFrame() or
-   * ReallyStartLoading().
+   * This will assert if mRemoteBrowser is non-null.  In practice,
+   * this means you can't have successfully run TryRemoteBrowser() on
+   * this object, which means you can't have called ShowRemoteFrame()
+   * or ReallyStartLoading().
    */
   void SetRemoteBrowser(nsITabParent* aTabParent);
 
   /**
    * Stashes a detached view on the frame loader. We do this when we're
    * destroying the nsSubDocumentFrame. If the nsSubdocumentFrame is
    * being reframed we'll restore the detached view when it's recreated,
    * otherwise we'll discard the old presentation and set the detached
@@ -225,17 +205,23 @@ public:
   void GetURL(nsString& aURL);
 
   void ActivateUpdateHitRegion();
   void DeactivateUpdateHitRegion();
 
   // Properly retrieves documentSize of any subdocument type.
   nsresult GetWindowDimensions(nsIntRect& aRect);
 
+  // public because a callback needs these.
+  nsRefPtr<nsFrameMessageManager> mMessageManager;
+  nsCOMPtr<nsIInProcessContentFrameMessageManager> mChildMessageManager;
+
 private:
+  nsFrameLoader(mozilla::dom::Element* aOwner, bool aNetworkCreated);
+  ~nsFrameLoader();
 
   void SetOwnerContent(mozilla::dom::Element* aContent);
 
   bool ShouldUseRemoteProcess();
 
   /**
    * Is this a frameloader for a bona fide <iframe mozbrowser> or
    * <iframe mozapp>?  (I.e., does the frame return true for
@@ -322,31 +308,33 @@ private:
   // After the frameloader has been removed from the DOM but before all of the
   // messages from the frame have been received, we keep a strong reference to
   // our <browser> element.
   nsRefPtr<mozilla::dom::Element> mOwnerContentStrong;
 
   // Note: this variable must be modified only by ResetPermissionManagerStatus()
   uint32_t mAppIdSentToPermissionManager;
 
-public:
-  // public because a callback needs these.
-  nsRefPtr<nsFrameMessageManager> mMessageManager;
-  nsCOMPtr<nsIInProcessContentFrameMessageManager> mChildMessageManager;
-private:
   // Stores the root view of the subdocument while the subdocument is being
   // reframed. Used to restore the presentation after reframing.
   nsView* mDetachedSubdocViews;
   // Stores the containing document of the frame corresponding to this
   // frame loader. This is reference is kept valid while the subframe's
   // presentation is detached and stored in mDetachedSubdocViews. This
   // enables us to detect whether the frame has moved documents during
   // a reframe, so that we know not to restore the presentation.
   nsCOMPtr<nsIDocument> mContainerDocWhileDetached;
 
+  TabParent* mRemoteBrowser;
+  uint64_t mChildID;
+
+  // See nsIFrameLoader.idl. EVENT_MODE_NORMAL_DISPATCH automatically
+  // forwards some input events to out-of-process content.
+  uint32_t mEventMode;
+
   bool mIsPrerendered : 1;
   bool mDepthTooGreat : 1;
   bool mIsTopLevelContent : 1;
   bool mDestroyCalled : 1;
   bool mNeedsAsyncDestroy : 1;
   bool mInSwap : 1;
   bool mInShow : 1;
   bool mHideCalled : 1;
@@ -360,22 +348,11 @@ private:
   bool mClipSubdocument : 1;
   bool mClampScrollPosition : 1;
   bool mObservingOwnerContent : 1;
 
   // Backs nsIFrameLoader::{Get,Set}Visible.  Visibility state here relates to
   // whether this frameloader's <iframe mozbrowser> is setVisible(true)'ed, and
   // doesn't necessarily correlate with docshell/document visibility.
   bool mVisible : 1;
-
-  // The ContentParent associated with mRemoteBrowser.  This was added as a
-  // strong ref in bug 545237, and we're not sure if we can get rid of it.
-  nsRefPtr<mozilla::dom::nsIContentParent> mContentParent;
-  RenderFrameParent* mCurrentRemoteFrame;
-  TabParent* mRemoteBrowser;
-  uint64_t mChildID;
-
-  // See nsIFrameLoader.idl. EVENT_MODE_NORMAL_DISPATCH automatically
-  // forwards some input events to out-of-process content.
-  uint32_t mEventMode;
 };
 
 #endif
--- a/dom/base/nsGlobalWindow.cpp
+++ b/dom/base/nsGlobalWindow.cpp
@@ -6114,22 +6114,16 @@ nsGlobalWindow::SetFullScreenInternal(bo
     // If we are exiting from DOM fullscreen while we
     // initially make the window fullscreen because of
     // fullscreen mode, don't restore the window.
     if (!aFullScreen && mFullscreenMode) {
       return NS_OK;
     }
   }
 
-  // dispatch a "fullscreen" DOM event so that XUL apps can
-  // respond visually if we are kicked into full screen mode
-  if (!DispatchCustomEvent(NS_LITERAL_STRING("fullscreen"))) {
-    return NS_OK;
-  }
-
   // Prevent chrome documents which are still loading from resizing
   // the window after we set fullscreen mode.
   nsCOMPtr<nsIBaseWindow> treeOwnerAsWin = GetTreeOwnerWindow();
   nsCOMPtr<nsIXULWindow> xulWin(do_GetInterface(treeOwnerAsWin));
   if (aFullScreen && xulWin) {
     xulWin->SetIntrinsicallySized(false);
   }
 
@@ -6147,47 +6141,86 @@ nsGlobalWindow::SetFullScreenInternal(bo
       nsCOMPtr<nsIScreen> screen;
       if (aHMD) {
         screen = aHMD->GetScreen();
       }
       if (!aFullscreenMode) {
         widget->PrepareForDOMFullscreenTransition();
       }
       widget->MakeFullScreen(aFullScreen, screen);
-    }
-  }
+      // The rest of code for switching fullscreen is in nsGlobalWindow::
+      // FinishFullscreenChange() which will be called after sizemodechange
+      // event is dispatched.
+      return NS_OK;
+    }
+  }
+
+  FinishFullscreenChange(aFullScreen);
+  return NS_OK;
+}
+
+/* virtual */ void
+nsGlobalWindow::FinishFullscreenChange(bool aIsFullscreen)
+{
+  MOZ_ASSERT(IsOuterWindow());
+
+  if (aIsFullscreen != mFullScreen) {
+    NS_WARNING("Failed to toggle fullscreen state of the widget");
+    // We failed to make the widget enter fullscreen.
+    // Stop further changes and restore the state.
+    if (!aIsFullscreen) {
+      mFullScreen = false;
+      mFullscreenMode = false;
+    } else {
+      MOZ_ASSERT_UNREACHABLE("Failed to exit fullscreen?");
+      mFullScreen = true;
+      // We don't know how code can reach here. Not sure
+      // what value should be set for fullscreen mode.
+      mFullscreenMode = false;
+    }
+    return;
+  }
+
+  // Ask the document to handle any pending DOM fullscreen change. Note
+  // we must make the state changes before dispatching the "fullscreen"
+  // event below, so that the chrome can distinguish between browser
+  // fullscreen mode and DOM fullscreen.
+  if (mFullScreen) {
+    nsIDocument::HandlePendingFullscreenRequests(mDoc);
+  }
+
+  // dispatch a "fullscreen" DOM event so that XUL apps can
+  // respond visually if we are kicked into full screen mode
+  DispatchCustomEvent(NS_LITERAL_STRING("fullscreen"));
 
   if (!mFullScreen) {
     // Force exit from DOM full-screen mode. This is so that if we're in
     // DOM full-screen mode and the user exits full-screen mode with
     // the browser full-screen mode toggle keyboard-shortcut, we'll detect
     // that and leave DOM API full-screen mode too.
     nsIDocument::ExitFullscreen(mDoc, /* async */ false);
   }
 
   if (!mWakeLock && mFullScreen) {
     nsRefPtr<power::PowerManagerService> pmService =
       power::PowerManagerService::GetInstance();
-    NS_ENSURE_TRUE(pmService, NS_OK);
+    if (!pmService) {
+      return;
+    }
 
     ErrorResult rv;
     mWakeLock = pmService->NewWakeLock(NS_LITERAL_STRING("DOM_Fullscreen"),
                                        this, rv);
-    if (rv.Failed()) {
-      return rv.StealNSResult();
-    }
-
+    NS_WARN_IF_FALSE(!rv.Failed(), "Failed to lock the wakelock");
   } else if (mWakeLock && !mFullScreen) {
     ErrorResult rv;
     mWakeLock->Unlock(rv);
     NS_WARN_IF_FALSE(!rv.Failed(), "Failed to unlock the wakelock.");
     mWakeLock = nullptr;
   }
-
-  return NS_OK;
 }
 
 bool
 nsGlobalWindow::FullScreen() const
 {
   MOZ_ASSERT(IsOuterWindow());
 
   NS_ENSURE_TRUE(mDocShell, mFullScreen);
--- a/dom/base/nsGlobalWindow.h
+++ b/dom/base/nsGlobalWindow.h
@@ -486,17 +486,18 @@ public:
   virtual bool DispatchCustomEvent(const nsAString& aEventName) override;
   bool DispatchResizeEvent(const mozilla::CSSIntSize& aSize);
 
   // Inner windows only.
   virtual void RefreshCompartmentPrincipal() override;
 
   // Outer windows only.
   virtual nsresult SetFullScreenInternal(bool aIsFullscreen, bool aFullscreenMode,
-                                         mozilla::gfx::VRHMDInfo *aHMD = nullptr) override;
+                                         mozilla::gfx::VRHMDInfo *aHMD = nullptr) override final;
+  virtual void FinishFullscreenChange(bool aIsFullscreen) override final;
   bool FullScreen() const;
 
   // Inner windows only.
   virtual void SetHasGamepadEventListener(bool aHasGamepad = true) override;
 
   // nsIInterfaceRequestor
   NS_DECL_NSIINTERFACEREQUESTOR
 
--- a/dom/base/nsIDocument.h
+++ b/dom/base/nsIDocument.h
@@ -43,16 +43,17 @@ class nsHTMLCSSStyleSheet;
 class nsHTMLDocument;
 class nsHTMLStyleSheet;
 class nsIAtom;
 class nsIBFCacheEntry;
 class nsIChannel;
 class nsIContent;
 class nsIContentSink;
 class nsIDocShell;
+class nsIDocShellTreeItem;
 class nsIDocumentEncoder;
 class nsIDocumentObserver;
 class nsIDOMDocument;
 class nsIDOMDocumentType;
 class nsIDOMElement;
 class nsIDOMNodeFilter;
 class nsIDOMNodeList;
 class nsIHTMLCollection;
@@ -78,16 +79,17 @@ class nsScriptLoader;
 class nsSMILAnimationController;
 class nsStyleSet;
 class nsTextNode;
 class nsWindowSizes;
 class nsDOMCaretPosition;
 class nsViewportInfo;
 class nsIGlobalObject;
 struct nsCSSSelectorList;
+struct FullscreenRequest; // For nsIDocument::HandlePendingFullscreenRequest
 
 namespace mozilla {
 class CSSStyleSheet;
 class ErrorResult;
 class EventStates;
 class PendingAnimationTracker;
 class SVGAttrAnimationRuleProcessor;
 
@@ -141,16 +143,26 @@ template<typename> class OwningNonNull;
 template<typename> class Sequence;
 
 template<typename, typename> class CallbackObjectHolder;
 typedef CallbackObjectHolder<NodeFilter, nsIDOMNodeFilter> NodeFilterHolder;
 
 struct FullScreenOptions {
   FullScreenOptions();
   nsRefPtr<gfx::VRHMDInfo> mVRHMDDevice;
+  // This value should be true if the fullscreen request is
+  // originated from chrome code.
+  bool mIsCallerChrome = false;
+  // This value denotes whether we should trigger a NewOrigin event if
+  // requesting fullscreen in its document causes the origin which is
+  // fullscreen to change. We may want *not* to trigger that event if
+  // we're calling RequestFullScreen() as part of a continuation of a
+  // request in a subdocument in different process, whereupon the caller
+  // need to send some notification itself with the real origin.
+  bool mShouldNotifyNewOrigin = true;
 };
 
 } // namespace dom
 } // namespace mozilla
 
 #define NS_IDOCUMENT_IID \
 { 0xdcfa30f2, 0x2197, 0x421f, \
   { 0xa7, 0x5a, 0x3e, 0x70, 0x18, 0x08, 0xde, 0x81 } }
@@ -1165,16 +1177,32 @@ public:
    *
    * If aRunAsync is true, fullscreen is executed asynchronously.
    *
    * Note if aDocument is not fullscreen this function has no effect, even if
    * aDocument has fullscreen ancestors.
    */
   static void ExitFullscreen(nsIDocument* aDocument, bool aRunAsync);
 
+  /**
+   * Handles one single fullscreen request, updates `aHandled` if the request
+   * is handled, and returns whether this request should be removed from the
+   * request queue.
+   */
+  static bool HandlePendingFullscreenRequest(const FullscreenRequest& aRequest,
+                                             nsIDocShellTreeItem* aRootShell,
+                                             bool* aHandled);
+
+  /**
+   * Handles any pending fullscreen in aDocument or its subdocuments.
+   *
+   * Returns whether there is any fullscreen request handled.
+   */
+  static bool HandlePendingFullscreenRequests(nsIDocument* aDocument);
+
   virtual void RequestPointerLock(Element* aElement) = 0;
 
   static void UnlockPointer(nsIDocument* aDoc = nullptr);
 
 
   //----------------------------------------------------------------------
 
   // Document notification API's
--- a/dom/base/nsPIDOMWindow.h
+++ b/dom/base/nsPIDOMWindow.h
@@ -57,18 +57,18 @@ enum PopupControlState {
 enum UIStateChangeType
 {
   UIStateChangeType_NoChange,
   UIStateChangeType_Set,
   UIStateChangeType_Clear
 };
 
 #define NS_PIDOMWINDOW_IID \
-{ 0x2485d4d7, 0xf7cb, 0x481e, \
-  { 0x9c, 0x89, 0xb2, 0xa8, 0x12, 0x67, 0x7f, 0x97 } }
+{ 0x0df7578f, 0x31d4, 0x4391, \
+  { 0x98, 0xd4, 0xf3, 0x7d, 0x51, 0x8e, 0xa4, 0x37 } }
 
 class nsPIDOMWindow : public nsIDOMWindowInternal
 {
 public:
   NS_DECLARE_STATIC_IID_ACCESSOR(NS_PIDOMWINDOW_IID)
 
   virtual nsPIDOMWindow* GetPrivateRoot() = 0;
 
@@ -471,16 +471,28 @@ public:
    * device instead of its currrent display.
    *
    * Outer windows only.
    */
   virtual nsresult SetFullScreenInternal(bool aIsFullscreen, bool aFullscreenMode,
                                          mozilla::gfx::VRHMDInfo *aHMD = nullptr) = 0;
 
   /**
+   * This function should be called when the fullscreen state is flipped.
+   * If no widget is involved the fullscreen change, this method is called
+   * by SetFullScreenInternal, otherwise, it is called when the widget
+   * finishes its change to or from fullscreen.
+   *
+   * @param aIsFullscreen indicates whether the widget is in fullscreen.
+   *
+   * Outer windows only.
+   */
+  virtual void FinishFullscreenChange(bool aIsFullscreen) = 0;
+
+  /**
    * Call this to check whether some node (this window, its document,
    * or content in that document) has a mouseenter/leave event listener.
    */
   bool HasMouseEnterLeaveEventListeners()
   {
     return mMayHaveMouseEnterLeaveEventListener;
   }
 
--- a/dom/base/nsPIWindowRoot.h
+++ b/dom/base/nsPIWindowRoot.h
@@ -4,31 +4,24 @@
  * 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 nsPIWindowRoot_h__
 #define nsPIWindowRoot_h__
 
 #include "nsISupports.h"
 #include "mozilla/dom/EventTarget.h"
-#include "nsWeakReference.h"
 
 class nsPIDOMWindow;
 class nsIControllers;
 class nsIController;
 
-namespace mozilla {
-namespace dom {
-class TabParent;
-}
-}
-
 #define NS_IWINDOWROOT_IID \
-{ 0x238edca0, 0xb30d, 0x46d3, \
- { 0xb2, 0x6a, 0x17, 0xb6, 0x21, 0x28, 0x89, 0x7e } }
+{ 0x728a2682, 0x55c0, 0x4860, \
+ { 0x82, 0x6b, 0x0c, 0x30, 0x0a, 0xac, 0xaa, 0x60 } }
 
 class nsPIWindowRoot : public mozilla::dom::EventTarget
 {
 public:
   NS_DECLARE_STATIC_IID_ACCESSOR(NS_IWINDOWROOT_IID)
 
   virtual nsPIDOMWindow* GetWindow()=0;
 
@@ -40,22 +33,13 @@ public:
                                            nsIController** aResult) = 0;
   virtual nsresult GetControllers(nsIControllers** aResult) = 0;
 
   virtual void GetEnabledDisabledCommands(nsTArray<nsCString>& aEnabledCommands,
                                           nsTArray<nsCString>& aDisabledCommands) = 0;
 
   virtual void SetParentTarget(mozilla::dom::EventTarget* aTarget) = 0;
   virtual mozilla::dom::EventTarget* GetParentTarget() = 0;
-
-  // Stores a weak reference to the browser.
-  virtual void AddBrowser(mozilla::dom::TabParent* aBrowser) = 0;
-  virtual void RemoveBrowser(mozilla::dom::TabParent* aBrowser) = 0;
-
-  typedef void (*BrowserEnumerator)(mozilla::dom::TabParent* aTab, void* aArg);
-
-  // Enumerate all stored browsers that for which the weak reference is valid.
-  virtual void EnumerateBrowsers(BrowserEnumerator aEnumFunc, void* aArg) = 0;
 };
 
 NS_DEFINE_STATIC_IID_ACCESSOR(nsPIWindowRoot, NS_IWINDOWROOT_IID)
 
 #endif // nsPIWindowRoot_h__
--- a/dom/base/nsWindowRoot.cpp
+++ b/dom/base/nsWindowRoot.cpp
@@ -19,17 +19,16 @@
 #include "nsFocusManager.h"
 #include "nsIContent.h"
 #include "nsIDOMHTMLInputElement.h"
 #include "nsIDOMHTMLTextAreaElement.h"
 #include "nsIControllers.h"
 #include "nsIController.h"
 #include "xpcpublic.h"
 #include "nsCycleCollectionParticipant.h"
-#include "mozilla/dom/TabParent.h"
 
 #ifdef MOZ_XUL
 #include "nsIDOMXULElement.h"
 #endif
 
 using namespace mozilla;
 using namespace mozilla::dom;
 
@@ -381,56 +380,16 @@ nsWindowRoot::GetParentObject()
 }
 
 JSObject*
 nsWindowRoot::WrapObject(JSContext* aCx, JS::Handle<JSObject*> aGivenProto)
 {
   return mozilla::dom::WindowRootBinding::Wrap(aCx, this, aGivenProto);
 }
 
-void
-nsWindowRoot::AddBrowser(mozilla::dom::TabParent* aBrowser)
-{
-  nsWeakPtr weakBrowser = do_GetWeakReference(static_cast<nsITabParent*>(aBrowser));
-  mWeakBrowsers.PutEntry(weakBrowser);
-}
-
-void
-nsWindowRoot::RemoveBrowser(mozilla::dom::TabParent* aBrowser)
-{
-  nsWeakPtr weakBrowser = do_GetWeakReference(static_cast<nsITabParent*>(aBrowser));
-  mWeakBrowsers.RemoveEntry(weakBrowser);
-}
-
-static PLDHashOperator
-WeakBrowserEnumFunc(nsRefPtrHashKey<nsIWeakReference>* aKey, void* aArg)
-{
-  nsTArray<nsRefPtr<TabParent>>* tabParents =
-    static_cast<nsTArray<nsRefPtr<TabParent>>*>(aArg);
-  nsCOMPtr<nsITabParent> tabParent(do_QueryReferent((*aKey).GetKey()));
-  TabParent* tab = TabParent::GetFrom(tabParent);
-  if (tab) {
-    tabParents->AppendElement(tab);
-  }
-  return PL_DHASH_NEXT;
-}
-
-void
-nsWindowRoot::EnumerateBrowsers(BrowserEnumerator aEnumFunc, void* aArg)
-{
-  // Collect strong references to all browsers in a separate array in
-  // case aEnumFunc alters mWeakBrowsers.
-  nsTArray<nsRefPtr<TabParent>> tabParents;
-  mWeakBrowsers.EnumerateEntries(WeakBrowserEnumFunc, &tabParents);
-
-  for (uint32_t i = 0; i < tabParents.Length(); ++i) {
-    aEnumFunc(tabParents[i], aArg);
-  }
-}
-
 ///////////////////////////////////////////////////////////////////////////////////
 
 already_AddRefed<EventTarget>
 NS_NewWindowRoot(nsPIDOMWindow* aWindow)
 {
   nsCOMPtr<EventTarget> result = new nsWindowRoot(aWindow);
   return result.forget();
 }
--- a/dom/base/nsWindowRoot.h
+++ b/dom/base/nsWindowRoot.h
@@ -64,37 +64,29 @@ public:
 
   nsIGlobalObject* GetParentObject();
 
   virtual JSObject* WrapObject(JSContext* aCx, JS::Handle<JSObject*> aGivenProto) override;
 
   NS_DECL_CYCLE_COLLECTION_SCRIPT_HOLDER_CLASS_AMBIGUOUS(nsWindowRoot,
                                                          nsIDOMEventTarget)
 
-  virtual void AddBrowser(mozilla::dom::TabParent* aBrowser) override;
-  virtual void RemoveBrowser(mozilla::dom::TabParent* aBrowser) override;
-  virtual void EnumerateBrowsers(BrowserEnumerator aEnumFunc, void *aArg) override;
-
 protected:
   virtual ~nsWindowRoot();
 
   void GetEnabledDisabledCommandsForControllers(nsIControllers* aControllers,
                                                 nsTHashtable<nsCharPtrHashKey>& aCommandsHandled,
                                                 nsTArray<nsCString>& aEnabledCommands,
                                                 nsTArray<nsCString>& aDisabledCommands);
 
   // Members
   nsCOMPtr<nsPIDOMWindow> mWindow;
   // We own the manager, which owns event listeners attached to us.
   nsRefPtr<mozilla::EventListenerManager> mListenerManager; // [Strong]
   nsCOMPtr<nsIDOMNode> mPopupNode; // [OWNER]
 
   nsCOMPtr<mozilla::dom::EventTarget> mParent;
-
-  // The TabParents that are currently registered with this top-level window.
-  typedef nsTHashtable<nsRefPtrHashKey<nsIWeakReference>> WeakBrowserTable;
-  WeakBrowserTable mWeakBrowsers;
 };
 
 extern already_AddRefed<mozilla::dom::EventTarget>
 NS_NewWindowRoot(nsPIDOMWindow* aWindow);
 
 #endif
deleted file mode 100644
--- a/dom/base/test/csp/mochitest.ini
+++ /dev/null
@@ -1,177 +0,0 @@
-[DEFAULT]
-support-files =
-  file_base-uri.html
-  file_blob_data_schemes.html
-  file_connect-src.html
-  file_connect-src-fetch.html
-  file_CSP.css
-  file_CSP.sjs
-  file_csp_allow_https_schemes.html
-  file_CSP_bug663567.xsl
-  file_CSP_bug663567_allows.xml
-  file_CSP_bug663567_allows.xml^headers^
-  file_CSP_bug663567_blocks.xml
-  file_CSP_bug663567_blocks.xml^headers^
-  file_CSP_bug802872.html
-  file_CSP_bug802872.html^headers^
-  file_CSP_bug802872.js
-  file_CSP_bug802872.sjs
-  file_CSP_bug885433_allows.html
-  file_CSP_bug885433_allows.html^headers^
-  file_CSP_bug885433_blocks.html
-  file_CSP_bug885433_blocks.html^headers^
-  file_CSP_bug888172.html
-  file_CSP_bug888172.sjs
-  file_CSP_evalscript_main.js
-  file_CSP_evalscript_main_allowed.js
-  file_CSP_evalscript_main.html
-  file_CSP_evalscript_main.html^headers^
-  file_CSP_evalscript_main_allowed.html
-  file_CSP_evalscript_main_allowed.html^headers^
-  file_CSP_frameancestors_main.html
-  file_CSP_frameancestors_main.js
-  file_CSP_frameancestors.sjs
-  file_CSP_inlinescript_main.html
-  file_CSP_inlinescript_main.html^headers^
-  file_CSP_inlinescript_main_allowed.html
-  file_CSP_inlinescript_main_allowed.html^headers^
-  file_CSP_inlinestyle_main.html
-  file_CSP_inlinestyle_main.html^headers^
-  file_CSP_inlinestyle_main_allowed.html
-  file_CSP_inlinestyle_main_allowed.html^headers^
-  file_csp_invalid_source_expression.html
-  file_CSP_main.html
-  file_CSP_main.html^headers^
-  file_CSP_main.js
-  file_CSP_web_manifest.html
-  file_CSP_web_manifest_remote.html
-  file_CSP_web_manifest_https.html
-  file_CSP_web_manifest.json
-  file_CSP_web_manifest.json^headers^
-  file_CSP_web_manifest_https.json
-  file_CSP_web_manifest_mixed_content.html
-  file_bug836922_npolicies.html
-  file_bug836922_npolicies.html^headers^
-  file_bug836922_npolicies_ro_violation.sjs
-  file_bug836922_npolicies_violation.sjs
-  file_bug886164.html
-  file_bug886164.html^headers^
-  file_bug886164_2.html
-  file_bug886164_2.html^headers^
-  file_bug886164_3.html
-  file_bug886164_3.html^headers^
-  file_bug886164_4.html
-  file_bug886164_4.html^headers^
-  file_bug886164_5.html
-  file_bug886164_5.html^headers^
-  file_bug886164_6.html
-  file_bug886164_6.html^headers^
-  file_csp_bug768029.html
-  file_csp_bug768029.sjs
-  file_csp_bug773891.html
-  file_csp_bug773891.sjs
-  file_csp_redirects_main.html
-  file_csp_redirects_page.sjs
-  file_csp_redirects_resource.sjs
-  file_CSP_bug910139.sjs
-  file_CSP_bug910139.xml
-  file_CSP_bug910139.xsl
-  file_CSP_bug909029_star.html
-  file_CSP_bug909029_star.html^headers^
-  file_CSP_bug909029_none.html
-  file_CSP_bug909029_none.html^headers^
-  file_policyuri_regression_from_multipolicy.html
-  file_policyuri_regression_from_multipolicy.html^headers^
-  file_policyuri_regression_from_multipolicy_policy
-  file_nonce_source.html
-  file_nonce_source.html^headers^
-  file_CSP_bug941404.html
-  file_CSP_bug941404_xhr.html
-  file_CSP_bug941404_xhr.html^headers^
-  file_hash_source.html
-  file_dual_header_testserver.sjs
-  file_hash_source.html^headers^
-  file_scheme_relative_sources.js
-  file_scheme_relative_sources.sjs
-  file_ignore_unsafe_inline.html
-  file_self_none_as_hostname_confusion.html
-  file_self_none_as_hostname_confusion.html^headers^
-  file_csp_path_matching.html
-  file_csp_path_matching_incl_query.html
-  file_csp_path_matching.js
-  file_csp_path_matching_redirect.html
-  file_csp_path_matching_redirect_server.sjs
-  file_csp_testserver.sjs
-  file_report_uri_missing_in_report_only_header.html
-  file_report_uri_missing_in_report_only_header.html^headers^
-  file_csp_report.html
-  file_redirect_content.sjs
-  file_redirect_report.sjs
-  file_subframe_run_js_if_allowed.html
-  file_subframe_run_js_if_allowed.html^headers^
-  file_leading_wildcard.html
-  file_multi_policy_injection_bypass.html
-  file_multi_policy_injection_bypass.html^headers^
-  file_multi_policy_injection_bypass_2.html
-  file_multi_policy_injection_bypass_2.html^headers^
-  file_null_baseuri.html
-  file_form-action.html
-  file_worker_redirect.html
-  file_worker_redirect.sjs
-  file_csp_referrerdirective.html
-  referrerdirective.sjs
-
-[test_base-uri.html]
-[test_blob_data_schemes.html]
-[test_connect-src.html]
-[test_CSP.html]
-[test_csp_allow_https_schemes.html]
-skip-if = buildapp == 'b2g' #no ssl support
-[test_CSP_bug663567.html]
-[test_CSP_bug802872.html]
-[test_CSP_bug885433.html]
-[test_CSP_bug888172.html]
-[test_CSP_evalscript.html]
-[test_CSP_frameancestors.html]
-skip-if = (buildapp == 'b2g' && (toolkit != 'gonk' || debug)) || toolkit == 'android' # Times out, not sure why (bug 1008445)
-[test_CSP_inlinescript.html]
-[test_CSP_inlinestyle.html]
-[test_csp_invalid_source_expression.html]
-[test_bug836922_npolicies.html]
-[test_bug886164.html]
-[test_csp_redirects.html]
-[test_CSP_bug910139.html]
-[test_CSP_bug909029.html]
-[test_policyuri_regression_from_multipolicy.html]
-[test_nonce_source.html]
-[test_CSP_bug941404.html]
-[test_form-action.html]
-skip-if = e10s || buildapp == 'b2g' # http-on-opening-request observers are not available in child processes
-[test_hash_source.html]
-skip-if = e10s || buildapp == 'b2g' # can't compute hashes in child process (bug 958702)
-[test_scheme_relative_sources.html]
-skip-if = buildapp == 'b2g' #no ssl support
-[test_ignore_unsafe_inline.html]
-[test_self_none_as_hostname_confusion.html]
-[test_bug949549.html]
-[test_csp_path_matching.html]
-[test_csp_path_matching_redirect.html]
-[test_report_uri_missing_in_report_only_header.html]
-[test_csp_report.html]
-skip-if = e10s || buildapp == 'b2g' # http-on-opening-request observer not supported in child process (bug 1009632)
-[test_301_redirect.html]
-skip-if = buildapp == 'b2g' # intermittent orange (bug 1028490)
-[test_302_redirect.html]
-skip-if = buildapp == 'b2g' # intermittent orange (bug 1028490)
-[test_303_redirect.html]
-skip-if = buildapp == 'b2g' # intermittent orange (bug 1028490)
-[test_307_redirect.html]
-skip-if = buildapp == 'b2g' # intermittent orange (bug 1028490)
-[test_subframe_run_js_if_allowed.html]
-[test_leading_wildcard.html]
-[test_multi_policy_injection_bypass.html]
-[test_null_baseuri.html]
-[test_CSP_referrerdirective.html]
-skip-if = buildapp == 'b2g' #no ssl support
-[test_dual_header.html]
-[test_worker_redirect.html]
--- a/dom/base/test/mochitest.ini
+++ b/dom/base/test/mochitest.ini
@@ -61,21 +61,16 @@ support-files =
   delayedServerEvents.sjs
   echo.sjs
   eventsource.resource
   eventsource.resource^headers^
   eventsource_redirect.resource
   eventsource_redirect.resource^headers^
   eventsource_redirect_to.resource
   eventsource_redirect_to.resource^headers^
-  file_CrossSiteXHR_cache_server.sjs
-  file_CrossSiteXHR_inner.html
-  file_CrossSiteXHR_inner.jar
-  file_CrossSiteXHR_inner_data.sjs
-  file_CrossSiteXHR_server.sjs
   file_XHRDocURI.text
   file_XHRDocURI.text^headers^
   file_XHRDocURI.xml
   file_XHRDocURI.xml^headers^
   file_XHRDocURI.html
   file_XHRDocURI.html^headers^
   file_XHRDocURI.sjs
   file_XHRResponseURL.js
@@ -326,20 +321,16 @@ skip-if = e10s || buildapp == 'b2g'
 [test_window_cross_origin_props.html]
 [test_window_define_symbol.html]
 [test_window_enumeration.html]
 [test_window_extensible.html]
 [test_window_indexing.html]
 [test_window_named_frame_enumeration.html]
 [test_writable-replaceable.html]
 [test_navigatorPrefOverride.html]
-[test_CrossSiteXHR.html]
-[test_CrossSiteXHR_cache.html]
-[test_CrossSiteXHR_origin.html]
-skip-if = buildapp == 'b2g' || e10s # last test fails to trigger onload on e10s/b2g
 [test_EventSource_redirects.html]
 [test_NodeIterator_basics_filters.xhtml]
 [test_NodeIterator_mutations_1.xhtml]
 [test_NodeIterator_mutations_2.html]
 [test_NodeIterator_mutations_3.html]
 [test_XHR.html]
 [test_XHRDocURI.html]
 [test_XHRResponseURL.html]
--- a/dom/base/test/moz.build
+++ b/dom/base/test/moz.build
@@ -5,39 +5,34 @@
 # file, You can obtain one at http://mozilla.org/MPL/2.0/.
 
 XPCSHELL_TESTS_MANIFESTS += [
     'unit/xpcshell.ini',
     'unit_ipc/xpcshell.ini',
 ]
 
 GeckoCppUnitTests([
-    'TestCSPParser',
     'TestGetURL',
     'TestNativeXMLHttpRequest',
     'TestPlainTextSerializer',
 ])
 
 MOCHITEST_MANIFESTS += [
     'chrome/mochitest.ini',
-    'csp/mochitest.ini',
-    'mixedcontentblocker/mochitest.ini',
     'mochitest.ini',
     'websocket_hybi/mochitest.ini',
 ]
 # OOP tests don't work on Windows (bug 763081) or native-fennec
 # (see Bug 774939). App permission checks are also disabled on
 # anything but B2G (Bug 900707).
 if CONFIG['MOZ_CHILD_PERMISSIONS']:
     MOCHITEST_MANIFESTS += [
         'mochitest-child-permissions.ini',
     ]
 
 MOCHITEST_CHROME_MANIFESTS += [
     'chrome.ini',
     'chrome/chrome.ini',
-    'csp/chrome.ini',
 ]
 
 BROWSER_CHROME_MANIFESTS += [
     'browser.ini',
-    'csp/browser.ini',
 ]
--- a/dom/base/test/test_warning_for_blocked_cross_site_request.html
+++ b/dom/base/test/test_warning_for_blocked_cross_site_request.html
@@ -8,17 +8,17 @@ https://bugzilla.mozilla.org/show_bug.cg
   <title>Test for Bug 713980</title>
   <script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
   <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
 
   <!-- Load a cross-origin webfont without CORS (common pain point -->
   <style>
     @font-face {
       font-family: "bad_cross_origin_webfont";
-      src: url('http://example.org/tests/dom/base/test/csp/file_CSP.sjs?testid=font_bad&type=application/octet-stream');
+      src: url('http://example.org/tests/dom/security/test/csp/file_CSP.sjs?testid=font_bad&type=application/octet-stream');
     }
     div#bad_webfont { font-family: "bad_cross_origin_webfont"; }
   </style>
 </head>
 <body>
 <pre id="test">
 
 <script class="testbody" type="text/javascript">
@@ -71,17 +71,17 @@ SpecialPowers.registerConsoleListener(fu
 
 function cleanup() {
   SpecialPowers.postConsoleSentinel();
   SimpleTest.finish();
 }
 
 // Send a cross-origin XHR request without CORS
 var xhr = new XMLHttpRequest();
-xhr.open("GET", "http://example.org/tests/dom/base/test/file_CrossSiteXHR_server.sjs?allowOrigin=http://invalid", true);
+xhr.open("GET", "http://example.org/tests/dom/security/test/cors/file_CrossSiteXHR_server.sjs?allowOrigin=http://invalid", true);
 xhr.send(null);
 
 // Create a div that triggers a cross-origin webfont request
 // We do this in Javascript in order to guarantee the console listener has
 // already been registered; otherwise, there could be a race.
 var badDiv = document.createElement('div');
 badDiv.setAttribute('id', 'bad_webfont');
 document.body.appendChild(badDiv);
--- a/dom/base/test/unit/xpcshell.ini
+++ b/dom/base/test/unit/xpcshell.ini
@@ -18,18 +18,16 @@ support-files =
   4_result_2.xml
   4_result_3.xml
   4_result_4.xml
   4_result_5.xml
   4_result_6.xml
 
 [test_bug553888.js]
 [test_bug737966.js]
-[test_cspreports.js]
-skip-if = buildapp == 'mulet'
 [test_error_codes.js]
 run-sequentially = Hardcoded 4444 port.
 # Bug 1018414: hardcoded localhost doesn't work properly on some OS X installs
 skip-if = os == 'mac'
 [test_thirdpartyutil.js]
 [test_xhr_document.js]
 [test_xhr_standalone.js]
 [test_xmlserializer.js]
--- a/dom/bindings/Codegen.py
+++ b/dom/bindings/Codegen.py
@@ -10984,17 +10984,17 @@ class CGDOMJSProxyHandler_getElements(Cl
         # we have all properties from 0 to length.  If that ever changes
         # (unlikely), we'll need to do something a bit more clever with how we
         # forward on to our ancestor.
 
         templateValues = {
             'jsvalRef': 'temp',
             'jsvalHandle': '&temp',
             'obj': 'proxy',
-            'successCode': ("adder->append(cx, temp);\n"
+            'successCode': ("if (!adder->append(cx, temp)) return false;\n"
                             "continue;\n")
         }
         get = CGProxyIndexedGetter(self.descriptor, templateValues, False, False).define()
 
         return fill(
             """
             JS::Rooted<JS::Value> temp(cx);
             MOZ_ASSERT(!xpc::WrapperFactory::IsXrayWrapper(proxy),
--- a/dom/browser-element/BrowserElementChildPreload.js
+++ b/dom/browser-element/BrowserElementChildPreload.js
@@ -139,18 +139,18 @@ BrowserElementChild.prototype = {
                      /* useCapture = */ true,
                      /* wantsUntrusted = */ false);
 
     addEventListener('MozScrolledAreaChanged',
                      this._mozScrollAreaChanged.bind(this),
                      /* useCapture = */ true,
                      /* wantsUntrusted = */ false);
 
-    addEventListener("MozDOMFullscreen:Entered",
-                     this._mozEnteredDomFullscreen.bind(this),
+    addEventListener("MozDOMFullscreen:Request",
+                     this._mozRequestedDOMFullscreen.bind(this),
                      /* useCapture = */ true,
                      /* wantsUntrusted = */ false);
 
     addEventListener("MozDOMFullscreen:NewOrigin",
                      this._mozFullscreenOriginChange.bind(this),
                      /* useCapture = */ true,
                      /* wantsUntrusted = */ false);
 
@@ -219,16 +219,17 @@ BrowserElementChild.prototype = {
       "go-back": this._recvGoBack,
       "go-forward": this._recvGoForward,
       "reload": this._recvReload,
       "stop": this._recvStop,
       "zoom": this._recvZoom,
       "unblock-modal-prompt": this._recvStopWaiting,
       "fire-ctx-callback": this._recvFireCtxCallback,
       "owner-visibility-change": this._recvOwnerVisibilityChange,
+      "entered-fullscreen": this._recvEnteredFullscreen,
       "exit-fullscreen": this._recvExitFullscreen.bind(this),
       "activate-next-paint-listener": this._activateNextPaintListener.bind(this),
       "set-input-method-active": this._recvSetInputMethodActive.bind(this),
       "deactivate-next-paint-listener": this._deactivateNextPaintListener.bind(this),
       "do-command": this._recvDoCommand
     }
 
     addMessageListener("browser-element-api:call", function(aMessage) {
@@ -286,16 +287,22 @@ BrowserElementChild.prototype = {
    */
   _unloadHandler: function() {
     this._shuttingDown = true;
     OBSERVED_EVENTS.forEach((aTopic) => {
       Services.obs.removeObserver(this, aTopic);
     });
   },
 
+  get _windowUtils() {
+    return content.document.defaultView
+                  .QueryInterface(Ci.nsIInterfaceRequestor)
+                  .getInterface(Ci.nsIDOMWindowUtils);
+  },
+
   _tryGetInnerWindowID: function(win) {
     let utils = win.QueryInterface(Ci.nsIInterfaceRequestor)
                    .getInterface(Ci.nsIDOMWindowUtils);
     try {
       return utils.currentInnerWindowID;
     }
     catch(e) {
       return null;
@@ -429,21 +436,28 @@ BrowserElementChild.prototype = {
       return;
     }
 
     debug("recvStopWaiting " + win);
     win.modalReturnValue = returnValue;
     win.modalDepth--;
   },
 
+  _recvEnteredFullscreen: function() {
+    if (!this._windowUtils.handleFullscreenRequests() &&
+        !content.document.mozFullScreen) {
+      // If we don't actually have any pending fullscreen request
+      // to handle, neither we have been in fullscreen, tell the
+      // parent to just exit.
+      sendAsyncMsg("exited-dom-fullscreen");
+    }
+  },
+
   _recvExitFullscreen: function() {
-    var utils = content.document.defaultView
-                       .QueryInterface(Ci.nsIInterfaceRequestor)
-                       .getInterface(Ci.nsIDOMWindowUtils);
-    utils.exitFullscreen();
+    this._windowUtils.exitFullscreen();
   },
 
   _titleChangedHandler: function(e) {
     debug("Got titlechanged: (" + e.target.title + ")");
     var win = e.target.defaultView;
 
     // Ignore titlechanges which don't come from the top-level
     // <iframe mozbrowser> window.
@@ -965,18 +979,18 @@ BrowserElementChild.prototype = {
   _mozScrollAreaChanged: function(e) {
     let dimensions = this._getContentDimensions();
     sendAsyncMsg('scrollareachanged', {
       width: dimensions.width,
       height: dimensions.height
     });
   },
 
-  _mozEnteredDomFullscreen: function(e) {
-    sendAsyncMsg("entered-dom-fullscreen");
+  _mozRequestedDOMFullscreen: function(e) {
+    sendAsyncMsg("requested-dom-fullscreen");
   },
 
   _mozFullscreenOriginChange: function(e) {
     sendAsyncMsg("fullscreen-origin-change", {
       originNoSuffix: e.target.nodePrincipal.originNoSuffix
     });
   },
 
@@ -1419,16 +1433,22 @@ BrowserElementChild.prototype = {
         stateDesc = 'secure';
       }
       else if (state & Ci.nsIWebProgressListener.STATE_IS_BROKEN) {
         stateDesc = 'broken';
       }
       else if (state & Ci.nsIWebProgressListener.STATE_IS_INSECURE) {
         stateDesc = 'insecure';
       }
+      else if (state & Ci.nsIWebProgressListener.STATE_LOADED_TRACKING_CONTENT) {
+        stateDesc = 'loaded_tracking_content';
+      }
+      else if (state & Ci.nsIWebProgressListener.STATE_BLOCKED_TRACKING_CONTENT) {
+        stateDesc = 'blocked_tracking_content';
+      }
       else {
         debug("Unexpected securitychange state!");
         stateDesc = '???';
       }
 
       var isEV = !!(state & Ci.nsIWebProgressListener.STATE_IDENTITY_EV_TOPLEVEL);
 
       sendAsyncMsg('securitychange', { state: stateDesc, extendedValidation: isEV });
--- a/dom/browser-element/BrowserElementParent.js
+++ b/dom/browser-element/BrowserElementParent.js
@@ -79,16 +79,17 @@ function defineDOMRequestMethod(msgName)
 function BrowserElementParent() {
   debug("Creating new BrowserElementParent object");
   this._domRequestCounter = 0;
   this._domRequestReady = false;
   this._pendingAPICalls = [];
   this._pendingDOMRequests = {};
   this._pendingSetInputMethodActive = [];
   this._nextPaintListeners = [];
+  this._pendingDOMFullscreen = false;
 
   Services.obs.addObserver(this, 'oop-frameloader-crashed', /* ownsWeak = */ true);
   Services.obs.addObserver(this, 'copypaste-docommand', /* ownsWeak = */ true);
   Services.obs.addObserver(this, 'ask-children-to-execute-copypaste-command', /* ownsWeak = */ true);
 }
 
 BrowserElementParent.prototype = {
 
@@ -191,17 +192,17 @@ BrowserElementParent.prototype = {
       "firstpaint": this._fireProfiledEventFromMsg,
       "documentfirstpaint": this._fireProfiledEventFromMsg,
       "nextpaint": this._recvNextPaint,
       "got-purge-history": this._gotDOMRequestResult,
       "got-screenshot": this._gotDOMRequestResult,
       "got-contentdimensions": this._gotDOMRequestResult,
       "got-can-go-back": this._gotDOMRequestResult,
       "got-can-go-forward": this._gotDOMRequestResult,
-      "entered-dom-fullscreen": this._enteredDomFullscreen,
+      "requested-dom-fullscreen": this._requestedDOMFullscreen,
       "fullscreen-origin-change": this._fullscreenOriginChange,
       "exited-dom-fullscreen": this._exitedDomFullscreen,
       "got-visible": this._gotDOMRequestResult,
       "visibilitychange": this._childVisibilityChange,
       "got-set-input-method-active": this._gotDOMRequestResult,
       "selectionstatechanged": this._handleSelectionStateChanged,
       "scrollviewchange": this._handleScrollViewChange,
       "caretstatechanged": this._handleCaretStateChanged,
@@ -965,33 +966,37 @@ BrowserElementParent.prototype = {
    */
   _childVisibilityChange: function(data) {
     debug("_childVisibilityChange(" + data.json.visible + ")");
     this._frameLoader.visible = data.json.visible;
 
     this._fireEventFromMsg(data);
   },
 
-  _enteredDomFullscreen: function() {
+  _requestedDOMFullscreen: function() {
+    this._pendingDOMFullscreen = true;
     this._windowUtils.remoteFrameFullscreenChanged(this._frameElement);
   },
 
   _fullscreenOriginChange: function(data) {
     Services.obs.notifyObservers(
       this._frameElement, "fullscreen-origin-change", data.json.originNoSuffix);
   },
 
   _exitedDomFullscreen: function(data) {
     this._windowUtils.remoteFrameFullscreenReverted();
   },
 
   _fullscreenChange: function(evt) {
     if (this._isAlive() && evt.target == this._window.document) {
       if (!this._window.document.mozFullScreen) {
         this._sendAsyncMsg("exit-fullscreen");
+      } else if (this._pendingDOMFullscreen) {
+        this._pendingDOMFullscreen = false;
+        this._sendAsyncMsg("entered-fullscreen");
       }
     }
   },
 
   _fireFatalError: function() {
     let evt = this._createEvent('error', {type: 'fatal'},
                                 /* cancelable = */ false);
     this._frameElement.dispatchEvent(evt);
--- a/dom/cache/Context.cpp
+++ b/dom/cache/Context.cpp
@@ -107,24 +107,28 @@ public:
     MOZ_ASSERT(!mConnection);
     mConnection = aConn;
     MOZ_ASSERT(mConnection);
   }
 
 private:
   ~Data()
   {
-    if (mConnection) {
-      NS_ProxyRelease(mTarget, mConnection);
-    }
+    // We could proxy release our data here, but instead just assert.  The
+    // Context code should guarantee that we are destroyed on the target
+    // thread.  If we're not, then QuotaManager might race and try to clear the
+    // origin out from under us.
+    MOZ_ASSERT(mTarget == NS_GetCurrentThread());
   }
 
   nsCOMPtr<nsIThread> mTarget;
   nsCOMPtr<mozIStorageConnection> mConnection;
 
+  // Threadsafe counting because we're created on the PBackground thread
+  // and destroyed on the target IO thread.
   NS_INLINE_DECL_THREADSAFE_REFCOUNTING(Context::Data)
 };
 
 // Executed to perform the complicated dance of steps necessary to initialize
 // the QuotaManager.  This must be performed for each origin before any disk
 // IO occurrs.
 class Context::QuotaInitRunnable final : public nsIRunnable
 {
@@ -416,16 +420,18 @@ Context::QuotaInitRunnable::Run()
 
       mState = STATE_RUNNING;
 
       // Execute the provided initialization Action.  The Action must Resolve()
       // before returning.
       mInitAction->RunOnTarget(resolver, mQuotaInfo, mData);
       MOZ_ASSERT(resolver->Resolved());
 
+      mData = nullptr;
+
       break;
     }
     // -------------------
     case STATE_COMPLETING:
     {
       NS_ASSERT_OWNINGTHREAD(QuotaInitRunnable);
       if (mInitAction) {
         mInitAction->CompleteOnInitiatingThread(mResult);
@@ -910,16 +916,17 @@ Context::CancelForCacheId(CacheId aCache
     }
   }
 }
 
 Context::~Context()
 {
   NS_ASSERT_OWNINGTHREAD(Context);
   MOZ_ASSERT(mManager);
+  MOZ_ASSERT(!mData);
 
   if (mThreadsafeHandle) {
     mThreadsafeHandle->ContextDestroyed(this);
   }
 
   mManager->RemoveContext(this);
 
   if (mNextContext) {
--- a/dom/canvas/WebGLContextState.cpp
+++ b/dom/canvas/WebGLContextState.cpp
@@ -421,25 +421,27 @@ WebGLContext::GetParameter(JSContext* cx
             if (!IsWebGL2()) {
                 break;
             }
             return JS::Int32Value(mGLMaxTransformFeedbackSeparateAttribs);
         }
 
         // unsigned int. here we may have to return very large values like 2^32-1 that can't be represented as
         // javascript integer values. We just return them as doubles and javascript doesn't care.
-        case LOCAL_GL_STENCIL_BACK_VALUE_MASK:
-        case LOCAL_GL_STENCIL_BACK_WRITEMASK:
-        case LOCAL_GL_STENCIL_VALUE_MASK:
+        case LOCAL_GL_STENCIL_BACK_VALUE_MASK: {
+            return JS::DoubleValue(mStencilValueMaskBack); // pass as FP value to allow large values such as 2^32-1.
+        }
+        case LOCAL_GL_STENCIL_BACK_WRITEMASK: {
+            return JS::DoubleValue(mStencilWriteMaskBack);
+        }
+        case LOCAL_GL_STENCIL_VALUE_MASK: {
+            return JS::DoubleValue(mStencilValueMaskFront);
+        }
         case LOCAL_GL_STENCIL_WRITEMASK: {
-            GLint i = 0; // the GL api (glGetIntegerv) only does signed ints
-            gl->fGetIntegerv(pname, &i);
-            GLuint i_unsigned(i); // this is where -1 becomes 2^32-1
-            double i_double(i_unsigned); // pass as FP value to allow large values such as 2^32-1.
-            return JS::DoubleValue(i_double);
+            return JS::DoubleValue(mStencilWriteMaskFront);
         }
 
         // float
         case LOCAL_GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT: {
             if (IsExtensionEnabled(WebGLExtensionID::EXT_texture_filter_anisotropic)) {
                 GLfloat f = 0.f;
                 gl->fGetFloatv(pname, &f);
                 return JS::DoubleValue(f);
--- a/dom/canvas/WebGLContextUtils.cpp
+++ b/dom/canvas/WebGLContextUtils.cpp
@@ -1193,22 +1193,21 @@ WebGLContext::AssertCachedState()
     }
 
     // GLES 3.0.4, $4.1.4, p177:
     //   [...] the front and back stencil mask are both set to the value `2^s - 1`, where
     //   `s` is greater than or equal to the number of bits in the deepest stencil buffer
     //   supported by the GL implementation.
     const int maxStencilBits = 8;
     const GLuint maxStencilBitsMask = (1 << maxStencilBits) - 1;
-
     AssertMaskedUintParamCorrect(gl, LOCAL_GL_STENCIL_VALUE_MASK,      maxStencilBitsMask, mStencilValueMaskFront);
     AssertMaskedUintParamCorrect(gl, LOCAL_GL_STENCIL_BACK_VALUE_MASK, maxStencilBitsMask, mStencilValueMaskBack);
 
-    AssertUintParamCorrect(gl, LOCAL_GL_STENCIL_WRITEMASK,      mStencilWriteMaskFront);
-    AssertUintParamCorrect(gl, LOCAL_GL_STENCIL_BACK_WRITEMASK, mStencilWriteMaskBack);
+    AssertMaskedUintParamCorrect(gl, LOCAL_GL_STENCIL_WRITEMASK,       maxStencilBitsMask, mStencilWriteMaskFront);
+    AssertMaskedUintParamCorrect(gl, LOCAL_GL_STENCIL_BACK_WRITEMASK,  maxStencilBitsMask, mStencilWriteMaskBack);
 
     // Viewport
     GLint int4[4] = {0, 0, 0, 0};
     gl->fGetIntegerv(LOCAL_GL_VIEWPORT, int4);
     MOZ_ASSERT(int4[0] == mViewportX &&
                int4[1] == mViewportY &&
                int4[2] == mViewportWidth &&
                int4[3] == mViewportHeight);
--- a/dom/devicestorage/DeviceStorageRequestChild.cpp
+++ b/dom/devicestorage/DeviceStorageRequestChild.cpp
@@ -188,21 +188,22 @@ DeviceStorageRequestChild::
 
     case DeviceStorageResponseValue::TEnumerationResponse:
     {
       EnumerationResponse r = aValue;
       nsDOMDeviceStorageCursor* cursor
         = static_cast<nsDOMDeviceStorageCursor*>(mRequest.get());
 
       uint32_t count = r.paths().Length();
+      cursor->mFiles.SetCapacity(count);
       for (uint32_t i = 0; i < count; i++) {
         nsRefPtr<DeviceStorageFile> dsf
           = new DeviceStorageFile(r.type(), r.paths()[i].storageName(),
                                   r.rootdir(), r.paths()[i].name());
-        cursor->mFiles.AppendElement(dsf);
+        cursor->mFiles.AppendElement(dsf.forget());
       }
 
       nsRefPtr<ContinueCursorEvent> event = new ContinueCursorEvent(cursor);
       event->Continue();
       break;
     }
 
     default:
--- a/dom/devicestorage/nsDeviceStorage.cpp
+++ b/dom/devicestorage/nsDeviceStorage.cpp
@@ -1456,16 +1456,20 @@ DeviceStorageFile::collectFilesInternal(
 
   nsCOMPtr<nsISimpleEnumerator> e;
   mFile->GetDirectoryEntries(getter_AddRefs(e));
 
   if (!e) {
     return;
   }
 
+  DeviceStorageTypeChecker* typeChecker
+    = DeviceStorageTypeChecker::CreateOrGet();
+  MOZ_ASSERT(typeChecker);
+
   nsCOMPtr<nsIDirectoryEnumerator> files = do_QueryInterface(e);
   nsCOMPtr<nsIFile> f;
 
   while (NS_SUCCEEDED(files->GetNextFile(getter_AddRefs(f))) && f) {
 
     bool isFile;
     f->IsFile(&isFile);
 
@@ -1482,16 +1486,20 @@ DeviceStorageFile::collectFilesInternal(
     f->IsDirectory(&isDir);
 
     nsString fullpath;
     nsresult rv = f->GetPath(fullpath);
     if (NS_FAILED(rv)) {
       continue;
     }
 
+    if (isFile && !typeChecker->Check(mStorageType, fullpath)) {
+      continue;
+    }
+
     if (!StringBeginsWith(fullpath, aRootPath)) {
       NS_ERROR("collectFiles returned a path that does not belong!");
       continue;
     }
 
     nsAString::size_type len = aRootPath.Length() + 1; // +1 for the trailing /
     nsDependentSubstring newPath = Substring(fullpath, len);
 
@@ -2028,31 +2036,23 @@ ContinueCursorEvent::GetNextFile()
 {
   MOZ_ASSERT(NS_IsMainThread());
 
   nsDOMDeviceStorageCursor* cursor
     = static_cast<nsDOMDeviceStorageCursor*>(mRequest.get());
   nsString cursorStorageType;
   cursor->GetStorageType(cursorStorageType);
 
-  DeviceStorageTypeChecker* typeChecker
-    = DeviceStorageTypeChecker::CreateOrGet();
-  if (!typeChecker) {
-    return nullptr;
-  }
-
-  while (cursor->mFiles.Length() > 0) {
-    nsRefPtr<DeviceStorageFile> file = cursor->mFiles[0];
-    cursor->mFiles.RemoveElementAt(0);
-    if (!typeChecker->Check(cursorStorageType, file->mFile)) {
-      continue;
+  while (cursor->mIndex < cursor->mFiles.Length()) {
+    nsRefPtr<DeviceStorageFile> file = cursor->mFiles[cursor->mIndex].forget();
+    ++cursor->mIndex;
+    if (file) {
+      file->CalculateMimeType();
+      return file.forget();
     }
-
-    file->CalculateMimeType();
-    return file.forget();
   }
 
   return nullptr;
 }
 
 ContinueCursorEvent::~ContinueCursorEvent() {}
 
 void
@@ -2167,16 +2167,17 @@ NS_IMPL_RELEASE_INHERITED(nsDOMDeviceSto
 
 nsDOMDeviceStorageCursor::nsDOMDeviceStorageCursor(nsPIDOMWindow* aWindow,
                                                    nsIPrincipal* aPrincipal,
                                                    DeviceStorageFile* aFile,
                                                    PRTime aSince)
   : DOMCursor(aWindow, nullptr)
   , mOkToCallContinue(false)
   , mSince(aSince)
+  , mIndex(0)
   , mFile(aFile)
   , mPrincipal(aPrincipal)
   , mRequester(new nsContentPermissionRequester(GetOwner()))
 {
 }
 
 nsDOMDeviceStorageCursor::~nsDOMDeviceStorageCursor()
 {
--- a/dom/devicestorage/nsDeviceStorage.h
+++ b/dom/devicestorage/nsDeviceStorage.h
@@ -211,16 +211,17 @@ public:
                            nsIPrincipal* aPrincipal,
                            DeviceStorageFile* aFile,
                            PRTime aSince);
 
 
   nsTArray<nsRefPtr<DeviceStorageFile> > mFiles;
   bool mOkToCallContinue;
   PRTime mSince;
+  size_t mIndex;
 
   void GetStorageType(nsAString & aType);
 
   void RequestComplete() override;
 
 private:
   ~nsDOMDeviceStorageCursor();
 
--- a/dom/devicestorage/test/mochitest.ini
+++ b/dom/devicestorage/test/mochitest.ini
@@ -20,17 +20,17 @@ support-files = devicestorage_common.js
 [test_lastModificationFilter.html]
 [test_overrideDir.html]
 [test_overwrite.html]
 [test_sanity.html]
 [test_usedSpace.html]
 [test_watch.html]
 [test_watchOther.html]
 [test_storageAreaListener.html]
-skip-if = toolkit != 'gonk'
+skip-if = (toolkit != 'gonk') || (toolkit == 'gonk' && debug) # Bug 1173484
 
 # FileSystem API tests
 [test_fs_basic.html]
 [test_fs_createDirectory.html]
 [test_fs_get.html]
 [test_fs_remove.html]
 [test_fs_createFile.html]
 [test_fs_appendFile.html]
--- a/dom/fetch/Fetch.cpp
+++ b/dom/fetch/Fetch.cpp
@@ -543,23 +543,36 @@ ExtractFromURLSearchParams(const URLSear
                            nsCString& aContentType)
 {
   nsAutoString serialized;
   aParams.Stringify(serialized);
   aContentType = NS_LITERAL_CSTRING("application/x-www-form-urlencoded;charset=UTF-8");
   return NS_NewStringInputStream(aStream, serialized);
 }
 
-void
-FillFormData(const nsString& aName, const nsString& aValue, void* aFormData)
+class MOZ_STACK_CLASS FillFormIterator final
+  : public URLSearchParams::ForEachIterator
 {
-  MOZ_ASSERT(aFormData);
-  nsFormData* fd = static_cast<nsFormData*>(aFormData);
-  fd->Append(aName, aValue);
-}
+public:
+  explicit FillFormIterator(nsFormData* aFormData)
+    : mFormData(aFormData)
+  {
+    MOZ_ASSERT(aFormData);
+  }
+
+  bool URLSearchParamsIterator(const nsString& aName,
+                               const nsString& aValue) override
+  {
+    mFormData->Append(aName, aValue);
+    return true;
+  }
+
+private:
+  nsFormData* mFormData;
+};
 
 /**
  * A simple multipart/form-data parser as defined in RFC 2388 and RFC 2046.
  * This does not respect any encoding specified per entry, using UTF-8
  * throughout. This is as the Fetch spec states in the consume body algorithm.
  * Borrows some things from Necko's nsMultiMixedConv, but is simpler since
  * unlike Necko we do not have to deal with receiving incomplete chunks of data.
  *
@@ -1586,17 +1599,20 @@ FetchBody<Derived>::ContinueConsumeBody(
           isValidUrlEncodedMimeType = mMimeType[urlDataMimeType.Length()] == ';';
         }
 
         if (isValidUrlEncodedMimeType) {
           nsRefPtr<URLSearchParams> params = new URLSearchParams();
           params->ParseInput(data, /* aObserver */ nullptr);
 
           nsRefPtr<nsFormData> fd = new nsFormData(DerivedClass()->GetParentObject());
-          params->ForEach(FillFormData, static_cast<void*>(fd));
+          FillFormIterator iterator(fd);
+          DebugOnly<bool> status = params->ForEach(iterator);
+          MOZ_ASSERT(status);
+
           localPromise->MaybeResolve(fd);
         } else {
           ErrorResult result;
           result.ThrowTypeError(MSG_BAD_FORMDATA);
           localPromise->MaybeReject(result);
         }
       }
       return;
--- a/dom/icc/gonk/IccService.js
+++ b/dom/icc/gonk/IccService.js
@@ -134,16 +134,21 @@ IccService.prototype = {
    */
   notifyStkCommand: function(aServiceId, aStkcommand) {
     if (DEBUG) {
       debug("notifyStkCommand for service Id: " + aServiceId);
     }
 
     let icc = this.getIccByServiceId(aServiceId);
 
+    if (!icc.iccInfo || !icc.iccInfo.iccid) {
+      debug("Warning: got STK command when iccid is invalid.");
+      return;
+    }
+
     gIccMessenger.notifyStkProactiveCommand(icc.iccInfo.iccid, aStkcommand);
 
     icc._deliverListenerEvent("notifyStkCommand", [aStkcommand]);
   },
 
   notifyStkSessionEnd: function(aServiceId) {
     if (DEBUG) {
       debug("notifyStkSessionEnd for service Id: " + aServiceId);
--- a/dom/interfaces/base/nsIDOMWindowUtils.idl
+++ b/dom/interfaces/base/nsIDOMWindowUtils.idl
@@ -44,17 +44,17 @@ interface nsIDOMClientRect;
 interface nsIURI;
 interface nsIDOMEventTarget;
 interface nsIRunnable;
 interface nsITranslationNodeList;
 interface nsIJSRAIIHelper;
 interface nsIContentPermissionRequest;
 interface nsIObserver;
 
-[scriptable, uuid(ec176f3b-2886-4090-938e-dded103c5f1c)]
+[scriptable, uuid(a01d5bb4-3e81-4529-b139-2f4ebb78f717)]
 interface nsIDOMWindowUtils : nsISupports {
 
   /**
    * Image animation mode of the window. When this attribute's value
    * is changed, the implementation should set all images in the window
    * to the given value. That is, when set to kDontAnimMode, all images
    * will stop animating. The attribute's value must be one of the
    * animationMode values from imgIContainer.
@@ -1189,16 +1189,25 @@ interface nsIDOMWindowUtils : nsISupport
 
   /**
    * Called when the remote frame has popped all fullscreen elements off its
    * stack, so that the operation can complete on the parent side.
    */
   void remoteFrameFullscreenReverted();
 
   /**
+   * Calls the document to handle any pending fullscreen requests.
+   * It is called when the parent document has entered fullscreen, and
+   * we want to put the current document into fullscreen as well.
+   * The return value indicates whether there is any fullscreen request
+   * handled by this call.
+   */
+  boolean handleFullscreenRequests();
+
+  /**
    * Called when the child frame has fully exit fullscreen, so that the parent
    * process can also fully exit.
    */
   void exitFullscreen();
 
   /**
    * If sendQueryContentEvent()'s aAdditionalFlags argument is
    * SELECTION_SET_FLAG_USE_NATIVE_LINE_BREAK, aOffset and aLength are offset
--- a/dom/interfaces/base/nsIServiceWorkerManager.idl
+++ b/dom/interfaces/base/nsIServiceWorkerManager.idl
@@ -28,17 +28,17 @@ interface nsIServiceWorkerInfo : nsISupp
   readonly attribute DOMString scope;
   readonly attribute DOMString scriptSpec;
   readonly attribute DOMString currentWorkerURL;
 
   readonly attribute DOMString activeCacheName;
   readonly attribute DOMString waitingCacheName;
 };
 
-[scriptable, builtinclass, uuid(d130fcbd-1afe-4dd9-b70d-08a4b2373af5)]
+[scriptable, builtinclass, uuid(5e112a42-df4c-4ae9-bc71-e6e681ab5f38)]
 interface nsIServiceWorkerManager : nsISupports
 {
   /**
    * Registers a ServiceWorker with script loaded from `aScriptURI` to act as
    * the ServiceWorker for aScope.  Requires a valid entry settings object on
    * the stack. This means you must call this from content code 'within'
    * a window.
    *
@@ -92,23 +92,16 @@ interface nsIServiceWorkerManager : nsIS
   [noscript] nsISupports GetActive(in nsIDOMWindow aWindow, in DOMString aScope);
 
   /*
    * Returns a ServiceWorker.
    */
   [noscript] nsISupports GetDocumentController(in nsIDOMWindow aWindow);
 
   /*
-   * This implements the soft update algorithm.
-   * XXXbaku this can be removed when bug 1155153 lands.
-   */
-  [implicit_jscontext] void softUpdate(in jsval aOriginAttributes,
-                                       in DOMString aScope);
-
-  /*
    * Clears ServiceWorker registrations from memory and disk for the specified
    * host.
    * - All ServiceWorker instances change their state to redundant.
    * - Existing ServiceWorker instances handling fetches will keep running.
    * - All documents will immediately stop being controlled.
    * - Unregister jobs will be queued for all registrations.
    *   This eventually results in the registration being deleted from disk too.
    */
@@ -117,20 +110,32 @@ interface nsIServiceWorkerManager : nsIS
   /*
    * Clear all registrations for all hosts. See remove().
    */
   void removeAll();
 
   // Testing
   DOMString getScopeForUrl(in nsIPrincipal aPrincipal, in DOMString aPath);
 
-  // This is meant to be used only by about:serviceworkers. It returns an array
-  // of nsIServiceWorkerInfo.
+  // Note: This is meant to be used only by about:serviceworkers.
+  //It returns an array of nsIServiceWorkerInfo.
   nsIArray getAllRegistrations();
 
+  // Note: This is meant to be used only by about:serviceworkers.
+  // It calls softUpdate() for each child process.
+  [implicit_jscontext] void propagateSoftUpdate(in jsval aOriginAttributes,
+                                                in DOMString aScope);
+
+  // Note: This is meant to be used only by about:serviceworkers.
+  // It calls unregister() in each child process. The callback is used to
+  // inform when unregister() is completed on the current process.
+  void propagateUnregister(in nsIPrincipal aPrincipal,
+                           in nsIServiceWorkerUnregisterCallback aCallback,
+                           in DOMString aScope);
+
   [implicit_jscontext] void sendPushEvent(in jsval aOriginAttributes,
                                           in ACString aScope,
                                           in DOMString aData);
   [implicit_jscontext] void sendPushSubscriptionChangeEvent(in jsval aOriginAttributes,
                                                             in ACString scope);
 
   void updateAllRegistrations();
 };
--- a/dom/ipc/PBrowser.ipdl
+++ b/dom/ipc/PBrowser.ipdl
@@ -20,17 +20,16 @@ include JavaScriptTypes;
 include URIParams;
 include BrowserConfiguration;
 
 
 using class IPC::Principal from "mozilla/dom/PermissionMessageUtils.h";
 using class mozilla::gfx::Matrix from "mozilla/gfx/Matrix.h";
 using struct gfxSize from "gfxPoint.h";
 using CSSRect from "Units.h";
-using CSSSize from "Units.h";
 using LayoutDeviceIntRect from "Units.h";
 using mozilla::LayoutDeviceIntPoint from "Units.h";
 using ScreenIntSize from "Units.h";
 using struct mozilla::layers::FrameMetrics from "FrameMetrics.h";
 using struct mozilla::layers::ScrollableLayerGuid from "FrameMetrics.h";
 using struct mozilla::layers::ZoomConstraints from "FrameMetrics.h";
 using FrameMetrics::ViewID from "FrameMetrics.h";
 using struct mozilla::void_t from "ipc/IPCMessageUtils.h";
@@ -544,17 +543,17 @@ child:
          uint64_t layersId,
          nullable PRenderFrame renderFrame,
          bool parentIsActive);
 
     LoadURL(nsCString uri, BrowserConfiguration config);
 
     CacheFileDescriptor(nsString path, FileDescriptor fd);
 
-    UpdateDimensions(CSSRect rect, CSSSize size, ScreenOrientation orientation,
+    UpdateDimensions(IntRect rect, ScreenIntSize size, ScreenOrientation orientation,
                      LayoutDeviceIntPoint chromeDisp) compressall;
 
     UpdateFrame(FrameMetrics frame);
 
     // The following methods correspond to functions on the GeckoContentController
     // interface in gfx/layers/apz/public/GeckoContentController.h. Refer to documentation
     // in that file for these functions.
     RequestFlingSnap(ViewID aScrollID, CSSPoint aDestination);
--- a/dom/ipc/TabChild.cpp
+++ b/dom/ipc/TabChild.cpp
@@ -87,17 +87,16 @@
 #include "nsDOMClassInfoID.h"
 #include "nsColorPickerProxy.h"
 #include "nsPresShell.h"
 #include "nsIAppsService.h"
 #include "nsNetUtil.h"
 #include "nsIPermissionManager.h"
 #include "nsIScriptError.h"
 #include "mozilla/EventForwards.h"
-#include "nsDeviceContext.h"
 
 #define BROWSER_ELEMENT_CHILD_SCRIPT \
     NS_LITERAL_STRING("chrome://global/content/BrowserElementChild.js")
 
 #define TABC_LOG(...)
 // #define TABC_LOG(...) printf_stderr("TABC: " __VA_ARGS__)
 
 using namespace mozilla;
@@ -161,16 +160,17 @@ UsingCompositorLRU()
 }
 
 NS_IMPL_ISUPPORTS(TabChild::DelayedFireContextMenuEvent,
                   nsITimerCallback)
 
 TabChildBase::TabChildBase()
   : mContentDocumentIsDisplayed(false)
   , mTabChildGlobal(nullptr)
+  , mInnerSize(0, 0)
 {
   mozilla::HoldJSObjects(this);
 }
 
 TabChildBase::~TabChildBase()
 {
   mAnonymousGlobalScopes.Clear();
   mozilla::DropJSObjects(this);
@@ -231,21 +231,19 @@ void
 TabChildBase::InitializeRootMetrics()
 {
   // Calculate a really simple resolution that we probably won't
   // be keeping, as well as putting the scroll offset back to
   // the top-left of the page.
   mLastRootMetrics.SetViewport(CSSRect(CSSPoint(), kDefaultViewportSize));
   mLastRootMetrics.SetCompositionBounds(ParentLayerRect(
       ParentLayerPoint(),
-      ParentLayerSize(
-        ViewAs<ParentLayerPixel>(GetInnerSize(),
-                                 PixelCastJustification::ScreenIsParentLayerForRoot))));
+      ParentLayerSize(ViewAs<ParentLayerPixel>(mInnerSize, PixelCastJustification::ScreenIsParentLayerForRoot))));
   mLastRootMetrics.SetZoom(CSSToParentLayerScale2D(
-      ConvertScaleForRoot(CalculateIntrinsicScale(GetInnerSize(), kDefaultViewportSize))));
+      ConvertScaleForRoot(CalculateIntrinsicScale(mInnerSize, kDefaultViewportSize))));
   mLastRootMetrics.SetDevPixelsPerCSSPixel(WebWidget()->GetDefaultScale());
   // We use ParentLayerToLayerScale(1) below in order to turn the
   // async zoom amount into the gecko zoom amount.
   mLastRootMetrics.SetCumulativeResolution(mLastRootMetrics.GetZoom() / mLastRootMetrics.GetDevPixelsPerCSSPixel() * ParentLayerToLayerScale(1));
   // This is the root layer, so the cumulative resolution is the same
   // as the resolution.
   mLastRootMetrics.SetPresShellResolution(mLastRootMetrics.GetCumulativeResolution().ToScaleFactor().scale);
   mLastRootMetrics.SetScrollOffset(CSSPoint(0, 0));
@@ -296,42 +294,42 @@ bool
 TabChildBase::HandlePossibleViewportChange(const ScreenIntSize& aOldScreenSize)
 {
   nsIWidget* widget = WebWidget();
   if (!widget || !widget->AsyncPanZoomEnabled()) {
     return false;
   }
 
   TABC_LOG("HandlePossibleViewportChange aOldScreenSize=%s mInnerSize=%s\n",
-    Stringify(aOldScreenSize).c_str(), Stringify(GetInnerSize()).c_str());
+    Stringify(aOldScreenSize).c_str(), Stringify(mInnerSize).c_str());
 
   nsCOMPtr<nsIDocument> document(GetDocument());
   if (!document) {
     return false;
   }
 
-  nsViewportInfo viewportInfo = nsContentUtils::GetViewportInfo(document, GetInnerSize());
+  nsViewportInfo viewportInfo = nsContentUtils::GetViewportInfo(document, mInnerSize);
   uint32_t presShellId = 0;
   mozilla::layers::FrameMetrics::ViewID viewId = FrameMetrics::NULL_SCROLL_ID;
   bool scrollIdentifiersValid = APZCCallbackHelper::GetOrCreateScrollIdentifiers(
         document->GetDocumentElement(), &presShellId, &viewId);
   if (scrollIdentifiersValid) {
     ZoomConstraints constraints(
       viewportInfo.IsZoomAllowed(),
       viewportInfo.IsDoubleTapZoomAllowed(),
       ConvertScaleForRoot(viewportInfo.GetMinZoom()),
       ConvertScaleForRoot(viewportInfo.GetMaxZoom()));
     DoUpdateZoomConstraints(presShellId,
                             viewId,
                             /* isRoot = */ true,
                             constraints);
   }
 
-  float screenW = GetInnerSize().width;
-  float screenH = GetInnerSize().height;
+  float screenW = mInnerSize.width;
+  float screenH = mInnerSize.height;
   CSSSize viewport(viewportInfo.GetSize());
 
   // We're not being displayed in any way; don't bother doing anything because
   // that will just confuse future adjustments.
   if (!screenW || !screenH) {
     return false;
   }
 
@@ -355,58 +353,56 @@ TabChildBase::HandlePossibleViewportChan
   // window.innerWidth before they are painted have a correct value (bug
   // 771575).
   if (!mContentDocumentIsDisplayed) {
     return false;
   }
 
   ScreenIntSize oldScreenSize = aOldScreenSize;
   if (oldScreenSize == ScreenIntSize()) {
-    oldScreenSize = GetInnerSize();
+    oldScreenSize = mInnerSize;
   }
 
   FrameMetrics metrics(mLastRootMetrics);
   metrics.SetViewport(CSSRect(CSSPoint(), viewport));
 
-  // Calculate the composition bounds based on the inner size, excluding the sizes
+  // Calculate the composition bounds based on mInnerSize, excluding the sizes
   // of the scrollbars if they are not overlay scrollbars.
-  ScreenSize compositionSize(GetInnerSize());
+  ScreenSize compositionSize(mInnerSize);
   nsCOMPtr<nsIPresShell> shell = GetPresShell();
   if (shell) {
     nsMargin scrollbarsAppUnits =
         nsLayoutUtils::ScrollbarAreaToExcludeFromCompositionBoundsFor(shell->GetRootScrollFrame());
     // Scrollbars are not subject to scaling, so CSS pixels = screen pixels for them.
     ScreenMargin scrollbars = CSSMargin::FromAppUnits(scrollbarsAppUnits)
                             * CSSToScreenScale(1.0f);
     compositionSize.width -= scrollbars.LeftRight();
     compositionSize.height -= scrollbars.TopBottom();
   }
 
   metrics.SetCompositionBounds(ParentLayerRect(
       ParentLayerPoint(),
-      ParentLayerSize(
-        ViewAs<ParentLayerPixel>(GetInnerSize(),
-                                 PixelCastJustification::ScreenIsParentLayerForRoot))));
+      ParentLayerSize(ViewAs<ParentLayerPixel>(compositionSize, PixelCastJustification::ScreenIsParentLayerForRoot))));
   metrics.SetRootCompositionSize(
       ScreenSize(compositionSize) * ScreenToLayoutDeviceScale(1.0f) / metrics.GetDevPixelsPerCSSPixel());
 
   // This change to the zoom accounts for all types of changes I can conceive:
   // 1. screen size changes, CSS viewport does not (pages with no meta viewport
   //    or a fixed size viewport)
   // 2. screen size changes, CSS viewport also does (pages with a device-width
   //    viewport)
   // 3. screen size remains constant, but CSS viewport changes (meta viewport
   //    tag is added or removed)
   // 4. neither screen size nor CSS viewport changes
   //
   // In all of these cases, we maintain how much actual content is visible
   // within the screen width. Note that "actual content" may be different with
   // respect to CSS pixels because of the CSS viewport size changing.
   CSSToScreenScale oldIntrinsicScale = CalculateIntrinsicScale(oldScreenSize, oldBrowserSize);
-  CSSToScreenScale newIntrinsicScale = CalculateIntrinsicScale(GetInnerSize(), viewport);
+  CSSToScreenScale newIntrinsicScale = CalculateIntrinsicScale(mInnerSize, viewport);
   metrics.ZoomBy(newIntrinsicScale.scale / oldIntrinsicScale.scale);
 
   // Changing the zoom when we're not doing a first paint will get ignored
   // by AsyncPanZoomController and causes a blurry flash.
   bool isFirstPaint = true;
   if (shell) {
     isFirstPaint = shell->GetIsFirstPaint();
   }
@@ -880,16 +876,17 @@ TabChild::TabChild(nsIContentChild* aMan
                    const TabId& aTabId,
                    const TabContext& aContext,
                    uint32_t aChromeFlags)
   : TabContext(aContext)
   , mRemoteFrame(nullptr)
   , mManager(aManager)
   , mChromeFlags(aChromeFlags)
   , mLayersId(0)
+  , mOuterRect(0, 0, 0, 0)
   , mActivePointerId(-1)
   , mAppPackageFileDescriptorRecved(false)
   , mLastBackgroundColor(NS_RGB(255, 255, 255))
   , mDidFakeShow(false)
   , mNotified(false)
   , mTriedBrowserInit(false)
   , mOrientation(eScreenOrientation_PortraitPrimary)
   , mUpdateHitRegion(false)
@@ -920,19 +917,19 @@ TabChild::TabChild(nsIContentChild* aMan
 NS_IMETHODIMP
 TabChild::HandleEvent(nsIDOMEvent* aEvent)
 {
   nsAutoString eventType;
   aEvent->GetType(eventType);
   if (eventType.EqualsLiteral("DOMMetaAdded")) {
     // This meta data may or may not have been a meta viewport tag. If it was,
     // we should handle it immediately.
-    HandlePossibleViewportChange(GetInnerSize());
+    HandlePossibleViewportChange(mInnerSize);
   } else if (eventType.EqualsLiteral("FullZoomChange")) {
-    HandlePossibleViewportChange(GetInnerSize());
+    HandlePossibleViewportChange(mInnerSize);
   }
 
   return NS_OK;
 }
 
 NS_IMETHODIMP
 TabChild::Observe(nsISupports *aSubject,
                   const char *aTopic,
@@ -964,24 +961,24 @@ TabChild::Observe(nsISupports *aSubject,
         if (shell) {
           shell->SetIsFirstPaint(true);
         }
 
         mContentDocumentIsDisplayed = true;
 
         // In some cases before-first-paint gets called before
         // RecvUpdateDimensions is called and therefore before we have an
-        // inner size value set. In such cases defer initializing the viewport
+        // mInnerSize value set. In such cases defer initializing the viewport
         // until we we get an inner size.
         if (HasValidInnerSize()) {
           InitializeRootMetrics();
           if (shell) {
             nsLayoutUtils::SetResolutionAndScaleTo(shell, mLastRootMetrics.GetPresShellResolution());
           }
-          HandlePossibleViewportChange(GetInnerSize());
+          HandlePossibleViewportChange(mInnerSize);
         }
       }
     }
   }
 
   return NS_OK;
 }
 
@@ -1311,28 +1308,27 @@ TabChild::SetDimensions(uint32_t aFlags,
 
   return NS_OK;
 }
 
 NS_IMETHODIMP
 TabChild::GetDimensions(uint32_t aFlags, int32_t* aX,
                              int32_t* aY, int32_t* aCx, int32_t* aCy)
 {
-  ScreenIntRect rect = GetOuterRect();
   if (aX) {
-    *aX = rect.x;
+    *aX = mOuterRect.x;
   }
   if (aY) {
-    *aY = rect.y;
+    *aY = mOuterRect.y;
   }
   if (aCx) {
-    *aCx = rect.width;
+    *aCx = mOuterRect.width;
   }
   if (aCy) {
-    *aCy = rect.height;
+    *aCy = mOuterRect.height;
   }
 
   return NS_OK;
 }
 
 NS_IMETHODIMP
 TabChild::SetFocus()
 {
@@ -2049,51 +2045,47 @@ TabChild::RecvShow(const ScreenIntSize& 
     bool res = InitTabChildGlobal();
     ApplyShowInfo(aInfo);
     RecvParentActivated(aParentIsActive);
 
     return res;
 }
 
 bool
-TabChild::RecvUpdateDimensions(const CSSRect& rect, const CSSSize& size,
-                               const ScreenOrientation& orientation,
-                               const LayoutDeviceIntPoint& chromeDisp)
+TabChild::RecvUpdateDimensions(const nsIntRect& rect, const ScreenIntSize& size,
+                               const ScreenOrientation& orientation, const LayoutDeviceIntPoint& chromeDisp)
 {
     if (!mRemoteFrame) {
         return true;
     }
 
-    mUnscaledOuterRect = rect;
+    mOuterRect = rect;
     mChromeDisp = chromeDisp;
 
     bool initialSizing = !HasValidInnerSize()
                       && (size.width != 0 && size.height != 0);
-
-    mOrientation = orientation;
-    ScreenIntSize oldScreenSize = GetInnerSize();
-    SetUnscaledInnerSize(size);
-    ScreenIntSize screenSize = GetInnerSize();
     bool sizeChanged = true;
     if (initialSizing) {
       mHasValidInnerSize = true;
-    } else if (screenSize == oldScreenSize) {
+    } else if (mInnerSize == size) {
       sizeChanged = false;
     }
 
-    ScreenIntRect screenRect = GetOuterRect();
-    mWidget->Resize(screenRect.x + chromeDisp.x, screenRect.y + chromeDisp.y,
-                    screenSize.width, screenSize.height, true);
+    mOrientation = orientation;
+    ScreenIntSize oldScreenSize = mInnerSize;
+    mInnerSize = size;
+    mWidget->Resize(rect.x + chromeDisp.x, rect.y + chromeDisp.y, size.width, size.height,
+                     true);
 
     nsCOMPtr<nsIBaseWindow> baseWin = do_QueryInterface(WebNavigation());
-    baseWin->SetPositionAndSize(0, 0, screenSize.width, screenSize.height,
+    baseWin->SetPositionAndSize(0, 0, size.width, size.height,
                                 true);
 
     if (initialSizing && mContentDocumentIsDisplayed) {
-      // If this is the first time we're getting a valid inner size, and the
+      // If this is the first time we're getting a valid mInnerSize, and the
       // before-first-paint event has already been handled, then we need to set
       // up our default viewport here. See the corresponding call to
       // InitializeRootMetrics in the before-first-paint handler.
       InitializeRootMetrics();
     }
 
     if (sizeChanged) {
       HandlePossibleViewportChange(oldScreenSize);
@@ -3247,40 +3239,27 @@ TabChild::RecvRequestNotifyAfterRemotePa
   // RenderFrameParent.
   compositor->RequestNotifyAfterRemotePaint(this);
   return true;
 }
 
 bool
 TabChild::RecvUIResolutionChanged()
 {
-  ScreenIntSize oldScreenSize = GetInnerSize();
   mDPI = 0;
   mDefaultScale = 0;
   static_cast<PuppetWidget*>(mWidget.get())->ClearBackingScaleCache();
   nsCOMPtr<nsIDocument> document(GetDocument());
   nsCOMPtr<nsIPresShell> presShell = document->GetShell();
   if (presShell) {
     nsRefPtr<nsPresContext> presContext = presShell->GetPresContext();
     if (presContext) {
-      presContext->UIResolutionChangedSync();
+      presContext->UIResolutionChanged();
     }
   }
-
-  ScreenIntSize screenSize = GetInnerSize();
-  if (mHasValidInnerSize && oldScreenSize != screenSize) {
-    ScreenIntRect screenRect = GetOuterRect();
-    mWidget->Resize(screenRect.x + mChromeDisp.x, screenRect.y + mChromeDisp.y,
-                    screenSize.width, screenSize.height, true);
-
-    nsCOMPtr<nsIBaseWindow> baseWin = do_QueryInterface(WebNavigation());
-    baseWin->SetPositionAndSize(0, 0, screenSize.width, screenSize.height,
-                                true);
-  }
-
   return true;
 }
 
 bool
 TabChild::RecvThemeChanged(nsTArray<LookAndFeelInt>&& aLookAndFeelIntCache)
 {
   LookAndFeel::SetIntCache(aLookAndFeelIntCache);
   nsCOMPtr<nsIDocument> document(GetDocument());
@@ -3332,32 +3311,16 @@ TabChild::CreatePluginWidget(nsIWidget* 
                                      nsIntSize(0, 0)), &initData);
   if (NS_FAILED(rv)) {
     NS_WARNING("Creating native plugin widget on the chrome side failed.");
   }
   pluginWidget.forget(aOut);
   return rv;
 }
 
-ScreenIntSize
-TabChild::GetInnerSize()
-{
-  LayoutDeviceIntSize innerSize =
-    RoundedToInt(mUnscaledInnerSize * mWidget->GetDefaultScale());
-  return ViewAs<ScreenPixel>(innerSize, PixelCastJustification::LayoutDeviceIsScreenForTabDims);
-};
-
-ScreenIntRect
-TabChild::GetOuterRect()
-{
-  LayoutDeviceIntRect outerRect =
-    RoundedToInt(mUnscaledOuterRect * mWidget->GetDefaultScale());
-  return ViewAs<ScreenPixel>(outerRect, PixelCastJustification::LayoutDeviceIsScreenForTabDims);
-}
-
 TabChildGlobal::TabChildGlobal(TabChildBase* aTabChild)
 : mTabChild(aTabChild)
 {
   SetIsNotDOMBinding();
 }
 
 TabChildGlobal::~TabChildGlobal()
 {
--- a/dom/ipc/TabChild.h
+++ b/dom/ipc/TabChild.h
@@ -184,18 +184,16 @@ public:
     // change, this function doesn't do anything.  However, it should
     // not be called all the time as it is fairly expensive.
     bool HandlePossibleViewportChange(const ScreenIntSize& aOldScreenSize);
     virtual bool DoUpdateZoomConstraints(const uint32_t& aPresShellId,
                                          const mozilla::layers::FrameMetrics::ViewID& aViewId,
                                          const bool& aIsRoot,
                                          const mozilla::layers::ZoomConstraints& aConstraints) = 0;
 
-    virtual ScreenIntSize GetInnerSize() = 0;
-
 protected:
     virtual ~TabChildBase();
     CSSSize GetPageSize(nsCOMPtr<nsIDocument> aDocument, const CSSSize& aViewport);
 
     // Get the DOMWindowUtils for the top-level window in this tab.
     already_AddRefed<nsIDOMWindowUtils> GetDOMWindowUtils();
     // Get the Document for the top-level window in this tab.
     already_AddRefed<nsIDocument> GetDocument() const;
@@ -219,16 +217,17 @@ protected:
     mozilla::layers::FrameMetrics ProcessUpdateFrame(const mozilla::layers::FrameMetrics& aFrameMetrics);
 
     bool UpdateFrameHandler(const mozilla::layers::FrameMetrics& aFrameMetrics);
 
 protected:
     CSSSize mOldViewportSize;
     bool mContentDocumentIsDisplayed;
     nsRefPtr<TabChildGlobal> mTabChildGlobal;
+    ScreenIntSize mInnerSize;
     mozilla::layers::FrameMetrics mLastRootMetrics;
     nsCOMPtr<nsIWebBrowserChrome3> mWebBrowserChrome;
 };
 
 class TabChild final : public TabChildBase,
                        public PBrowserChild,
                        public nsIWebBrowserChrome2,
                        public nsIEmbeddingSiteWindow,
@@ -315,18 +314,18 @@ public:
                                          const FileDescriptor& aFileDescriptor)
                                          override;
     virtual bool RecvShow(const ScreenIntSize& aSize,
                           const ShowInfo& aInfo,
                           const TextureFactoryIdentifier& aTextureFactoryIdentifier,
                           const uint64_t& aLayersId,
                           PRenderFrameChild* aRenderFrame,
                           const bool& aParentIsActive) override;
-    virtual bool RecvUpdateDimensions(const CSSRect& rect,
-                                      const CSSSize& size,
+    virtual bool RecvUpdateDimensions(const nsIntRect& rect,
+                                      const ScreenIntSize& size,
                                       const ScreenOrientation& orientation,
                                       const LayoutDeviceIntPoint& chromeDisp) override;
     virtual bool RecvUpdateFrame(const layers::FrameMetrics& aFrameMetrics) override;
     virtual bool RecvRequestFlingSnap(const ViewID& aScrollId,
                                       const CSSPoint& aDestination) override;
     virtual bool RecvAcknowledgeScrollUpdate(const ViewID& aScrollId,
                                              const uint32_t& aScrollGeneration) override;
     virtual bool RecvHandleDoubleTap(const CSSPoint& aPoint,
@@ -506,18 +505,16 @@ public:
     bool IPCOpen() { return mIPCOpen; }
 
     bool ParentIsActive()
     {
       return mParentIsActive;
     }
     bool AsyncPanZoomEnabled() { return mAsyncPanZoomEnabled; }
 
-    virtual ScreenIntSize GetInnerSize() override;
-
 protected:
     virtual ~TabChild();
 
     virtual PRenderFrameChild* AllocPRenderFrameChild() override;
     virtual bool DeallocPRenderFrameChild(PRenderFrameChild* aFrame) override;
     virtual bool RecvDestroy() override;
     virtual bool RecvSetUpdateHitRegion(const bool& aEnabled) override;
     virtual bool RecvSetIsDocShellActive(const bool& aIsActive) override;
@@ -597,35 +594,29 @@ private:
 
     bool HasValidInnerSize();
 
     // Get the pres shell resolution of the document in this tab.
     float GetPresShellResolution() const;
 
     void SetTabId(const TabId& aTabId);
 
-    ScreenIntRect GetOuterRect();
-
-    void SetUnscaledInnerSize(const CSSSize& aSize) {
-      mUnscaledInnerSize = aSize;
-    }
-
     class CachedFileDescriptorInfo;
     class CachedFileDescriptorCallbackRunnable;
     class DelayedDeleteRunnable;
 
     TextureFactoryIdentifier mTextureFactoryIdentifier;
     nsCOMPtr<nsIWebNavigation> mWebNav;
     nsCOMPtr<nsIWidget> mWidget;
     nsCOMPtr<nsIURI> mLastURI;
     RenderFrameChild* mRemoteFrame;
     nsRefPtr<nsIContentChild> mManager;
     uint32_t mChromeFlags;
     uint64_t mLayersId;
-    CSSRect mUnscaledOuterRect;
+    nsIntRect mOuterRect;
     // When we're tracking a possible tap gesture, this is the "down"
     // point of the touchstart.
     LayoutDevicePoint mGestureDownPoint;
     // The touch identifier of the active gesture.
     int32_t mActivePointerId;
     // A timer task that fires if the tap-hold timeout is exceeded by
     // the touch we're tracking.  That is, if touchend or a touchmove
     // that exceeds the gesture threshold doesn't happen.
@@ -650,17 +641,16 @@ private:
     // Position of tab, relative to parent widget (typically the window)
     LayoutDeviceIntPoint mChromeDisp;
     TabId mUniqueId;
     float mDPI;
     double mDefaultScale;
     bool mIPCOpen;
     bool mParentIsActive;
     bool mAsyncPanZoomEnabled;
-    CSSSize mUnscaledInnerSize;
 
     DISALLOW_EVIL_CONSTRUCTORS(TabChild);
 };
 
 }
 }
 
 #endif // mozilla_dom_TabChild_h
--- a/dom/ipc/TabParent.cpp
+++ b/dom/ipc/TabParent.cpp
@@ -85,17 +85,16 @@
 #include "SourceSurfaceRawData.h"
 #include "nsAuthInformationHolder.h"
 #include "nsICancelable.h"
 #include "gfxPrefs.h"
 #include "nsILoginManagerPrompter.h"
 #include "nsPIWindowRoot.h"
 #include "gfxDrawable.h"
 #include "ImageOps.h"
-#include "UnitTransforms.h"
 #include <algorithm>
 
 using namespace mozilla::dom;
 using namespace mozilla::ipc;
 using namespace mozilla::layers;
 using namespace mozilla::layout;
 using namespace mozilla::services;
 using namespace mozilla::widget;
@@ -329,37 +328,19 @@ TabParent::CacheFrameLoader(nsFrameLoade
 }
 
 void
 TabParent::SetOwnerElement(Element* aElement)
 {
   // If we held previous content then unregister for its events.
   RemoveWindowListeners();
 
-  // If we change top-level documents then we need to change our
-  // registration with them.
-  nsRefPtr<nsPIWindowRoot> curTopLevelWin, newTopLevelWin;
-  if (mFrameElement) {
-    curTopLevelWin = nsContentUtils::GetWindowRoot(mFrameElement->OwnerDoc());
-  }
-  if (aElement) {
-    newTopLevelWin = nsContentUtils::GetWindowRoot(aElement->OwnerDoc());
-  }
-  bool isSameTopLevelWin = curTopLevelWin == newTopLevelWin;
-  if (curTopLevelWin && !isSameTopLevelWin) {
-    curTopLevelWin->RemoveBrowser(this);
-  }
-
   // Update to the new content, and register to listen for events from it.
   mFrameElement = aElement;
 
-  if (newTopLevelWin && !isSameTopLevelWin) {
-    newTopLevelWin->AddBrowser(this);
-  }
-
   AddWindowListeners();
   TryCacheDPIAndScale();
 }
 
 void
 TabParent::AddWindowListeners()
 {
   if (mFrameElement && mFrameElement->OwnerDoc()) {
@@ -980,31 +961,17 @@ TabParent::UpdateDimensions(const nsIntR
       chromeOffset != mChromeOffset) {
 
     mUpdatedDimensions = true;
     mRect = contentRect;
     mDimensions = size;
     mOrientation = orientation;
     mChromeOffset = chromeOffset;
 
-    CSSToLayoutDeviceScale widgetScale;
-    if (widget) {
-      widgetScale = widget->GetDefaultScale();
-    }
-
-    LayoutDeviceIntRect devicePixelRect =
-      ViewAs<LayoutDevicePixel>(mRect,
-                                PixelCastJustification::LayoutDeviceIsScreenForTabDims);
-    LayoutDeviceIntSize devicePixelSize =
-      ViewAs<LayoutDevicePixel>(mDimensions.ToUnknownSize(),
-                                PixelCastJustification::LayoutDeviceIsScreenForTabDims);
-
-    CSSRect unscaledRect = devicePixelRect / widgetScale;
-    CSSSize unscaledSize = devicePixelSize / widgetScale;
-    unused << SendUpdateDimensions(unscaledRect, unscaledSize, orientation, chromeOffset);
+    unused << SendUpdateDimensions(mRect, mDimensions, mOrientation, mChromeOffset);
   }
 }
 
 void
 TabParent::UpdateFrame(const FrameMetrics& aFrameMetrics)
 {
   if (!mIsDestroyed) {
     unused << SendUpdateFrame(aFrameMetrics);
@@ -1013,17 +980,16 @@ TabParent::UpdateFrame(const FrameMetric
 
 void
 TabParent::UIResolutionChanged()
 {
   if (!mIsDestroyed) {
     // TryCacheDPIAndScale()'s cache is keyed off of
     // mDPI being greater than 0, so this invalidates it.
     mDPI = -1;
-    TryCacheDPIAndScale();
     unused << SendUIResolutionChanged();
   }
 }
 
 void
 TabParent::ThemeChanged()
 {
   if (!mIsDestroyed) {
--- a/dom/ipc/TabParent.h
+++ b/dom/ipc/TabParent.h
@@ -422,16 +422,17 @@ public:
                           const uint32_t& aWidth, const uint32_t& aHeight,
                           const uint32_t& aStride, const uint8_t& aFormat,
                           const int32_t& aDragAreaX, const int32_t& aDragAreaY) override;
 
     void AddInitialDnDDataTo(DataTransfer* aDataTransfer);
 
     void TakeDragVisualization(RefPtr<mozilla::gfx::SourceSurface>& aSurface,
                                int32_t& aDragAreaX, int32_t& aDragAreaY);
+    layout::RenderFrameParent* GetRenderFrame();
 protected:
     bool ReceiveMessage(const nsString& aMessage,
                         bool aSync,
                         const StructuredCloneData* aCloneData,
                         mozilla::jsipc::CpowHolder* aCpows,
                         nsIPrincipal* aPrincipal,
                         nsTArray<OwningSerializedStructuredCloneBuffer>* aJSONRetVal = nullptr);
 
@@ -475,17 +476,16 @@ protected:
     ScreenOrientation mOrientation;
     float mDPI;
     CSSToLayoutDeviceScale mDefaultScale;
     bool mUpdatedDimensions;
     LayoutDeviceIntPoint mChromeOffset;
 
 private:
     already_AddRefed<nsFrameLoader> GetFrameLoader(bool aUseCachedFrameLoaderAfterDestroy = false) const;
-    layout::RenderFrameParent* GetRenderFrame();
     nsRefPtr<nsIContentParent> mManager;
     void TryCacheDPIAndScale();
 
     nsresult UpdatePosition();
 
     CSSPoint AdjustTapToChildWidget(const CSSPoint& aPoint);
 
     bool AsyncPanZoomEnabled() const;
--- a/dom/media/fmp4/MP4Demuxer.cpp
+++ b/dom/media/fmp4/MP4Demuxer.cpp
@@ -153,17 +153,17 @@ MP4TrackDemuxer::MP4TrackDemuxer(MP4Demu
   , mStream(new mp4_demuxer::ResourceStream(mParent->mResource))
   , mNeedReIndex(true)
   , mMonitor("MP4TrackDemuxer")
 {
   mInfo = mParent->mMetadata->GetTrackInfo(aType, aTrackNumber);
 
   MOZ_ASSERT(mInfo);
 
-  nsTArray<mp4_demuxer::Index::Indice> indices;
+  FallibleTArray<mp4_demuxer::Index::Indice> indices;
   if (!mParent->mMetadata->ReadTrackIndex(indices, mInfo->mTrackId)) {
     MOZ_ASSERT(false);
   }
   mIndex = new mp4_demuxer::Index(indices,
                                   mStream,
                                   mInfo->mTrackId,
                                   mInfo->IsAudio(),
                                   &mMonitor);
--- a/dom/media/test/manifest.js
+++ b/dom/media/test/manifest.js
@@ -223,17 +223,17 @@ var gPlayTests = [
   { name:"test-5-5.0.opus", type:"audio/ogg; codecs=opus", duration:7.558 },
   { name:"test-6-5.1.opus", type:"audio/ogg; codecs=opus", duration:10.333 },
   { name:"test-7-6.1.opus", type:"audio/ogg; codecs=opus", duration:11.690 },
   { name:"test-8-7.1.opus", type:"audio/ogg; codecs=opus", duration:13.478 },
 
   { name:"gizmo.mp4", type:"video/mp4", duration:5.56 },
   // Test playback of a MP4 file with a non-zero start time (and audio starting
   // a second later).
-  { name:"bipbop-lateaudio.mp4", type:"video/mp4", duration:2.401 },
+  { name:"bipbop-lateaudio.mp4", type:"video/mp4" },
 
   { name:"small-shot.m4a", type:"audio/mp4", duration:0.29 },
   { name:"small-shot.mp3", type:"audio/mpeg", duration:0.27 },
   { name:"owl.mp3", type:"audio/mpeg", duration:3.29 },
   // owl.mp3 as above, but with something funny going on in the ID3v2 tag
   // that causes DirectShow to fail.
   { name:"owl-funny-id3.mp3", type:"audio/mpeg", duration:3.29 },
   // owl.mp3 as above, but with something even funnier going on in the ID3v2 tag
--- a/dom/media/webaudio/test/test_mediaElementAudioSourceNodeCrossOrigin.html
+++ b/dom/media/webaudio/test/test_mediaElementAudioSourceNodeCrossOrigin.html
@@ -39,17 +39,17 @@ tests.forEach(function(e) {
   if (e.cors) {
     a.crossOrigin = e.cors;
   }
   a.src = e.url;
   a.controls = true;
   var measn = e.ac.createMediaElementSource(a);
   var sp = e.ac.createScriptProcessor(2048, 1);
   // Set a couple expandos to track the status of the test
-  sp.iterationsLeft = 200;
+  sp.iterationsLeft = 300;
   sp.seenSound = false;
 
   measn.connect(sp);
   a.play();
   document.body.appendChild(a);
 
   function checkFinished(sp) {
     if (--sp.iterationsLeft == 0) {
--- a/dom/nfc/messages/HCIEventTransactionSystemMessageConfigurator.js
+++ b/dom/nfc/messages/HCIEventTransactionSystemMessageConfigurator.js
@@ -1,27 +1,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/. */
 
 "use strict";
 
-const {classes: Cc, interfaces: Ci, utils: Cu, results: Cr} = Components;
+const { interfaces: Ci, utils: Cu } = Components;
 
 Cu.import("resource://gre/modules/XPCOMUtils.jsm");
 Cu.import("resource://gre/modules/Promise.jsm");
 
 XPCOMUtils.defineLazyServiceGetter(this, "appsService",
                                    "@mozilla.org/AppsService;1",
                                    "nsIAppsService");
 
-let DEBUG = false;
+XPCOMUtils.defineLazyServiceGetter(this, "aceService",
+                                   "@mozilla.org/secureelement/access-control/ace;1",
+                                   "nsIAccessControlEnforcer");
+
+XPCOMUtils.defineLazyModuleGetter(this, "SEUtils",
+                                  "resource://gre/modules/SEUtils.jsm");
+
+XPCOMUtils.defineLazyGetter(this, "SE", () => {
+  let obj = {};
+  Cu.import("resource://gre/modules/se_consts.js", obj);
+  return obj;
+});
+
+let DEBUG = SE.DEBUG_SE;
 function debug(aMsg) {
   if (DEBUG) {
-    dump("-- HCIEventTransactionSystemMessageConfigurator.js " + Date.now() + " : " + aMsg + "\n");
+    dump("-*- HCIEventTransaction: " + aMsg);
   }
 }
 
 /**
   * nsISystemMessagesConfigurator implementation.
   */
 function HCIEventTransactionSystemMessageConfigurator() {
   debug("HCIEventTransactionSystemMessageConfigurator");
@@ -36,43 +49,42 @@ HCIEventTransactionSystemMessageConfigur
   shouldDispatch: function shouldDispatch(aManifestURL, aPageURL, aType, aMessage, aExtra) {
     DEBUG && debug("message to dispatch: " + JSON.stringify(aMessage));
     debug("aManifest url: " + aManifestURL);
 
     if (!aMessage) {
       return Promise.resolve(false);
     }
 
+    let appId = appsService.getAppLocalIdByManifestURL(aManifestURL);
+    if (appId === Ci.nsIScriptSecurityManager.NO_APP_ID) {
+      return Promise.resolve(false);
+    }
+
     return new Promise((resolve, reject) => {
       appsService.getManifestFor(aManifestURL)
       .then((aManifest) => this._checkAppManifest(aMessage.origin, aMessage.aid, aManifest))
-      .then(() => {
-        // FIXME: Bug 884594: Access Control Enforcer
-        // Here we will call ace.isAllowed function which will also return
-        // a Promise, for now we're just resolving shouldDispatch promise
-        debug("dispatching message");
-        resolve(true);
+      .then(() => aceService.isAccessAllowed(appId, aMessage.origin, aMessage.aid))
+      .then((allowed) => {
+        debug("dispatching message: " + allowed);
+        resolve(allowed);
       })
       .catch(() => {
-        // if the Promise chain was broken we don't dispatch the message
         debug("not dispatching");
         resolve(false);
       });
     });
   },
 
-  // we might be doing some async hash computations here, returning
-  // a resolved/rejected promise for now so we can easily fit the method
-  // into a Promise chain
   _checkAppManifest: function _checkAppManifest(aOrigin, aAid, aManifest) {
     DEBUG && debug("aManifest " + JSON.stringify(aManifest));
 
     // convert AID and Secure Element name to uppercased string for comparison
     // with manifest secure_element_access rules
-    let aid = this._byteAIDToHex(aAid);
+    let aid = SEUtils.byteArrayToHexString(aAid);
     let seName = (aOrigin) ? aOrigin.toUpperCase() : "";
 
     let hciRules = aManifest["secure_element_access"] || [];
     let matchingRule = hciRules.find((rule) => {
       rule = rule.toUpperCase();
       if(rule === "*" || rule === (seName + "/" + aid)) {
         return true;
       }
@@ -90,28 +102,13 @@ HCIEventTransactionSystemMessageConfigur
 
       return isMatching(rule.split('/')[0], seName) &&
              isMatching(rule.split('/')[1], aid);
     });
 
     return (matchingRule) ? Promise.resolve() : Promise.reject();
   },
 
-  // FIXME: there is probably something which does this
-  _byteAIDToHex: function _byteAIDToHex(uint8arr) {
-    if (!uint8arr) {
-      return "";
-    }
-
-    var hexStr = "";
-    for (var i = 0; i < uint8arr.length; i++) {
-      var hex = (uint8arr[i] & 0xff).toString(16);
-      hex = (hex.length === 1) ? '0' + hex : hex;
-      hexStr += hex;
-    }
-    return hexStr.toUpperCase();
-  },
-
   classID: Components.ID("{b501edd0-28bd-11e4-8c21-0800200c9a66}"),
   QueryInterface: XPCOMUtils.generateQI([Ci.nsISystemMessagesConfigurator])
 }
 
 this.NSGetFactory = XPCOMUtils.generateNSGetFactory([HCIEventTransactionSystemMessageConfigurator]);
--- a/dom/nfc/tests/unit/test_HCIEventTransactionSystemMessageConfigurator.js
+++ b/dom/nfc/tests/unit/test_HCIEventTransactionSystemMessageConfigurator.js
@@ -18,56 +18,71 @@ const MANIFEST = {
     // rule0, full AID, SIM1 Secure Element
     "SIM1/000102030405060708090A0B0C0D0E",
     // rule1, every AID from embedded Secure Element
     "eSE/*",
     // rule2, every AID which starts with 0xA0, from every Secure Element
     "*/a0*"
   ]
 };
+const APPID = 1111;
 const PAGE_URL = "app://system.gaiamobile.org/index.html";
 const TYPE = "nfc-hci-event-transaction";
 
 // dummy messages for testing with additional test property - |expectedResult|
 const TEST_MESSAGES = [
   { origin: "SIM1", expectedResult: false },
   { aid: new Uint8Array([0xA0]), expectedResult: true },
   { aid: new Uint8Array([0xDF]), origin: "eSE", expectedResult: true },
   { aid: new Uint8Array([0xA0, 0x01, 0x02, 0x03]), origin: "SIM2", expectedResult: true },
   { aid: new Uint8Array([0x02]), origin: "SIM3", expectedResult: false },
   { aid: new Uint8Array([0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
                          0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E]),
     origin: "SIM1", expectedResult: true }
 ];
 
 let HCIEvtTransactionConfigurator = null;
+let aceAccessAllowed = true;
 
-function setMockAppService(manifest) {
-  XPCOMUtils.defineLazyServiceGetter = (obj) => {
-    obj.appsService = {
-      getManifestFor: (manifestURL) => {
-        equal(manifestURL, MANIFEST_URL, "should pass proper manifestUrl");
-        return Promise.resolve(manifest);
-      }
-    };
+function setMockServices(manifest) {
+  XPCOMUtils.defineLazyServiceGetter = (obj, service) => {
+    if (service === "appsService") {
+      obj.appsService = {
+        getManifestFor: (manifestURL) => {
+          equal(manifestURL, MANIFEST_URL, "should pass proper manifestUrl");
+          return Promise.resolve(manifest);
+        },
+        getAppLocalIdByManifestURL: (manifestURL) => {
+          equal(manifestURL, MANIFEST_URL, "should pass proper manifestUrl");
+          return APPID;
+        },
+      };
+    }
+    else if (service === "aceService") {
+      obj.aceService = {
+        isAccessAllowed: () => {
+          return Promise.resolve(aceAccessAllowed);
+        }
+      };
+    }
   };
 }
 
 function getSystemMessageConfigurator() {
   return Cc[
     "@mozilla.org/dom/system-messages/configurator/nfc-hci-event-transaction;1"
   ].createInstance(Ci.nsISystemMessagesConfigurator);
 }
 
 function handleRejectedPromise() {
   ok(false, "Promise should not be rejected");
 }
 
 function run_test() {
-  setMockAppService(MANIFEST);
+  setMockServices(MANIFEST);
   HCIEvtTransactionConfigurator = getSystemMessageConfigurator();
 
   ok(!!HCIEvtTransactionConfigurator, "Configurator should be instantiated");
   ok((typeof HCIEvtTransactionConfigurator.shouldDispatch) === "function",
      "shouldDispatch should be a function");
 
   run_next_test();
 }
@@ -91,8 +106,26 @@ add_test(function test_shouldDispatch_ge
   Promise.all(promises).then((results) => {
     results.forEach((result, idx) => {
       ok(result === TEST_MESSAGES[idx].expectedResult, "tested message: " + JSON.stringify(TEST_MESSAGES[idx]));
     });
   })
   .catch(handleRejectedPromise)
   .then(run_next_test);
 });
+
+add_test(function test_shouldDispatch_aceIsAccessAllowed() {
+  var testAccessAllowed = () => {
+    return HCIEvtTransactionConfigurator
+    .shouldDispatch(MANIFEST_URL, PAGE_URL, TYPE, TEST_MESSAGES[1])
+    .then((result) => {
+      ok(result === aceAccessAllowed, "Should be equal to ACE access decision");
+    });
+  };
+
+  aceAccessAllowed = false;
+  testAccessAllowed().then(() => {
+    aceAccessAllowed = true;
+    return testAccessAllowed();
+  })
+  .catch(handleRejectedPromise)
+  .then(run_next_test);
+});
--- a/dom/plugins/ipc/PluginModuleParent.cpp
+++ b/dom/plugins/ipc/PluginModuleParent.cpp
@@ -1817,17 +1817,17 @@ PluginModuleParent::StreamCast(NPP insta
 {
     PluginInstanceParent* ip = PluginInstanceParent::Cast(instance, aSurrogate);
     if (!ip || (aSurrogate && *aSurrogate && ip->UseSurrogate())) {
         return nullptr;
     }
 
     BrowserStreamParent* sp =
         static_cast<BrowserStreamParent*>(static_cast<AStream*>(s->pdata));
-    if (sp->mNPP != ip || s != sp->mStream) {
+    if (sp && (sp->mNPP != ip || s != sp->mStream)) {
         NS_RUNTIMEABORT("Corrupted plugin stream data.");
     }
     return sp;
 }
 
 bool
 PluginModuleParent::HasRequiredFunctions()
 {
--- a/dom/plugins/test/mochitest/test_instance_re-parent.html
+++ b/dom/plugins/test/mochitest/test_instance_re-parent.html
@@ -7,16 +7,18 @@
   <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
   <script type="text/javascript" src="utils.js"></script>
 </head>
 <body onload="begin()">
   <script type="application/javascript;version=1.8">
   SimpleTest.waitForExplicitFinish();
   setTestPluginEnabledState(SpecialPowers.Ci.nsIPluginTag.STATE_ENABLED);
 
+  const MAX_CHECK_PLUGIN_STOPPED_ATTEMPTS = 5;
+  var numCheckPluginStoppedAttempts = 0;
   var exceptionThrown = false;
   var p = null;
   var d1 = null;
   var d2 = null;
 
   var destroyed = false;
 
   function begin() {
@@ -33,16 +35,30 @@
       destroyed = false;
       exceptionThrown = false;
       runTests(function () {
         SimpleTest.finish();
       });
     });
   }
 
+  function checkPluginStopped(callback, param) {
+    if (numCheckPluginStoppedAttempts < MAX_CHECK_PLUGIN_STOPPED_ATTEMPTS &&
+        !destroyed) {
+      ++numCheckPluginStoppedAttempts;
+      SimpleTest.executeSoon(function() {
+          checkPluginStopped(callback, param);
+      });
+    } else {
+      info("Number of check plugin stopped attempts: " +
+           numCheckPluginStoppedAttempts);
+      callback(param);
+    }
+  }
+
   function runTests(callback) {
     p = document.getElementById('plugin1');
     d1 = document.getElementById('div1');
     d2 = document.getElementById('div2');
 
     // First tests involve moving the instance from one div to another.
     p.startWatchingInstanceCount();
     p.callOnDestroy(function() {
@@ -66,32 +82,33 @@
     is(destroyed, false, "No instances should have been destroyed at this point.");
     is(p.getInstanceCount(), 0, "No new instances should have been created at this point.");
 
     // Wait for the event loop to spin and ensure the plugin still wasn't touched
     SimpleTest.executeSoon(function() {
       is(destroyed, false, "No instances should have been destroyed at this point.");
       is(p.getInstanceCount(), 0, "No new instances should have been created at this point.");
 
-      // Removing the instance for a full event loop *should* respawn
       d2.removeChild(p);
-      SimpleTest.executeSoon(function() {
-        d2.appendChild(p);
-        SimpleTest.executeSoon(function() {
-          try {
-            is(p.getInstanceCount(), 1, "One new instance should have been created at this point.");
-          } catch (e) {
-            exceptionThrown = true;
-          }
-          is(exceptionThrown, false, "Testing for exception getting instance count from plugin.");
+      checkPluginStopped(continueTestsAfterPluginDestruction, callback);
+    });
+  }
 
-          p.stopWatchingInstanceCount();
-          callback.apply(null);
-        });
-      });
+  function continueTestsAfterPluginDestruction(callback) {
+    d2.appendChild(p);
+    SimpleTest.executeSoon(function() {
+      try {
+        is(p.getInstanceCount(), 1, "One new instance should have been created at this point.");
+      } catch (e) {
+        exceptionThrown = true;
+      }
+      is(exceptionThrown, false, "Testing for exception getting instance count from plugin.");
+
+      p.stopWatchingInstanceCount();
+      callback.apply(null);
     });
   }
   </script>
 
   <p id="display"></p>
 
   <div id="div1">
     <!-- This embed has to have a "src" attribute. Part of this test involves seeing if we
--- a/dom/security/moz.build
+++ b/dom/security/moz.build
@@ -1,14 +1,16 @@
 # -*- Mode: python; c-basic-offset: 4; indent-tabs-mode: nil; tab-width: 40 -*-
 # vim: set filetype=python:
 # This Source Code Form is subject to the terms of the Mozilla Public
 # License, v. 2.0. If a copy of the MPL was not distributed with this
 # file, You can obtain one at http://mozilla.org/MPL/2.0/.
 
+TEST_DIRS += ['test']
+
 EXPORTS.mozilla.dom += [
     'nsCSPContext.h',
     'nsCSPService.h',
     'nsCSPUtils.h',
     'nsMixedContentBlocker.h',
 ]
 
 EXPORTS += [
rename from dom/base/test/TestCSPParser.cpp
rename to dom/security/test/TestCSPParser.cpp
rename from dom/base/test/file_CrossSiteXHR_cache_server.sjs
rename to dom/security/test/cors/file_CrossSiteXHR_cache_server.sjs
--- a/dom/base/test/file_CrossSiteXHR_cache_server.sjs
+++ b/dom/security/test/cors/file_CrossSiteXHR_cache_server.sjs
@@ -2,32 +2,32 @@ function handleRequest(request, response
 {
   var query = {};
   request.queryString.split('&').forEach(function (val) {
     var [name, value] = val.split('=');
     query[name] = unescape(value);
   });
 
   if ("setState" in query) {
-    setState("test/dom/base/test_CrossSiteXHR_cache:secData",
+    setState("test/dom/security/test_CrossSiteXHR_cache:secData",
              query.setState);
 
     response.setHeader("Cache-Control", "no-cache", false);
     response.setHeader("Content-Type", "text/plain", false);
     response.write("hi");
 
     return;
   }
 
   var isPreflight = request.method == "OPTIONS";
 
   // Send response
 
   secData =
-    eval(getState("test/dom/base/test_CrossSiteXHR_cache:secData"));
+    eval(getState("test/dom/security/test_CrossSiteXHR_cache:secData"));
 
   if (secData.allowOrigin)
     response.setHeader("Access-Control-Allow-Origin", secData.allowOrigin);
 
   if (isPreflight) {
     if (secData.allowHeaders)
       response.setHeader("Access-Control-Allow-Headers", secData.allowHeaders);
 
rename from dom/base/test/file_CrossSiteXHR_inner.html
rename to dom/security/test/cors/file_CrossSiteXHR_inner.html
rename from dom/base/test/file_CrossSiteXHR_inner.jar
rename to dom/security/test/cors/file_CrossSiteXHR_inner.jar
rename from dom/base/test/file_CrossSiteXHR_inner_data.sjs
rename to dom/security/test/cors/file_CrossSiteXHR_inner_data.sjs
rename from dom/base/test/file_CrossSiteXHR_server.sjs
rename to dom/security/test/cors/file_CrossSiteXHR_server.sjs
--- a/dom/base/test/file_CrossSiteXHR_server.sjs
+++ b/dom/security/test/cors/file_CrossSiteXHR_server.sjs
@@ -133,17 +133,17 @@ function handleRequest(request, response
     }
 
     if (query.exposeHeaders)
       response.setHeader("Access-Control-Expose-Headers", query.exposeHeaders);
   }
 
   if (query.hop && query.hop < hops.length) {
     newURL = hops[query.hop].server +
-             "/tests/dom/base/test/file_CrossSiteXHR_server.sjs?" +
+             "/tests/dom/security/test/cors/file_CrossSiteXHR_server.sjs?" +
              "hop=" + (query.hop + 1) + "&hops=" + query.hops;
     response.setStatusLine(null, 307, "redirect");
     response.setHeader("Location", newURL);
 
     return;
   }
 
   // Send response body
new file mode 100644
--- /dev/null
+++ b/dom/security/test/cors/mochitest.ini
@@ -0,0 +1,12 @@
+[DEFAULT]
+support-files =
+  file_CrossSiteXHR_cache_server.sjs
+  file_CrossSiteXHR_inner.html
+  file_CrossSiteXHR_inner.jar
+  file_CrossSiteXHR_inner_data.sjs
+  file_CrossSiteXHR_server.sjs
+
+[test_CrossSiteXHR.html]
+[test_CrossSiteXHR_cache.html]
+[test_CrossSiteXHR_origin.html]
+skip-if = buildapp == 'b2g' || e10s # last test fails to trigger onload on e10s/b2g
rename from dom/base/test/test_CrossSiteXHR.html
rename to dom/security/test/cors/test_CrossSiteXHR.html
--- a/dom/base/test/test_CrossSiteXHR.html
+++ b/dom/security/test/cors/test_CrossSiteXHR.html
@@ -39,21 +39,21 @@ function initTestCallback() {
 }
 
 function runTest() {
   var loader = document.getElementById('loader');
   var loaderWindow = loader.contentWindow;
   loader.onload = function () { gen.next() };
 
   // Test preflight-less requests
-  basePath = "/tests/dom/base/test/file_CrossSiteXHR_server.sjs?"
+  basePath = "/tests/dom/security/test/cors/file_CrossSiteXHR_server.sjs?"
   baseURL = "http://mochi.test:8888" + basePath;
 
   // Test preflighted requests
-  loader.src = "http://example.org/tests/dom/base/test/file_CrossSiteXHR_inner.html";
+  loader.src = "http://example.org/tests/dom/security/test/cors/file_CrossSiteXHR_inner.html";
   origin = "http://example.org";
   yield undefined;
 
   tests =     [// Plain request
                { pass: 1,
                  method: "GET",
                  noAllowPreflight: 1,
                },
@@ -869,17 +869,17 @@ function runTest() {
   }
 
   // Make sure to clear cookies to avoid affecting other tests
   document.cookie = "a=; path=/; expires=Thu, 01-Jan-1970 00:00:01 GMT"
   is(document.cookie, "", "No cookies should be left over");
 
 
   // Test redirects
-  is(loader.src, "http://example.org/tests/dom/base/test/file_CrossSiteXHR_inner.html");
+  is(loader.src, "http://example.org/tests/dom/security/test/cors/file_CrossSiteXHR_inner.html");
   is(origin, "http://example.org");
 
   tests = [{ pass: 1,
              method: "GET",
              hops: [{ server: "http://example.com",
                       allowOrigin: origin
                     },
                     ],
rename from dom/base/test/test_CrossSiteXHR_cache.html
rename to dom/security/test/cors/test_CrossSiteXHR_cache.html
--- a/dom/base/test/test_CrossSiteXHR_cache.html
+++ b/dom/security/test/cors/test_CrossSiteXHR_cache.html
@@ -25,17 +25,17 @@ window.addEventListener("message", funct
 
 gen = runTest();
 
 function runTest() {
   var loader = document.getElementById('loader');
   var loaderWindow = loader.contentWindow;
   loader.onload = function () { gen.next() };
 
-  loader.src = "http://example.org/tests/dom/base/test/file_CrossSiteXHR_inner.html";
+  loader.src = "http://example.org/tests/dom/security/test/cors/file_CrossSiteXHR_inner.html";
   origin = "http://example.org";
   yield undefined;
 
   tests = [{ pass: 0,
              method: "GET",
              headers: { "x-my-header": "myValue" },
            },
            { pass: 1,
@@ -423,17 +423,17 @@ function runTest() {
     tests.push({ newTest: "*******" },
                { pass: 1,
                  method: "DELETE",
                  allowMethods: "DELETE",
                  cacheTime: 3600,
                });
   }
 
-  baseURL = "http://mochi.test:8888/tests/dom/base/test/" +
+  baseURL = "http://mochi.test:8888/tests/dom/security/test/cors/" +
              "file_CrossSiteXHR_cache_server.sjs?";
   setStateURL = baseURL + "setState=";
 
   var unique = Date.now();
   for (test of tests) {
     if (test.newTest) {
       unique++;
       continue;
rename from dom/base/test/test_CrossSiteXHR_origin.html
rename to dom/security/test/cors/test_CrossSiteXHR_origin.html
--- a/dom/base/test/test_CrossSiteXHR_origin.html
+++ b/dom/security/test/cors/test_CrossSiteXHR_origin.html
@@ -34,20 +34,20 @@ var origins =
    { server: 'http://ex\xe4mple.test',
      origin: 'http://xn--exmple-cua.test'
    },
    { server: 'http://xn--exmple-cua.test' },
    { server: 'http://\u03c0\u03b1\u03c1\u03ac\u03b4\u03b5\u03b9\u03b3\u03bc\u03b1.\u03b4\u03bf\u03ba\u03b9\u03bc\u03ae',
      origin: 'http://xn--hxajbheg2az3al.xn--jxalpdlp'
    },
    { origin: 'http://example.org',
-     file: 'jar:http://example.org/tests/dom/base/test/file_CrossSiteXHR_inner.jar!/file_CrossSiteXHR_inner.html'
+     file: 'jar:http://example.org/tests/dom/security/test/cors/file_CrossSiteXHR_inner.jar!/file_CrossSiteXHR_inner.html'
    },
    { origin: 'null',
-     file: 'http://example.org/tests/dom/base/test/file_CrossSiteXHR_inner_data.sjs'
+     file: 'http://example.org/tests/dom/security/test/cors/file_CrossSiteXHR_inner_data.sjs'
    },
    ];
 
    //['https://example.com:443'],
    //['https://sub1.test1.example.com:443'],
 
 window.addEventListener("message", function(e) {
   gen.send(e.data);
@@ -56,24 +56,24 @@ window.addEventListener("message", funct
 gen = runTest();
 
 function runTest() {
   var loader = document.getElementById('loader');
   var loaderWindow = loader.contentWindow;
   loader.onload = function () { gen.next() };
 
   // Test preflight-less requests
-  basePath = "/tests/dom/base/test/file_CrossSiteXHR_server.sjs?"
+  basePath = "/tests/dom/security/test/cors/file_CrossSiteXHR_server.sjs?"
   baseURL = "http://mochi.test:8888" + basePath;
 
   for (originEntry of origins) {
     origin = originEntry.origin || originEntry.server;
 
     loader.src = originEntry.file ||
-                 (originEntry.server + "/tests/dom/base/test/file_CrossSiteXHR_inner.html");
+                 (originEntry.server + "/tests/dom/security/test/cors/file_CrossSiteXHR_inner.html");
     yield undefined;
 
     var isNullOrigin = origin == "null";
 
     port = /:\d+/;
     passTests = [
       origin,
       "*",
rename from dom/base/test/csp/browser.ini
rename to dom/security/test/csp/browser.ini
rename from dom/base/test/csp/browser_test_web_manifest.js
rename to dom/security/test/csp/browser_test_web_manifest.js
--- a/dom/base/test/csp/browser_test_web_manifest.js
+++ b/dom/security/test/csp/browser_test_web_manifest.js
@@ -6,22 +6,22 @@
  *   are respected by the ManifestObtainer.
  */
 /*globals Components*/
 'use strict';
 requestLongerTimeout(10); // e10s tests take time.
 const {
   ManifestObtainer
 } = Components.utils.import('resource://gre/modules/WebManifest.jsm', {});
-const path = '/tests/dom/base/test/csp/';
-const testFile = `file=${path}file_CSP_web_manifest.html`;
-const remoteFile = `file=${path}file_CSP_web_manifest_remote.html`;
-const httpsManifest = `file=${path}file_CSP_web_manifest_https.html`;
-const mixedContent = `file=${path}file_CSP_web_manifest_mixed_content.html`;
-const server = 'file_csp_testserver.sjs';
+const path = '/tests/dom/security/test/csp/';
+const testFile = `file=${path}file_web_manifest.html`;
+const remoteFile = `file=${path}file_web_manifest_remote.html`;
+const httpsManifest = `file=${path}file_web_manifest_https.html`;
+const mixedContent = `file=${path}file_web_manifest_mixed_content.html`;
+const server = 'file_testserver.sjs';
 const defaultURL = `http://example.org${path}${server}`;
 const remoteURL = `http://mochi.test:8888`;
 const secureURL = `https://example.com${path}${server}`;
 const tests = [
   // CSP block everything, so trying to load a manifest
   // will result in a policy violation.
   {
     expected: `default-src 'none' blocks fetching manifest.`,
rename from dom/base/test/csp/browser_test_web_manifest_mixed_content.js
rename to dom/security/test/csp/browser_test_web_manifest_mixed_content.js
--- a/dom/base/test/csp/browser_test_web_manifest_mixed_content.js
+++ b/dom/security/test/csp/browser_test_web_manifest_mixed_content.js
@@ -2,22 +2,22 @@
  * Description of the test:
  *   Check that mixed content blocker works prevents fetches of
  *   mixed content manifests.
  */
 'use strict';
 const {
   ManifestObtainer
 } = Components.utils.import('resource://gre/modules/WebManifest.jsm', {});
-const path = '/tests/dom/base/test/csp/';
-const mixedContent = `file=${path}file_CSP_web_manifest_mixed_content.html`;
-const server = 'file_csp_testserver.sjs';
+const path = '/tests/dom/security/test/csp/';
+const mixedContent = `file=${path}file_web_manifest_mixed_content.html`;
+const server = 'file_testserver.sjs';
 const secureURL = `https://example.com${path}${server}`;
 const tests = [
-  // Trying to load mixed content in file_CSP_web_manifest_mixed_content.html
+  // Trying to load mixed content in file_web_manifest_mixed_content.html
   // needs to result in an error.
   {
     expected: `Mixed Content Blocker prevents fetching manifest.`,
     get tabURL() {
       let queryParts = [
         mixedContent
       ];
       return `${secureURL}?${queryParts.join('&')}`;
rename from dom/base/test/csp/chrome.ini
rename to dom/security/test/csp/chrome.ini
--- a/dom/base/test/csp/chrome.ini
+++ b/dom/security/test/csp/chrome.ini
@@ -1,5 +1,5 @@
 [DEFAULT]
 skip-if = buildapp == 'b2g'
 
-[test_csp_bug768029.html]
-[test_csp_bug773891.html]
+[test_bug768029.html]
+[test_bug773891.html]
rename from dom/base/test/csp/file_CSP.css
rename to dom/security/test/csp/file_CSP.css
--- a/dom/base/test/csp/file_CSP.css
+++ b/dom/security/test/csp/file_CSP.css
@@ -7,14 +7,14 @@
 
 /* CSS font embedding tests */
 @font-face {
   font-family: "arbitrary_good";
   src: url('file_CSP.sjs?testid=font_good&type=application/octet-stream');
 }
 @font-face {
   font-family: "arbitrary_bad";
-  src: url('http://example.org/tests/dom/base/test/csp/file_CSP.sjs?testid=font_bad&type=application/octet-stream');
+  src: url('http://example.org/tests/dom/security/test/csp/file_CSP.sjs?testid=font_bad&type=application/octet-stream');
 }
 
 .div_arbitrary_good { font-family: "arbitrary_good"; }
 .div_arbitrary_bad { font-family: "arbitrary_bad"; }
 
rename from dom/base/test/csp/file_CSP.sjs
rename to dom/security/test/csp/file_CSP.sjs
rename from dom/base/test/csp/file_csp_allow_https_schemes.html
rename to dom/security/test/csp/file_allow_https_schemes.html
--- a/dom/base/test/csp/file_csp_allow_https_schemes.html
+++ b/dom/security/test/csp/file_allow_https_schemes.html
@@ -1,14 +1,14 @@
 <!DOCTYPE HTML>
 <html>
   <head>
     <title>Bug 826805 - CSP: Allow http and https for scheme-less sources</title>
   </head>
   <body>
   <div id="testdiv">blocked</div>
   <!--
-    We resue file_csp_path_matching.js which just updates the contents of 'testdiv' to contain allowed.
-    Note, that we are loading the file_csp_path_matchting.js using a scheme of 'https'.
+    We resue file_path_matching.js which just updates the contents of 'testdiv' to contain allowed.
+    Note, that we are loading the file_path_matchting.js using a scheme of 'https'.
    -->
-  <script src="https://example.com/tests/dom/base/test/csp/file_csp_path_matching.js#foo"></script>
+  <script src="https://example.com/tests/dom/security/test/csp/file_path_matching.js#foo"></script>
 </body>
 </html>
rename from dom/base/test/csp/file_base-uri.html
rename to dom/security/test/csp/file_base-uri.html
rename from dom/base/test/csp/file_blob_data_schemes.html
rename to dom/security/test/csp/file_blob_data_schemes.html
rename from dom/base/test/csp/file_CSP_bug663567.xsl
rename to dom/security/test/csp/file_bug663567.xsl
rename from dom/base/test/csp/file_CSP_bug663567_allows.xml
rename to dom/security/test/csp/file_bug663567_allows.xml
--- a/dom/base/test/csp/file_CSP_bug663567_allows.xml
+++ b/dom/security/test/csp/file_bug663567_allows.xml
@@ -1,10 +1,10 @@
 <?xml version="1.0" encoding="ISO-8859-1"?>
-<?xml-stylesheet type="text/xsl" href="file_CSP_bug663567.xsl"?>
+<?xml-stylesheet type="text/xsl" href="file_bug663567.xsl"?>
 <catalog>
 	<cd>
 		<title>Empire Burlesque</title>
 		<artist>Bob Dylan</artist>
 		<country>USA</country>
 		<company>Columbia</company>
 		<price>10.90</price>
 		<year>1985</year>
rename from dom/base/test/csp/file_CSP_bug663567_allows.xml^headers^
rename to dom/security/test/csp/file_bug663567_allows.xml^headers^
rename from dom/base/test/csp/file_CSP_bug663567_blocks.xml
rename to dom/security/test/csp/file_bug663567_blocks.xml
--- a/dom/base/test/csp/file_CSP_bug663567_blocks.xml
+++ b/dom/security/test/csp/file_bug663567_blocks.xml
@@ -1,10 +1,10 @@
 <?xml version="1.0" encoding="ISO-8859-1"?>
-<?xml-stylesheet type="text/xsl" href="file_CSP_bug663567.xsl"?>
+<?xml-stylesheet type="text/xsl" href="file_bug663567.xsl"?>
 <catalog>
 	<cd>
 		<title>Empire Burlesque</title>
 		<artist>Bob Dylan</artist>
 		<country>USA</country>
 		<company>Columbia</company>
 		<price>10.90</price>
 		<year>1985</year>
rename from dom/base/test/csp/file_CSP_bug663567_blocks.xml^headers^
rename to dom/security/test/csp/file_bug663567_blocks.xml^headers^
rename from dom/base/test/csp/file_csp_bug768029.html
rename to dom/security/test/csp/file_bug768029.html
--- a/dom/base/test/csp/file_csp_bug768029.html
+++ b/dom/security/test/csp/file_bug768029.html
@@ -3,23 +3,23 @@
 <!--
   https://bugzilla.mozilla.org/show_bug.cgi?id=768029
 -->
 <head>
   <meta charset="utf-8">
     <title>This is an app for testing</title>
 
     <link rel="stylesheet" type="text/css"
-          href="file_csp_bug768029.sjs?type=style&origin=same_origin" />
+          href="file_bug768029.sjs?type=style&origin=same_origin" />
     <link rel="stylesheet" type="text/css"
-          href="http://example.com/tests/dom/base/test/csp/file_csp_bug768029.sjs?type=style&origin=cross_origin" />
+          href="http://example.com/tests/dom/security/test/csp/file_bug768029.sjs?type=style&origin=cross_origin" />
   </head>
   <body>
 
-    <script src="file_csp_bug768029.sjs?type=script&origin=same_origin"></script>
-    <script src="http://example.com/tests/dom/base/test/csp/file_csp_bug768029.sjs?type=script&origin=cross_origin"></script>
-    <img src="file_csp_bug768029.sjs?type=img&origin=same_origin" />
-    <img src="http://example.com/tests/dom/base/test/csp/file_csp_bug768029.sjs?type=img&origin=cross_origin" />
+    <script src="file_bug768029.sjs?type=script&origin=same_origin"></script>
+    <script src="http://example.com/tests/dom/security/test/csp/file_bug768029.sjs?type=script&origin=cross_origin"></script>
+    <img src="file_bug768029.sjs?type=img&origin=same_origin" />
+    <img src="http://example.com/tests/dom/security/test/csp/file_bug768029.sjs?type=img&origin=cross_origin" />
 
     Test for CSP applied to (simulated) app.
 
   </body>
 </html>
rename from dom/base/test/csp/file_csp_bug768029.sjs
rename to dom/security/test/csp/file_bug768029.sjs
rename from dom/base/test/csp/file_csp_bug773891.html
rename to dom/security/test/csp/file_bug773891.html
--- a/dom/base/test/csp/file_csp_bug773891.html
+++ b/dom/security/test/csp/file_bug773891.html
@@ -3,23 +3,23 @@
 <!--
   https://bugzilla.mozilla.org/show_bug.cgi?id=773891
 -->
 <head>
   <meta charset="utf-8">
     <title>This is an app for csp testing</title>
 
     <link rel="stylesheet" type="text/css"
-          href="file_csp_bug773891.sjs?type=style&origin=same_origin" />
+          href="file_bug773891.sjs?type=style&origin=same_origin" />
     <link rel="stylesheet" type="text/css"
-          href="http://example.com/tests/dom/base/test/csp/file_csp_bug773891.sjs?type=style&origin=cross_origin" />
+          href="http://example.com/tests/dom/security/test/csp/file_bug773891.sjs?type=style&origin=cross_origin" />
   </head>
   <body>
 
-    <script src="file_csp_bug773891.sjs?type=script&origin=same_origin"></script>
-    <script src="http://example.com/tests/dom/base/test/csp/file_csp_bug773891.sjs?type=script&origin=cross_origin"></script>
-    <img src="file_csp_bug773891.sjs?type=img&origin=same_origin" />
-    <img src="http://example.com/tests/dom/base/test/csp/file_csp_bug773891.sjs?type=img&origin=cross_origin" />
+    <script src="file_bug773891.sjs?type=script&origin=same_origin"></script>
+    <script src="http://example.com/tests/dom/security/test/csp/file_bug773891.sjs?type=script&origin=cross_origin"></script>
+    <img src="file_bug773891.sjs?type=img&origin=same_origin" />
+    <img src="http://example.com/tests/dom/security/test/csp/file_bug773891.sjs?type=img&origin=cross_origin" />
 
     Test for CSP applied to (simulated) app.
 
   </body>
 </html>
rename from dom/base/test/csp/file_csp_bug773891.sjs
rename to dom/security/test/csp/file_bug773891.sjs
rename from dom/base/test/csp/file_CSP_bug802872.html
rename to dom/security/test/csp/file_bug802872.html
--- a/dom/base/test/csp/file_CSP_bug802872.html
+++ b/dom/security/test/csp/file_bug802872.html
@@ -2,11 +2,11 @@
 <html>
 <head>
   <title>Bug 802872</title>
   <!-- Including SimpleTest.js so we can use AddLoadEvent !-->
   <script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
   <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
 </head>
 <body>
-  <script src='file_CSP_bug802872.js'></script>
+  <script src='file_bug802872.js'></script>
 </body>
 </html>
rename from dom/base/test/csp/file_CSP_bug802872.html^headers^
rename to dom/security/test/csp/file_bug802872.html^headers^
rename from dom/base/test/csp/file_CSP_bug802872.js
rename to dom/security/test/csp/file_bug802872.js
--- a/dom/base/test/csp/file_CSP_bug802872.js
+++ b/dom/security/test/csp/file_bug802872.js
@@ -3,17 +3,17 @@
  *   Content-Security-Policy: default-src 'self'
  */
 
 function createAllowedEvent() {
   /*
    * Creates a new EventSource using 'http://mochi.test:8888'. Since all mochitests run on
    * 'http://mochi.test', a default-src of 'self' allows this request.
    */
-  var src_event = new EventSource("http://mochi.test:8888/tests/dom/base/test/csp/file_CSP_bug802872.sjs");
+  var src_event = new EventSource("http://mochi.test:8888/tests/dom/security/test/csp/file_bug802872.sjs");
 
   src_event.onmessage = function(e) {
     src_event.close();
     parent.dispatchEvent(new Event('allowedEventSrcCallbackOK'));
   }
 
   src_event.onerror = function(e) {
     src_event.close();
@@ -21,17 +21,17 @@ function createAllowedEvent() {
   }
 }
 
 function createBlockedEvent() {
   /*
    * creates a new EventSource using 'http://example.com'. This domain is not whitelisted by the 
    * CSP of this page, therefore the CSP blocks this request.
    */
-  var src_event = new EventSource("http://example.com/tests/dom/base/test/csp/file_CSP_bug802872.sjs");
+  var src_event = new EventSource("http://example.com/tests/dom/security/test/csp/file_bug802872.sjs");
 
   src_event.onmessage = function(e) {
     src_event.close();
     parent.dispatchEvent(new Event('blockedEventSrcCallbackOK'));
   }
 
   src_event.onerror = function(e) {
     src_event.close();
rename from dom/base/test/csp/file_CSP_bug802872.sjs
rename to dom/security/test/csp/file_bug802872.sjs
rename from dom/base/test/csp/file_bug836922_npolicies.html
rename to dom/security/test/csp/file_bug836922_npolicies.html
--- a/dom/base/test/csp/file_bug836922_npolicies.html
+++ b/dom/security/test/csp/file_bug836922_npolicies.html
@@ -1,15 +1,15 @@
 <html>
   <head>
     <link rel='stylesheet' type='text/css'
-          href='/tests/dom/base/test/csp/file_CSP.sjs?testid=css_self&type=text/css' />
+          href='/tests/dom/security/test/csp/file_CSP.sjs?testid=css_self&type=text/css' />
     <link rel='stylesheet' type='text/css'
-          href='http://example.com/tests/dom/base/test/csp/file_CSP.sjs?testid=css_examplecom&type=text/css' />
+          href='http://example.com/tests/dom/security/test/csp/file_CSP.sjs?testid=css_examplecom&type=text/css' />
 
   </head>
   <body>
-    <img src="/tests/dom/base/test/csp/file_CSP.sjs?testid=img_self&type=img/png"> </img>
-    <img src="http://example.com/tests/dom/base/test/csp/file_CSP.sjs?testid=img_examplecom&type=img/png"> </img>
-    <script src='/tests/dom/base/test/csp/file_CSP.sjs?testid=script_self&type=text/javascript'></script>
+    <img src="/tests/dom/security/test/csp/file_CSP.sjs?testid=img_self&type=img/png"> </img>
+    <img src="http://example.com/tests/dom/security/test/csp/file_CSP.sjs?testid=img_examplecom&type=img/png"> </img>
+    <script src='/tests/dom/security/test/csp/file_CSP.sjs?testid=script_self&type=text/javascript'></script>
 
   </body>
 </html>
rename from dom/base/test/csp/file_bug836922_npolicies.html^headers^
rename to dom/security/test/csp/file_bug836922_npolicies.html^headers^
--- a/dom/base/test/csp/file_bug836922_npolicies.html^headers^
+++ b/dom/security/test/csp/file_bug836922_npolicies.html^headers^
@@ -1,2 +1,2 @@
-content-security-policy: default-src 'self'; img-src 'none'; report-uri http://mochi.test:8888/tests/dom/base/test/csp/file_bug836922_npolicies_violation.sjs
-content-security-policy-report-only: default-src *; img-src 'self'; script-src 'none'; report-uri http://mochi.test:8888/tests/dom/base/test/csp/file_bug836922_npolicies_ro_violation.sjs
+content-security-policy: default-src 'self'; img-src 'none'; report-uri http://mochi.test:8888/tests/dom/security/test/csp/file_bug836922_npolicies_violation.sjs
+content-security-policy-report-only: default-src *; img-src 'self'; script-src 'none'; report-uri http://mochi.test:8888/tests/dom/security/test/csp/file_bug836922_npolicies_ro_violation.sjs
rename from dom/base/test/csp/file_bug836922_npolicies_ro_violation.sjs
rename to dom/security/test/csp/file_bug836922_npolicies_ro_violation.sjs
rename from dom/base/test/csp/file_bug836922_npolicies_violation.sjs
rename to dom/security/test/csp/file_bug836922_npolicies_violation.sjs
rename from dom/base/test/csp/file_CSP_bug885433_allows.html
rename to dom/security/test/csp/file_bug885433_allows.html
rename from dom/base/test/csp/file_CSP_bug885433_allows.html^headers^
rename to dom/security/test/csp/file_bug885433_allows.html^headers^
rename from dom/base/test/csp/file_CSP_bug885433_blocks.html
rename to dom/security/test/csp/file_bug885433_blocks.html
rename from dom/base/test/csp/file_CSP_bug885433_blocks.html^headers^
rename to dom/security/test/csp/file_bug885433_blocks.html^headers^
rename from dom/base/test/csp/file_bug886164.html
rename to dom/security/test/csp/file_bug886164.html
--- a/dom/base/test/csp/file_bug886164.html
+++ b/dom/security/test/csp/file_bug886164.html
@@ -1,15 +1,15 @@
 <html>
 <head> <meta charset="utf-8"> </head>
   <body>
     <!-- sandbox="allow-same-origin" -->
     <!-- Content-Security-Policy: default-src 'self' -->
 
     <!-- these should be stopped by CSP -->
-    <img src="http://example.org/tests/dom/base/test/csp/file_CSP.sjs?testid=img_bad&type=img/png"> </img>
+    <img src="http://example.org/tests/dom/security/test/csp/file_CSP.sjs?testid=img_bad&type=img/png"> </img>
 
     <!-- these should load ok -->
-    <img src="/tests/dom/base/test/csp/file_CSP.sjs?testid=img_good&type=img/png" />
-    <script src='/tests/dom/base/test/csp/file_CSP.sjs?testid=scripta_bad&type=text/javascript'></script>
+    <img src="/tests/dom/security/test/csp/file_CSP.sjs?testid=img_good&type=img/png" />
+    <script src='/tests/dom/security/test/csp/file_CSP.sjs?testid=scripta_bad&type=text/javascript'></script>
 
   </body>
 </html>
rename from dom/base/test/csp/file_bug886164.html^headers^
rename to dom/security/test/csp/file_bug886164.html^headers^
rename from dom/base/test/csp/file_bug886164_2.html
rename to dom/security/test/csp/file_bug886164_2.html
--- a/dom/base/test/csp/file_bug886164_2.html
+++ b/dom/security/test/csp/file_bug886164_2.html
@@ -1,14 +1,14 @@
 <html>
 <head> <meta charset="utf-8"> </head>
   <body>
     <!-- sandbox -->
     <!-- Content-Security-Policy: default-src 'self' -->
 
     <!-- these should be stopped by CSP -->
-    <img src="http://example.org/tests/dom/base/test/csp/file_CSP.sjs?testid=img2_bad&type=img/png"> </img>
+    <img src="http://example.org/tests/dom/security/test/csp/file_CSP.sjs?testid=img2_bad&type=img/png"> </img>
 
     <!-- these should load ok -->
-    <img src="/tests/dom/base/test/csp/file_CSP.sjs?testid=img2a_good&type=img/png" />
+    <img src="/tests/dom/security/test/csp/file_CSP.sjs?testid=img2a_good&type=img/png" />
 
   </body>
 </html>
rename from dom/base/test/csp/file_bug886164_2.html^headers^
rename to dom/security/test/csp/file_bug886164_2.html^headers^
rename from dom/base/test/csp/file_bug886164_3.html
rename to dom/security/test/csp/file_bug886164_3.html
--- a/dom/base/test/csp/file_bug886164_3.html
+++ b/dom/security/test/csp/file_bug886164_3.html
@@ -1,12 +1,12 @@
 <html>
 <head> <meta charset="utf-8"> </head>
   <body>
     <!-- sandbox -->
     <!-- Content-Security-Policy: default-src 'none' -->
 
     <!-- these should be stopped by CSP -->
-    <img src="http://example.org/tests/dom/base/test/csp/file_CSP.sjs?testid=img3_bad&type=img/png"> </img>
-    <img src="/tests/dom/base/test/csp/file_CSP.sjs?testid=img3a_bad&type=img/png" />
+    <img src="http://example.org/tests/dom/security/test/csp/file_CSP.sjs?testid=img3_bad&type=img/png"> </img>
+    <img src="/tests/dom/security/test/csp/file_CSP.sjs?testid=img3a_bad&type=img/png" />
 
   </body>
 </html>
rename from dom/base/test/csp/file_bug886164_3.html^headers^
rename to dom/security/test/csp/file_bug886164_3.html^headers^
rename from dom/base/test/csp/file_bug886164_4.html
rename to dom/security/test/csp/file_bug886164_4.html
--- a/dom/base/test/csp/file_bug886164_4.html
+++ b/dom/security/test/csp/file_bug886164_4.html
@@ -1,12 +1,12 @@
 <html>
 <head> <meta charset="utf-8"> </head>
   <body>
     <!-- sandbox -->
     <!-- Content-Security-Policy: default-src 'none' -->
 
     <!-- these should be stopped by CSP -->
-    <img src="http://example.org/tests/dom/base/test/csp/file_CSP.sjs?testid=img4_bad&type=img/png"> </img>
-    <img src="/tests/dom/base/test/csp/file_CSP.sjs?testid=img4a_bad&type=img/png" />
+    <img src="http://example.org/tests/dom/security/test/csp/file_CSP.sjs?testid=img4_bad&type=img/png"> </img>
+    <img src="/tests/dom/security/test/csp/file_CSP.sjs?testid=img4a_bad&type=img/png" />
 
   </body>
 </html>
rename from dom/base/test/csp/file_bug886164_4.html^headers^
rename to dom/security/test/csp/file_bug886164_4.html^headers^
rename from dom/base/test/csp/file_bug886164_5.html
rename to dom/security/test/csp/file_bug886164_5.html
--- a/dom/base/test/csp/file_bug886164_5.html
+++ b/dom/security/test/csp/file_bug886164_5.html
@@ -13,14 +13,14 @@
 <script src='file_iframe_sandbox_pass.js'></script>
 <body onLoad='ok(true, "documents sandboxed with allow-scripts should be able to run script from event listeners");doStuff();'>
   I am sandboxed but with only inline "allow-scripts"
 
  <!-- sandbox="allow-scripts" -->
  <!-- Content-Security-Policy: default-src 'none' 'unsafe-inline'-->
 
  <!-- these should be stopped by CSP -->
- <img src="/tests/dom/base/test/csp/file_CSP.sjs?testid=img5_bad&type=img/png" />
- <img src="http://example.org/tests/dom/base/test/csp/file_CSP.sjs?testid=img5a_bad&type=img/png"> </img>
- <script src='/tests/dom/base/test/csp/file_CSP.sjs?testid=script5_bad&type=text/javascript'></script>
- <script src='http://example.org/tests/dom/base/test/csp/file_CSP.sjs?testid=script5a_bad&type=text/javascript'></script>
+ <img src="/tests/dom/security/test/csp/file_CSP.sjs?testid=img5_bad&type=img/png" />
+ <img src="http://example.org/tests/dom/security/test/csp/file_CSP.sjs?testid=img5a_bad&type=img/png"> </img>
+ <script src='/tests/dom/security/test/csp/file_CSP.sjs?testid=script5_bad&type=text/javascript'></script>
+ <script src='http://example.org/tests/dom/security/test/csp/file_CSP.sjs?testid=script5a_bad&type=text/javascript'></script>
 </body>
 </html>
rename from dom/base/test/csp/file_bug886164_5.html^headers^
rename to dom/security/test/csp/file_bug886164_5.html^headers^
rename from dom/base/test/csp/file_bug886164_6.html
rename to dom/security/test/csp/file_bug886164_6.html
--- a/dom/base/test/csp/file_bug886164_6.html
+++ b/dom/security/test/csp/file_bug886164_6.html
@@ -16,18 +16,18 @@
 
     // trigger the javascript: url test
     sendMouseEvent({type:'click'}, 'a_link');
   }
 </script>
 <script src='file_iframe_sandbox_pass.js'></script>
 <body onLoad='ok(true, "documents sandboxed with allow-scripts should be able to run script from event listeners");doStuff();'>
   I am sandboxed but with "allow-scripts"
-  <img src="http://example.org/tests/dom/base/test/csp/file_CSP.sjs?testid=img6_bad&type=img/png"> </img>
-  <script src='http://example.org/tests/dom/base/test/csp/file_CSP.sjs?testid=script6_bad&type=text/javascript'></script>
+  <img src="http://example.org/tests/dom/security/test/csp/file_CSP.sjs?testid=img6_bad&type=img/png"> </img>
+  <script src='http://example.org/tests/dom/security/test/csp/file_CSP.sjs?testid=script6_bad&type=text/javascript'></script>
 
   <form method="get" action="file_iframe_sandbox_form_fail.html" id="a_form">
     First name: <input type="text" name="firstname">
     Last name: <input type="text" name="lastname">
     <input type="submit" onclick="doSubmit()" id="a_button">
   </form>
 
   <a href = 'javascript:ok(true, "documents sandboxed with allow-scripts should be able to run script from javascript: URLs");' id='a_link'>click me</a>
rename from dom/base/test/csp/file_bug886164_6.html^headers^
rename to dom/security/test/csp/file_bug886164_6.html^headers^
rename from dom/base/test/csp/file_CSP_bug888172.html
rename to dom/security/test/csp/file_bug888172.html
rename from dom/base/test/csp/file_CSP_bug888172.sjs
rename to dom/security/test/csp/file_bug888172.sjs
--- a/dom/base/test/csp/file_CSP_bug888172.sjs
+++ b/dom/security/test/csp/file_bug888172.sjs
@@ -34,10 +34,10 @@ function handleRequest(request, response
   response.setHeader("Cache-Control", "no-cache", false);
 
   // Deliver the CSP policy encoded in the URI
   if (query['csp'])
     response.setHeader("Content-Security-Policy", unescape(query['csp']), false);
 
   // Send HTML to test allowed/blocked behaviors
   response.setHeader("Content-Type", "text/html", false);
-  response.write(loadHTMLFromFile("tests/dom/base/test/csp/file_CSP_bug888172.html"));
+  response.write(loadHTMLFromFile("tests/dom/security/test/csp/file_bug888172.html"));
 }
rename from dom/base/test/csp/file_CSP_bug909029_none.html
rename to dom/security/test/csp/file_bug909029_none.html
rename from dom/base/test/csp/file_CSP_bug909029_none.html^headers^
rename to dom/security/test/csp/file_bug909029_none.html^headers^
rename from dom/base/test/csp/file_CSP_bug909029_star.html
rename to dom/security/test/csp/file_bug909029_star.html
rename from dom/base/test/csp/file_CSP_bug909029_star.html^headers^
rename to dom/security/test/csp/file_bug909029_star.html^headers^
rename from dom/base/test/csp/file_CSP_bug910139.sjs
rename to dom/security/test/csp/file_bug910139.sjs
--- a/dom/base/test/csp/file_CSP_bug910139.sjs
+++ b/dom/security/test/csp/file_bug910139.sjs
@@ -1,9 +1,9 @@
-// Server side js file for bug 910139, see file test_CSP_bug910139.html for details.
+// Server side js file for bug 910139, see file test_bug910139.html for details.
 
 Components.utils.import("resource://gre/modules/NetUtil.jsm");
 
 function loadResponseFromFile(path) {
   var testHTMLFile =
     Components.classes["@mozilla.org/file/directory_service;1"].
     getService(Components.interfaces.nsIProperties).
     get("CurWorkD", Components.interfaces.nsILocalFile);
@@ -43,10 +43,10 @@ function handleRequest(request, response
 {
   // avoid confusing cache behaviors
   response.setHeader("Cache-Control", "no-cache", false);
 
   // set the required CSP
   response.setHeader("Content-Security-Policy", getPolicy(), false);
 
   // return the requested XML file.
-  response.write(loadResponseFromFile("tests/dom/base/test/csp/file_CSP_bug910139.xml"));
+  response.write(loadResponseFromFile("tests/dom/security/test/csp/file_bug910139.xml"));
 }
rename from dom/base/test/csp/file_CSP_bug910139.xml
rename to dom/security/test/csp/file_bug910139.xml
--- a/dom/base/test/csp/file_CSP_bug910139.xml
+++ b/dom/security/test/csp/file_bug910139.xml
@@ -1,10 +1,10 @@
 <?xml version="1.0" encoding="ISO-8859-1"?>
-<?xml-stylesheet type="text/xsl" href="file_CSP_bug910139.xsl"?>
+<?xml-stylesheet type="text/xsl" href="file_bug910139.xsl"?>
 <catalog>
 	<cd>
 		<title>Empire Burlesque</title>
 		<artist>Bob Dylan</artist>
 		<country>USA</country>
 		<company>Columbia</company>
 		<price>10.90</price>
 		<year>1985</year>
rename from dom/base/test/csp/file_CSP_bug910139.xsl
rename to dom/security/test/csp/file_bug910139.xsl
rename from dom/base/test/csp/file_CSP_bug941404.html
rename to dom/security/test/csp/file_bug941404.html
--- a/dom/base/test/csp/file_CSP_bug941404.html
+++ b/dom/security/test/csp/file_bug941404.html
@@ -1,27 +1,27 @@
 <html>
 <head> <meta charset="utf-8"> </head>
   <body>
 
     <!-- this should be allowed (no CSP)-->
-    <img src="http://example.org/tests/dom/base/test/csp/file_CSP.sjs?testid=img_good&type=img/png"> </img>
+    <img src="http://example.org/tests/dom/security/test/csp/file_CSP.sjs?testid=img_good&type=img/png"> </img>
 
 
     <script type="text/javascript">
       var req = new XMLHttpRequest();
       req.onload = function() {
         //this should be allowed (no CSP)
         try {
         var img = document.createElement("img");
-        img.src="http://example.org/tests/dom/base/test/csp/file_CSP.sjs?testid=img2_good&type=img/png";
+        img.src="http://example.org/tests/dom/security/test/csp/file_CSP.sjs?testid=img2_good&type=img/png";
         document.body.appendChild(img);
         } catch(e) {
           console.log("yo: "+e);
         }
       };
-      req.open("get", "file_CSP_bug941404_xhr.html", true);
+      req.open("get", "file_bug941404_xhr.html", true);
       req.responseType = "document";
       req.send();
     </script>
 
   </body>
 </html>
rename from dom/base/test/csp/file_CSP_bug941404_xhr.html
rename to dom/security/test/csp/file_bug941404_xhr.html
rename from dom/base/test/csp/file_CSP_bug941404_xhr.html^headers^
rename to dom/security/test/csp/file_bug941404_xhr.html^headers^
rename from dom/base/test/csp/file_connect-src-fetch.html
rename to dom/security/test/csp/file_connect-src-fetch.html
--- a/dom/base/test/csp/file_connect-src-fetch.html
+++ b/dom/security/test/csp/file_connect-src-fetch.html
@@ -1,16 +1,16 @@
 <!DOCTYPE HTML>
 <html>
   <head>
     <title>Bug 1139667 - Test mapping of fetch() to connect-src</title>
   </head>
   <body>
   <script type="text/javascript">
 
-    // Please note that file_csp_testserver.sjs?foo does not return a response.
+    // Please note that file_testserver.sjs?foo does not return a response.
     // For testing purposes this is not necessary because we only want to check
     // whether CSP allows or blocks the load.
-    fetch( "file_csp_testserver.sjs?foo");
+    fetch( "file_testserver.sjs?foo");
 
   </script>
 </body>
 </html>
rename from dom/base/test/csp/file_connect-src.html
rename to dom/security/test/csp/file_connect-src.html
--- a/dom/base/test/csp/file_connect-src.html
+++ b/dom/security/test/csp/file_connect-src.html
@@ -2,20 +2,20 @@
 <html>
   <head>
     <title>Bug 1031530 - Test mapping of XMLHttpRequest to connect-src</title>
   </head>
   <body>
   <script type="text/javascript">
 
     try {
-      // Please note that file_csp_testserver.sjs?foo does not return a response.
+      // Please note that file_testserver.sjs?foo does not return a response.
       // For testing purposes this is not necessary because we only want to check
       // whether CSP allows or blocks the load.
       var xhr = new XMLHttpRequest();
-      xhr.open("GET", "file_csp_testserver.sjs?foo", false);
+      xhr.open("GET", "file_testserver.sjs?foo", false);
       xhr.send(null);
     }
     catch (e) { }
 
   </script>
 </body>
 </html>
rename from dom/base/test/csp/file_dual_header_testserver.sjs
rename to dom/security/test/csp/file_dual_header_testserver.sjs
rename from dom/base/test/csp/file_CSP_evalscript_main.html
rename to dom/security/test/csp/file_evalscript_main.html
--- a/dom/base/test/csp/file_CSP_evalscript_main.html
+++ b/dom/security/test/csp/file_evalscript_main.html
@@ -1,12 +1,12 @@
 <html>
   <head>
     <title>CSP eval script tests</title>
     <script type="application/javascript"
-             src="file_CSP_evalscript_main.js"></script>
+             src="file_evalscript_main.js"></script>
   </head>
   <body>
 
     Foo.
 
   </body>
 </html>
rename from dom/base/test/csp/file_CSP_evalscript_main.html^headers^
rename to dom/security/test/csp/file_evalscript_main.html^headers^
rename from dom/base/test/csp/file_CSP_evalscript_main.js
rename to dom/security/test/csp/file_evalscript_main.js
rename from dom/base/test/csp/file_CSP_evalscript_main_allowed.html
rename to dom/security/test/csp/file_evalscript_main_allowed.html
--- a/dom/base/test/csp/file_CSP_evalscript_main_allowed.html
+++ b/dom/security/test/csp/file_evalscript_main_allowed.html
@@ -1,12 +1,12 @@
 <html>
   <head>
     <title>CSP eval script tests</title>
     <script type="application/javascript"
-             src="file_CSP_evalscript_main_allowed.js"></script>
+             src="file_evalscript_main_allowed.js"></script>
   </head>
   <body>
 
     Foo.
 
   </body>
 </html>
rename from dom/base/test/csp/file_CSP_evalscript_main_allowed.html^headers^
rename to dom/security/test/csp/file_evalscript_main_allowed.html^headers^
rename from dom/base/test/csp/file_CSP_evalscript_main_allowed.js
rename to dom/security/test/csp/file_evalscript_main_allowed.js
rename from dom/base/test/csp/file_form-action.html
rename to dom/security/test/csp/file_form-action.html
rename from dom/base/test/csp/file_CSP_frameancestors.sjs
rename to dom/security/test/csp/file_frameancestors.sjs
--- a/dom/base/test/csp/file_CSP_frameancestors.sjs
+++ b/dom/security/test/csp/file_frameancestors.sjs
@@ -25,19 +25,19 @@ function handleRequest(request, response
       response.write('window.parent.parent.parent.postMessage({call: "frameLoaded", testname: "' + query['scriptedreport'] + '", uri: "window.location.toString()"}, "*");');
     else
       response.write('window.parent.parent.postMessage({call: "frameLoaded", testname: "' + query['scriptedreport'] + '", uri: "window.location.toString()"}, "*");');
   } else if (query['internalframe']) {
     // spit back an internal iframe (one that might be blocked)
     response.setHeader("Content-Type", "text/html", false);
     response.write('<html><head>');
     if (query['double'])
-      response.write('<script src="file_CSP_frameancestors.sjs?double=1&scriptedreport=' + query['testid'] + '"></script>');
+      response.write('<script src="file_frameancestors.sjs?double=1&scriptedreport=' + query['testid'] + '"></script>');
     else
-      response.write('<script src="file_CSP_frameancestors.sjs?scriptedreport=' + query['testid'] + '"></script>');
+      response.write('<script src="file_frameancestors.sjs?scriptedreport=' + query['testid'] + '"></script>');
     response.write('</head><body>');
     response.write(unescape(query['internalframe']));
     response.write('</body></html>');
   } else if (query['externalframe']) {
     // spit back an internal iframe (one that won't be blocked, and probably
     // has no CSP)
     response.setHeader("Content-Type", "text/html", false);
     response.write('<html><head>');
rename from dom/base/test/csp/file_CSP_frameancestors_main.html
rename to dom/security/test/csp/file_frameancestors_main.html
--- a/dom/base/test/csp/file_CSP_frameancestors_main.html
+++ b/dom/security/test/csp/file_frameancestors_main.html
@@ -1,14 +1,14 @@
 <html>
   <head>
     <title>CSP frame ancestors tests</title>
 
     <!-- this page shouldn't have a CSP, just the sub-pages. -->
-    <script src='file_CSP_frameancestors_main.js'></script>
+    <script src='file_frameancestors_main.js'></script>
 
   </head>
   <body>
 
 <!-- These iframes will get populated by the attached javascript. -->
 <tt>  aa_allow:   /* innermost frame allows a */</tt><br/>
 <iframe id='aa_allow'></iframe><br/>
 
rename from dom/base/test/csp/file_CSP_frameancestors_main.js
rename to dom/security/test/csp/file_frameancestors_main.js
--- a/dom/base/test/csp/file_CSP_frameancestors_main.js
+++ b/dom/security/test/csp/file_frameancestors_main.js
@@ -1,17 +1,17 @@
 // Script to populate the test frames in the frame ancestors mochitest.
 //
 function setupFrames() {
 
   var $ = function(v) { return document.getElementById(v); }
   var base = {
-        self: '/tests/dom/base/test/csp/file_CSP_frameancestors.sjs',
-        a: 'http://mochi.test:8888/tests/dom/base/test/csp/file_CSP_frameancestors.sjs',
-        b: 'http://example.com/tests/dom/base/test/csp/file_CSP_frameancestors.sjs'
+        self: '/tests/dom/security/test/csp/file_frameancestors.sjs',
+        a: 'http://mochi.test:8888/tests/dom/security/test/csp/file_frameancestors.sjs',
+        b: 'http://example.com/tests/dom/security/test/csp/file_frameancestors.sjs'
   };
 
   var host = { a: 'http://mochi.test:8888', b: 'http://example.com:80' };
 
   var innerframeuri = null;
   var elt = null;
 
   elt = $('aa_allow');
rename from dom/base/test/csp/file_hash_source.html
rename to dom/security/test/csp/file_hash_source.html
rename from dom/base/test/csp/file_hash_source.html^headers^
rename to dom/security/test/csp/file_hash_source.html^headers^
rename from dom/base/test/csp/file_ignore_unsafe_inline.html
rename to dom/security/test/csp/file_ignore_unsafe_inline.html
rename from dom/base/test/csp/file_CSP_inlinescript_main.html
rename to dom/security/test/csp/file_inlinescript_main.html
rename from dom/base/test/csp/file_CSP_inlinescript_main.html^headers^
rename to dom/security/test/csp/file_inlinescript_main.html^headers^
rename from dom/base/test/csp/file_CSP_inlinescript_main_allowed.html
rename to dom/security/test/csp/file_inlinescript_main_allowed.html
rename from dom/base/test/csp/file_CSP_inlinescript_main_allowed.html^headers^
rename to dom/security/test/csp/file_inlinescript_main_allowed.html^headers^
rename from dom/base/test/csp/file_CSP_inlinestyle_main.html
rename to dom/security/test/csp/file_inlinestyle_main.html
rename from dom/base/test/csp/file_CSP_inlinestyle_main.html^headers^
rename to dom/security/test/csp/file_inlinestyle_main.html^headers^
rename from dom/base/test/csp/file_CSP_inlinestyle_main_allowed.html
rename to dom/security/test/csp/file_inlinestyle_main_allowed.html
rename from dom/base/test/csp/file_CSP_inlinestyle_main_allowed.html^headers^
rename to dom/security/test/csp/file_inlinestyle_main_allowed.html^headers^
rename from dom/base/test/csp/file_csp_invalid_source_expression.html
rename to dom/security/test/csp/file_invalid_source_expression.html
--- a/dom/base/test/csp/file_csp_invalid_source_expression.html
+++ b/dom/security/test/csp/file_invalid_source_expression.html
@@ -1,11 +1,11 @@
 <!DOCTYPE HTML>
 <html>
   <head>
     <title>Bug 1086612 - CSP: Let source expression be the empty set in case no valid source can be parsed</title>
   </head>
   <body>
   <div id="testdiv">blocked</div>
-  <!-- Note, we reuse file_csp_path_matching.js which only updates the testdiv to 'allowed' if loaded !-->
-  <script src="http://test1.example.com/tests/dom/base/test/csp/file_csp_path_matching.js"></script>
+  <!-- Note, we reuse file_path_matching.js which only updates the testdiv to 'allowed' if loaded !-->
+  <script src="http://test1.example.com/tests/dom/security/test/csp/file_path_matching.js"></script>
 </body>
 </html>
rename from dom/base/test/csp/file_leading_wildcard.html
rename to dom/security/test/csp/file_leading_wildcard.html
--- a/dom/base/test/csp/file_leading_wildcard.html
+++ b/dom/security/test/csp/file_leading_wildcard.html
@@ -1,11 +1,11 @@
 <!DOCTYPE HTML>
 <html>
   <head>
     <title>Bug 1032303 - CSP - Keep FULL STOP when matching *.foo.com to disallow loads from foo.com</title>
   </head>
   <body>
   <!-- Please note that both scripts do *not* exist in the file system -->
-  <script src="http://test1.example.com/tests/dom/base/test/csp/leading_wildcard_allowed.js" ></script>
-  <script src="http://example.com/tests/dom/base/test/csp/leading_wildcard_blocked.js" ></script>
+  <script src="http://test1.example.com/tests/dom/security/test/csp/leading_wildcard_allowed.js" ></script>
+  <script src="http://example.com/tests/dom/security/test/csp/leading_wildcard_blocked.js" ></script>
 </body>
 </html>
rename from dom/base/test/csp/file_CSP_main.html
rename to dom/security/test/csp/file_main.html
--- a/dom/base/test/csp/file_CSP_main.html
+++ b/dom/security/test/csp/file_main.html
@@ -1,55 +1,55 @@
 <html>
   <head>
     <link rel='stylesheet' type='text/css'
-          href='http://example.org/tests/dom/base/test/csp/file_CSP.sjs?testid=style_bad&type=text/css' />
+          href='http://example.org/tests/dom/security/test/csp/file_CSP.sjs?testid=style_bad&type=text/css' />
     <link rel='stylesheet' type='text/css'
           href='file_CSP.sjs?testid=style_good&type=text/css' />
 
 
     <style>
       /* CSS font embedding tests */
       @font-face {
         font-family: "arbitrary_good";
         src: url('file_CSP.sjs?testid=font_good&type=application/octet-stream');
       }
       @font-face {
         font-family: "arbitrary_bad";
-        src: url('http://example.org/tests/dom/base/test/csp/file_CSP.sjs?testid=font_bad&type=application/octet-stream');
+        src: url('http://example.org/tests/dom/security/test/csp/file_CSP.sjs?testid=font_bad&type=application/octet-stream');
       }
 
       .div_arbitrary_good { font-family: "arbitrary_good"; }
       .div_arbitrary_bad { font-family: "arbitrary_bad"; }
     </style>
   </head>
   <body>
     <!-- these should be stopped by CSP.  :) -->
-    <img src="http://example.org/tests/dom/base/test/csp/file_CSP.sjs?testid=img_bad&type=img/png"> </img>
-    <audio src="http://example.org/tests/dom/base/test/csp/file_CSP.sjs?testid=media_bad&type=audio/vorbis"></audio>
-    <script src='http://example.org/tests/dom/base/test/csp/file_CSP.sjs?testid=script_bad&type=text/javascript'></script>
-    <iframe src='http://example.org/tests/dom/base/test/csp/file_CSP.sjs?testid=frame_bad&content=FAIL'></iframe>
+    <img src="http://example.org/tests/dom/security/test/csp/file_CSP.sjs?testid=img_bad&type=img/png"> </img>
+    <audio src="http://example.org/tests/dom/security/test/csp/file_CSP.sjs?testid=media_bad&type=audio/vorbis"></audio>
+    <script src='http://example.org/tests/dom/security/test/csp/file_CSP.sjs?testid=script_bad&type=text/javascript'></script>
+    <iframe src='http://example.org/tests/dom/security/test/csp/file_CSP.sjs?testid=frame_bad&content=FAIL'></iframe>
     <object width="10" height="10">
-      <param name="movie" value="http://example.org/tests/dom/base/test/csp/file_CSP.sjs?testid=object_bad&type=application/x-shockwave-flash">
-      <embed src="http://example.org/tests/dom/base/test/csp/file_CSP.sjs?testid=object_bad&type=application/x-shockwave-flash"></embed>
+      <param name="movie" value="http://example.org/tests/dom/security/test/csp/file_CSP.sjs?testid=object_bad&type=application/x-shockwave-flash">
+      <embed src="http://example.org/tests/dom/security/test/csp/file_CSP.sjs?testid=object_bad&type=application/x-shockwave-flash"></embed>
     </object>
 
     <!-- these should load ok.  :) -->
     <img src="file_CSP.sjs?testid=img_good&type=img/png" />
     <audio src="file_CSP.sjs?testid=media_good&type=audio/vorbis"></audio>
     <script src='file_CSP.sjs?testid=script_good&type=text/javascript'></script>
     <iframe src='file_CSP.sjs?testid=frame_good&content=PASS'></iframe>
 
     <object width="10" height="10">
       <param name="movie" value="file_CSP.sjs?testid=object_good&type=application/x-shockwave-flash">
       <embed src="file_CSP.sjs?testid=object_good&type=application/x-shockwave-flash"></embed>
     </object>
 
     <!-- XHR tests... they're taken care of in this script,
          and since the URI doesn't have any 'testid' values,
          it will just be ignored by the test framework.  -->
-    <script src='file_CSP_main.js'></script>
+    <script src='file_main.js'></script>
 
     <!-- Support elements for the @font-face test -->
     <div class="div_arbitrary_good">arbitrary good</div>
     <div class="div_arbitrary_bad">arbitrary_bad</div>
   </body>
 </html>
rename from dom/base/test/csp/file_CSP_main.html^headers^
rename to dom/security/test/csp/file_main.html^headers^
rename from dom/base/test/csp/file_CSP_main.js
rename to dom/security/test/csp/file_main.js
--- a/dom/base/test/csp/file_CSP_main.js
+++ b/dom/security/test/csp/file_main.js
@@ -1,16 +1,16 @@
 // some javascript for the CSP XHR tests
 //
 
 try {
   var xhr_good = new XMLHttpRequest();
-  var xhr_good_uri ="http://mochi.test:8888/tests/dom/base/test/csp/file_CSP.sjs?testid=xhr_good";
+  var xhr_good_uri ="http://mochi.test:8888/tests/dom/security/test/csp/file_CSP.sjs?testid=xhr_good";
   xhr_good.open("GET", xhr_good_uri, true);
   xhr_good.send(null);
 } catch(e) {}
 
 try {
   var xhr_bad = new XMLHttpRequest();
-  var xhr_bad_uri ="http://example.com/tests/dom/base/test/csp/file_CSP.sjs?testid=xhr_bad";
+  var xhr_bad_uri ="http://example.com/tests/dom/security/test/csp/file_CSP.sjs?testid=xhr_bad";
   xhr_bad.open("GET", xhr_bad_uri, true);
   xhr_bad.send(null);
 } catch(e) {}
rename from dom/base/test/csp/file_multi_policy_injection_bypass.html
rename to dom/security/test/csp/file_multi_policy_injection_bypass.html
--- a/dom/base/test/csp/file_multi_policy_injection_bypass.html
+++ b/dom/security/test/csp/file_multi_policy_injection_bypass.html
@@ -1,15 +1,15 @@
 <html>
 <!--
 https://bugzilla.mozilla.org/show_bug.cgi?id=717511
 -->
   <body>
     <!-- these should be stopped by CSP after fixing bug 717511.  :) -->
-    <img src="http://example.org/tests/dom/base/test/file_CSP.sjs?testid=img_bad&type=img/png"> </img>
-    <script src='http://example.org/tests/dom/base/test/file_CSP.sjs?testid=script_bad&type=text/javascript'></script>
+    <img src="http://example.org/tests/dom/security/test/csp/file_CSP.sjs?testid=img_bad&type=img/png"> </img>
+    <script src='http://example.org/tests/dom/security/test/csp/file_CSP.sjs?testid=script_bad&type=text/javascript'></script>
 
     <!-- these should load ok after fixing bug 717511.  :) -->
     <img src="file_CSP.sjs?testid=img_good&type=img/png" />
     <script src='file_CSP.sjs?testid=script_good&type=text/javascript'></script>
 
   </body>
 </html>
rename from dom/base/test/csp/file_multi_policy_injection_bypass.html^headers^
rename to dom/security/test/csp/file_multi_policy_injection_bypass.html^headers^
rename from dom/base/test/csp/file_multi_policy_injection_bypass_2.html
rename to dom/security/test/csp/file_multi_policy_injection_bypass_2.html
--- a/dom/base/test/csp/file_multi_policy_injection_bypass_2.html
+++ b/dom/security/test/csp/file_multi_policy_injection_bypass_2.html
@@ -1,15 +1,15 @@
 <html>
 <!--
 https://bugzilla.mozilla.org/show_bug.cgi?id=717511
 -->
   <body>
     <!-- these should be stopped by CSP after fixing bug 717511.  :) -->
-    <img src="http://example.org/tests/dom/base/test/file_CSP.sjs?testid=img2_bad&type=img/png"> </img>
-    <script src='http://example.org/tests/dom/base/test/file_CSP.sjs?testid=script2_bad&type=text/javascript'></script>
+    <img src="http://example.org/tests/dom/security/test/csp/file_CSP.sjs?testid=img2_bad&type=img/png"> </img>
+    <script src='http://example.org/tests/dom/security/test/csp/file_CSP.sjs?testid=script2_bad&type=text/javascript'></script>
 
     <!-- these should load ok after fixing bug 717511.  :) -->
     <img src="file_CSP.sjs?testid=img2_good&type=img/png" />
     <script src='file_CSP.sjs?testid=script2_good&type=text/javascript'></script>
 
   </body>
 </html>
rename from dom/base/test/csp/file_multi_policy_injection_bypass_2.html^headers^
rename to dom/security/test/csp/file_multi_policy_injection_bypass_2.html^headers^
rename from dom/base/test/csp/file_nonce_source.html
rename to dom/security/test/csp/file_nonce_source.html
--- a/dom/base/test/csp/file_nonce_source.html
+++ b/dom/security/test/csp/file_nonce_source.html
@@ -24,21 +24,21 @@
     <script nonce="correctstylenonce">
       document.getElementById("inline-script-correct-style-nonce").style.color = "rgb(255, 0, 0)";
     </script>
     <script>
       document.getElementById("inline-script-no-nonce").style.color = "rgb(255, 0, 0)";
     </script>
 
     <!-- external scripts -->
-    <script nonce="correctscriptnonce" src="http://example.org/tests/dom/base/test/csp/file_CSP.sjs?testid=external_script_correct_nonce_good&type=text/javascript"></script>
-    <script nonce="anothercorrectscriptnonce" src="http://example.org/tests/dom/base/test/csp/file_CSP.sjs?testid=external_script_another_correct_nonce_good&type=text/javascript"></script>
-    <script nonce="incorrectscriptnonce" src="http://example.org/tests/dom/base/test/csp/file_CSP.sjs?testid=external_script_incorrect_nonce_bad&type=text/javascript"></script>
-    <script nonce="correctstylenonce" src="http://example.org/tests/dom/base/test/csp/file_CSP.sjs?testid=external_script_correct_style_nonce_bad&type=text/javascript"></script>
-    <script src="http://example.org/tests/dom/base/test/csp/file_CSP.sjs?testid=external_script_no_nonce_bad&type=text/javascript"></script>
+    <script nonce="correctscriptnonce" src="http://example.org/tests/dom/security/test/csp/file_CSP.sjs?testid=external_script_correct_nonce_good&type=text/javascript"></script>
+    <script nonce="anothercorrectscriptnonce" src="http://example.org/tests/dom/security/test/csp/file_CSP.sjs?testid=external_script_another_correct_nonce_good&type=text/javascript"></script>
+    <script nonce="incorrectscriptnonce" src="http://example.org/tests/dom/security/test/csp/file_CSP.sjs?testid=external_script_incorrect_nonce_bad&type=text/javascript"></script>
+    <script nonce="correctstylenonce" src="http://example.org/tests/dom/security/test/csp/file_CSP.sjs?testid=external_script_correct_style_nonce_bad&type=text/javascript"></script>
+    <script src="http://example.org/tests/dom/security/test/csp/file_CSP.sjs?testid=external_script_no_nonce_bad&type=text/javascript"></script>
 
     <!-- This external script has the correct nonce and comes from a whitelisted URI. It should be allowed. -->
     <script nonce="correctscriptnonce" src="file_CSP.sjs?testid=external_script_correct_nonce_correct_uri_good&type=text/javascript"></script>
     <!-- This external script has an incorrect nonce, but comes from a whitelisted URI. It should be allowed. -->
     <script nonce="incorrectscriptnonce" src="file_CSP.sjs?testid=external_script_incorrect_nonce_correct_uri_good&type=text/javascript"></script>
     <!-- This external script has no nonce and comes from a whitelisted URI. It should be allowed. -->
     <script src="file_CSP.sjs?testid=external_script_no_nonce_correct_uri_good&type=text/javascript"></script>
 
rename from dom/base/test/csp/file_nonce_source.html^headers^
rename to dom/security/test/csp/file_nonce_source.html^headers^
rename from dom/base/test/csp/file_null_baseuri.html
rename to dom/security/test/csp/file_null_baseuri.html
rename from dom/base/test/csp/file_csp_path_matching.html
rename to dom/security/test/csp/file_path_matching.html
--- a/dom/base/test/csp/file_csp_path_matching.html
+++ b/dom/security/test/csp/file_path_matching.html
@@ -1,10 +1,10 @@
 <!DOCTYPE HTML>
 <html>
   <head>
     <title>Bug 808292 - Implement path-level host-source matching to CSP</title>
   </head>
   <body>
   <div id="testdiv">blocked</div>
-  <script src="http://test1.example.com/tests/dom/base/test/csp/file_csp_path_matching.js#foo"></script>
+  <script src="http://test1.example.com/tests/dom/security/test/csp/file_path_matching.js#foo"></script>
 </body>
 </html>
rename from dom/base/test/csp/file_csp_path_matching.js
rename to dom/security/test/csp/file_path_matching.js
rename from dom/base/test/csp/file_csp_path_matching_incl_query.html
rename to dom/security/test/csp/file_path_matching_incl_query.html
--- a/dom/base/test/csp/file_csp_path_matching_incl_query.html
+++ b/dom/security/test/csp/file_path_matching_incl_query.html
@@ -1,10 +1,10 @@
 <!DOCTYPE HTML>
 <html>
   <head>
     <title>Bug 1147026 - CSP should ignore query string when checking a resource load</title>
   </head>
   <body>
   <div id="testdiv">blocked</div>
-  <script src="http://test1.example.com/tests/dom/base/test/csp/file_csp_path_matching.js?val=foo"></script>
+  <script src="http://test1.example.com/tests/dom/security/test/csp/file_path_matching.js?val=foo"></script>
 </body>
 </html>
rename from dom/base/test/csp/file_csp_path_matching_redirect.html
rename to dom/security/test/csp/file_path_matching_redirect.html
--- a/dom/base/test/csp/file_csp_path_matching_redirect.html
+++ b/dom/security/test/csp/file_path_matching_redirect.html
@@ -1,10 +1,10 @@
 <!DOCTYPE HTML>
 <html>
   <head>
     <title>Bug 808292 - Implement path-level host-source matching to CSP</title>
   </head>
   <body>
   <div id="testdiv">blocked</div>
-  <script src="http://example.com/tests/dom/base/test/csp/file_csp_path_matching_redirect_server.sjs"></script>
+  <script src="http://example.com/tests/dom/security/test/csp/file_path_matching_redirect_server.sjs"></script>
 </body>
 </html>
rename from dom/base/test/csp/file_csp_path_matching_redirect_server.sjs
rename to dom/security/test/csp/file_path_matching_redirect_server.sjs
--- a/dom/base/test/csp/file_csp_path_matching_redirect_server.sjs
+++ b/dom/security/test/csp/file_path_matching_redirect_server.sjs
@@ -1,13 +1,13 @@
 // Redirect server specifically to handle redirects
 // for path-level host-source matching
 // see https://bugzilla.mozilla.org/show_bug.cgi?id=808292
 
 function handleRequest(request, response)
 {
 
-  var newLocation = "http://test1.example.com/tests/dom/base/test/csp/file_csp_path_matching.js";
+  var newLocation = "http://test1.example.com/tests/dom/security/test/csp/file_path_matching.js";
 
   response.setStatusLine("1.1", 302, "Found");
   response.setHeader("Cache-Control", "no-cache", false);
   response.setHeader("Location", newLocation, false);
 }
rename from dom/base/test/csp/file_policyuri_regression_from_multipolicy.html
rename to dom/security/test/csp/file_policyuri_regression_from_multipolicy.html
rename from dom/base/test/csp/file_policyuri_regression_from_multipolicy.html^headers^
rename to dom/security/test/csp/file_policyuri_regression_from_multipolicy.html^headers^
--- a/dom/base/test/csp/file_policyuri_regression_from_multipolicy.html^headers^
+++ b/dom/security/test/csp/file_policyuri_regression_from_multipolicy.html^headers^
@@ -1,1 +1,1 @@
-content-security-policy-report-only: policy-uri /tests/dom/base/test/csp/file_CSP_policyuri_regression_from_multipolicy_policy
+content-security-policy-report-only: policy-uri /tests/dom/security/test/csp/file_policyuri_regression_from_multipolicy_policy
rename from dom/base/test/csp/file_policyuri_regression_from_multipolicy_policy
rename to dom/security/test/csp/file_policyuri_regression_from_multipolicy_policy
rename from dom/base/test/csp/file_redirect_content.sjs
rename to dom/security/test/csp/file_redirect_content.sjs
--- a/dom/base/test/csp/file_redirect_content.sjs
+++ b/dom/security/test/csp/file_redirect_content.sjs
@@ -18,17 +18,17 @@ function handleRequest(request, response
     // do a 302 redirect to the same URL as the report URI
     // redirects to - this will fail the test.
     var loc = "http://example.com/some/fake/path";
     response.setStatusLine("1.1", 302, "Found");
     response.setHeader("Location", loc, false);
     return;
   }
 
-  var csp = "default-src \'self\';report-uri http://mochi.test:8888/tests/dom/base/test/csp/file_redirect_report.sjs?" + redirect;
+  var csp = "default-src \'self\';report-uri http://mochi.test:8888/tests/dom/security/test/csp/file_redirect_report.sjs?" + redirect;
 
   response.setHeader("Content-Security-Policy", csp, false);
 
   // the actual file content.
   // this image load will (intentionally) fail due to the CSP policy of default-src: 'self'
   // specified by the CSP string above.
   var content = "<!DOCTYPE HTML><html><body><img src = \"http://some.other.domain.example.com\"></body></html>";
 
rename from dom/base/test/csp/file_redirect_report.sjs
rename to dom/security/test/csp/file_redirect_report.sjs
rename from dom/base/test/csp/file_csp_redirects_main.html
rename to dom/security/test/csp/file_redirects_main.html
--- a/dom/base/test/csp/file_csp_redirects_main.html
+++ b/dom/security/test/csp/file_redirects_main.html
@@ -4,17 +4,17 @@
 </head>
 <body>
 <div id="container"></div>
 </body>
 
 <script>
 var thisSite = "http://mochi.test:8888";
 var otherSite = "http://example.com";
-var page = "/tests/dom/base/test/csp/file_csp_redirects_page.sjs";
+var page = "/tests/dom/security/test/csp/file_redirects_page.sjs";
 
 var tests = { "font-src": thisSite+page+"?testid=font-src&csp=1",
               "frame-src": thisSite+page+"?testid=frame-src&csp=1",
               "img-src":  thisSite+page+"?testid=img-src&csp=1",
               "media-src":  thisSite+page+"?testid=media-src&csp=1",
               "object-src":  thisSite+page+"?testid=object-src&csp=1",
               "script-src":  thisSite+page+"?testid=script-src&csp=1",
               "style-src":  thisSite+page+"?testid=style-src&csp=1",
rename from dom/base/test/csp/file_csp_redirects_page.sjs
rename to dom/security/test/csp/file_redirects_page.sjs
--- a/dom/base/test/csp/file_csp_redirects_page.sjs
+++ b/dom/security/test/csp/file_redirects_page.sjs
@@ -6,17 +6,17 @@ function handleRequest(request, response
   request.queryString.split('&').forEach(function (val) {
     var [name, value] = val.split('=');
     query[name] = unescape(value);
   });
 
   response.setHeader("Cache-Control", "no-cache", false);
   response.setHeader("Content-Type", "text/html", false);
 
-  var resource = "/tests/dom/base/test/csp/file_csp_redirects_resource.sjs";
+  var resource = "/tests/dom/security/test/csp/file_redirects_resource.sjs";
 
   // CSP header value
   if (query["csp"] == 1) {
     response.setHeader("Content-Security-Policy", "default-src 'self' ; style-src 'self' 'unsafe-inline'", false);
   }
 
   // downloadable font that redirects to another site
   if (query["testid"] == "font-src") {
rename from dom/base/test/csp/file_csp_redirects_resource.sjs
rename to dom/security/test/csp/file_redirects_resource.sjs
--- a/dom/base/test/csp/file_csp_redirects_resource.sjs
+++ b/dom/security/test/csp/file_redirects_resource.sjs
@@ -6,17 +6,17 @@ function handleRequest(request, response
   var query = {};
   request.queryString.split('&').forEach(function (val) {
     var [name, value] = val.split('=');
     query[name] = unescape(value);
   });
 
   var thisSite = "http://mochi.test:8888";
   var otherSite = "http://example.com";
-  var resource = "/tests/dom/base/test/csp/file_csp_redirects_resource.sjs";
+  var resource = "/tests/dom/security/test/csp/file_redirects_resource.sjs";
 
   response.setHeader("Cache-Control", "no-cache", false);
 
   // redirect to a resource on this site
   if (query["redir"] == "same") {
     var loc = thisSite+resource+"?res="+query["res"]+"&testid="+query["id"];
     response.setStatusLine("1.1", 302, "Found");
     response.setHeader("Location", loc, false);
rename from dom/base/test/csp/file_csp_referrerdirective.html
rename to dom/security/test/csp/file_referrerdirective.html
--- a/dom/base/test/csp/file_csp_referrerdirective.html
+++ b/dom/security/test/csp/file_referrerdirective.html
@@ -39,17 +39,17 @@ var postResult = function(loadType, refe
   console.log(JSON.stringify(results));
 }
 
 </script>
 </head>
 <body>
 Testing ...
 
-<script src="https://example.com/tests/dom/base/test/csp/referrerdirective.sjs?type=sameorigin&"
+<script src="https://example.com/tests/dom/security/test/csp/referrerdirective.sjs?type=sameorigin&"
         onerror="postResult('sameorigin', 'error');"></script>
-<script src="https://test2.example.com/tests/dom/base/test/csp/referrerdirective.sjs?type=crossorigin&"
+<script src="https://test2.example.com/tests/dom/security/test/csp/referrerdirective.sjs?type=crossorigin&"
         onerror="postResult('crossorigin', 'error');"></script>
-<script src="http://example.com/tests/dom/base/test/csp/referrerdirective.sjs?type=downgrade&"
+<script src="http://example.com/tests/dom/security/test/csp/referrerdirective.sjs?type=downgrade&"
         onerror="postResult('downgrade', 'error');"></script>
 
 </body>
 </html>
rename from dom/base/test/csp/file_csp_report.html
rename to dom/security/test/csp/file_report.html
rename from dom/base/test/csp/file_report_uri_missing_in_report_only_header.html
rename to dom/security/test/csp/file_report_uri_missing_in_report_only_header.html
rename from dom/base/test/csp/file_report_uri_missing_in_report_only_header.html^headers^
rename to dom/security/test/csp/file_report_uri_missing_in_report_only_header.html^headers^
rename from dom/base/test/csp/file_scheme_relative_sources.js
rename to dom/security/test/csp/file_scheme_relative_sources.js
rename from dom/base/test/csp/file_scheme_relative_sources.sjs
rename to dom/security/test/csp/file_scheme_relative_sources.sjs
--- a/dom/base/test/csp/file_scheme_relative_sources.sjs
+++ b/dom/security/test/csp/file_scheme_relative_sources.sjs
@@ -7,17 +7,17 @@ function handleRequest(request, response
 {
   Components.utils.importGlobalProperties(["URLSearchParams"]);
   let query = new URLSearchParams(request.queryString);
 
   let scheme = query.get("scheme");
   let policy = query.get("policy");
 
   let linkUrl = scheme +
-  	"://example.com/tests/dom/base/test/csp/file_scheme_relative_sources.js";
+  	"://example.com/tests/dom/security/test/csp/file_scheme_relative_sources.js";
 
   let html = "<!DOCTYPE HTML>" +
              "<html>" +
              "<head>" +
              "<title>test schemeless sources within CSP</title>" +
              "</head>" +
              "<body> " +
              "<div id='testdiv'>blocked</div>" +
rename from dom/base/test/csp/file_self_none_as_hostname_confusion.html
rename to dom/security/test/csp/file_self_none_as_hostname_confusion.html
rename from dom/base/test/csp/file_self_none_as_hostname_confusion.html^headers^
rename to dom/security/test/csp/file_self_none_as_hostname_confusion.html^headers^
rename from dom/base/test/csp/file_subframe_run_js_if_allowed.html
rename to dom/security/test/csp/file_subframe_run_js_if_allowed.html
rename from dom/base/test/csp/file_subframe_run_js_if_allowed.html^headers^
rename to dom/security/test/csp/file_subframe_run_js_if_allowed.html^headers^
rename from dom/base/test/csp/file_csp_testserver.sjs
rename to dom/security/test/csp/file_testserver.sjs
rename from dom/base/test/csp/file_CSP_web_manifest.html
rename to dom/security/test/csp/file_web_manifest.html
--- a/dom/base/test/csp/file_CSP_web_manifest.html
+++ b/dom/security/test/csp/file_web_manifest.html
@@ -1,6 +1,6 @@
 <!doctype html>
 <meta charset=utf-8>
 <head>
-<link rel="manifest" href="file_CSP_web_manifest.json">
+<link rel="manifest" href="file_web_manifest.json">
 </head>
 <h1>Support Page for Web Manifest Tests</h1>
\ No newline at end of file
rename from dom/base/test/csp/file_CSP_web_manifest.json
rename to dom/security/test/csp/file_web_manifest.json
rename from dom/base/test/csp/file_CSP_web_manifest.json^headers^
rename to dom/security/test/csp/file_web_manifest.json^headers^
rename from dom/base/test/csp/file_CSP_web_manifest_https.html
rename to dom/security/test/csp/file_web_manifest_https.html
--- a/dom/base/test/csp/file_CSP_web_manifest_https.html
+++ b/dom/security/test/csp/file_web_manifest_https.html
@@ -1,4 +1,4 @@
 <!doctype html>
 <meta charset=utf-8>
-<link rel="manifest" href="https://example.com:443/tests/dom/base/test/csp/file_CSP_web_manifest_https.json">
+<link rel="manifest" href="https://example.com:443/tests/dom/security/test/csp/file_web_manifest_https.json">
 <h1>Support Page for Web Manifest Tests</h1>
\ No newline at end of file
rename from dom/base/test/csp/file_CSP_web_manifest_https.json
rename to dom/security/test/csp/file_web_manifest_https.json
rename from dom/base/test/csp/file_CSP_web_manifest_mixed_content.html
rename to dom/security/test/csp/file_web_manifest_mixed_content.html
--- a/dom/base/test/csp/file_CSP_web_manifest_mixed_content.html
+++ b/dom/security/test/csp/file_web_manifest_mixed_content.html
@@ -1,9 +1,9 @@
 <!doctype html>
 <meta charset=utf-8>
 <head>
 <link
   rel="manifest"
-  href="http://example.org/tests/dom/base/test/csp/file_csp_testserver.sjs?file=/test/dom/base/test/csp/file_CSP_web_manifest.json&amp;cors=*">
+  href="http://example.org/tests/dom/security/test/csp/file_testserver.sjs?file=/test/dom/security/test/csp/file_web_manifest.json&amp;cors=*">
 </head>
 <h1>Support Page for Web Manifest Tests</h1>
 <p>Used to try to load a resource over an insecure connection to trigger mixed content blocking.</p>
\ No newline at end of file
rename from dom/base/test/csp/file_CSP_web_manifest_remote.html
rename to dom/security/test/csp/file_web_manifest_remote.html
--- a/dom/base/test/csp/file_CSP_web_manifest_remote.html
+++ b/dom/security/test/csp/file_web_manifest_remote.html
@@ -1,8 +1,8 @@
 <!doctype html>
 <meta charset=utf-8>
 <link rel="manifest"
       crossorigin
-	  href="//mochi.test:8888/tests/dom/base/test/csp/file_csp_testserver.sjs?file=/tests/dom/base/test/csp/file_CSP_web_manifest.json&amp;cors=*">
+	  href="//mochi.test:8888/tests/dom/security/test/csp/file_testserver.sjs?file=/tests/dom/security/test/csp/file_web_manifest.json&amp;cors=*">
 
 <h1>Support Page for Web Manifest Tests</h1>
 <p>Loads a manifest from mochi.test:8888 with CORS set to "*".</p>
\ No newline at end of file
rename from dom/base/test/csp/file_worker_redirect.html
rename to dom/security/test/csp/file_worker_redirect.html
rename from dom/base/test/csp/file_worker_redirect.sjs
rename to dom/security/test/csp/file_worker_redirect.sjs
--- a/dom/base/test/csp/file_worker_redirect.sjs
+++ b/dom/security/test/csp/file_worker_redirect.sjs
@@ -19,17 +19,17 @@ function handleRequest(request, response
 
   if (query === "stage_1_worker_import_scripts") {
     response.write("importScripts(\"file_worker_redirect.sjs?stage_2_redirect_imported_script\");");
     return;
   }
 
   if (query === "stage_2_redirect_imported_script") {
     var newLocation =
-      "http://test1.example.com/tests/dom/base/test/csp/file_worker_redirect.sjs?stage_3_target_script";
+      "http://test1.example.com/tests/dom/security/test/csp/file_worker_redirect.sjs?stage_3_target_script";
     response.setStatusLine("1.1", 302, "Found");
     response.setHeader("Location", newLocation, false);
     return;
   }
 
   if (query === "stage_3_target_script") {
     response.write("postMessage(\"imported script loaded\");");
     return;
new file mode 100644
--- /dev/null
+++ b/dom/security/test/csp/mochitest.ini
@@ -0,0 +1,177 @@
+[DEFAULT]
+support-files =
+  file_base-uri.html
+  file_blob_data_schemes.html
+  file_connect-src.html
+  file_connect-src-fetch.html
+  file_CSP.css
+  file_CSP.sjs
+  file_allow_https_schemes.html
+  file_bug663567.xsl
+  file_bug663567_allows.xml
+  file_bug663567_allows.xml^headers^
+  file_bug663567_blocks.xml
+  file_bug663567_blocks.xml^headers^
+  file_bug802872.html
+  file_bug802872.html^headers^
+  file_bug802872.js
+  file_bug802872.sjs
+  file_bug885433_allows.html
+  file_bug885433_allows.html^headers^
+  file_bug885433_blocks.html
+  file_bug885433_blocks.html^headers^
+  file_bug888172.html
+  file_bug888172.sjs
+  file_evalscript_main.js
+  file_evalscript_main_allowed.js
+  file_evalscript_main.html
+  file_evalscript_main.html^headers^
+  file_evalscript_main_allowed.html
+  file_evalscript_main_allowed.html^headers^
+  file_frameancestors_main.html
+  file_frameancestors_main.js
+  file_frameancestors.sjs
+  file_inlinescript_main.html
+  file_inlinescript_main.html^headers^
+  file_inlinescript_main_allowed.html
+  file_inlinescript_main_allowed.html^headers^
+  file_inlinestyle_main.html
+  file_inlinestyle_main.html^headers^
+  file_inlinestyle_main_allowed.html
+  file_inlinestyle_main_allowed.html^headers^
+  file_invalid_source_expression.html
+  file_main.html
+  file_main.html^headers^
+  file_main.js
+  file_web_manifest.html
+  file_web_manifest_remote.html
+  file_web_manifest_https.html
+  file_web_manifest.json
+  file_web_manifest.json^headers^
+  file_web_manifest_https.json
+  file_web_manifest_mixed_content.html
+  file_bug836922_npolicies.html
+  file_bug836922_npolicies.html^headers^
+  file_bug836922_npolicies_ro_violation.sjs
+  file_bug836922_npolicies_violation.sjs
+  file_bug886164.html
+  file_bug886164.html^headers^
+  file_bug886164_2.html
+  file_bug886164_2.html^headers^
+  file_bug886164_3.html
+  file_bug886164_3.html^headers^
+  file_bug886164_4.html
+  file_bug886164_4.html^headers^
+  file_bug886164_5.html
+  file_bug886164_5.html^headers^
+  file_bug886164_6.html
+  file_bug886164_6.html^headers^
+  file_bug768029.html
+  file_bug768029.sjs
+  file_bug773891.html
+  file_bug773891.sjs
+  file_redirects_main.html
+  file_redirects_page.sjs
+  file_redirects_resource.sjs
+  file_bug910139.sjs
+  file_bug910139.xml
+  file_bug910139.xsl
+  file_bug909029_star.html
+  file_bug909029_star.html^headers^
+  file_bug909029_none.html
+  file_bug909029_none.html^headers^
+  file_policyuri_regression_from_multipolicy.html
+  file_policyuri_regression_from_multipolicy.html^headers^
+  file_policyuri_regression_from_multipolicy_policy
+  file_nonce_source.html
+  file_nonce_source.html^headers^
+  file_bug941404.html
+  file_bug941404_xhr.html
+  file_bug941404_xhr.html^headers^
+  file_hash_source.html
+  file_dual_header_testserver.sjs
+  file_hash_source.html^headers^
+  file_scheme_relative_sources.js
+  file_scheme_relative_sources.sjs
+  file_ignore_unsafe_inline.html
+  file_self_none_as_hostname_confusion.html
+  file_self_none_as_hostname_confusion.html^headers^
+  file_path_matching.html
+  file_path_matching_incl_query.html
+  file_path_matching.js
+  file_path_matching_redirect.html
+  file_path_matching_redirect_server.sjs
+  file_testserver.sjs
+  file_report_uri_missing_in_report_only_header.html
+  file_report_uri_missing_in_report_only_header.html^headers^
+  file_report.html
+  file_redirect_content.sjs
+  file_redirect_report.sjs
+  file_subframe_run_js_if_allowed.html
+  file_subframe_run_js_if_allowed.html^headers^
+  file_leading_wildcard.html
+  file_multi_policy_injection_bypass.html
+  file_multi_policy_injection_bypass.html^headers^
+  file_multi_policy_injection_bypass_2.html
+  file_multi_policy_injection_bypass_2.html^headers^
+  file_null_baseuri.html
+  file_form-action.html
+  file_worker_redirect.html
+  file_worker_redirect.sjs
+  file_referrerdirective.html
+  referrerdirective.sjs
+
+[test_base-uri.html]
+[test_blob_data_schemes.html]
+[test_connect-src.html]
+[test_CSP.html]
+[test_allow_https_schemes.html]
+skip-if = buildapp == 'b2g' #no ssl support
+[test_bug663567.html]
+[test_bug802872.html]
+[test_bug885433.html]
+[test_bug888172.html]
+[test_evalscript.html]
+[test_frameancestors.html]
+skip-if = (buildapp == 'b2g' && (toolkit != 'gonk' || debug)) || toolkit == 'android' # Times out, not sure why (bug 1008445)
+[test_inlinescript.html]
+[test_inlinestyle.html]
+[test_invalid_source_expression.html]
+[test_bug836922_npolicies.html]
+[test_bug886164.html]
+[test_redirects.html]
+[test_bug910139.html]
+[test_bug909029.html]
+[test_policyuri_regression_from_multipolicy.html]
+[test_nonce_source.html]
+[test_bug941404.html]
+[test_form-action.html]
+skip-if = e10s || buildapp == 'b2g' # http-on-opening-request observers are not available in child processes
+[test_hash_source.html]
+skip-if = e10s || buildapp == 'b2g' # can't compute hashes in child process (bug 958702)
+[test_scheme_relative_sources.html]
+skip-if = buildapp == 'b2g' #no ssl support
+[test_ignore_unsafe_inline.html]
+[test_self_none_as_hostname_confusion.html]
+[test_bug949549.html]
+[test_path_matching.html]
+[test_path_matching_redirect.html]
+[test_report_uri_missing_in_report_only_header.html]
+[test_report.html]
+skip-if = e10s || buildapp == 'b2g' # http-on-opening-request observer not supported in child process (bug 1009632)
+[test_301_redirect.html]
+skip-if = buildapp == 'b2g' # intermittent orange (bug 1028490)
+[test_302_redirect.html]
+skip-if = buildapp == 'b2g' # intermittent orange (bug 1028490)
+[test_303_redirect.html]
+skip-if = buildapp == 'b2g' # intermittent orange (bug 1028490)
+[test_307_redirect.html]
+skip-if = buildapp == 'b2g' # intermittent orange (bug 1028490)
+[test_subframe_run_js_if_allowed.html]
+[test_leading_wildcard.html]
+[test_multi_policy_injection_bypass.html]
+[test_null_baseuri.html]
+[test_referrerdirective.html]
+skip-if = buildapp == 'b2g' #no ssl support
+[test_dual_header.html]
+[test_worker_redirect.html]
rename from dom/base/test/csp/referrerdirective.sjs
rename to dom/security/test/csp/referrerdirective.sjs
--- a/dom/base/test/csp/referrerdirective.sjs
+++ b/dom/security/test/csp/referrerdirective.sjs
@@ -12,17 +12,17 @@ function handleRequest(request, response
     params[parts[0]] = unescape(parts[1]);
   });
 
   var loadType = params['type'];
   var referrerLevel = 'error';
 
   if (request.hasHeader('Referer')) {
     var referrer = request.getHeader('Referer');
-    if (referrer.indexOf("file_csp_testserver.sjs") > -1) {
+    if (referrer.indexOf("file_testserver.sjs") > -1) {
       referrerLevel = "full";
     } else {
       referrerLevel = "origin";
     }
   } else {
     referrerLevel = 'none';
   }
 
rename from dom/base/test/csp/test_301_redirect.html
rename to dom/security/test/csp/test_301_redirect.html
rename from dom/base/test/csp/test_302_redirect.html
rename to dom/security/test/csp/test_302_redirect.html
rename from dom/base/test/csp/test_303_redirect.html
rename to dom/security/test/csp/test_303_redirect.html
rename from dom/base/test/csp/test_307_redirect.html
rename to dom/security/test/csp/test_307_redirect.html
rename from dom/base/test/csp/test_CSP.html
rename to dom/security/test/csp/test_CSP.html
--- a/dom/base/test/csp/test_CSP.html
+++ b/dom/security/test/csp/test_CSP.html
@@ -105,14 +105,14 @@ SpecialPowers.pushPrefEnv(
           // blocks loading the resource until the user interacts with a
           // corresponding widget, which breaks the media_* tests. We set it
           // back to the default used by desktop Firefox to get consistent
           // behavior.
           ["media.preload.default", 2]]},
     function() {
       // save this for last so that our listeners are registered.
       // ... this loads the testbed of good and bad requests.
-      document.getElementById('cspframe').src = 'file_CSP_main.html';
+      document.getElementById('cspframe').src = 'file_main.html';
     });
 </script>
 </pre>
 </body>
 </html>
rename from dom/base/test/csp/test_csp_allow_https_schemes.html
rename to dom/security/test/csp/test_allow_https_schemes.html
--- a/dom/base/test/csp/test_csp_allow_https_schemes.html
+++ b/dom/security/test/csp/test_allow_https_schemes.html
@@ -13,17 +13,17 @@
   </div>
 
 <script class="testbody" type="text/javascript">
 
 SimpleTest.waitForExplicitFinish();
 
 /* Description of the test:
  * We are loading the following url (including a fragment portion):
- *   https://example.com/tests/dom/base/test/csp/file_csp_path_matching.js#foo
+ *   https://example.com/tests/dom/security/test/csp/file_path_matching.js#foo
  * using different policies that lack specification of a scheme.
  *
  * Since the file is served over http:, the upgrade to https should be
  * permitted by CSP in case no port is specified.
  */
 
 var policies = [
   ["allowed", "example.com"],
@@ -35,19 +35,19 @@ var counter = 0;
 var policy;
 
 function loadNextTest() {
   if (counter == policies.length) {
     SimpleTest.finish();
   }
   else {
     policy = policies[counter++];
-    var src = "file_csp_testserver.sjs";
+    var src = "file_testserver.sjs";
     // append the file that should be served
-    src += "?file=" + escape("tests/dom/base/test/csp/file_csp_allow_https_schemes.html");
+    src += "?file=" + escape("tests/dom/security/test/csp/file_allow_https_schemes.html");
     // append the CSP that should be used to serve the file
     src += "&csp=" + escape("default-src 'none'; script-src " + policy[1]);
 
     document.getElementById("testframe").addEventListener("load", test, false);
     document.getElementById("testframe").src = src;
   }
 }
 
rename from dom/base/test/csp/test_base-uri.html
rename to dom/security/test/csp/test_base-uri.html
--- a/dom/base/test/csp/test_base-uri.html
+++ b/dom/security/test/csp/test_base-uri.html
@@ -55,19 +55,19 @@ examiner.prototype  = {
 window.BaseURIExaminer = new examiner();
 
 function loadNextTest() {
   counter++;
   if (counter == testPolicies.length) {
     window.BaseURIExaminer.remove();
     SimpleTest.finish();
   }
-  var src = "http://example.com/tests/dom/base/test/csp/file_csp_testserver.sjs";
+  var src = "http://example.com/tests/dom/security/test/csp/file_testserver.sjs";
   // append the file that should be served
-  src += "?file=" + escape("tests/dom/base/test/csp/file_base-uri.html");
+  src += "?file=" + escape("tests/dom/security/test/csp/file_base-uri.html");
   // append the CSP that should be used to serve the file
   src += "&csp=" + escape(testPolicies[counter]);
   document.getElementById("testframe").src = src;
 }
 
 // start running the tests
 loadNextTest();
 
rename from dom/base/test/csp/test_blob_data_schemes.html
rename to dom/security/test/csp/test_blob_data_schemes.html
--- a/dom/base/test/csp/test_blob_data_schemes.html
+++ b/dom/security/test/csp/test_blob_data_schemes.html
@@ -67,19 +67,19 @@ function loadNextTest() {
 
   dataRan = false;
   blobRan = false;
 
   curTest = tests[testIndex++];
   // reset the messageCounter to make sure we receive all the postMessages from the iframe
   messageCounter = 0;
 
-  var src = "file_csp_testserver.sjs";
+  var src = "file_testserver.sjs";
   // append the file that should be served
-  src += "?file=" + escape("tests/dom/base/test/csp/file_blob_data_schemes.html");
+  src += "?file=" + escape("tests/dom/security/test/csp/file_blob_data_schemes.html");
   // append the CSP that should be used to serve the file
   src += "&csp=" + escape(curTest.policy);
 
   document.getElementById("testframe").src = src;
 }
 
 SimpleTest.waitForExplicitFinish();
 loadNextTest();
rename from dom/base/test/csp/test_CSP_bug663567.html
rename to dom/security/test/csp/test_bug663567.html
--- a/dom/base/test/csp/test_CSP_bug663567.html
+++ b/dom/security/test/csp/test_bug663567.html
@@ -29,17 +29,17 @@ var checkExplicitFinish = function() {
   }
 }
 
 function checkAllowed () {
   /*   The policy for this test is:
    *   Content-Security-Policy: default-src 'self'
    *
    *   we load the xsl file using:
-   *   <?xml-stylesheet type="text/xsl" href="file_CSP_bug663467.xsl"?>
+   *   <?xml-stylesheet type="text/xsl" href="file_bug663467.xsl"?>
    */
   try {
     var cspframe = document.getElementById('xsltframe');
     var xsltAllowedHeader = cspframe.contentWindow.document.getElementById('xsltheader').innerHTML;
     is(xsltAllowedHeader, header, "XSLT loaded from 'self' should be allowed!");
   }
   catch (e) {
     ok(false, "Error: could not access content in xsltframe!")
@@ -47,30 +47,30 @@ function checkAllowed () {
   checkExplicitFinish();
 }
 
 function checkBlocked () {
   /*   The policy for this test is:
    *   Content-Security-Policy: default-src *.example.com
    *
    *   we load the xsl file using:
-   *   <?xml-stylesheet type="text/xsl" href="file_CSP_bug663467.xsl"?>
+   *   <?xml-stylesheet type="text/xsl" href="file_bug663467.xsl"?>
    */
   try {
     var cspframe = document.getElementById('xsltframe2');
     var xsltBlockedHeader = cspframe.contentWindow.document.getElementById('xsltheader');
     is(xsltBlockedHeader, null, "XSLT loaded from different host should be blocked!");
   }
   catch (e) {
     ok(false, "Error: could not access content in xsltframe2!")
   }
   checkExplicitFinish();
 }
 
 document.getElementById('xsltframe').addEventListener('load', checkAllowed, false);
-document.getElementById('xsltframe').src = 'file_CSP_bug663567_allows.xml';
+document.getElementById('xsltframe').src = 'file_bug663567_allows.xml';
 
 document.getElementById('xsltframe2').addEventListener('load', checkBlocked, false);
-document.getElementById('xsltframe2').src = 'file_CSP_bug663567_blocks.xml';
+document.getElementById('xsltframe2').src = 'file_bug663567_blocks.xml';
 
 </script>
 </body>
 </html>
rename from dom/base/test/csp/test_csp_bug768029.html
rename to dom/security/test/csp/test_bug768029.html
--- a/dom/base/test/csp/test_csp_bug768029.html
+++ b/dom/security/test/csp/test_bug768029.html
@@ -30,43 +30,43 @@ const DEFAULT_CSP_CERT = "default-src *;
 
 SimpleTest.waitForExplicitFinish();
 
 var gData = [
   {
     app: "https://example.com/manifest.webapp",
     appStatus: Components.interfaces.nsIPrincipal.APP_STATUS_INSTALLED,
     origin: "https://example.com",
-    uri: "https://example.com/tests/dom/base/test/csp/file_csp_bug768029.html",
+    uri: "https://example.com/tests/dom/security/test/csp/file_bug768029.html",
     statusString: "installed app",
     expectedTestResults: {
       max_tests: 7, /* number of bools below plus one for the status check */
       cross_origin: { img: true,  script: true,  style: true },
       same_origin:  { img: true,  script: true,  style: true  },
     },
   },
 
   {
     app: "https://example.com/manifest_priv.webapp",
     appStatus: Components.interfaces.nsIPrincipal.APP_STATUS_PRIVILEGED,
     origin: "https://example.com",
-    uri: "https://example.com/tests/dom/base/test/csp/file_csp_bug768029.html",
+    uri: "https://example.com/tests/dom/security/test/csp/file_bug768029.html",
     statusString: "privileged app",
     expectedTestResults: {
       max_tests: 7, /* number of bools below plus one for the status check */
       cross_origin: { img: true,  script: false, style: false },
       same_origin:  { img: true,  script: true,  style: true  },
     },
   },
 
   {
     app: "https://example.com/manifest_cert.webapp",
     appStatus: Components.interfaces.nsIPrincipal.APP_STATUS_CERTIFIED,
     origin: "https://example.com",
-    uri: "https://example.com/tests/dom/base/test/csp/file_csp_bug768029.html",
+    uri: "https://example.com/tests/dom/security/test/csp/file_bug768029.html",
     statusString: "certified app",
     expectedTestResults: {
       max_tests: 7, /* number of bools below plus one for the status check */
       cross_origin: { img: true,  script: false, style: false },
       same_origin:  { img: true,  script: true,  style: true  },
     },
   },
 ];
@@ -82,17 +82,17 @@ function ThingyListener(app, iframe) {
   this._resultsRecorded = { cross_origin: {}, same_origin: {}};
   this._iframe = iframe;
   this._countedTests = 0;
 }
 ThingyListener.prototype = {
 
   observe: function(subject, topic, data) {
     // make sure to only observe app-generated calls to the helper for this test.
-    var testpat = new RegExp("file_csp_bug768029\\.sjs");
+    var testpat = new RegExp("file_bug768029\\.sjs");
 
     // used to extract which kind of load this is (img, script, etc).
     var typepat = new RegExp("type=([\\_a-z0-9]+)");
 
     // used to identify whether it's cross-origin or same-origin loads
     // (the applied CSP allows same-origin loads).
     var originpat = new RegExp("origin=([\\_a-z0-9]+)");
 
rename from dom/base/test/csp/test_csp_bug773891.html
rename to dom/security/test/csp/test_bug773891.html
--- a/dom/base/test/csp/test_csp_bug773891.html
+++ b/dom/security/test/csp/test_bug773891.html
@@ -36,43 +36,43 @@ SimpleTest.waitForExplicitFinish();
 
 var gData = [
 
   {
     app: "https://example.com/manifest_csp_inst.webapp",
     appStatus: Components.interfaces.nsIPrincipal.APP_STATUS_INSTALLED,
     csp: MANIFEST_CSP_INST,
     origin: "https://example.com",
-    uri: "https://example.com/tests/dom/base/test/csp/file_csp_bug773891.html",
+    uri: "https://example.com/tests/dom/security/test/csp/file_bug773891.html",
     statusString: "installed app",
     expectedTestResults: {
       max_tests: 7, /* number of bools below plus one for the status check */
       cross_origin: { img: true,  script: false, style: false },
       same_origin:  { img: true,  script: true,  style: true  },
     },
   },
   {
     app: "https://example.com/manifest_csp_cert.webapp",
     appStatus: Components.interfaces.nsIPrincipal.APP_STATUS_CERTIFIED,
     csp: MANIFEST_CSP_CERT,
     origin: "https://example.com",
-    uri: "https://example.com/tests/dom/base/test/csp/file_csp_bug773891.html",
+    uri: "https://example.com/tests/dom/security/test/csp/file_bug773891.html",
     statusString: "certified app",
     expectedTestResults: {
       max_tests: 7, /* number of bools below plus one for the status check */
       cross_origin: { img: true,  script: false, style: false },
       same_origin:  { img: true,  script: true,  style: true  },
     },
   },
   {
     app: "https://example.com/manifest_csp_priv.webapp",
     appStatus: Components.interfaces.nsIPrincipal.APP_STATUS_PRIVILEGED,
     csp: MANIFEST_CSP_PRIV,
     origin: "https://example.com",
-    uri: "https://example.com/tests/dom/base/test/csp/file_csp_bug773891.html",
+    uri: "https://example.com/tests/dom/security/test/csp/file_bug773891.html",
     statusString: "privileged app",
     expectedTestResults: {
       max_tests: 7, /* number of bools below plus one for the status check */
       cross_origin: { img: true,  script: false, style: false },
       same_origin:  { img: true,  script: true,  style: true  },
     },
   },
 ];
@@ -88,17 +88,17 @@ function ThingyListener(app, iframe) {
   this._resultsRecorded = { cross_origin: {}, same_origin: {}};
   this._iframe = iframe;
   this._countedTests = 0;
 }
 ThingyListener.prototype = {
 
   observe: function(subject, topic, data) {
     // make sure to only observe app-generated calls to the helper for this test.
-    var testpat = new RegExp("file_csp_bug773891\\.sjs");
+    var testpat = new RegExp("file_bug773891\\.sjs");
 
     // used to extract which kind of load this is (img, script, etc).
     var typepat = new RegExp("type=([\\_a-z0-9]+)");
 
     // used to identify whether it's cross-origin or same-origin loads
     // (the applied CSP allows same-origin loads).
     var originpat = new RegExp("origin=([\\_a-z0-9]+)");
 
rename from dom/base/test/csp/test_CSP_bug802872.html
rename to dom/security/test/csp/test_bug802872.html
--- a/dom/base/test/csp/test_CSP_bug802872.html
+++ b/dom/security/test/csp/test_bug802872.html
@@ -41,13 +41,13 @@ addEventListener('blockedEventSrcCallbac
   checkExplicitFinish();
 }, false);
 addEventListener('blockedEventSrcCallbackFailed', function (e) {
   ok(true, "OK: CSP blocks EventSource for not whitelisted domain!");
   checkExplicitFinish();
 }, false);
 
 // load it
-document.getElementById('eventframe').src = 'file_CSP_bug802872.html';
+document.getElementById('eventframe').src = 'file_bug802872.html';
 
 </script>
 </body>
 </html>
rename from dom/base/test/csp/test_bug836922_npolicies.html
rename to dom/security/test/csp/test_bug836922_npolicies.html
--- a/dom/base/test/csp/test_bug836922_npolicies.html
+++ b/dom/security/test/csp/test_bug836922_npolicies.html
@@ -9,17 +9,17 @@
 <body>
 <p id="display"></p>
 <div id="content" style="display: none">
 </div>
 
 <iframe style="width:200px;height:200px;" id='cspframe'></iframe>
 <script class="testbody" type="text/javascript">
 
-var path = "/tests/dom/base/test/csp/";
+var path = "/tests/dom/security/test/csp/";
 
 // These are test results: verified indicates whether or not the test has run.
 // true/false is the pass/fail result.
 window.loads = {
   css_self: {expected: true, verified: false},
   css_examplecom: {expected: false, verified: false},
   img_self: {expected: false, verified: false},
   img_examplecom: {expected: false, verified: false},
rename from dom/base/test/csp/test_CSP_bug885433.html
rename to dom/security/test/csp/test_bug885433.html
--- a/dom/base/test/csp/test_CSP_bug885433.html
+++ b/dom/security/test/csp/test_bug885433.html
@@ -30,17 +30,17 @@ function checkAllowed () {
 
   color = window.getComputedStyle(cspframe.contentDocument.getElementById('unsafe-inline-script-allowed')).color;
   ok(color === green, "Inline script should be allowed");
   color = window.getComputedStyle(cspframe.contentDocument.getElementById('unsafe-eval-script-allowed')).color;
   ok(color === green, "Eval should be allowed");
   color = window.getComputedStyle(cspframe.contentDocument.getElementById('unsafe-inline-style-allowed')).color;
   ok(color === green, "Inline style should be allowed");
 
-  document.getElementById('cspframe2').src = 'file_CSP_bug885433_blocks.html';
+  document.getElementById('cspframe2').src = 'file_bug885433_blocks.html';
   document.getElementById('cspframe2').addEventListener('load', checkBlocked, false);
 }
 
 function checkBlocked () {
   var cspframe = document.getElementById('cspframe2');
   var color;
 
   color = window.getComputedStyle(cspframe.contentDocument.getElementById('unsafe-inline-script-blocked')).color;
@@ -48,14 +48,14 @@ function checkBlocked () {
   color = window.getComputedStyle(cspframe.contentDocument.getElementById('unsafe-eval-script-blocked')).color;
   ok(color === black, "Eval should be blocked");
   color = window.getComputedStyle(cspframe.contentDocument.getElementById('unsafe-inline-style-blocked')).color;
   ok(color === black, "Inline style should be blocked");
 
   SimpleTest.finish();
 }
 
-document.getElementById('cspframe').src = 'file_CSP_bug885433_allows.html';
+document.getElementById('cspframe').src = 'file_bug885433_allows.html';
 document.getElementById('cspframe').addEventListener('load', checkAllowed, false);
 </script>
 </pre>
 </body>
 </html>
rename from dom/base/test/csp/test_bug886164.html
rename to dom/security/test/csp/test_bug886164.html
--- a/dom/base/test/csp/test_bug886164.html
+++ b/dom/security/test/csp/test_bug886164.html
@@ -14,17 +14,17 @@
 <iframe style="width:200px;height:200px;" id='cspframe2' sandbox></iframe>
 <iframe style="width:200px;height:200px;" id='cspframe3' sandbox="allow-same-origin"></iframe>
 <iframe style="width:200px;height:200px;" id='cspframe4' sandbox></iframe>
 <iframe style="width:200px;height:200px;" id='cspframe5' sandbox="allow-scripts"></iframe>
 <iframe style="width:200px;height:200px;" id='cspframe6' sandbox="allow-same-origin allow-scripts"></iframe>
 <script class="testbody" type="text/javascript">
 
 
-var path = "/tests/dom/base/test/csp/";
+var path = "/tests/dom/security/test/csp/";
 
 // These are test results: -1 means it hasn't run,
 // true/false is the pass/fail result.
 window.tests = {
   // sandbox allow-same-origin; 'self'
   img_good: -1, // same origin
   img_bad: -1, //example.com
 
rename from dom/base/test/csp/test_CSP_bug888172.html
rename to dom/security/test/csp/test_bug888172.html
--- a/dom/base/test/csp/test_CSP_bug888172.html
+++ b/dom/security/test/csp/test_bug888172.html
@@ -31,43 +31,43 @@ function getElementColorById(doc, id) {
 // We test both script and style execution by observing changes in computed styles
 function checkDefaultSrcOnly() {
   var testframe = document.getElementById('testframe1');
 
   ok(getElementColorById(testframe, 'unsafe-inline-script') === green, "Inline script should be allowed");
   ok(getElementColorById(testframe, 'unsafe-eval-script')  === green, "Eval should be allowed");
   ok(getElementColorById(testframe, 'unsafe-inline-style') === green, "Inline style should be allowed");
 
-  document.getElementById('testframe2').src = 'file_CSP_bug888172.sjs?csp=' +
+  document.getElementById('testframe2').src = 'file_bug888172.sjs?csp=' +
     escape("default-src 'self' 'unsafe-inline' 'unsafe-eval'; script-src 'self'");
   document.getElementById('testframe2').addEventListener('load', checkDefaultSrcWithScriptSrc, false);
 }
 
 function checkDefaultSrcWithScriptSrc() {
   var testframe = document.getElementById('testframe2');
 
   ok(getElementColorById(testframe, 'unsafe-inline-script') === black, "Inline script should be blocked");
   ok(getElementColorById(testframe, 'unsafe-eval-script')  === black, "Eval should be blocked");
   ok(getElementColorById(testframe, 'unsafe-inline-style') === green, "Inline style should be allowed");
 
-  document.getElementById('testframe3').src = 'file_CSP_bug888172.sjs?csp=' +
+  document.getElementById('testframe3').src = 'file_bug888172.sjs?csp=' +
     escape("default-src 'self' 'unsafe-inline' 'unsafe-eval'; style-src 'self'");
   document.getElementById('testframe3').addEventListener('load', checkDefaultSrcWithStyleSrc, false);
 }
 
 function checkDefaultSrcWithStyleSrc() {
   var testframe = document.getElementById('testframe3');
 
   ok(getElementColorById(testframe, 'unsafe-inline-script') === green, "Inline script should be allowed");
   ok(getElementColorById(testframe, 'unsafe-eval-script')  === green, "Eval should be allowed");
   ok(getElementColorById(testframe, 'unsafe-inline-style') === black, "Inline style should be blocked");
 
   // last test calls finish
   SimpleTest.finish();
 }
 
-document.getElementById('testframe1').src = 'file_CSP_bug888172.sjs?csp=' +
+document.getElementById('testframe1').src = 'file_bug888172.sjs?csp=' +
   escape("default-src 'self' 'unsafe-inline' 'unsafe-eval'");
 document.getElementById('testframe1').addEventListener('load', checkDefaultSrcOnly, false);
 </script>
 </pre>
 </body>
 </html>
rename from dom/base/test/csp/test_CSP_bug909029.html
rename to dom/security/test/csp/test_bug909029.html
--- a/dom/base/test/csp/test_CSP_bug909029.html
+++ b/dom/security/test/csp/test_bug909029.html
@@ -115,15 +115,15 @@ function checkInlineWithNone() {
   window.testResult("noneInlineStyleAllowed",
                     getElementColorById(testframe, 'inline-style') === green,
                     "Inline styles should be allowed (style-src 'unsafe-inline' with none)");
   window.testResult("noneInlineScriptBlocked",
                     getElementColorById(testframe, 'inline-script') === black,
                     "Inline scripts should be blocked (style-src 'unsafe-inline' with none)");
 }
 
-document.getElementById('testframe1').src = 'file_CSP_bug909029_star.html';
+document.getElementById('testframe1').src = 'file_bug909029_star.html';
 document.getElementById('testframe1').addEventListener('load', checkInlineWithStar, false);
-document.getElementById('testframe2').src = 'file_CSP_bug909029_none.html';
+document.getElementById('testframe2').src = 'file_bug909029_none.html';
 document.getElementById('testframe2').addEventListener('load', checkInlineWithNone, false);
     </script>
   </body>
 </html>
rename from dom/base/test/csp/test_CSP_bug910139.html
rename to dom/security/test/csp/test_bug910139.html
--- a/dom/base/test/csp/test_CSP_bug910139.html
+++ b/dom/security/test/csp/test_bug910139.html
@@ -19,48 +19,48 @@ SimpleTest.waitForExplicitFinish();
 // define the expected output of this test
 var header = "this xml file should be formatted using an xsl file(lower iframe should contain xml dump)!";
 
 function checkAllowed () {
   /*   The policy for this test is:
    *   Content-Security-Policy: default-src 'self'; script-src 'self'
    *
    *   we load the xsl file using:
-   *   <?xml-stylesheet type="text/xsl" href="file_CSP_bug910139.xsl"?>
+   *   <?xml-stylesheet type="text/xsl" href="file_bug910139.xsl"?>
    */
   try {
     var cspframe = document.getElementById('xsltframe');
     var xsltAllowedHeader = cspframe.contentWindow.document.getElementById('xsltheader').innerHTML;
     is(xsltAllowedHeader, header, "XSLT loaded from 'self' should be allowed!");
   }
   catch (e) {
     ok(false, "Error: could not access content in xsltframe!")
   }
 
   // continue with the next test
   document.getElementById('xsltframe2').addEventListener('load', checkBlocked, false);
-  document.getElementById('xsltframe2').src = 'file_CSP_bug910139.sjs';
+  document.getElementById('xsltframe2').src = 'file_bug910139.sjs';
 }
 
 function checkBlocked () {
   /*   The policy for this test is:
    *   Content-Security-Policy: default-src 'self'; script-src *.example.com
    *
    *   we load the xsl file using:
-   *   <?xml-stylesheet type="text/xsl" href="file_CSP_bug910139.xsl"?>
+   *   <?xml-stylesheet type="text/xsl" href="file_bug910139.xsl"?>
    */
   try {
     var cspframe = document.getElementById('xsltframe2');
     var xsltBlockedHeader = cspframe.contentWindow.document.getElementById('xsltheader');
     is(xsltBlockedHeader, null, "XSLT loaded from different host should be blocked!");
   }
   catch (e) {
     ok(false, "Error: could not access content in xsltframe2!")
   }
   SimpleTest.finish();
 }
 
 document.getElementById('xsltframe').addEventListener('load', checkAllowed, false);
-document.getElementById('xsltframe').src = 'file_CSP_bug910139.sjs';
+document.getElementById('xsltframe').src = 'file_bug910139.sjs';
 
 </script>
 </body>
 </html>
rename from dom/base/test/csp/test_CSP_bug941404.html
rename to dom/security/test/csp/test_bug941404.html
--- a/dom/base/test/csp/test_CSP_bug941404.html
+++ b/dom/security/test/csp/test_bug941404.html
@@ -12,17 +12,17 @@
 
 
 </div>
 
 <iframe style="width:200px;height:200px;" id='cspframe'></iframe>
 <script class="testbody" type="text/javascript">
 
 
-var path = "/tests/dom/base/test/csp/";
+var path = "/tests/dom/security/test/csp/";
 
 // These are test results: -1 means it hasn't run,
 // true/false is the pass/fail result.
 window.tests = {
   img_good: -1,
   img2_good: -1,
 };
 
@@ -94,14 +94,14 @@ window.testResult = function(testname, r
   window.examiner.remove();
   SimpleTest.finish();
 }
 
 SimpleTest.waitForExplicitFinish();
 
 // save this for last so that our listeners are registered.
 // ... this loads the testbed of good and bad requests.
-document.getElementById('cspframe').src = 'file_CSP_bug941404.html';
+document.getElementById('cspframe').src = 'file_bug941404.html';
 
 </script>
 </pre>
 </body>
 </html>
rename from dom/base/test/csp/test_bug949549.html
rename to dom/security/test/csp/test_bug949549.html
rename from dom/base/test/csp/test_connect-src.html
rename to dom/security/test/csp/test_connect-src.html
--- a/dom/base/test/csp/test_connect-src.html
+++ b/dom/security/test/csp/test_connect-src.html
@@ -73,30 +73,30 @@ function examiner() {
   SpecialPowers.addObserver(this, "csp-on-violate-policy", false);
   SpecialPowers.addObserver(this, "specialpowers-http-notify-request", false);
 }
 examiner.prototype  = {
   observe: function(subject, topic, data) {
    if (topic === "specialpowers-http-notify-request") {
       // making sure we do not bubble a result for something other
       // then the request in question.
-      if (!data.includes("file_csp_testserver.sjs?foo")) {
+      if (!data.includes("file_testserver.sjs?foo")) {
         return;
       }
       checkResult("allowed");
     }
 
     if (topic === "csp-on-violate-policy") {
       // making sure we do not bubble a result for something other
       // then the request in question.
       var asciiSpec = SpecialPowers.getPrivilegedProps(
                         SpecialPowers.do_QueryInterface(subject, "nsIURI"),
                         "asciiSpec");
 
-      if (!asciiSpec.includes("file_csp_testserver.sjs?foo")) {
+      if (!asciiSpec.includes("file_testserver.sjs?foo")) {
         return;
       }
       checkResult("blocked");
     }
   },
   remove: function() {
     SpecialPowers.removeObserver(this, "csp-on-violate-policy");
     SpecialPowers.removeObserver(this, "specialpowers-http-notify-request");
@@ -107,19 +107,19 @@ window.ConnectSrcExaminer = new examiner
 function loadNextTest() {
   counter++;
   if (counter == tests.length) {
     window.ConnectSrcExaminer.remove();
     SimpleTest.finish();
     return;
   }
 
-  var src = "file_csp_testserver.sjs";
+  var src = "file_testserver.sjs";
   // append the file that should be served
-  src += "?file=" + escape("tests/dom/base/test/csp/" + tests[counter].file);
+  src += "?file=" + escape("tests/dom/security/test/csp/" + tests[counter].file);
   // append the CSP that should be used to serve the file
   src += "&csp=" + escape(tests[counter].policy);
 
   document.getElementById("testframe").src = src;
 }
 
 // start running the tests
 loadNextTest();
rename from dom/base/test/csp/test_dual_header.html
rename to dom/security/test/csp/test_dual_header.html
rename from dom/base/test/csp/test_CSP_evalscript.html
rename to dom/security/test/csp/test_evalscript.html
--- a/dom/base/test/csp/test_CSP_evalscript.html
+++ b/dom/security/test/csp/test_evalscript.html
@@ -46,14 +46,14 @@ var checkTestResults = function() {
 }
 
 //////////////////////////////////////////////////////////////////////
 // set up and go
 SimpleTest.waitForExplicitFinish();
 
 // save this for last so that our listeners are registered.
 // ... this loads the testbed of good and bad requests.
-document.getElementById('cspframe').src = 'file_CSP_evalscript_main.html';
-document.getElementById('cspframe2').src = 'file_CSP_evalscript_main_allowed.html';
+document.getElementById('cspframe').src = 'file_evalscript_main.html';
+document.getElementById('cspframe2').src = 'file_evalscript_main_allowed.html';
 </script>
 </pre>
 </body>
 </html>
rename from dom/base/test/csp/test_form-action.html
rename to dom/security/test/csp/test_form-action.html
--- a/dom/base/test/csp/test_form-action.html
+++ b/dom/security/test/csp/test_form-action.html
@@ -83,19 +83,19 @@ window.FormActionExaminer = new examiner
 function loadNextTest() {
   counter++;
   if (counter == tests.length) {
     window.FormActionExaminer.remove();
     SimpleTest.finish();
     return;
   }
 
-  var src = "file_csp_testserver.sjs";
+  var src = "file_testserver.sjs";
   // append the file that should be served
-  src += "?file=" + escape("tests/dom/base/test/csp/" + tests[counter].page);
+  src += "?file=" + escape("tests/dom/security/test/csp/" + tests[counter].page);
   // append the CSP that should be used to serve the file
   src += "&csp=" + escape(tests[counter].policy);
 
   document.getElementById("testframe").src = src;
 }
 
 // start running the tests
 loadNextTest();
rename from dom/base/test/csp/test_CSP_frameancestors.html
rename to dom/security/test/csp/test_frameancestors.html
--- a/dom/base/test/csp/test_CSP_frameancestors.html
+++ b/dom/security/test/csp/test_frameancestors.html
@@ -68,17 +68,17 @@ examiner.prototype  = {
     try {
       asciiSpec = SpecialPowers.getPrivilegedProps(
                     SpecialPowers.do_QueryInterface(subject, "nsIURI"),
                     "asciiSpec");
 
       // skip checks on the test harness -- can't do this skipping for
       // cross-origin blocking since the observer doesn't get the URI.  This
       // can cause this test to over-succeed (but only in specific cases).
-      if (asciiSpec.includes("test_CSP_frameancestors.html")) {
+      if (asciiSpec.includes("test_frameancestors.html")) {
         return;
       }
     } catch (ex) {
       // was not an nsIURI, so it was probably a cross-origin report.
     }
 
 
     if (topic === "csp-on-violate-policy") {
@@ -144,14 +144,14 @@ function receiveMessage(event) {
 
 //////////////////////////////////////////////////////////////////////
 // set up and go
 window.examiner = new examiner();
 SimpleTest.waitForExplicitFinish();
 
 // save this for last so that our listeners are registered.
 // ... this loads the testbed of good and bad requests.
-document.getElementById('cspframe').src = 'file_CSP_frameancestors_main.html';
+document.getElementById('cspframe').src = 'file_frameancestors_main.html';
 
 </script>
 </pre>
 </body>
 </html>
rename from dom/base/test/csp/test_hash_source.html
rename to dom/security/test/csp/test_hash_source.html
rename from dom/base/test/csp/test_ignore_unsafe_inline.html
rename to dom/security/test/csp/test_ignore_unsafe_inline.html
--- a/dom/base/test/csp/test_ignore_unsafe_inline.html
+++ b/dom/security/test/csp/test_ignore_unsafe_inline.html
@@ -70,19 +70,19 @@ var curTest;
 function loadNextTest() {
   if (counter == tests.length) {
     document.getElementById("testframe").removeEventListener("load", test, false);
     SimpleTest.finish();
     return;
   }
 
   curTest = tests[counter++];
-  var src = "file_csp_testserver.sjs?file=";
+  var src = "file_testserver.sjs?file=";
   // append the file that should be served
-  src += escape("tests/dom/base/test/csp/" + curTest.file);
+  src += escape("tests/dom/security/test/csp/" + curTest.file);
 
   // append the CSP that should be used to serve the file
   src += "&csp=" + escape(curTest.policy);
 
   document.getElementById("testframe").addEventListener("load", test, false);
   document.getElementById("testframe").src = src;
 }
 
rename from dom/base/test/csp/test_CSP_inlinescript.html
rename to dom/security/test/csp/test_inlinescript.html
--- a/dom/base/test/csp/test_CSP_inlinescript.html
+++ b/dom/security/test/csp/test_inlinescript.html
@@ -98,16 +98,16 @@ function clickit1() {
 function clickit2() {
   var cspframe2 = document.getElementById('cspframe2');
   var a = cspframe2.contentDocument.getElementById('anchortoclick');
   sendMouseEvent({type:'click'}, a, cspframe2.contentWindow);
 }
 
 // save this for last so that our listeners are registered.
 // ... this loads the testbed of good and bad requests.
-document.getElementById('cspframe1').src = 'file_CSP_inlinescript_main.html';
+document.getElementById('cspframe1').src = 'file_inlinescript_main.html';
 document.getElementById('cspframe1').addEventListener('load', clickit1, false);
-document.getElementById('cspframe2').src = 'file_CSP_inlinescript_main_allowed.html';
+document.getElementById('cspframe2').src = 'file_inlinescript_main_allowed.html';
 document.getElementById('cspframe2').addEventListener('load', clickit2, false);
 </script>
 </pre>
 </body>
 </html>
rename from dom/base/test/csp/test_CSP_inlinestyle.html
rename to dom/security/test/csp/test_inlinestyle.html
--- a/dom/base/test/csp/test_CSP_inlinestyle.html
+++ b/dom/security/test/csp/test_inlinestyle.html
@@ -91,17 +91,17 @@ function checkStylesAllowed(evt) {
 function checkIfDone() {
   done++;
   if (done == 2)
     SimpleTest.finish();
 }
 
 // save this for last so that our listeners are registered.
 // ... this loads the testbed of good and bad requests.
-document.getElementById('cspframe1').src = 'file_CSP_inlinestyle_main.html';
+document.getElementById('cspframe1').src = 'file_inlinestyle_main.html';
 document.getElementById('cspframe1').addEventListener('load', checkStyles, false);
-document.getElementById('cspframe2').src = 'file_CSP_inlinestyle_main_allowed.html';
+document.getElementById('cspframe2').src = 'file_inlinestyle_main_allowed.html';
 document.getElementById('cspframe2').addEventListener('load', checkStylesAllowed, false);
 
 </script>
 </pre>
 </body>
 </html>
rename from dom/base/test/csp/test_csp_invalid_source_expression.html
rename to dom/security/test/csp/test_invalid_source_expression.html
--- a/dom/base/test/csp/test_csp_invalid_source_expression.html
+++ b/dom/security/test/csp/test_invalid_source_expression.html
@@ -22,19 +22,19 @@ SimpleTest.waitForExplicitFinish();
  * where the source expression (bankid:/*) is invalid. In that case the source-expression
  * should be the empty set ('none'), see: http://www.w3.org/TR/CSP11/#source-list-parsing
  * We confirm that the script is blocked by CSP.
  */
 
 const policy = "script-src bankid:/*";
 
 function runTest() {
-  var src = "file_csp_testserver.sjs";
+  var src = "file_testserver.sjs";
   // append the file that should be served
-  src += "?file=" + escape("tests/dom/base/test/csp/file_csp_invalid_source_expression.html");
+  src += "?file=" + escape("tests/dom/security/test/csp/file_invalid_source_expression.html");
   // append the CSP that should be used to serve the file
   src += "&csp=" + escape(policy);
 
   document.getElementById("testframe").addEventListener("load", test, false);
   document.getElementById("testframe").src = src;
 }
 
 function test() {
rename from dom/base/test/csp/test_leading_wildcard.html
rename to dom/security/test/csp/test_leading_wildcard.html
--- a/dom/base/test/csp/test_leading_wildcard.html
+++ b/dom/security/test/csp/test_leading_wildcard.html
@@ -79,19 +79,19 @@ examiner.prototype  = {
   remove: function() {
     SpecialPowers.removeObserver(this, "csp-on-violate-policy");
     SpecialPowers.removeObserver(this, "specialpowers-http-notify-request");
   }
 }
 window.wildCardExaminer = new examiner();
 
 function runTest() {
-  var src = "file_csp_testserver.sjs";
+  var src = "file_testserver.sjs";
   // append the file that should be served
-  src += "?file=" + escape("tests/dom/base/test/csp/file_leading_wildcard.html");
+  src += "?file=" + escape("tests/dom/security/test/csp/file_leading_wildcard.html");
   // append the CSP that should be used to serve the file
   src += "&csp=" + escape(policy);
 
   document.getElementById("testframe").src = src;
 }
 
 // start running the tests
 runTest();
rename from dom/base/test/csp/test_multi_policy_injection_bypass.html
rename to dom/security/test/csp/test_multi_policy_injection_bypass.html
--- a/dom/base/test/csp/test_multi_policy_injection_bypass.html
+++ b/dom/security/test/csp/test_multi_policy_injection_bypass.html
@@ -14,17 +14,17 @@ https://bugzilla.mozilla.org/show_bug.cg
 
 
 </div>
 
 <iframe style="width:200px;height:200px;" id='cspframe'></iframe>
 <iframe style="width:200px;height:200px;" id='cspframe2'></iframe>
 <script class="testbody" type="text/javascript">
 
-var path = "/tests/dom/base/test/";
+var path = "/tests/dom/security/test/csp/";
 
 // These are test results: -1 means it hasn't run,
 // true/false is the pass/fail result.
 // This is not exhaustive, just double-checking the 'self' vs * policy conflict in the two HTTP headers.
 window.tests = {
   img_good: -1,
   img_bad: -1,
   script_good: -1,
rename from dom/base/test/csp/test_nonce_source.html
rename to dom/security/test/csp/test_nonce_source.html
rename from dom/base/test/csp/test_null_baseuri.html
rename to dom/security/test/csp/test_null_baseuri.html
--- a/dom/base/test/csp/test_null_baseuri.html
+++ b/dom/security/test/csp/test_null_baseuri.html
@@ -43,19 +43,19 @@ function receiveMessage(event)
   }
 
   if (++test_counter === TOTAL_TESTS) {
     SimpleTest.finish();
   }
 }
 
 function startTest() {
-  var src = "file_csp_testserver.sjs";
+  var src = "file_testserver.sjs";
   // append the file that should be served
-  src += "?file=" + escape("tests/dom/base/test/csp/file_null_baseuri.html");
+  src += "?file=" + escape("tests/dom/security/test/csp/file_null_baseuri.html");
   // using 'unsafe-inline' since we load the testcase using an inline script
   // within file_null_baseuri.html
   src += "&csp=" + escape("default-src * 'unsafe-inline';");
 
   document.getElementById("testframe").src = src;
 }
 
 
rename from dom/base/test/csp/test_csp_path_matching.html
rename to dom/security/test/csp/test_path_matching.html
--- a/dom/base/test/csp/test_csp_path_matching.html
+++ b/dom/security/test/csp/test_path_matching.html
@@ -13,84 +13,84 @@
   </div>
 
 <script class="testbody" type="text/javascript">
 
 SimpleTest.waitForExplicitFinish();
 
 /* Description of the test:
  * We are loading the following url (including a fragment portion):
- * http://test1.example.com/tests/dom/base/test/csp/file_csp_path_matching.js#foo
+ * http://test1.example.com/tests/dom/security/test/csp/file_path_matching.js#foo
  * using different policies and verify that the applied policy is accurately enforced.
  */
 
 var policies = [
   ["allowed", "*"],
   ["allowed", "http://*"], // test for bug 1075230, enforcing scheme and wildcard
   ["allowed", "test1.example.com"],
   ["allowed", "test1.example.com/"],
-  ["allowed", "test1.example.com/tests/dom/base/test/csp/"],
-  ["allowed", "test1.example.com/tests/dom/base/test/csp/file_csp_path_matching.js"],
+  ["allowed", "test1.example.com/tests/dom/security/test/csp/"],
+  ["allowed", "test1.example.com/tests/dom/security/test/csp/file_path_matching.js"],
 
   ["allowed", "test1.example.com?foo=val"],
   ["allowed", "test1.example.com/?foo=val"],
-  ["allowed", "test1.example.com/tests/dom/base/test/csp/?foo=val"],
-  ["allowed", "test1.example.com/tests/dom/base/test/csp/file_csp_path_matching.js?foo=val"],
+  ["allowed", "test1.example.com/tests/dom/security/test/csp/?foo=val"],
+  ["allowed", "test1.example.com/tests/dom/security/test/csp/file_path_matching.js?foo=val"],
 
   ["allowed", "test1.example.com#foo"],
   ["allowed", "test1.example.com/#foo"],
-  ["allowed", "test1.example.com/tests/dom/base/test/csp/#foo"],
-  ["allowed", "test1.example.com/tests/dom/base/test/csp/file_csp_path_matching.js#foo"],
+  ["allowed", "test1.example.com/tests/dom/security/test/csp/#foo"],
+  ["allowed", "test1.example.com/tests/dom/security/test/csp/file_path_matching.js#foo"],
 
   ["allowed", "*.example.com"],
   ["allowed", "*.example.com/"],
-  ["allowed", "*.example.com/tests/dom/base/test/csp/"],
-  ["allowed", "*.example.com/tests/dom/base/test/csp/file_csp_path_matching.js"],
+  ["allowed", "*.example.com/tests/dom/security/test/csp/"],
+  ["allowed", "*.example.com/tests/dom/security/test/csp/file_path_matching.js"],
 
   ["allowed", "test1.example.com:80"],
   ["allowed", "test1.example.com:80/"],
-  ["allowed", "test1.example.com:80/tests/dom/base/test/csp/"],
-  ["allowed", "test1.example.com:80/tests/dom/base/test/csp/file_csp_path_matching.js"],
+  ["allowed", "test1.example.com:80/tests/dom/security/test/csp/"],
+  ["allowed", "test1.example.com:80/tests/dom/security/test/csp/file_path_matching.js"],
 
   ["allowed", "test1.example.com:*"],
   ["allowed", "test1.example.com:*/"],
-  ["allowed", "test1.example.com:*/tests/dom/base/test/csp/"],
-  ["allowed", "test1.example.com:*/tests/dom/base/test/csp/file_csp_path_matching.js"],
+  ["allowed", "test1.example.com:*/tests/dom/security/test/csp/"],
+  ["allowed", "test1.example.com:*/tests/dom/security/test/csp/file_path_matching.js"],
 
   ["blocked", "test1.example.com/tests"],
-  ["blocked", "test1.example.com/tests/dom/base/test/csp"],
-  ["blocked", "test1.example.com/tests/dom/base/test/csp/file_csp_path_matching.py"],
+  ["blocked", "test1.example.com/tests/dom/security/test/csp"],
+  ["blocked", "test1.example.com/tests/dom/security/test/csp/file_path_matching.py"],
 
   ["blocked", "test1.example.com:8888/tests"],
-  ["blocked", "test1.example.com:8888/tests/dom/base/test/csp"],
-  ["blocked", "test1.example.com:8888/tests/dom/base/test/csp/file_csp_path_matching.py"],
+  ["blocked", "test1.example.com:8888/tests/dom/security/test/csp"],
+  ["blocked", "test1.example.com:8888/tests/dom/security/test/csp/file_path_matching.py"],
 
   // case insensitive matching for scheme and host, but case sensitive matching for paths
   ["allowed", "HTTP://test1.EXAMPLE.com/tests/"],
   ["allowed", "test1.EXAMPLE.com/tests/"],
-  ["blocked", "test1.example.com/tests/dom/base/test/CSP/?foo=val"],
-  ["blocked", "test1.example.com/tests/dom/base/test/csp/FILE_csp_path_matching.js?foo=val"],
+  ["blocked", "test1.example.com/tests/dom/security/test/CSP/?foo=val"],
+  ["blocked", "test1.example.com/tests/dom/security/test/csp/FILE_path_matching.js?foo=val"],
 ]
 
 var counter = 0;
 var policy;
 
 function loadNextTest() {
   if (counter == policies.length) {
     SimpleTest.finish();
   }
   else {
     policy = policies[counter++];
-    var src = "file_csp_testserver.sjs?file=";
+    var src = "file_testserver.sjs?file=";
     // append the file that should be served
     src += (counter % 2 == 0)
                // load url including ref: example.com#foo
-             ? escape("tests/dom/base/test/csp/file_csp_path_matching.html")
+             ? escape("tests/dom/security/test/csp/file_path_matching.html")
                // load url including query: example.com?val=foo (bug 1147026)
-             : escape("tests/dom/base/test/csp/file_csp_path_matching_incl_query.html");
+             : escape("tests/dom/security/test/csp/file_path_matching_incl_query.html");
 
     // append the CSP that should be used to serve the file
     src += "&csp=" + escape("default-src 'none'; script-src " + policy[1]);
 
     document.getElementById("testframe").addEventListener("load", test, false);
     document.getElementById("testframe").src = src;
   }
 }
rename from dom/base/test/csp/test_csp_path_matching_redirect.html
rename to dom/security/test/csp/test_path_matching_redirect.html
--- a/dom/base/test/csp/test_csp_path_matching_redirect.html
+++ b/dom/security/test/csp/test_path_matching_redirect.html
@@ -26,31 +26,31 @@ SimpleTest.waitForExplicitFinish();
  * as described in the spec, see:
  * http://www.w3.org/TR/CSP11/#source-list-paths-and-redirects
  */
 
 var policy = "script-src http://example.com http://test1.example.com/CSPAllowsScriptsInThatFolder";
 
 var tests = [
   {
-    // the script in file_csp_path_matching.html
-    // <script src="http://test1.example.com/tests/dom/base/..">
+    // the script in file_path_matching.html
+    // <script src="http://test1.example.com/tests/dom/security/..">
     // is not within the whitelisted path by the csp-policy
     // hence the script is 'blocked' by CSP.
     expected: "blocked",
-    uri: "tests/dom/base/test/csp/file_csp_path_matching.html"
+    uri: "tests/dom/security/test/csp/file_path_matching.html"
   },
   {
-    // the script in file_csp_path_matching_redirect.html
+    // the script in file_path_matching_redirect.html
     // <script src="http://example.com/tests/dom/..">
     // gets redirected to: http://test1.example.com/tests/dom
     // where after the redirect the path of the policy is not enforced
     // anymore and hence execution of the script is 'allowed'.
     expected: "allowed",
-    uri: "tests/dom/base/test/csp/file_csp_path_matching_redirect.html"
+    uri: "tests/dom/security/test/csp/file_path_matching_redirect.html"
   },
 ];
 
 var counter = 0;
 var curTest;
 
 function checkResult() {
   try {
@@ -66,17 +66,17 @@ function checkResult() {
 }
 
 function loadNextTest() {
   if (counter == tests.length) {
     SimpleTest.finish();
   }
   else {
     curTest = tests[counter++];
-    var src = "file_csp_testserver.sjs";
+    var src = "file_testserver.sjs";
     // append the file that should be served
     src += "?file=" + escape(curTest.uri);
     // append the CSP that should be used to serve the file
     src += "&csp=" + escape(policy);
 
     document.getElementById("testframe").addEventListener("load", checkResult, false);
     document.getElementById("testframe").src = src;
   }
rename from dom/base/test/csp/test_policyuri_regression_from_multipolicy.html
rename to dom/security/test/csp/test_policyuri_regression_from_multipolicy.html
rename from dom/base/test/csp/test_csp_redirects.html
rename to dom/security/test/csp/test_redirects.html
--- a/dom/base/test/csp/test_csp_redirects.html
+++ b/dom/security/test/csp/test_redirects.html
@@ -10,17 +10,17 @@
 <div id="content" style="display: none">
 
 </div>
 
 <iframe style="width:100%;height:300px;" id="harness"></iframe>
 <pre id="log"></pre>
 <script class="testbody" type="text/javascript">
 
-var path = "/tests/dom/base/test/csp/";
+var path = "/tests/dom/security/test/csp/";
 
 // debugging
 function log(s) {
   return;
   dump("**" + s + "\n");
   var log = document.getElementById("log");
   log.textContent = log.textContent+s+"\n";
 }
@@ -119,15 +119,15 @@ SpecialPowers.pushPrefEnv(
           // blocks loading the resource until the user interacts with a
           // corresponding widget, which breaks the media_* tests. We set it
           // back to the default used by desktop Firefox to get consistent
           // behavior.
           ["media.preload.default", 2]]},
   function() {
     // save this for last so that our listeners are registered.
     // ... this loads the testbed of good and bad requests.
-    document.getElementById("harness").src = "file_csp_redirects_main.html";
+    document.getElementById("harness").src = "file_redirects_main.html";
   });
 </script>
 </pre>
 
 </body>
 </html>
rename from dom/base/test/csp/test_CSP_referrerdirective.html
rename to dom/security/test/csp/test_referrerdirective.html
--- a/dom/base/test/csp/test_CSP_referrerdirective.html
+++ b/dom/security/test/csp/test_referrerdirective.html
@@ -107,19 +107,19 @@ SpecialPowers.pushPrefEnv({
     },
     function() {
       // each of the iframes we create will call us back when its contents are loaded.
       window.addEventListener("message", referrerDirectiveTests.onIframeComplete.bind(window), false);
 
       // one iframe created for each test case
       for (var id in testData) {
         var elt = document.createElement("iframe");
-        elt.src = "https://example.com/tests/dom/base/test/csp/file_csp_testserver.sjs?" +
+        elt.src = "https://example.com/tests/dom/security/test/csp/file_testserver.sjs?" +
                   "id=" + id +
                   "&csp=" + escape(testData[id]['csp']) +
-                  "&file=tests/dom/base/test/csp/file_csp_referrerdirective.html";
+                  "&file=tests/dom/security/test/csp/file_referrerdirective.html";
         document.getElementById("content").appendChild(elt);
       }
     });
 </script>
 </pre>
 </body>
 </html>
rename from dom/base/test/csp/test_csp_report.html
rename to dom/security/test/csp/test_report.html
--- a/dom/base/test/csp/test_csp_report.html
+++ b/dom/security/test/csp/test_report.html
@@ -22,35 +22,35 @@ https://bugzilla.mozilla.org/show_bug.cg
  * all scripts from running (default-src 'none'). We verify that
  * the generated csp-report contains the expceted values. If any
  * of the JSON is not formatted properly (e.g. not properly escaped)
  * then JSON.parse will fail, which allows to pinpoint such errors
  * in the catch block, and the test will fail. Since we use an
  * observer, we can set the actual report-uri to a foo value.
  */
 
-const testfile = "tests/dom/base/test/csp/file_csp_report.html";
+const testfile = "tests/dom/security/test/csp/file_report.html";
 const reportURI = "http://mochi.test:8888/foo.sjs";
 const policy = "default-src 'none'; report-uri " + reportURI;
-const docUri = "http://mochi.test:8888/tests/dom/base/test/csp/file_csp_testserver.sjs" +
-               "?file=tests/dom/base/test/csp/file_csp_report.html" +
+const docUri = "http://mochi.test:8888/tests/dom/security/test/csp/file_testserver.sjs" +
+               "?file=tests/dom/security/test/csp/file_report.html" +
                "&csp=default-src%20%27none%27%3B%20report-uri%20http%3A//mochi.test%3A8888/foo.sjs";
 
 window.checkResults = function(reportObj) {
   var cspReport = reportObj["csp-report"];
 
   // The following uris' fragments should be stripped before reporting:
   //    * document-uri
   //    * blocked-uri
   //    * source-file
   // see http://www.w3.org/TR/CSP11/#violation-reports
   is(cspReport["document-uri"], docUri, "Incorrect document-uri");
 
   // we can not test for the whole referrer since it includes platform specific information
-  ok(cspReport["referrer"].startsWith("http://mochi.test:8888/tests/dom/base/test/csp/test_csp_report.html"),
+  ok(cspReport["referrer"].startsWith("http://mochi.test:8888/tests/dom/security/test/csp/test_report.html"),
      "Incorrect referrer");
 
   is(cspReport["blocked-uri"], "self", "Incorrect blocked-uri");
 
   is(cspReport["violated-directive"], "default-src 'none'", "Incorrect violated-directive");
 
   is(cspReport["original-policy"], "default-src 'none'; report-uri http://mochi.test:8888/foo.sjs",
      "Incorrect original-policy");
@@ -125,17 +125,17 @@ examiner.prototype  = {
     SpecialPowers.removeObserver(this, "http-on-opening-request");
   }
 }
 window.examiner = new examiner();
 SimpleTest.waitForExplicitFinish();
 
 // load the resource which will generate a CSP violation report
 // save this for last so that our listeners are registered.
-var src = "file_csp_testserver.sjs";
+var src = "file_testserver.sjs";
 // append the file that should be served
 src += "?file=" + escape(testfile);
 // append the CSP that should be used to serve the file
 src += "&csp=" + escape(policy);
 // appending a fragment so we can test that it's correctly stripped
 // for document-uri and source-file.
 src += "#foo";
 document.getElementById("cspframe").src = src;
rename from dom/base/test/csp/test_report_uri_missing_in_report_only_header.html
rename to dom/security/test/csp/test_report_uri_missing_in_report_only_header.html
rename from dom/base/test/csp/test_scheme_relative_sources.html
rename to dom/security/test/csp/test_scheme_relative_sources.html
--- a/dom/base/test/csp/test_scheme_relative_sources.html
+++ b/dom/security/test/csp/test_scheme_relative_sources.html
@@ -59,17 +59,17 @@ function loadNextTest() {
     window.removeEventListener("message", receiveMessage, false);
     SimpleTest.finish();
     return;
   }
 
   curTest = tests[counter++];
 
   var src = curTest.from +
-             "://example.com/tests/dom/base/test/csp/file_scheme_relative_sources.sjs" +
+             "://example.com/tests/dom/security/test/csp/file_scheme_relative_sources.sjs" +
             "?scheme=" + curTest.to +
             "&policy=" + escape(POLICY);
 
   document.getElementById("testframe").src = src;
 }
 
 // using a postMessage handler to report the result back from
 // within the sandboxed iframe without 'allow-same-origin'.
rename from dom/base/test/csp/test_self_none_as_hostname_confusion.html
rename to dom/security/test/csp/test_self_none_as_hostname_confusion.html
rename from dom/base/test/csp/test_subframe_run_js_if_allowed.html
rename to dom/security/test/csp/test_subframe_run_js_if_allowed.html
rename from dom/base/test/csp/test_worker_redirect.html
rename to dom/security/test/csp/test_worker_redirect.html
--- a/dom/base/test/csp/test_worker_redirect.html
+++ b/dom/security/test/csp/test_worker_redirect.html
@@ -55,19 +55,19 @@ function checkResult(aResult) {
 }
 
 function loadNextTest() {
   if (counter == tests.length) {
     SimpleTest.finish();
     return;
   }
   curTest = tests[counter++];
-  var src = "file_csp_testserver.sjs";
+  var src = "file_testserver.sjs";
   // append the file that should be served
-  src += "?file=" + escape("tests/dom/base/test/csp/file_worker_redirect.html");
+  src += "?file=" + escape("tests/dom/security/test/csp/file_worker_redirect.html");
   // append the CSP that should be used to serve the file
   src += "&csp=" + escape(curTest.policy);
   document.getElementById("testframe").src = src;
 }
 
 SimpleTest.waitForExplicitFinish();
 loadNextTest();
 
rename from dom/base/test/mixedcontentblocker/bug803225_test_mailto.html
rename to dom/security/test/mixedcontentblocker/file_bug803225_test_mailto.html
rename from dom/base/test/mixedcontentblocker/file_mixed_content_frameNavigation.html
rename to dom/security/test/mixedcontentblocker/file_frameNavigation.html
--- a/dom/base/test/mixedcontentblocker/file_mixed_content_frameNavigation.html
+++ b/dom/security/test/mixedcontentblocker/file_frameNavigation.html
@@ -7,17 +7,17 @@ https://bugzilla.mozilla.org/show_bug.cg
 <head>
   <meta charset="utf-8">
   <title>Tests for Mixed Content Frame Navigation</title>
 </head>
 <body>
 <div id="testContent"></div>
 
 <script>
-  var baseUrlHttps = "https://example.com/tests/dom/base/test/mixedcontentblocker/file_mixed_content_frameNavigation_innermost.html";
+  var baseUrlHttps = "https://example.com/tests/dom/security/test/mixedcontentblocker/file_frameNavigation_innermost.html";
 
   // For tests that require setTimeout, set the maximum polling time to 50 x 100ms = 5 seconds.
   var MAX_COUNT = 50;
   var TIMEOUT_INTERVAL = 100;
 
   var testContent = document.getElementById("testContent");
 
   // Test 1: Navigate secure iframe to insecure iframe on an insecure page
@@ -39,17 +39,17 @@ https://bugzilla.mozilla.org/show_bug.cg
     } catch(e) {
       if (e.name === "SecurityError") {
         // We received an exception we didn't expect.
         throw e;
       }
       counter_test1++;
       return;
     }
-    if (loc == "http://example.com/tests/dom/base/test/mixedcontentblocker/file_mixed_content_frameNavigation_innermost.html?insecurePage_navigate_child_response") {
+    if (loc == "http://example.com/tests/dom/security/test/mixedcontentblocker/file_frameNavigation_innermost.html?insecurePage_navigate_child_response") {
       return;
     }
     else {
       if(counter_test1 < MAX_COUNT) {
         counter_test1++;
         setTimeout(navigationStatus, TIMEOUT_INTERVAL, iframe_test1);
       }
       else {
@@ -58,17 +58,17 @@ https://bugzilla.mozilla.org/show_bug.cg
       }
     }
   }
 
   setTimeout(navigationStatus, TIMEOUT_INTERVAL, iframe_test1);
 
   // Test 2: Navigate secure grandchild iframe to insecure grandchild iframe on a page that has no secure parents
   var iframe_test2 = document.createElement("iframe");
-  iframe_test2.src = "http://example.com/tests/dom/base/test/mixedcontentblocker/file_mixed_content_frameNavigation_grandchild.html"
+  iframe_test2.src = "http://example.com/tests/dom/security/test/mixedcontentblocker/file_frameNavigation_grandchild.html"
   iframe_test2.onerror = function() {
     parent.postMessage({"test": "insecurePage_navigate_grandchild", "msg": "got an on error alert when loading or navigating testing iframe"}, "http://mochi.test:8888");
   };
   testContent.appendChild(iframe_test2);
 
 </script>
 </body>
 </html>
rename from dom/base/test/mixedcontentblocker/file_mixed_content_frameNavigation_blankTarget.html
rename to dom/security/test/mixedcontentblocker/file_frameNavigation_blankTarget.html
--- a/dom/base/test/mixedcontentblocker/file_mixed_content_frameNavigation_blankTarget.html
+++ b/dom/security/test/mixedcontentblocker/file_frameNavigation_blankTarget.html
@@ -4,17 +4,17 @@
 Tests for Mixed Content Blocker - Opening link with _blank target in an https iframe.
 https://bugzilla.mozilla.org/show_bug.cgi?id=841850
 -->
 <head>
   <meta charset="utf-8">
   <title>Tests for Mixed Content Frame Navigation</title>
 </head>
 <body>
-<a href="http://example.com/tests/dom/base/test/mixedcontentblocker/file_mixed_content_frameNavigation_innermost.html?blankTarget" id="blankTarget" target="_blank">Go to http site</a>
+<a href="http://example.com/tests/dom/security/test/mixedcontentblocker/file_frameNavigation_innermost.html?blankTarget" id="blankTarget" target="_blank">Go to http site</a>
 
 <script>
   var blankTarget = document.getElementById("blankTarget");
   blankTarget.click();
 
   var os = SpecialPowers.Cc["@mozilla.org/observer-service;1"].
      getService(SpecialPowers.Components.interfaces.nsIObserverService);
   var observer = {
rename from dom/base/test/mixedcontentblocker/file_mixed_content_frameNavigation_grandchild.html
rename to dom/security/test/mixedcontentblocker/file_frameNavigation_grandchild.html
--- a/dom/base/test/mixedcontentblocker/file_mixed_content_frameNavigation_grandchild.html
+++ b/dom/security/test/mixedcontentblocker/file_frameNavigation_grandchild.html
@@ -4,17 +4,17 @@
 Tests for Mixed Content Blocker - Navigating Grandchild frames when a secure parent doesn't exist
 https://bugzilla.mozilla.org/show_bug.cgi?id=840388
 -->
 <head>
   <meta charset="utf-8">
   <title>Tests for Mixed Content Frame Navigation</title>
 </head>
 <body>
-<iframe src="https://example.com/tests/dom/base/test/mixedcontentblocker/file_mixed_content_frameNavigation_innermost.html?insecurePage_navigate_grandchild" id="child"></iframe>
+<iframe src="https://example.com/tests/dom/security/test/mixedcontentblocker/file_frameNavigation_innermost.html?insecurePage_navigate_grandchild" id="child"></iframe>
 
 <script>
   // For tests that require setTimeout, set the maximum polling time to 50 x 100ms = 5 seconds.
   var MAX_COUNT = 50;
   var TIMEOUT_INTERVAL = 100;
   var counter = 0;
 
   var child = document.getElementById("child");
@@ -27,17 +27,17 @@ https://bugzilla.mozilla.org/show_bug.cg
     } catch(e) {
       if (e.message && e.message.indexOf("Permission denied to access property") == -1) {
         // We received an exception we didn't expect.
         throw e;
       }
       counter++;
       return;
     }
-    if (loc == "http://example.com/tests/dom/base/test/mixedcontentblocker/file_mixed_content_frameNavigation_innermost.html?insecurePage_navigate_grandchild_response") {
+    if (loc == "http://example.com/tests/dom/security/test/mixedcontentblocker/file_frameNavigation_innermost.html?insecurePage_navigate_grandchild_response") {
       return;
     }
     else {
       if(counter < MAX_COUNT) {
         counter++;
         setTimeout(navigationStatus, TIMEOUT_INTERVAL, child);
       }
       else {
rename from dom/base/test/mixedcontentblocker/file_mixed_content_frameNavigation_innermost.html
rename to dom/security/test/mixedcontentblocker/file_frameNavigation_innermost.html
--- a/dom/base/test/mixedcontentblocker/file_mixed_content_frameNavigation_innermost.html
+++ b/dom/security/test/mixedcontentblocker/file_frameNavigation_innermost.html
@@ -4,50 +4,50 @@
 <div id="content"></div>
 <script>
   // get the case from the query string
   var type = location.search.substring(1);
 
   switch (type) {
     case "insecurePage_navigate_child":
       document.getElementById("content").innerHTML =
-        '<a href="http://example.com/tests/dom/base/test/mixedcontentblocker/file_mixed_content_frameNavigation_innermost.html?insecurePage_navigate_child_response" id="link">Testing\<\/a>';
+        '<a href="http://example.com/tests/dom/security/test/mixedcontentblocker/file_frameNavigation_innermost.html?insecurePage_navigate_child_response" id="link">Testing\<\/a>';
       document.getElementById("link").click();
       break;
 
     case "insecurePage_navigate_child_response":
       parent.parent.postMessage({"test": "insecurePage_navigate_child", "msg": "navigated to insecure iframe on insecure page"}, "http://mochi.test:8888");
       document.getElementById("content").innerHTML = "Navigated from secure to insecure frame on an insecure page";
       break;
 
     case "insecurePage_navigate_grandchild":
       document.getElementById("content").innerHTML =
-        '<a href="http://example.com/tests/dom/base/test/mixedcontentblocker/file_mixed_content_frameNavigation_innermost.html?insecurePage_navigate_grandchild_response" id="link">Testing\<\/a>';
+        '<a href="http://example.com/tests/dom/security/test/mixedcontentblocker/file_frameNavigation_innermost.html?insecurePage_navigate_grandchild_response" id="link">Testing\<\/a>';
       document.getElementById("link").click();
       break;
 
     case "insecurePage_navigate_grandchild_response":
       parent.parent.parent.postMessage({"test": "insecurePage_navigate_grandchild", "msg": "navigated to insecure grandchild iframe on insecure page"}, "http://mochi.test:8888");
       document.getElementById("content").innerHTML = "Navigated from secure to insecure grandchild frame on an insecure page";
       break;
 
     case "securePage_navigate_child":
       document.getElementById("content").innerHTML =
-        '<a href="http://example.com/tests/dom/base/test/mixedcontentblocker/file_mixed_content_frameNavigation_innermost.html?securePage_navigate_child_response" id="link">Testing\<\/a>';
+        '<a href="http://example.com/tests/dom/security/test/mixedcontentblocker/file_frameNavigation_innermost.html?securePage_navigate_child_response" id="link">Testing\<\/a>';
       document.getElementById("link").click();
       break;
 
     case "securePage_navigate_child_response":
       document.getElementById("content").innerHTML = "<p>Navigated from secure to insecure frame on a secure page</p>";
       parent.parent.postMessage({"test": "securePage_navigate_child", "msg": "navigated to insecure iframe on secure page"}, "http://mochi.test:8888");
       break;
 
     case "securePage_navigate_grandchild":
       document.getElementById("content").innerHTML=
-        '<a href="http://example.com/tests/dom/base/test/mixedcontentblocker/file_mixed_content_frameNavigation_innermost.html?securePage_navigate_grandchild_response" id="link">Testing\<\/a>';
+        '<a href="http://example.com/tests/dom/security/test/mixedcontentblocker/file_frameNavigation_innermost.html?securePage_navigate_grandchild_response" id="link">Testing\<\/a>';
       document.getElementById("link").click();
       break;
 
     case "securePage_navigate_grandchild_response":
       dump("\nNavigated to grandchild iframe from secure location to insecure location.  About to post message to the top page.\n");
       parent.parent.parent.postMessage({"test": "securePage_navigate_grandchild", "msg": "navigated to insecure grandchild iframe on secure page"}, "http://mochi.test:8888");
       dump("\npostMessage to parent attempted.\n");
       document.getElementById("content").innerHTML = "<p>Navigated from secure to insecure grandchild frame on a secure page</p>";
rename from dom/base/test/mixedcontentblocker/file_mixed_content_frameNavigation_secure.html
rename to dom/security/test/mixedcontentblocker/file_frameNavigation_secure.html
--- a/dom/base/test/mixedcontentblocker/file_mixed_content_frameNavigation_secure.html
+++ b/dom/security/test/mixedcontentblocker/file_frameNavigation_secure.html
@@ -7,17 +7,17 @@ https://bugzilla.mozilla.org/show_bug.cg
 <head>
   <meta charset="utf-8">
   <title>Tests for Mixed Content Frame Navigation</title>
 </head>
 <body>
 <div id="testContent"></div>
 
 <script>
-  var baseUrl = "https://example.com/tests/dom/base/test/mixedcontentblocker/file_mixed_content_frameNavigation_innermost.html";
+  var baseUrl = "https://example.com/tests/dom/security/test/mixedcontentblocker/file_frameNavigation_innermost.html";
 
   // For tests that require setTimeout, set the maximum polling time to 50 x 100ms = 5 seconds.
   var MAX_COUNT = 50;
   var TIMEOUT_INTERVAL = 100;
 
   var testContent = document.getElementById("testContent");
 
   // Test 1: Navigate secure iframe to insecure iframe on a secure page
@@ -39,17 +39,17 @@ https://bugzilla.mozilla.org/show_bug.cg
     } catch(e) {
       if (e.name === "SecurityError") {
         // We received an exception we didn't expect.
         throw e;
       }
       counter_test1++;
       return;
     }
-    if (loc == "http://example.com/tests/dom/base/test/mixedcontentblocker/file_mixed_content_frameNavigation_innermost.html?insecurePage_navigate_child_response") {
+    if (loc == "http://example.com/tests/dom/security/test/mixedcontentblocker/file_frameNavigation_innermost.html?insecurePage_navigate_child_response") {
       return;
     } else {
       if(counter_test1 < MAX_COUNT) {
         counter_test1++;
         setTimeout(navigationStatus, TIMEOUT_INTERVAL, iframe_test1);
       }
       else {
         // After we have called setTimeout the maximum number of times, assume navigating the iframe is blocked
@@ -57,17 +57,17 @@ https://bugzilla.mozilla.org/show_bug.cg
       }
     }
   }
 
   setTimeout(navigationStatus, TIMEOUT_INTERVAL, iframe_test1);
 
   // Test 2: Open an http page in a new tab from a link click with target=_blank.
   var iframe_test3 = document.createElement("iframe");
-  iframe_test3.src = "https://example.com/tests/dom/base/test/mixedcontentblocker/file_mixed_content_frameNavigation_blankTarget.html";
+  iframe_test3.src = "https://example.com/tests/dom/security/test/mixedcontentblocker/file_frameNavigation_blankTarget.html";
   iframe_test3.onerror = function() {
     parent.postMessage({"test": "blankTarget", "msg": "got an onerror event when loading or navigating testing iframe"}, "http://mochi.test:8888");
   };
   testContent.appendChild(iframe_test3);
 
 </script>
 </body>
 </html>
rename from dom/base/test/mixedcontentblocker/file_mixed_content_frameNavigation_secure_grandchild.html
rename to dom/security/test/mixedcontentblocker/file_frameNavigation_secure_grandchild.html
--- a/dom/base/test/mixedcontentblocker/file_mixed_content_frameNavigation_secure_grandchild.html
+++ b/dom/security/test/mixedcontentblocker/file_frameNavigation_secure_grandchild.html
@@ -5,17 +5,17 @@ Tests for Mixed Content Blocker - Naviga
 https://bugzilla.mozilla.org/show_bug.cgi?id=840388
 -->
 <head>
   <meta charset="utf-8">
   <title>Tests for Mixed Content Frame Navigation</title>
 </head>
 <body>
 
-<iframe src="https://example.com/tests/dom/base/test/mixedcontentblocker/file_mixed_content_frameNavigation_innermost.html?securePage_navigate_grandchild" id="child"></iframe>
+<iframe src="https://example.com/tests/dom/security/test/mixedcontentblocker/file_frameNavigation_innermost.html?securePage_navigate_grandchild" id="child"></iframe>
 <script>
   // For tests that require setTimeout, set the maximum polling time to 50 x 100ms = 5 seconds.
   var MAX_COUNT = 50;
   var TIMEOUT_INTERVAL = 100;
   var counter = 0;
 
   var child = document.getElementById("child");
   function navigationStatus(child)
@@ -28,17 +28,17 @@ https://bugzilla.mozilla.org/show_bug.cg
     } catch(e) {
       if (e.message && e.message.indexOf("Permission denied to access property") == -1) {
         // We received an exception we didn't expect.
         throw e;
       }
       counter++;
       return;
     }
-    if (loc == "http://example.com/tests/dom/base/test/mixedcontentblocker/file_mixed_content_frameNavigation_innermost.html?securePage_navigate_grandchild_response") {
+    if (loc == "http://example.com/tests/dom/security/test/mixedcontentblocker/file_frameNavigation_innermost.html?securePage_navigate_grandchild_response") {
       return;
     }
     else {
       if(counter < MAX_COUNT) {
         counter++;
         setTimeout(navigationStatus, TIMEOUT_INTERVAL, child);
       }
       else {
rename from dom/base/test/mixedcontentblocker/file_mixed_content_main.html
rename to dom/security/test/mixedcontentblocker/file_main.html
--- a/dom/base/test/mixedcontentblocker/file_mixed_content_main.html
+++ b/dom/security/test/mixedcontentblocker/file_main.html
@@ -33,17 +33,17 @@ https://bugzilla.mozilla.org/show_bug.cg
     our ping implementation is off by default and does not comply with the current spec (bug 786347)
   case nsIContentPolicy::TYPE_BEACON:
 
   }
      */
 -->
 
 <script>
-  var baseUrl = "http://example.com/tests/dom/base/test/mixedcontentblocker/file_mixed_content_server.sjs";
+  var baseUrl = "http://example.com/tests/dom/security/test/mixedcontentblocker/file_server.sjs";
 
   //For tests that require setTimeout, set the maximum polling time to 100 x 100ms = 10 seconds.
   var MAX_COUNT = 100;
   var TIMEOUT_INTERVAL = 100;
 
   var testContent = document.getElementById("testContent");
 
   /* Part 1: Mixed Script tests */
rename from dom/base/test/mixedcontentblocker/file_mixed_content_main_bug803225.html
rename to dom/security/test/mixedcontentblocker/file_main_bug803225.html
--- a/dom/base/test/mixedcontentblocker/file_mixed_content_main_bug803225.html
+++ b/dom/security/test/mixedcontentblocker/file_main_bug803225.html
@@ -107,17 +107,17 @@ https://bugzilla.mozilla.org/show_bug.cg
 
   // Test 7: mailto protocol
   var ioService = SpecialPowers.Cc["@mozilla.org/network/io-service;1"].
      getService(SpecialPowers.Ci.nsIIOService);
 
   var webHandler = SpecialPowers.Cc["@mozilla.org/uriloader/web-handler-app;1"].
                    createInstance(SpecialPowers.Ci.nsIWebHandlerApp);
   webHandler.name = "Web Handler";
-  webHandler.uriTemplate = "http://example.com/tests/dom/base/test/mixedcontentblocker/bug803225_test_mailto.html?s=%";
+  webHandler.uriTemplate = "http://example.com/tests/dom/security/test/mixedcontentblocker/file_bug803225_test_mailto.html?s=%";
 
   var uri = ioService.newURI("mailto:foo@bar.com", null, null);
   webHandler.launchWithURI(uri);
 
   var mailto = false;
 
   // listen for a messages from a new window
   var os = SpecialPowers.Cc["@mozilla.org/observer-service;1"].
@@ -139,17 +139,17 @@ https://bugzilla.mozilla.org/show_bug.cg
       setTimeout(mailtoProtocolStatus, TIMEOUT_INTERVAL);
     }
   }
 
   mailtoProtocolStatus();
 
   // Test 8: wss protocol
   var wss;
-  wss = new WebSocket("wss://example.com/tests/dom/base/test/mixedcontentblocker/file_mixed_content_main_bug803225_websocket");
+  wss = new WebSocket("wss://example.com/tests/dom/security/test/mixedcontentblocker/file_main_bug803225_websocket");
 
   var status_wss = "started";
   wss.onopen = function(e) {
      status_wss = "opened";
      wss.close();
   }
   wss.onclose = function(e) {
     if(status_wss == "opened") {
rename from dom/base/test/mixedcontentblocker/file_mixed_content_main_bug803225_websocket_wsh.py
rename to dom/security/test/mixedcontentblocker/file_main_bug803225_websocket_wsh.py
rename from dom/base/test/mixedcontentblocker/file_mixed_content_server.sjs
rename to dom/security/test/mixedcontentblocker/file_server.sjs
rename from dom/base/test/mixedcontentblocker/mochitest.ini
rename to dom/security/test/mixedcontentblocker/mochitest.ini
--- a/dom/base/test/mixedcontentblocker/mochitest.ini
+++ b/dom/security/test/mixedcontentblocker/mochitest.ini
@@ -1,20 +1,20 @@
 [DEFAULT]
 support-files =
-  bug803225_test_mailto.html
-  file_mixed_content_frameNavigation.html
-  file_mixed_content_frameNavigation_blankTarget.html
-  file_mixed_content_frameNavigation_grandchild.html
-  file_mixed_content_frameNavigation_innermost.html
-  file_mixed_content_frameNavigation_secure.html
-  file_mixed_content_frameNavigation_secure_grandchild.html
-  file_mixed_content_main.html
-  file_mixed_content_main_bug803225.html
-  file_mixed_content_main_bug803225_websocket_wsh.py
-  file_mixed_content_server.sjs
+  file_bug803225_test_mailto.html
+  file_frameNavigation.html
+  file_frameNavigation_blankTarget.html
+  file_frameNavigation_grandchild.html
+  file_frameNavigation_innermost.html
+  file_frameNavigation_secure.html
+  file_frameNavigation_secure_grandchild.html
+  file_main.html
+  file_main_bug803225.html
+  file_main_bug803225_websocket_wsh.py
+  file_server.sjs
 
-[test_mixed_content_blocker.html]
+[test_main.html]
 skip-if = buildapp == 'mulet' || buildapp == 'b2g' || toolkit == 'android' || e10s #TIMED_OUT, SSL_REQUIRED # Bug 1141029 Mulet parity with B2G Desktop for TC
-[test_mixed_content_blocker_bug803225.html]
+[test_bug803225.html]
 skip-if = buildapp == 'mulet' || buildapp == 'b2g' || toolkit == 'android' || e10s #TIMED_OUT, SSL_REQUIRED # Bug 1141029 Mulet parity with B2G Desktop for TC
-[test_mixed_content_blocker_frameNavigation.html]
+[test_frameNavigation.html]
 skip-if = buildapp == 'mulet' || buildapp == 'b2g' || toolkit == 'android' || e10s #TIMED_OUT, SSL_REQUIRED # Bug 1141029 Mulet parity with B2G Desktop for TC
rename from dom/base/test/mixedcontentblocker/test_mixed_content_blocker_bug803225.html
rename to dom/security/test/mixedcontentblocker/test_bug803225.html
--- a/dom/base/test/mixedcontentblocker/test_mixed_content_blocker_bug803225.html
+++ b/dom/security/test/mixedcontentblocker/test_bug803225.html
@@ -59,17 +59,17 @@ https://bugzilla.mozilla.org/show_bug.cg
     if(counter < 4) {
        for (var prop in testsToRun) {
          testsToRun[prop] = false;
        }
       //call to change the preferences
       changePrefs(counter);
       counter++;
       log("\nblockDisplay set to "+blockDisplay+", blockActive set to "+blockActive+".");
-      document.getElementById('framediv').innerHTML = '<iframe id="testHarness" src="https://example.com/tests/dom/base/test/mixedcontentblocker/file_mixed_content_main_bug803225.html"></iframe>';
+      document.getElementById('framediv').innerHTML = '<iframe id="testHarness" src="https://example.com/tests/dom/security/test/mixedcontentblocker/file_main_bug803225.html"></iframe>';
     }
     else {
       //set the prefs back to what they were set to originally
       SpecialPowers.setBoolPref("security.mixed_content.block_display_content", origBlockDisplay);
       SpecialPowers.setBoolPref("security.mixed_content.block_active_content", origBlockActive);
       SimpleTest.finish();
     }
   }
@@ -136,13 +136,13 @@ https://bugzilla.mozilla.org/show_bug.cg
   }
 
   SimpleTest.waitForExplicitFinish();
   </script>
 </head>
 
 <body>
   <div id="framediv">
-    <iframe id="testHarness" src="https://example.com/tests/dom/base/test/mixedcontentblocker/file_mixed_content_main_bug803225.html"></iframe>
+    <iframe id="testHarness" src="https://example.com/tests/dom/security/test/mixedcontentblocker/file_main_bug803225.html"></iframe>
   </div>
   <pre id="log"></pre>
 </body>
 </html>
rename from dom/base/test/mixedcontentblocker/test_mixed_content_blocker_frameNavigation.html
rename to dom/security/test/mixedcontentblocker/test_frameNavigation.html
--- a/dom/base/test/mixedcontentblocker/test_mixed_content_blocker_frameNavigation.html
+++ b/dom/security/test/mixedcontentblocker/test_frameNavigation.html
@@ -37,17 +37,17 @@ https://bugzilla.mozilla.org/show_bug.cg
     for (var prop in testsToRunInsecure) {
       // some test hasn't run yet so we're not done
       if (!testsToRunInsecure[prop])
         return;
     }
     // If we are here, all the insecure tests have run.
     // If we haven't changed the iframe to run the secure tests, change it now.
     if (!secureTestsStarted) {
-      document.getElementById('testing_frame').src = "https://example.com/tests/dom/base/test/mixedcontentblocker/file_mixed_content_frameNavigation_secure.html";
+      document.getElementById('testing_frame').src = "https://example.com/tests/dom/security/test/mixedcontentblocker/file_frameNavigation_secure.html";
       secureTestsStarted = true;
     }
     for (var prop in testsToRunSecure) {
       // some test hasn't run yet so we're not done
       if (!testsToRunSecure[prop])
         return;
     }
     //if the secure and insecure testsToRun are all completed, change the block mixed active content pref and run the tests again.
@@ -59,17 +59,17 @@ https://bugzilla.mozilla.org/show_bug.cg
          testsToRunInsecure[prop] = false;
        }
       //call to change the preferences
       counter++;
       SpecialPowers.setBoolPref("security.mixed_content.block_active_content", false);
       blockActive = SpecialPowers.getBoolPref("security.mixed_content.block_active_content");
       log("blockActive set to "+blockActive+".");
       secureTestsStarted = false;
-      document.getElementById('framediv').innerHTML = '<iframe src="http://example.com/tests/dom/base/test/mixedcontentblocker/file_mixed_content_frameNavigation.html" id="testing_frame"></iframe>';
+      document.getElementById('framediv').innerHTML = '<iframe src="http://example.com/tests/dom/security/test/mixedcontentblocker/file_frameNavigation.html" id="testing_frame"></iframe>';
     }
     else {
       //set the prefs back to what they were set to originally
       SpecialPowers.setBoolPref("security.mixed_content.block_active_content", origBlockActive);
       SimpleTest.finish();
     }
   }
 
@@ -114,14 +114,14 @@ https://bugzilla.mozilla.org/show_bug.cg
   }
 
   SimpleTest.waitForExplicitFinish();
   </script>
 </head>
 
 <body>
   <div id="framediv">
-    <iframe src="http://example.com/tests/dom/base/test/mixedcontentblocker/file_mixed_content_frameNavigation.html" id="testing_frame"></iframe>
+    <iframe src="http://example.com/tests/dom/security/test/mixedcontentblocker/file_frameNavigation.html" id="testing_frame"></iframe>
   </div>
 
   <pre id="log"></pre>
 </body>
 </html>
rename from dom/base/test/mixedcontentblocker/test_mixed_content_blocker.html
rename to dom/security/test/mixedcontentblocker/test_main.html
--- a/dom/base/test/mixedcontentblocker/test_mixed_content_blocker.html
+++ b/dom/security/test/mixedcontentblocker/test_main.html
@@ -57,17 +57,17 @@ https://bugzilla.mozilla.org/show_bug.cg
     xhr: false,
   };
 
   function log(msg) {
     document.getElementById("log").textContent += "\n" + msg;
   }
 
   function reloadFrame() {
-    document.getElementById('framediv').innerHTML = '<iframe id="testHarness" src="https://example.com/tests/dom/base/test/mixedcontentblocker/file_mixed_content_main.html"></iframe>';
+    document.getElementById('framediv').innerHTML = '<iframe id="testHarness" src="https://example.com/tests/dom/security/test/mixedcontentblocker/file_main.html"></iframe>';
   }
 
   function checkTestsCompleted() {
     for (var prop in testsToRun) {
       // some test hasn't run yet so we're not done
       if (!testsToRun[prop])
         return;
     }
new file mode 100644
--- /dev/null
+++ b/dom/security/test/moz.build
@@ -0,0 +1,27 @@
+# -*- Mode: python; c-basic-offset: 4; indent-tabs-mode: nil; tab-width: 40 -*-
+# vim: set filetype=python:
+# This Source Code Form is subject to the terms of the Mozilla Public
+# License, v. 2.0. If a copy of the MPL was not distributed with this
+# file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+XPCSHELL_TESTS_MANIFESTS += [
+    'unit/xpcshell.ini',
+]
+
+GeckoCppUnitTests([
+     'TestCSPParser',
+])
+
+MOCHITEST_MANIFESTS += [
+    'cors/mochitest.ini',
+    'csp/mochitest.ini',
+    'mixedcontentblocker/mochitest.ini',
+]
+
+MOCHITEST_CHROME_MANIFESTS += [
+    'csp/chrome.ini',
+]
+
+BROWSER_CHROME_MANIFESTS += [
+    'csp/browser.ini',
+]
rename from dom/base/test/unit/test_cspreports.js
rename to dom/security/test/unit/test_csp_reports.js
--- a/dom/base/test/unit/test_cspreports.js
+++ b/dom/security/test/unit/test_csp_reports.js
@@ -4,16 +4,17 @@
 
 const Cc = Components.classes;
 const Ci = Components.interfaces;
 const Cu = Components.utils;
 const Cr = Components.results;
 
 Cu.import('resource://gre/modules/NetUtil.jsm');
 Cu.import("resource://gre/modules/Services.jsm");
+Cu.import("resource://testing-common/httpd.js");
 
 var httpServer = new HttpServer();
 httpServer.start(-1);
 var testsToFinish = 0;
 
 const REPORT_SERVER_PORT = httpServer.identity.primaryPort;
 const REPORT_SERVER_URI = "http://localhost";
 const REPORT_SERVER_PATH = "/report";
new file mode 100644
--- /dev/null
+++ b/dom/security/test/unit/xpcshell.ini
@@ -0,0 +1,7 @@
+[DEFAULT]
+head =
+tail =
+skip-if = toolkit == 'gonk'
+
+[test_csp_reports.js]
+skip-if = buildapp == 'mulet'
--- a/dom/tests/mochitest/chrome/MozDomFullscreen_chrome.xul
+++ b/dom/tests/mochitest/chrome/MozDomFullscreen_chrome.xul
@@ -38,25 +38,26 @@ var gOuterDoc = null;
 var gInnerDoc = null;
 
 var gReceivedFullscreenEnteredEvent = false;
 var gReceivedNewOriginEvent = false;
 function firstEntry(event) {
   if (event.type == "MozDOMFullscreen:Entered") {
     window.removeEventListener("MozDOMFullscreen:Entered", firstEntry, false);
     ok(!gReceivedFullscreenEnteredEvent, "MozDOMFullscreen:Entered shouldn't have been triggered twice");
+    ok(event.target, gOuterDoc.body, "First MozDOMFullscreen:Entered should be targeted at outer body");
     gReceivedFullscreenEnteredEvent = true;
   } else if (event.type == "MozDOMFullscreen:NewOrigin") {
     window.removeEventListener("MozDOMFullscreen:NewOrigin", firstEntry, false);
     ok(!gReceivedNewOriginEvent, "MozDOMFullscreen:NewOrigin shouldn't have been triggered twice");
+    ok(event.target, gOuterDoc, "First MozDOMFullscreen:NewOrigin should be targeted at outer doc");
     gReceivedNewOriginEvent = true;
   } else {
     ok(false, "Unknown event received");
   }
-  is(event.target, gOuterDoc, "First " + event.type + " should be targeted at outer doc");
   if (!gReceivedFullscreenEnteredEvent || !gReceivedNewOriginEvent) {
     return;
   }
 
   ok(gOuterDoc.mozFullScreenElement != null, "Outer doc should be in fullscreen");
   gInnerDoc = gOuterDoc.getElementById("innerFrame").contentDocument;
   window.addEventListener("MozDOMFullscreen:NewOrigin", secondEntry, false);
   gInnerDoc.defaultView.focus();
--- a/dom/tests/mochitest/chrome/chrome.ini
+++ b/dom/tests/mochitest/chrome/chrome.ini
@@ -10,17 +10,16 @@ support-files =
   file_MozDomFullscreen.html
   file_bug799299.xul
   file_bug800817.xul
   file_bug830858.xul
   file_subscript_bindings.js
   focus_frameset.html
   focus_window2.xul
   fullscreen.xul
-  fullscreen_preventdefault.xul
   queryCaretRectUnix.html
   queryCaretRectWin.html
   selectAtPoint.html
   sizemode_attribute.xul
   window_activation.xul
   window_callback_wrapping.xul
   window_docshell_swap.xul
   window_focus.xul
@@ -40,17 +39,16 @@ support-files =
 [test_focus.xul]
 skip-if = buildapp == 'mulet'
 [test_focus_docnav.xul]
 [test_focus_switchbinding.xul]
 [test_focused_link_scroll.xul]
 [test_fullscreen.xul]
 # disabled on linux for timeouts--bug-867745
 skip-if = os == 'linux'
-[test_fullscreen_preventdefault.xul]
 [test_geolocation.xul]
 [test_indexedSetter.html]
 [test_moving_nodeList.xul]
 [test_moving_xhr.xul]
 [test_MozDomFullscreen_event.xul]
 # disabled on OS X for intermittent failures--bug-798848
 skip-if = toolkit == 'cocoa'
 [test_nodesFromRect.html]
deleted file mode 100644
--- a/dom/tests/mochitest/chrome/fullscreen_preventdefault.xul
+++ /dev/null
@@ -1,27 +0,0 @@
-<?xml version="1.0"?>
-<?xml-stylesheet href="chrome://global/skin" type="text/css"?>
-<?xml-stylesheet href="chrome://mochikit/content/tests/SimpleTest/test.css" type="text/css"?>
-<!--
-  Test for fullscreen sizemode in chrome
-  -->
-<window xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"
-        sizemode="fullscreen">
-
-<script>
-
-window.addEventListener("fullscreen", onFullScreen, true);
-
-function onFullScreen(event)
-{
-  event.preventDefault();
-  window.opener.wrappedJSObject.done();
-}
-
-</script>
-
-<body xmlns="http://www.w3.org/1999/xhtml">
-
-<button id="find-button" label="Find"/>
-<button id="cancel-button" label="Cancel"/>
-</body>
-</window>
deleted file mode 100644
--- a/dom/tests/mochitest/chrome/test_fullscreen_preventdefault.xul
+++ /dev/null
@@ -1,37 +0,0 @@
-<?xml version="1.0"?>
-<?xml-stylesheet href="chrome://global/skin" type="text/css"?>
-<?xml-stylesheet href="chrome://mochikit/content/tests/SimpleTest/test.css" type="text/css"?>
-<!--
-  Test for fullscreen sizemode in chrome
-  -->
-<window xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"
-        sizemode="fullscreen">
-
-  <script type="application/javascript" 
-          src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"></script>      
-
-<script>
-SimpleTest.waitForExplicitFinish();
-
-newwindow = window.open("fullscreen_preventdefault.xul", "_blank","chrome,resizable=yes");
-
-function done()
-{
-  // because we are cancelling the fullscreen event, it
-  // takes a bit for the fullScreen property to be set
-  setTimeout("complete()", 0);
-}
-