merge mozilla-central to autoland. r=merge a=merge
authorSebastian Hengst <archaeopteryx@coole-files.de>
Tue, 01 Aug 2017 11:25:13 +0200
changeset 420885 5f1092d7ac02ba594d1884efdd615ca4bb196193
parent 420884 6639cc7b2321a3056c7b86d2df6244d4a08aa48d (current diff)
parent 420875 51ffb9283f0c7c00e08eb8c39b33fbee218c370d (diff)
child 420886 7266739602ca1035af71e4f860a2be9059768e40
push id7566
push usermtabara@mozilla.com
push dateWed, 02 Aug 2017 08:25:16 +0000
treeherdermozilla-beta@86913f512c3c [default view] [failures only]
perfherder[talos] [build metrics] [platform microbench] (compared to previous push)
reviewersmerge, merge
milestone56.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 mozilla-central to autoland. r=merge a=merge
browser/extensions/onboarding/content/onboarding.js
dom/plugins/base/android/ANPAudio.cpp
dom/plugins/base/android/ANPBase.h
dom/plugins/base/android/ANPEvent.cpp
dom/plugins/base/android/ANPKeyCodes.h
dom/plugins/base/android/ANPLog.cpp
dom/plugins/base/android/ANPNativeWindow.cpp
dom/plugins/base/android/ANPSurface.cpp
dom/plugins/base/android/ANPSystem.cpp
dom/plugins/base/android/ANPVideo.cpp
dom/plugins/base/android/ANPWindow.cpp
dom/plugins/base/android/android_npapi.h
dom/plugins/base/android/moz.build
mobile/android/tests/browser/robocop/robocop_adobe_flash.html
mobile/android/tests/browser/robocop/src/org/mozilla/gecko/tests/testAdobeFlash.java
modules/libpref/init/all.js
other-licenses/skia-npapi/ANPCanvas.cpp
other-licenses/skia-npapi/ANPPaint.cpp
other-licenses/skia-npapi/ANPTypeface.cpp
other-licenses/skia-npapi/SkANP.cpp
other-licenses/skia-npapi/SkANP.h
other-licenses/skia-npapi/moz.build
widget/android/fennec/GeckoApp.h
--- a/browser/base/content/test/performance/browser.ini
+++ b/browser/base/content/test/performance/browser.ini
@@ -1,13 +1,13 @@
 [DEFAULT]
 support-files =
   head.js
 [browser_appmenu_reflows.js]
-skip-if = (os == 'mac' || os == 'win') && debug # Bug 1382809
+skip-if = asan || debug # Bug 1382809, bug 1369959
 [browser_startup.js]
 [browser_startup_content.js]
 skip-if = !e10s
 [browser_startup_images.js]
 skip-if = !debug
 [browser_tabclose_grow_reflows.js]
 [browser_tabclose_reflows.js]
 [browser_tabopen_reflows.js]
--- a/browser/extensions/activity-stream/bootstrap.js
+++ b/browser/extensions/activity-stream/bootstrap.js
@@ -2,23 +2,22 @@
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 "use strict";
 
 const {classes: Cc, interfaces: Ci, utils: Cu} = Components;
 Cu.import("resource://gre/modules/XPCOMUtils.jsm");
 Cu.importGlobalProperties(["fetch"]);
 
-XPCOMUtils.defineLazyModuleGetter(this, "Preferences",
-  "resource://gre/modules/Preferences.jsm");
 XPCOMUtils.defineLazyModuleGetter(this, "Services",
   "resource://gre/modules/Services.jsm");
 
 const ACTIVITY_STREAM_ENABLED_PREF = "browser.newtabpage.activity-stream.enabled";
 const BROWSER_READY_NOTIFICATION = "sessionstore-windows-restored";
+const PREF_CHANGED_TOPIC = "nsPref:changed";
 const REASON_SHUTDOWN_ON_PREF_CHANGE = "PREF_OFF";
 const REASON_STARTUP_ON_PREF_CHANGE = "PREF_ON";
 const RESOURCE_BASE = "resource://activity-stream";
 
 const ACTIVITY_STREAM_OPTIONS = {newTabURL: "about:newtab"};
 
 let activityStream;
 let modulesToUnload = new Set();
@@ -79,51 +78,55 @@ function uninit(reason) {
   if (activityStream) {
     activityStream.uninit(reason);
   }
 }
 
 /**
  * onPrefChanged - handler for changes to ACTIVITY_STREAM_ENABLED_PREF
  *
- * @param  {bool} isEnabled Determines whether Activity Stream is enabled
  */
-function onPrefChanged(isEnabled) {
-  if (isEnabled) {
+function onPrefChanged() {
+  if (Services.prefs.getBoolPref(ACTIVITY_STREAM_ENABLED_PREF, false)) {
     init(REASON_STARTUP_ON_PREF_CHANGE);
   } else {
     uninit(REASON_SHUTDOWN_ON_PREF_CHANGE);
   }
 }
 
 /**
  * onBrowserReady - Continues startup of the add-on after browser is ready.
  */
 function onBrowserReady() {
   waitingForBrowserReady = false;
 
   // Listen for changes to the pref that enables Activity Stream
-  Preferences.observe(ACTIVITY_STREAM_ENABLED_PREF, onPrefChanged);
+  Services.prefs.addObserver(ACTIVITY_STREAM_ENABLED_PREF, observe);
 
   // Only initialize if the pref is true
-  if (Preferences.get(ACTIVITY_STREAM_ENABLED_PREF)) {
+  if (Services.prefs.getBoolPref(ACTIVITY_STREAM_ENABLED_PREF, false)) {
     init(startupReason);
   }
 }
 
 /**
  * observe - nsIObserver callback to handle various browser notifications.
  */
 function observe(subject, topic, data) {
   switch (topic) {
     case BROWSER_READY_NOTIFICATION:
       Services.obs.removeObserver(observe, BROWSER_READY_NOTIFICATION);
       // Avoid running synchronously during this event that's used for timing
       Services.tm.dispatchToMainThread(() => onBrowserReady());
       break;
+    case PREF_CHANGED_TOPIC:
+      if (data == ACTIVITY_STREAM_ENABLED_PREF) {
+        onPrefChanged();
+      }
+      break;
   }
 }
 
 // The functions below are required by bootstrap.js
 
 this.install = function install(data, reason) {};
 
 this.startup = function startup(data, reason) {
@@ -147,17 +150,17 @@ this.shutdown = function shutdown(data, 
   startupReason = null;
   uninit(reason);
 
   // Stop waiting for browser to be ready
   if (waitingForBrowserReady) {
     Services.obs.removeObserver(observe, BROWSER_READY_NOTIFICATION);
   } else {
     // Stop listening to the pref that enables Activity Stream
-    Preferences.ignore(ACTIVITY_STREAM_ENABLED_PREF, onPrefChanged);
+    Services.prefs.removeObserver(ACTIVITY_STREAM_ENABLED_PREF, observe);
   }
 
   // Unload any add-on modules that might might have been imported
   modulesToUnload.forEach(Cu.unload);
 };
 
 this.uninstall = function uninstall(data, reason) {
   if (activityStream) {
--- a/browser/extensions/clicktoplay-rollout/bootstrap.js
+++ b/browser/extensions/clicktoplay-rollout/bootstrap.js
@@ -1,17 +1,17 @@
 /* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 "use strict";
 
 const {classes: Cc, interfaces: Ci, utils: Cu} = Components;
 
-Cu.import("resource://gre/modules/Preferences.jsm");
+Cu.import("resource://gre/modules/XPCOMUtils.jsm");
 Cu.import("resource://gre/modules/Services.jsm");
 Cu.import("resource://gre/modules/UpdateUtils.jsm");
 Cu.import("resource://gre/modules/AppConstants.jsm");
 Cu.import("resource://gre/modules/TelemetryEnvironment.jsm");
 
 // The amount of people to be part of the rollout
 const TEST_THRESHOLD = {
   "beta": 0.5,  // 50%
@@ -41,23 +41,23 @@ function startup() {
 }
 
 function defineCohort() {
   let updateChannel = UpdateUtils.getUpdateChannel(false);
   if (!(updateChannel in TEST_THRESHOLD)) {
     return;
   }
 
-  let cohort = Preferences.get(PREF_COHORT_NAME);
+  let cohort = Services.prefs.getStringPref(PREF_COHORT_NAME);
 
   if (!cohort) {
     // The cohort has not been defined yet: this is the first
     // time that we're running. Let's see if the user has
     // a non-default setting to avoid changing it.
-    let currentPluginState = Preferences.get(PREF_FLASH_STATE);
+    let currentPluginState = Services.prefs.getIntPref(PREF_FLASH_STATE);
     switch (currentPluginState) {
       case Ci.nsIPluginTag.STATE_CLICKTOPLAY:
         cohort = "early-adopter-ctp";
         break;
 
       case Ci.nsIPluginTag.STATE_DISABLED:
         cohort = "early-adopter-disabled";
         break;
@@ -76,18 +76,18 @@ function defineCohort() {
     {
       // If it's either test/control, the cohort might have changed
       // if the desired sampling has been changed.
       let testThreshold = TEST_THRESHOLD[updateChannel];
       let userSample = getUserSample();
 
       if (userSample < testThreshold) {
         cohort = "test";
-        let defaultPrefs = new Preferences({defaultBranch: true});
-        defaultPrefs.set(PREF_FLASH_STATE, Ci.nsIPluginTag.STATE_CLICKTOPLAY);
+        let defaultPrefs = Services.prefs.getDefaultBranch("");
+        defaultPrefs.setIntPref(PREF_FLASH_STATE, Ci.nsIPluginTag.STATE_CLICKTOPLAY);
       } else if (userSample >= 1.0 - testThreshold) {
         cohort = "control";
       } else {
         cohort = "excluded";
       }
 
       setCohort(cohort);
       watchForPrefChanges();
@@ -100,45 +100,43 @@ function defineCohort() {
       // "user-changed-from-*" will fall into this default case and
       // not do anything special.
       setCohort(cohort);
       break;
   }
 }
 
 function getUserSample() {
-  let prefValue = Preferences.get(PREF_COHORT_SAMPLE, undefined);
-  let value = 0.0;
+  let prefType = Services.prefs.getPrefType(PREF_COHORT_SAMPLE);
 
-  if (typeof(prefValue) == "string") {
-    value = parseFloat(prefValue, 10);
-    return value;
+  if (prefType == Ci.nsIPrefBranch.PREF_STRING) {
+    return parseFloat(Services.prefs.getStringPref(PREF_COHORT_SAMPLE), 10);
   }
 
-  value = Math.random();
-  Preferences.set(PREF_COHORT_SAMPLE, value.toString().substr(0, 8));
+  let value = Math.random();
+  Services.prefs.setStringPref(PREF_COHORT_SAMPLE, value.toString().substr(0, 8));
   return value;
 }
 
 function setCohort(cohortName) {
-  Preferences.set(PREF_COHORT_NAME, cohortName);
+  Services.prefs.setStringPref(PREF_COHORT_NAME, cohortName);
   TelemetryEnvironment.setExperimentActive("clicktoplay-rollout", cohortName);
 
   try {
     if (Ci.nsICrashReporter) {
       Services.appinfo.QueryInterface(Ci.nsICrashReporter).annotateCrashReport("CTPCohort", cohortName);
     }
   } catch (e) {}
 }
 
 function watchForPrefChanges() {
-  Preferences.observe(PREF_FLASH_STATE, function prefWatcher() {
-    let currentCohort = Preferences.get(PREF_COHORT_NAME, "unknown");
+  Services.prefs.addObserver(PREF_FLASH_STATE, function prefWatcher() {
+    let currentCohort = Services.prefs.getStringPref(PREF_COHORT_NAME, "unknown");
     setCohort(`user-changed-from-${currentCohort}`);
-    Preferences.ignore(PREF_FLASH_STATE, prefWatcher);
+    Services.prefs.removeObserver(PREF_FLASH_STATE, prefWatcher);
   });
 }
 
 function install() {
 }
 
 function shutdown(data, reason) {
 }
--- a/browser/extensions/e10srollout/bootstrap.js
+++ b/browser/extensions/e10srollout/bootstrap.js
@@ -1,17 +1,16 @@
 /* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 "use strict";
 
 const {classes: Cc, interfaces: Ci, utils: Cu} = Components;
 
-Cu.import("resource://gre/modules/Preferences.jsm");
 Cu.import("resource://gre/modules/Services.jsm");
 Cu.import("resource://gre/modules/UpdateUtils.jsm");
 Cu.import("resource://gre/modules/AppConstants.jsm");
 Cu.import("resource://gre/modules/TelemetryEnvironment.jsm");
 
 // The amount of people to be part of e10s
 const TEST_THRESHOLD = {
   "beta": 0.9,  // 90%
@@ -106,31 +105,31 @@ function defineCohort() {
   if (!(updateChannel in TEST_THRESHOLD)) {
     setCohort("unsupportedChannel");
     return;
   }
 
   let addonPolicy = "unknown";
   if (updateChannel in ADDON_ROLLOUT_POLICY) {
     addonPolicy = ADDON_ROLLOUT_POLICY[updateChannel];
-    Preferences.set(PREF_E10S_ADDON_POLICY, addonPolicy);
+    Services.prefs.setStringPref(PREF_E10S_ADDON_POLICY, addonPolicy);
 
     // This is also the proper place to set the blocklist pref
     // in case it is necessary.
-    Preferences.set(PREF_E10S_ADDON_BLOCKLIST, "");
+    Services.prefs.setStringPref(PREF_E10S_ADDON_BLOCKLIST, "");
   } else {
-    Preferences.reset(PREF_E10S_ADDON_POLICY);
+    Services.prefs.clearUserPref(PREF_E10S_ADDON_POLICY);
   }
 
   let userOptedOut = optedOut();
   let userOptedIn = optedIn();
   let disqualified = (Services.appinfo.multiprocessBlockPolicy != 0);
   let testThreshold = TEST_THRESHOLD[updateChannel];
   let testGroup = (getUserSample(false) < testThreshold);
-  let hasNonExemptAddon = Preferences.get(PREF_E10S_HAS_NONEXEMPT_ADDON, false);
+  let hasNonExemptAddon = Services.prefs.getBoolPref(PREF_E10S_HAS_NONEXEMPT_ADDON, false);
   let temporaryDisqualification = getTemporaryDisqualification();
   let temporaryQualification = getTemporaryQualification();
 
   let cohortPrefix = "";
   if (disqualified) {
     cohortPrefix = "disqualified-";
   } else if (hasNonExemptAddon) {
     cohortPrefix = `addons-set${addonPolicy}-`;
@@ -148,34 +147,34 @@ function defineCohort() {
     // Users who are disqualified by the backend (from multiprocessBlockPolicy)
     // can be put into either the test or control groups, because e10s will
     // still be denied by the backend, which is useful so that the E10S_STATUS
     // telemetry probe can be correctly set.
 
     // For these volatile disqualification reasons, however, we must not try
     // to activate e10s because the backend doesn't know about it. E10S_STATUS
     // here will be accumulated as "2 - Disabled", which is fine too.
-    Preferences.reset(PREF_TOGGLE_E10S);
-    Preferences.reset(PREF_E10S_PROCESSCOUNT + ".web");
+    Services.prefs.clearUserPref(PREF_TOGGLE_E10S);
+    Services.prefs.clearUserPref(PREF_E10S_PROCESSCOUNT + ".web");
     setCohort(`temp-disqualified-${temporaryDisqualification}`);
   } else if (!disqualified && testThreshold < 1.0 &&
              temporaryQualification != "") {
     // Users who are qualified for e10s and on channels where some population
     // would not receive e10s can be pushed into e10s anyway via a temporary
     // qualification which overrides the user sample value when non-empty.
-    Preferences.set(PREF_TOGGLE_E10S, true);
+    Services.prefs.setBoolPref.set(PREF_TOGGLE_E10S, true);
     eligibleForMulti = true;
     setCohort(`temp-qualified-${temporaryQualification}`);
   } else if (testGroup) {
-    Preferences.set(PREF_TOGGLE_E10S, true);
+    Services.prefs.setBoolPref(PREF_TOGGLE_E10S, true);
     eligibleForMulti = true;
     setCohort(`${cohortPrefix}test`);
   } else {
-    Preferences.reset(PREF_TOGGLE_E10S);
-    Preferences.reset(PREF_E10S_PROCESSCOUNT + ".web");
+    Services.prefs.clearUserPref(PREF_TOGGLE_E10S);
+    Services.prefs.clearUserPref(PREF_E10S_PROCESSCOUNT + ".web");
     setCohort(`${cohortPrefix}control`);
   }
 
   // Now determine if this user should be in the e10s-multi experiment.
   // - We only run the experiment on channels defined in MULTI_EXPERIMENT.
   // - If this experiment doesn't allow addons and we have a cohort prefix
   //   (i.e. there's at least one addon installed) we stop here.
   // - We decided above whether this user qualifies for the experiment.
@@ -184,17 +183,17 @@ function defineCohort() {
   // - If the user has addons that disqualify them for multi, leave them with
   //   the default number of content processes (1 on beta) but still in the
   //   test cohort.
   if (!(updateChannel in MULTI_EXPERIMENT) ||
       MULTI_EXPERIMENT[updateChannel].addonsDisableExperiment(cohortPrefix) ||
       !eligibleForMulti ||
       userOptedIn.multi ||
       disqualified) {
-    Preferences.reset(PREF_E10S_PROCESSCOUNT + ".web");
+    Services.prefs.clearUserPref(PREF_E10S_PROCESSCOUNT + ".web");
     return;
   }
 
   // If we got here with a cohortPrefix, it must be "addons-set50allmpc-",
   // which means that there's at least one add-on installed. If
   // getAddonsDisqualifyForMulti returns false, that means that all installed
   // addons are webextension based, so note that in the cohort name.
   if (cohortPrefix && !getAddonsDisqualifyForMulti()) {
@@ -204,78 +203,77 @@ function defineCohort() {
   // The user is in the multi experiment!
   // Decide how many content processes to use for this user.
   let buckets = MULTI_EXPERIMENT[updateChannel].buckets;
 
   let multiUserSample = getUserSample(true);
   for (let sampleName of Object.getOwnPropertyNames(buckets)) {
     if (multiUserSample < buckets[sampleName]) {
       // NB: Coerce sampleName to an integer because this is an integer pref.
-      Preferences.set(PREF_E10S_PROCESSCOUNT + ".web", +sampleName);
+      Services.prefs.setIntPref(PREF_E10S_PROCESSCOUNT + ".web", +sampleName);
       setCohort(`${cohortPrefix}multiBucket${sampleName}`);
       break;
     }
   }
 }
 
 function shutdown(data, reason) {
 }
 
 function uninstall() {
 }
 
 function getUserSample(multi) {
   let pref = multi ? (PREF_COHORT_SAMPLE + ".multi") : PREF_COHORT_SAMPLE;
-  let prefValue = Preferences.get(pref, undefined);
-  let value = 0.0;
+  let prefType = Services.prefs.getPrefType(pref);
 
-  if (typeof(prefValue) == "string") {
-    value = parseFloat(prefValue, 10);
-    return value;
+  if (prefType == Ci.nsIPrefBranch.PREF_STRING) {
+    return parseFloat(Services.prefs.getStringPref(pref), 10);
   }
 
-  if (typeof(prefValue) == "number") {
+  let value = 0.0;
+  if (prefType == Ci.nsIPrefBranch.PREF_INT) {
     // convert old integer value
-    value = prefValue / 100;
+    value = Services.prefs.getIntPref(pref) / 100;
   } else {
     value = Math.random();
   }
 
-  Preferences.set(pref, value.toString().substr(0, 8));
+  Services.prefs.setStringPref(pref, value.toString().substr(0, 8));
   return value;
 }
 
 function setCohort(cohortName) {
-  Preferences.set(PREF_COHORT_NAME, cohortName);
+  Services.prefs.setStringPref(PREF_COHORT_NAME, cohortName);
   if (cohortName != "unsupportedChannel") {
     TelemetryEnvironment.setExperimentActive("e10sCohort", cohortName);
   }
   try {
     if (Ci.nsICrashReporter) {
       Services.appinfo.QueryInterface(Ci.nsICrashReporter).annotateCrashReport("E10SCohort", cohortName);
     }
   } catch (e) {}
 }
 
 function optedIn() {
-  let e10s = Preferences.get(PREF_E10S_OPTED_IN, false) ||
-             Preferences.get(PREF_E10S_FORCE_ENABLED, false);
-  let multi = Preferences.isSet(PREF_E10S_PROCESSCOUNT) ||
-             !Preferences.get(PREF_USE_DEFAULT_PERF_SETTINGS, true);
+  let e10s = Services.prefs.getBoolPref(PREF_E10S_OPTED_IN, false) ||
+             Services.prefs.getBoolPref(PREF_E10S_FORCE_ENABLED, false);
+  let multi = Services.prefs.prefHasUserValue(PREF_E10S_PROCESSCOUNT) ||
+             !Services.prefs.getBoolPref(PREF_USE_DEFAULT_PERF_SETTINGS, true);
   return { e10s, multi };
 }
 
 function optedOut() {
   // Users can also opt-out by toggling back the pref to false.
   // If they reset the pref instead they might be re-enabled if
   // they are still part of the threshold.
-  let e10s = Preferences.get(PREF_E10S_FORCE_DISABLED, false) ||
-               (Preferences.isSet(PREF_TOGGLE_E10S) &&
-                Preferences.get(PREF_TOGGLE_E10S) == false);
-  let multi = Preferences.get(PREF_E10S_MULTI_OPTOUT, 0) >=
+  let e10s = Services.prefs.getBoolPref(PREF_E10S_FORCE_DISABLED, false) ||
+               (Services.prefs.prefHasUserValue(PREF_TOGGLE_E10S) &&
+                Services.prefs.getBoolPref(PREF_TOGGLE_E10S) == false);
+  let multi = Services.prefs.getIntPref(PREF_E10S_MULTI_OPTOUT, 0) >=
               Services.appinfo.E10S_MULTI_EXPERIMENT;
   return { e10s, multi };
 }
 
 /* If this function returns a non-empty string, it
  * means that this particular user should be temporarily
  * disqualified due to some particular reason.
  * If a user shouldn't be disqualified, then an empty
@@ -292,20 +290,20 @@ function getTemporaryDisqualification() 
  * string must be returned.
  */
 function getTemporaryQualification() {
   // Whenever the DevTools toolbox is opened for the first time in a release, it
   // records this fact in the following pref as part of the DevTools telemetry
   // system.  If this pref is set, then it means the user has opened DevTools at
   // some point in time.
   const PREF_OPENED_DEVTOOLS = "devtools.telemetry.tools.opened.version";
-  let hasOpenedDevTools = Preferences.isSet(PREF_OPENED_DEVTOOLS);
+  let hasOpenedDevTools = Services.prefs.prefHasUserValue(PREF_OPENED_DEVTOOLS);
   if (hasOpenedDevTools) {
     return "devtools";
   }
 
   return "";
 }
 
 function getAddonsDisqualifyForMulti() {
-  return Preferences.get("extensions.e10sMultiBlocksEnabling", false) &&
-         Preferences.get("extensions.e10sMultiBlockedByAddons", false);
+  return Services.prefs.getBoolPref("extensions.e10sMultiBlocksEnabling", false) &&
+         Services.prefs.getBoolPref("extensions.e10sMultiBlockedByAddons", false);
 }
--- a/browser/extensions/onboarding/bootstrap.js
+++ b/browser/extensions/onboarding/bootstrap.js
@@ -1,65 +1,85 @@
 /* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 /* globals  APP_STARTUP, ADDON_INSTALL */
 "use strict";
 
-const {utils: Cu} = Components;
+const {utils: Cu, interfaces: Ci} = Components;
 Cu.import("resource://gre/modules/XPCOMUtils.jsm");
 XPCOMUtils.defineLazyModuleGetter(this, "OnboardingTourType",
   "resource://onboarding/modules/OnboardingTourType.jsm");
-XPCOMUtils.defineLazyModuleGetter(this, "Preferences",
-  "resource://gre/modules/Preferences.jsm");
 XPCOMUtils.defineLazyModuleGetter(this, "Services",
   "resource://gre/modules/Services.jsm");
 XPCOMUtils.defineLazyModuleGetter(this, "fxAccounts",
   "resource://gre/modules/FxAccounts.jsm");
 
+const {PREF_STRING, PREF_BOOL, PREF_INT} = Ci.nsIPrefBranch;
+
 const BROWSER_READY_NOTIFICATION = "browser-delayed-startup-finished";
 const BROWSER_SESSION_STORE_NOTIFICATION = "sessionstore-windows-restored";
 const PREF_WHITELIST = [
-  "browser.onboarding.enabled",
-  "browser.onboarding.hidden",
-  "browser.onboarding.notification.finished",
-  "browser.onboarding.notification.prompt-count",
-  "browser.onboarding.notification.last-time-of-changing-tour-sec",
-  "browser.onboarding.notification.tour-ids-queue"
+  ["browser.onboarding.enabled", PREF_BOOL],
+  ["browser.onboarding.hidden", PREF_BOOL],
+  ["browser.onboarding.notification.finished", PREF_BOOL],
+  ["browser.onboarding.notification.prompt-count", PREF_INT],
+  ["browser.onboarding.notification.last-time-of-changing-tour-sec", PREF_INT],
+  ["browser.onboarding.notification.tour-ids-queue", PREF_STRING],
 ];
 
 [
   "onboarding-tour-addons",
   "onboarding-tour-customize",
   "onboarding-tour-default-browser",
   "onboarding-tour-library",
   "onboarding-tour-performance",
   "onboarding-tour-private-browsing",
   "onboarding-tour-search",
   "onboarding-tour-singlesearch",
   "onboarding-tour-sync",
-].forEach(tourId => PREF_WHITELIST.push(`browser.onboarding.tour.${tourId}.completed`));
+].forEach(tourId => PREF_WHITELIST.push([`browser.onboarding.tour.${tourId}.completed`, PREF_BOOL]));
 
 let waitingForBrowserReady = true;
 
 /**
  * Set pref. Why no `getPrefs` function is due to the priviledge level.
  * We cannot set prefs inside a framescript but can read.
  * For simplicity and effeciency, we still read prefs inside the framescript.
  *
  * @param {Array} prefs the array of prefs to set.
  *   The array element carrys info to set pref, should contain
  *   - {String} name the pref name, such as `browser.onboarding.hidden`
  *   - {*} value the value to set
  **/
 function setPrefs(prefs) {
   prefs.forEach(pref => {
-    if (PREF_WHITELIST.includes(pref.name)) {
-      Preferences.set(pref.name, pref.value);
+    let prefObj = PREF_WHITELIST.find(([name, ]) => name == pref.name);
+    if (!prefObj) {
+      return;
+    }
+
+    let [name, type] = prefObj;
+
+    switch (type) {
+      case PREF_BOOL:
+        Services.prefs.setBoolPref(name, pref.value);
+        break;
+
+      case PREF_INT:
+        Services.prefs.setIntPref(name, pref.value);
+        break;
+
+      case PREF_STRING:
+        Services.prefs.setStringPref(name, pref.value);
+        break;
+
+      default:
+        throw new TypeError(`Unexpected type (${type}) for preference ${name}.`)
     }
   });
 }
 
 /**
  * syncTourChecker listens to and maintains the login status inside, and can be
  * queried at any time once initialized.
  */
--- a/browser/extensions/onboarding/content/onboarding.js
+++ b/browser/extensions/onboarding/content/onboarding.js
@@ -2,18 +2,18 @@
  * License, v. 2.0. If a copy of the MPL was not distributed with this file,
  * You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 /* eslint-env mozilla/frame-script */
 
 "use strict";
 
 const {classes: Cc, interfaces: Ci, utils: Cu} = Components;
+Cu.import("resource://gre/modules/XPCOMUtils.jsm");
 Cu.import("resource://gre/modules/Services.jsm");
-Cu.import("resource://gre/modules/Preferences.jsm");
 
 const ONBOARDING_CSS_URL = "resource://onboarding/onboarding.css";
 const ABOUT_HOME_URL = "about:home";
 const ABOUT_NEWTAB_URL = "about:newtab";
 const BUNDLE_URI = "chrome://onboarding/locale/onboarding.properties";
 const UITOUR_JS_URI = "resource://onboarding/lib/UITour-lib.js";
 const TOUR_AGENT_JS_URI = "resource://onboarding/onboarding-tour-agent.js";
 const BRAND_SHORT_NAME = Services.strings
@@ -445,24 +445,24 @@ class Onboarding {
     });
     this._tours.forEach(tour => {
       let tourId = tour.id;
       this._prefsObserved.set(`browser.onboarding.tour.${tourId}.completed`, () => {
         this.markTourCompletionState(tourId);
       });
     });
     for (let [name, callback] of this._prefsObserved) {
-      Preferences.observe(name, callback);
+      Services.prefs.addObserver(name, callback);
     }
   }
 
   _clearPrefObserver() {
     if (this._prefsObserved) {
       for (let [name, callback] of this._prefsObserved) {
-        Preferences.ignore(name, callback);
+        Services.prefs.removeObserver(name, callback);
       }
       this._prefsObserved = null;
     }
   }
 
   handleEvent(evt) {
     if (evt.type === "resize") {
       this._window.cancelIdleCallback(this._resizeTimerId);
@@ -556,17 +556,17 @@ class Onboarding {
         li.classList.add("onboarding-active");
       } else {
         li.classList.remove("onboarding-active");
       }
     }
   }
 
   isTourCompleted(tourId) {
-    return Preferences.get(`browser.onboarding.tour.${tourId}.completed`, false);
+    return Services.prefs.getBoolPref(`browser.onboarding.tour.${tourId}.completed`, false);
   }
 
   setToursCompleted(tourIds) {
     let params = [];
     tourIds.forEach(id => {
       if (!this.isTourCompleted(id)) {
         params.push({
           name: `browser.onboarding.tour.${id}.completed`,
@@ -583,49 +583,49 @@ class Onboarding {
     // We are doing lazy load so there might be no items.
     if (this._tourItems && this._tourItems.length > 0 && this.isTourCompleted(tourId)) {
       let targetItem = this._tourItems.find(item => item.id == tourId);
       targetItem.classList.add("onboarding-complete");
     }
   }
 
   _muteNotificationOnFirstSession() {
-    if (Preferences.isSet("browser.onboarding.notification.tour-ids-queue")) {
+    if (Services.prefs.prefHasUserValue("browser.onboarding.notification.tour-ids-queue")) {
       // There is a queue. We had prompted before, this must not be the 1st session.
       return false;
     }
 
-    let muteDuration = Preferences.get("browser.onboarding.notification.mute-duration-on-first-session-ms");
+    let muteDuration = Services.prefs.getIntPref("browser.onboarding.notification.mute-duration-on-first-session-ms");
     if (muteDuration == 0) {
       // Don't mute when this is set to 0 on purpose.
       return false;
     }
 
     // Reuse the `last-time-of-changing-tour-sec` to save the time that
     // we try to prompt on the 1st session.
-    let lastTime = 1000 * Preferences.get("browser.onboarding.notification.last-time-of-changing-tour-sec", 0);
+    let lastTime = 1000 * Services.prefs.getIntPref("browser.onboarding.notification.last-time-of-changing-tour-sec", 0);
     if (lastTime <= 0) {
       sendMessageToChrome("set-prefs", [{
         name: "browser.onboarding.notification.last-time-of-changing-tour-sec",
         value: Math.floor(Date.now() / 1000)
       }]);
       return true;
     }
     return Date.now() - lastTime <= muteDuration;
   }
 
   _isTimeForNextTourNotification() {
-    let promptCount = Preferences.get("browser.onboarding.notification.prompt-count", 0);
-    let maxCount = Preferences.get("browser.onboarding.notification.max-prompt-count-per-tour");
+    let promptCount = Services.prefs.getIntPref("browser.onboarding.notification.prompt-count", 0);
+    let maxCount = Services.prefs.getIntPref("browser.onboarding.notification.max-prompt-count-per-tour");
     if (promptCount >= maxCount) {
       return true;
     }
 
-    let lastTime = 1000 * Preferences.get("browser.onboarding.notification.last-time-of-changing-tour-sec", 0);
-    let maxTime = Preferences.get("browser.onboarding.notification.max-life-time-per-tour-ms");
+    let lastTime = 1000 * Services.prefs.getIntPref("browser.onboarding.notification.last-time-of-changing-tour-sec", 0);
+    let maxTime = Services.prefs.getIntPref("browser.onboarding.notification.max-life-time-per-tour-ms");
     if (lastTime && Date.now() - lastTime >= maxTime) {
       return true;
     }
 
     return false;
   }
 
   _removeTourFromNotificationQueue(tourId) {
@@ -643,18 +643,18 @@ class Onboarding {
       name: "browser.onboarding.notification.prompt-count",
       value: 0
     });
     sendMessageToChrome("set-prefs", params);
   }
 
   _getNotificationQueue() {
     let queue = "";
-    if (Preferences.isSet("browser.onboarding.notification.tour-ids-queue")) {
-      queue = Preferences.get("browser.onboarding.notification.tour-ids-queue");
+    if (Services.prefs.prefHasUserValue("browser.onboarding.notification.tour-ids-queue")) {
+      queue = Services.prefs.getStringPref("browser.onboarding.notification.tour-ids-queue");
     } else {
       // For each tour, it only gets 2 chances to prompt with notification
       // (each chance includes 8 impressions or 5-days max life time)
       // if user never interact with it.
       // Assume there are tour #0 ~ #5. Here would form the queue as
       // "#0,#1,#2,#3,#4,#5,#0,#1,#2,#3,#4,#5".
       // Then we would loop through this queue and remove prompted tour from the queue
       // until the queue is empty.
@@ -664,17 +664,17 @@ class Onboarding {
         name: "browser.onboarding.notification.tour-ids-queue",
         value: queue
       }]);
     }
     return queue ? queue.split(",") : [];
   }
 
   showNotification() {
-    if (Preferences.get("browser.onboarding.notification.finished", false)) {
+    if (Services.prefs.getBoolPref("browser.onboarding.notification.finished", false)) {
       return;
     }
 
     if (this._muteNotificationOnFirstSession()) {
       return;
     }
 
     let queue = this._getNotificationQueue();
@@ -729,17 +729,17 @@ class Onboarding {
         name: PROMPT_COUNT_PREF,
         value: 1
       });
       params.push({
         name: "browser.onboarding.notification.tour-ids-queue",
         value: queue.join(",")
       });
     } else {
-      let promptCount = Preferences.get(PROMPT_COUNT_PREF, 0);
+      let promptCount = Services.prefs.getIntPref(PROMPT_COUNT_PREF, 0);
       params.push({
         name: PROMPT_COUNT_PREF,
         value: promptCount + 1
       });
     }
     sendMessageToChrome("set-prefs", params);
   }
 
--- a/browser/extensions/pdfjs/README.mozilla
+++ b/browser/extensions/pdfjs/README.mozilla
@@ -1,5 +1,5 @@
 This is the PDF.js project output, https://github.com/mozilla/pdf.js
 
-Current extension version is: 1.8.581
+Current extension version is: 1.8.593
 
-Taken from upstream commit: 343b4dc2
+Taken from upstream commit: f62d0a10
--- a/browser/extensions/pdfjs/content/build/pdf.js
+++ b/browser/extensions/pdfjs/content/build/pdf.js
@@ -100,17 +100,17 @@ return /******/ (function(modules) { // 
 
 Object.defineProperty(exports, "__esModule", {
   value: true
 });
 exports.unreachable = exports.warn = exports.utf8StringToString = exports.stringToUTF8String = exports.stringToPDFString = exports.stringToBytes = exports.string32 = exports.shadow = exports.setVerbosityLevel = exports.ReadableStream = exports.removeNullCharacters = exports.readUint32 = exports.readUint16 = exports.readInt8 = exports.log2 = exports.loadJpegStream = exports.isEvalSupported = exports.isLittleEndian = exports.createValidAbsoluteUrl = exports.isSameOrigin = exports.isNodeJS = exports.isSpace = exports.isString = exports.isNum = exports.isInt = exports.isEmptyObj = exports.isBool = exports.isArrayBuffer = exports.isArray = exports.info = exports.globalScope = exports.getVerbosityLevel = exports.getLookupTableFactory = exports.deprecated = exports.createObjectURL = exports.createPromiseCapability = exports.createBlob = exports.bytesToString = exports.assert = exports.arraysToBytes = exports.arrayByteLength = exports.FormatError = exports.XRefParseException = exports.Util = exports.UnknownErrorException = exports.UnexpectedResponseException = exports.TextRenderingMode = exports.StreamType = exports.StatTimer = exports.PasswordResponses = exports.PasswordException = exports.PageViewport = exports.NotImplementedException = exports.NativeImageDecoding = exports.MissingPDFException = exports.MissingDataException = exports.MessageHandler = exports.InvalidPDFException = exports.CMapCompressionType = exports.ImageKind = exports.FontType = exports.AnnotationType = exports.AnnotationFlag = exports.AnnotationFieldFlag = exports.AnnotationBorderStyleType = exports.UNSUPPORTED_FEATURES = exports.VERBOSITY_LEVELS = exports.OPS = exports.IDENTITY_MATRIX = exports.FONT_IDENTITY_MATRIX = undefined;
 
 __w_pdfjs_require__(15);
 
-var _streamsLib = __w_pdfjs_require__(9);
+var _streams_polyfill = __w_pdfjs_require__(16);
 
 var globalScope = typeof window !== 'undefined' && window.Math === Math ? window : typeof global !== 'undefined' && global.Math === Math ? global : typeof self !== 'undefined' && self.Math === Math ? self : undefined;
 var FONT_IDENTITY_MATRIX = [0.001, 0, 0, 0.001, 0, 0];
 const NativeImageDecoding = {
   NONE: 'none',
   DECODE: 'decode',
   DISPLAY: 'display'
 };
@@ -1126,17 +1126,17 @@ MessageHandler.prototype = {
       capability.reject(e);
     }
     return capability.promise;
   },
   sendWithStream(actionName, data, queueingStrategy, transfers) {
     let streamId = this.streamId++;
     let sourceName = this.sourceName;
     let targetName = this.targetName;
-    return new _streamsLib.ReadableStream({
+    return new _streams_polyfill.ReadableStream({
       start: controller => {
         let startCapability = createPromiseCapability();
         this.streamControllers[streamId] = {
           controller,
           startCall: startCapability,
           isClosed: false
         };
         this.postMessage({
@@ -1430,17 +1430,17 @@ exports.createValidAbsoluteUrl = createV
 exports.isLittleEndian = isLittleEndian;
 exports.isEvalSupported = isEvalSupported;
 exports.loadJpegStream = loadJpegStream;
 exports.log2 = log2;
 exports.readInt8 = readInt8;
 exports.readUint16 = readUint16;
 exports.readUint32 = readUint32;
 exports.removeNullCharacters = removeNullCharacters;
-exports.ReadableStream = _streamsLib.ReadableStream;
+exports.ReadableStream = _streams_polyfill.ReadableStream;
 exports.setVerbosityLevel = setVerbosityLevel;
 exports.shadow = shadow;
 exports.string32 = string32;
 exports.stringToBytes = stringToBytes;
 exports.stringToPDFString = stringToPDFString;
 exports.stringToUTF8String = stringToUTF8String;
 exports.utf8StringToString = utf8StringToString;
 exports.warn = warn;
@@ -2500,17 +2500,24 @@ function _fetchDocument(worker, source, 
   source.disableStream = (0, _dom_utils.getDefaultSetting)('disableStream');
   source.chunkedViewerLoading = !!pdfDataRangeTransport;
   if (pdfDataRangeTransport) {
     source.length = pdfDataRangeTransport.length;
     source.initialData = pdfDataRangeTransport.initialData;
   }
   return worker.messageHandler.sendWithPromise('GetDocRequest', {
     docId,
-    source,
+    source: {
+      data: source.data,
+      url: source.url,
+      password: source.password,
+      disableAutoFetch: source.disableAutoFetch,
+      rangeChunkSize: source.rangeChunkSize,
+      length: source.length
+    },
     maxImageSize: (0, _dom_utils.getDefaultSetting)('maxImageSize'),
     disableFontFace: (0, _dom_utils.getDefaultSetting)('disableFontFace'),
     disableCreateObjectURL: (0, _dom_utils.getDefaultSetting)('disableCreateObjectURL'),
     postMessageTransfers: (0, _dom_utils.getDefaultSetting)('postMessageTransfers') && !isPostMessageTransfersDisabled,
     docBaseUrl: source.docBaseUrl,
     nativeImageDecoderSupport: source.nativeImageDecoderSupport,
     ignoreErrors: source.ignoreErrors
   }).then(function (workerId) {
@@ -3801,18 +3808,18 @@ var _UnsupportedManager = function Unsup
       for (var i = 0, ii = listeners.length; i < ii; i++) {
         listeners[i](featureId);
       }
     }
   };
 }();
 var version, build;
 {
-  exports.version = version = '1.8.581';
-  exports.build = build = '343b4dc2';
+  exports.version = version = '1.8.593';
+  exports.build = build = 'f62d0a10';
 }
 exports.getDocument = getDocument;
 exports.LoopbackPort = LoopbackPort;
 exports.PDFDataRangeTransport = PDFDataRangeTransport;
 exports.PDFWorker = PDFWorker;
 exports.PDFDocumentProxy = PDFDocumentProxy;
 exports.PDFPageProxy = PDFPageProxy;
 exports.setPDFNetworkStreamClass = setPDFNetworkStreamClass;
@@ -4852,18 +4859,18 @@ var _text_layer = __w_pdfjs_require__(5)
 var _svg = __w_pdfjs_require__(4);
 
 var isWorker = typeof window === 'undefined';
 if (!_util.globalScope.PDFJS) {
   _util.globalScope.PDFJS = {};
 }
 var PDFJS = _util.globalScope.PDFJS;
 {
-  PDFJS.version = '1.8.581';
-  PDFJS.build = '343b4dc2';
+  PDFJS.version = '1.8.593';
+  PDFJS.build = 'f62d0a10';
 }
 PDFJS.pdfBug = false;
 if (PDFJS.verbosity !== undefined) {
   (0, _util.setVerbosityLevel)(PDFJS.verbosity);
 }
 delete PDFJS.verbosity;
 Object.defineProperty(PDFJS, 'verbosity', {
   get() {
@@ -10419,18 +10426,18 @@ exports.PDFDataTransportStream = PDFData
 
 /***/ }),
 /* 14 */
 /***/ (function(module, exports, __w_pdfjs_require__) {
 
 "use strict";
 
 
-var pdfjsVersion = '1.8.581';
-var pdfjsBuild = '343b4dc2';
+var pdfjsVersion = '1.8.593';
+var pdfjsBuild = 'f62d0a10';
 var pdfjsSharedUtil = __w_pdfjs_require__(0);
 var pdfjsDisplayGlobal = __w_pdfjs_require__(8);
 var pdfjsDisplayAPI = __w_pdfjs_require__(3);
 var pdfjsDisplayTextLayer = __w_pdfjs_require__(5);
 var pdfjsDisplayAnnotationLayer = __w_pdfjs_require__(2);
 var pdfjsDisplayDOMUtils = __w_pdfjs_require__(1);
 var pdfjsDisplaySVG = __w_pdfjs_require__(4);
 ;
@@ -10468,11 +10475,24 @@ exports.StatTimer = pdfjsSharedUtil.Stat
 /* 15 */
 /***/ (function(module, exports, __w_pdfjs_require__) {
 
 "use strict";
 
 
 ;
 
+/***/ }),
+/* 16 */
+/***/ (function(module, exports, __w_pdfjs_require__) {
+
+"use strict";
+
+
+if (typeof ReadableStream !== 'undefined') {
+  exports.ReadableStream = ReadableStream;
+} else {
+  exports.ReadableStream = __w_pdfjs_require__(9).ReadableStream;
+}
+
 /***/ })
 /******/ ]);
 });
\ No newline at end of file
--- a/browser/extensions/pdfjs/content/build/pdf.worker.js
+++ b/browser/extensions/pdfjs/content/build/pdf.worker.js
@@ -100,17 +100,17 @@ return /******/ (function(modules) { // 
 
 Object.defineProperty(exports, "__esModule", {
   value: true
 });
 exports.unreachable = exports.warn = exports.utf8StringToString = exports.stringToUTF8String = exports.stringToPDFString = exports.stringToBytes = exports.string32 = exports.shadow = exports.setVerbosityLevel = exports.ReadableStream = exports.removeNullCharacters = exports.readUint32 = exports.readUint16 = exports.readInt8 = exports.log2 = exports.loadJpegStream = exports.isEvalSupported = exports.isLittleEndian = exports.createValidAbsoluteUrl = exports.isSameOrigin = exports.isNodeJS = exports.isSpace = exports.isString = exports.isNum = exports.isInt = exports.isEmptyObj = exports.isBool = exports.isArrayBuffer = exports.isArray = exports.info = exports.globalScope = exports.getVerbosityLevel = exports.getLookupTableFactory = exports.deprecated = exports.createObjectURL = exports.createPromiseCapability = exports.createBlob = exports.bytesToString = exports.assert = exports.arraysToBytes = exports.arrayByteLength = exports.FormatError = exports.XRefParseException = exports.Util = exports.UnknownErrorException = exports.UnexpectedResponseException = exports.TextRenderingMode = exports.StreamType = exports.StatTimer = exports.PasswordResponses = exports.PasswordException = exports.PageViewport = exports.NotImplementedException = exports.NativeImageDecoding = exports.MissingPDFException = exports.MissingDataException = exports.MessageHandler = exports.InvalidPDFException = exports.CMapCompressionType = exports.ImageKind = exports.FontType = exports.AnnotationType = exports.AnnotationFlag = exports.AnnotationFieldFlag = exports.AnnotationBorderStyleType = exports.UNSUPPORTED_FEATURES = exports.VERBOSITY_LEVELS = exports.OPS = exports.IDENTITY_MATRIX = exports.FONT_IDENTITY_MATRIX = undefined;
 
 __w_pdfjs_require__(36);
 
-var _streamsLib = __w_pdfjs_require__(18);
+var _streams_polyfill = __w_pdfjs_require__(37);
 
 var globalScope = typeof window !== 'undefined' && window.Math === Math ? window : typeof global !== 'undefined' && global.Math === Math ? global : typeof self !== 'undefined' && self.Math === Math ? self : undefined;
 var FONT_IDENTITY_MATRIX = [0.001, 0, 0, 0.001, 0, 0];
 const NativeImageDecoding = {
   NONE: 'none',
   DECODE: 'decode',
   DISPLAY: 'display'
 };
@@ -1126,17 +1126,17 @@ MessageHandler.prototype = {
       capability.reject(e);
     }
     return capability.promise;
   },
   sendWithStream(actionName, data, queueingStrategy, transfers) {
     let streamId = this.streamId++;
     let sourceName = this.sourceName;
     let targetName = this.targetName;
-    return new _streamsLib.ReadableStream({
+    return new _streams_polyfill.ReadableStream({
       start: controller => {
         let startCapability = createPromiseCapability();
         this.streamControllers[streamId] = {
           controller,
           startCall: startCapability,
           isClosed: false
         };
         this.postMessage({
@@ -1430,17 +1430,17 @@ exports.createValidAbsoluteUrl = createV
 exports.isLittleEndian = isLittleEndian;
 exports.isEvalSupported = isEvalSupported;
 exports.loadJpegStream = loadJpegStream;
 exports.log2 = log2;
 exports.readInt8 = readInt8;
 exports.readUint16 = readUint16;
 exports.readUint32 = readUint32;
 exports.removeNullCharacters = removeNullCharacters;
-exports.ReadableStream = _streamsLib.ReadableStream;
+exports.ReadableStream = _streams_polyfill.ReadableStream;
 exports.setVerbosityLevel = setVerbosityLevel;
 exports.shadow = shadow;
 exports.string32 = string32;
 exports.stringToBytes = stringToBytes;
 exports.stringToPDFString = stringToPDFString;
 exports.stringToUTF8String = stringToUTF8String;
 exports.utf8StringToString = utf8StringToString;
 exports.warn = warn;
@@ -4171,21 +4171,17 @@ var CalRGBCS = function CalRGBCSClosure(
     var sR = sRGBTransferFunction(SRGB[0]);
     var sG = sRGBTransferFunction(SRGB[1]);
     var sB = sRGBTransferFunction(SRGB[2]);
     dest[destOffset] = Math.round(sR * 255);
     dest[destOffset + 1] = Math.round(sG * 255);
     dest[destOffset + 2] = Math.round(sB * 255);
   }
   CalRGBCS.prototype = {
-    getRgb: function CalRGBCS_getRgb(src, srcOffset) {
-      var rgb = new Uint8Array(3);
-      this.getRgbItem(src, srcOffset, rgb, 0);
-      return rgb;
-    },
+    getRgb: ColorSpace.prototype.getRgb,
     getRgbItem: function CalRGBCS_getRgbItem(src, srcOffset, dest, destOffset) {
       convertToRgb(this, src, srcOffset, dest, destOffset, 1);
     },
     getRgbBuffer: function CalRGBCS_getRgbBuffer(src, srcOffset, count, dest, destOffset, bits, alpha01) {
       var scale = 1 / ((1 << bits) - 1);
       for (var i = 0; i < count; ++i) {
         convertToRgb(this, src, srcOffset, dest, destOffset, scale);
         srcOffset += 3;
@@ -39833,25 +39829,38 @@ exports.Type1Parser = Type1Parser;
 
 /***/ }),
 /* 35 */
 /***/ (function(module, exports, __w_pdfjs_require__) {
 
 "use strict";
 
 
-var pdfjsVersion = '1.8.581';
-var pdfjsBuild = '343b4dc2';
+var pdfjsVersion = '1.8.593';
+var pdfjsBuild = 'f62d0a10';
 var pdfjsCoreWorker = __w_pdfjs_require__(17);
 exports.WorkerMessageHandler = pdfjsCoreWorker.WorkerMessageHandler;
 
 /***/ }),
 /* 36 */
 /***/ (function(module, exports, __w_pdfjs_require__) {
 
 "use strict";
 
 
 ;
 
+/***/ }),
+/* 37 */
+/***/ (function(module, exports, __w_pdfjs_require__) {
+
+"use strict";
+
+
+if (typeof ReadableStream !== 'undefined') {
+  exports.ReadableStream = ReadableStream;
+} else {
+  exports.ReadableStream = __w_pdfjs_require__(18).ReadableStream;
+}
+
 /***/ })
 /******/ ]);
 });
\ No newline at end of file
--- a/browser/extensions/pdfjs/content/web/viewer.js
+++ b/browser/extensions/pdfjs/content/web/viewer.js
@@ -1326,16 +1326,19 @@ let PDFViewerApplication = {
           moreInfoText.push(this.l10n.get('error_line', { line: moreInfo.lineNumber }, 'Line: {{line}}'));
         }
       }
     }
     console.error(message + '\n' + moreInfoText);
     this.fallback();
   },
   progress(level) {
+    if (this.downloadComplete) {
+      return;
+    }
     let percent = Math.round(level * 100);
     if (percent > this.loadingBar.percent || isNaN(percent)) {
       this.loadingBar.percent = percent;
       if (_pdfjsLib.PDFJS.disableAutoFetch && percent) {
         if (this.disableAutoFetchLoadingBarTimeout) {
           clearTimeout(this.disableAutoFetchLoadingBarTimeout);
           this.disableAutoFetchLoadingBarTimeout = null;
         }
--- a/browser/extensions/shield-recipe-client/lib/PreferenceExperiments.jsm
+++ b/browser/extensions/shield-recipe-client/lib/PreferenceExperiments.jsm
@@ -53,37 +53,37 @@
 const {utils: Cu} = Components;
 Cu.import("resource://gre/modules/XPCOMUtils.jsm");
 
 XPCOMUtils.defineLazyModuleGetter(this, "Services", "resource://gre/modules/Services.jsm");
 XPCOMUtils.defineLazyModuleGetter(this, "CleanupManager", "resource://shield-recipe-client/lib/CleanupManager.jsm");
 XPCOMUtils.defineLazyModuleGetter(this, "JSONFile", "resource://gre/modules/JSONFile.jsm");
 XPCOMUtils.defineLazyModuleGetter(this, "OS", "resource://gre/modules/osfile.jsm");
 XPCOMUtils.defineLazyModuleGetter(this, "LogManager", "resource://shield-recipe-client/lib/LogManager.jsm");
-XPCOMUtils.defineLazyModuleGetter(this, "Preferences", "resource://gre/modules/Preferences.jsm");
 XPCOMUtils.defineLazyModuleGetter(this, "TelemetryEnvironment", "resource://gre/modules/TelemetryEnvironment.jsm");
 
 this.EXPORTED_SYMBOLS = ["PreferenceExperiments"];
 
 const EXPERIMENT_FILE = "shield-preference-experiments.json";
 
 const PREFERENCE_TYPE_MAP = {
   boolean: Services.prefs.PREF_BOOL,
   string: Services.prefs.PREF_STRING,
   integer: Services.prefs.PREF_INT,
 };
 
-const DefaultPreferences = new Preferences({defaultBranch: true});
+const UserPreferences = Services.prefs;
+const DefaultPreferences = Services.prefs.getDefaultBranch("");
 
 /**
  * Enum storing Preference modules for each type of preference branch.
  * @enum {Object}
  */
 const PreferenceBranchType = {
-  user: Preferences,
+  user: UserPreferences,
   default: DefaultPreferences,
 };
 
 /**
  * Asynchronously load the JSON file that stores experiment status in the profile.
  */
 let storePromise;
 function ensureStorage() {
@@ -96,41 +96,76 @@ function ensureStorage() {
 }
 
 const log = LogManager.getLogger("preference-experiments");
 
 // List of active preference observers. Cleaned up on shutdown.
 let experimentObservers = new Map();
 CleanupManager.addCleanupHandler(() => PreferenceExperiments.stopAllObservers());
 
+function getPref(prefBranch, prefName, prefType, defaultVal) {
+  switch (prefType) {
+    case "boolean":
+      return prefBranch.getBoolPref(prefName, defaultVal);
+
+    case "string":
+      return prefBranch.getStringPref(prefName, defaultVal);
+
+    case "integer":
+      return prefBranch.getIntPref(prefName, defaultVal);
+
+    default:
+      throw new TypeError(`Unexpected preference type (${prefType}) for ${prefName}.`);
+  }
+}
+
+function setPref(prefBranch, prefName, prefType, prefValue) {
+  switch (prefType) {
+    case "boolean":
+      prefBranch.setBoolPref(prefName, prefValue);
+      break;
+
+    case "string":
+      prefBranch.setStringPref(prefName, prefValue);
+      break;
+
+    case "integer":
+      prefBranch.setIntPref(prefName, prefValue);
+      break;
+
+    default:
+      throw new TypeError(`Unexpected preference type (${prefType}) for ${prefName}.`);
+  }
+}
+
 this.PreferenceExperiments = {
   /**
    * Set the default preference value for active experiments that use the
    * default preference branch.
    */
   async init() {
     for (const experiment of await this.getAllActive()) {
       // Set experiment default preferences, since they don't persist between restarts
       if (experiment.preferenceBranchType === "default") {
-        DefaultPreferences.set(experiment.preferenceName, experiment.preferenceValue);
+        setPref(DefaultPreferences, experiment.preferenceName, experiment.preferenceType, experiment.preferenceValue);
       }
 
       // Check that the current value of the preference is still what we set it to
-      if (Preferences.get(experiment.preferenceName, undefined) !== experiment.preferenceValue) {
+      if (getPref(UserPreferences, experiment.preferenceName, experiment.preferenceType) !== experiment.preferenceValue) {
         // if not, stop the experiment, and skip the remaining steps
         log.info(`Stopping experiment "${experiment.name}" because its value changed`);
         await this.stop(experiment.name, false);
         continue;
       }
 
       // Notify Telemetry of experiments we're running, since they don't persist between restarts
       TelemetryEnvironment.setExperimentActive(experiment.name, experiment.branch);
 
       // Watch for changes to the experiment's preference
-      this.startObserver(experiment.name, experiment.preferenceName, experiment.preferenceValue);
+      this.startObserver(experiment.name, experiment.preferenceName, experiment.preferenceType, experiment.preferenceValue);
     }
   },
 
   /**
    * Test wrapper that temporarily replaces the stored experiment data with fake
    * data for testing.
    */
   withMockExperiments(testFunction) {
@@ -202,17 +237,17 @@ this.PreferenceExperiments = {
     const experiment = {
       name,
       branch,
       expired: false,
       lastSeen: new Date().toJSON(),
       preferenceName,
       preferenceValue,
       preferenceType,
-      previousPreferenceValue: preferences.get(preferenceName, undefined),
+      previousPreferenceValue: getPref(preferences, preferenceName, preferenceType),
       preferenceBranchType,
     };
 
     const prevPrefType = Services.prefs.getPrefType(preferenceName);
     const givenPrefType = PREFERENCE_TYPE_MAP[preferenceType];
 
     if (!preferenceType || !givenPrefType) {
       throw new Error(`Invalid preferenceType provided (given "${preferenceType}")`);
@@ -220,53 +255,54 @@ this.PreferenceExperiments = {
 
     if (prevPrefType !== Services.prefs.PREF_INVALID && prevPrefType !== givenPrefType) {
       throw new Error(
         `Previous preference value is of type "${prevPrefType}", but was given ` +
         `"${givenPrefType}" (${preferenceType})`
       );
     }
 
-    preferences.set(preferenceName, preferenceValue);
-    PreferenceExperiments.startObserver(name, preferenceName, preferenceValue);
+    setPref(preferences, preferenceName, preferenceType, preferenceValue);
+    PreferenceExperiments.startObserver(name, preferenceName, preferenceType, preferenceValue);
     store.data[name] = experiment;
     store.saveSoon();
 
     TelemetryEnvironment.setExperimentActive(name, branch);
   },
 
   /**
    * Register a preference observer that stops an experiment when the user
    * modifies the preference.
    * @param {string} experimentName
    * @param {string} preferenceName
    * @param {string|integer|boolean} preferenceValue
    * @throws {Error}
    *   If an observer for the named experiment is already active.
    */
-  startObserver(experimentName, preferenceName, preferenceValue) {
+  startObserver(experimentName, preferenceName, preferenceType, preferenceValue) {
     log.debug(`PreferenceExperiments.startObserver(${experimentName})`);
 
     if (experimentObservers.has(experimentName)) {
       throw new Error(
         `An observer for the preference experiment ${experimentName} is already active.`
       );
     }
 
     const observerInfo = {
       preferenceName,
-      observer(newValue) {
+      observer() {
+        let newValue = getPref(UserPreferences, preferenceName, preferenceType);
         if (newValue !== preferenceValue) {
           PreferenceExperiments.stop(experimentName, false)
                                .catch(Cu.reportError);
         }
       },
     };
     experimentObservers.set(experimentName, observerInfo);
-    Preferences.observe(preferenceName, observerInfo.observer);
+    Services.prefs.addObserver(preferenceName, observerInfo.observer);
   },
 
   /**
    * Check if a preference observer is active for an experiment.
    * @param {string} experimentName
    * @return {Boolean}
    */
   hasObserver(experimentName) {
@@ -283,27 +319,27 @@ this.PreferenceExperiments = {
   stopObserver(experimentName) {
     log.debug(`PreferenceExperiments.stopObserver(${experimentName})`);
 
     if (!experimentObservers.has(experimentName)) {
       throw new Error(`No observer for the preference experiment ${experimentName} found.`);
     }
 
     const {preferenceName, observer} = experimentObservers.get(experimentName);
-    Preferences.ignore(preferenceName, observer);
+    Services.prefs.removeObserver(preferenceName, observer);
     experimentObservers.delete(experimentName);
   },
 
   /**
    * Disable all currently-active preference observers for experiments.
    */
   stopAllObservers() {
     log.debug("PreferenceExperiments.stopAllObservers()");
     for (const {preferenceName, observer} of experimentObservers.values()) {
-      Preferences.ignore(preferenceName, observer);
+      Services.prefs.removeObserver(preferenceName, observer);
     }
     experimentObservers.clear();
   },
 
   /**
    * Update the timestamp storing when Normandy last sent a recipe for the named
    * experiment.
    * @param {string} experimentName
@@ -347,25 +383,25 @@ this.PreferenceExperiments = {
       );
     }
 
     if (PreferenceExperiments.hasObserver(experimentName)) {
       PreferenceExperiments.stopObserver(experimentName);
     }
 
     if (resetValue) {
-      const {preferenceName, previousPreferenceValue, preferenceBranchType} = experiment;
+      const {preferenceName, preferenceType, previousPreferenceValue, preferenceBranchType} = experiment;
       const preferences = PreferenceBranchType[preferenceBranchType];
       if (previousPreferenceValue !== undefined) {
-        preferences.set(preferenceName, previousPreferenceValue);
+        setPref(preferences, preferenceName, preferenceType, previousPreferenceValue);
       } else {
         // This does nothing if we're on the default branch, which is fine. The
         // preference will be reset on next restart, and most preferences should
         // have had a default value set before the experiment anyway.
-        preferences.reset(preferenceName);
+        preferences.clearUserPref(preferenceName);
       }
     }
 
     experiment.expired = true;
     store.saveSoon();
 
     TelemetryEnvironment.setExperimentInactive(experimentName, experiment.branch);
   },
--- a/browser/extensions/shield-recipe-client/lib/ShieldRecipeClient.jsm
+++ b/browser/extensions/shield-recipe-client/lib/ShieldRecipeClient.jsm
@@ -1,50 +1,51 @@
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 "use strict";
 
-const {utils: Cu} = Components;
+const {utils: Cu, interfaces: Ci} = Components;
 Cu.import("resource://gre/modules/Services.jsm");
-Cu.import("resource://gre/modules/Preferences.jsm");
 Cu.import("resource://gre/modules/Log.jsm");
 Cu.import("resource://gre/modules/XPCOMUtils.jsm");
 
 XPCOMUtils.defineLazyModuleGetter(this, "LogManager",
   "resource://shield-recipe-client/lib/LogManager.jsm");
 XPCOMUtils.defineLazyModuleGetter(this, "RecipeRunner",
   "resource://shield-recipe-client/lib/RecipeRunner.jsm");
 XPCOMUtils.defineLazyModuleGetter(this, "CleanupManager",
   "resource://shield-recipe-client/lib/CleanupManager.jsm");
 XPCOMUtils.defineLazyModuleGetter(this, "PreferenceExperiments",
   "resource://shield-recipe-client/lib/PreferenceExperiments.jsm");
 
 this.EXPORTED_SYMBOLS = ["ShieldRecipeClient"];
 
+const {PREF_STRING, PREF_BOOL, PREF_INT} = Ci.nsIPrefBranch;
+
 const REASONS = {
   APP_STARTUP: 1,      // The application is starting up.
   APP_SHUTDOWN: 2,     // The application is shutting down.
   ADDON_ENABLE: 3,     // The add-on is being enabled.
   ADDON_DISABLE: 4,    // The add-on is being disabled. (Also sent during uninstallation)
   ADDON_INSTALL: 5,    // The add-on is being installed.
   ADDON_UNINSTALL: 6,  // The add-on is being uninstalled.
   ADDON_UPGRADE: 7,    // The add-on is being upgraded.
   ADDON_DOWNGRADE: 8,  // The add-on is being downgraded.
 };
 const PREF_BRANCH = "extensions.shield-recipe-client.";
 const DEFAULT_PREFS = {
-  api_url: "https://normandy.cdn.mozilla.net/api/v1",
-  dev_mode: false,
-  enabled: true,
-  startup_delay_seconds: 300,
-  "logging.level": Log.Level.Warn,
-  user_id: "",
-  run_interval_seconds: 86400, // 24 hours
-  first_run: true,
+  api_url: ["https://normandy.cdn.mozilla.net/api/v1", PREF_STRING],
+  dev_mode: [false, PREF_BOOL],
+  enabled: [true, PREF_BOOL],
+  startup_delay_seconds: [300, PREF_INT],
+  "logging.level": [Log.Level.Warn, PREF_INT],
+  user_id: ["", PREF_STRING],
+  run_interval_seconds: [86400, PREF_INT], // 24 hours
+  first_run: [true, PREF_BOOL],
 };
 const PREF_DEV_MODE = "extensions.shield-recipe-client.dev_mode";
 const PREF_LOGGING_LEVEL = PREF_BRANCH + "logging.level";
 
 let log = null;
 
 /**
  * Handles startup and shutdown of the entire add-on. Bootsrap.js defers to this
@@ -52,19 +53,19 @@ let log = null;
  * (bootstrap.js is difficult to import in tests).
  */
 this.ShieldRecipeClient = {
   async startup() {
     ShieldRecipeClient.setDefaultPrefs();
 
     // Setup logging and listen for changes to logging prefs
     LogManager.configure(Services.prefs.getIntPref(PREF_LOGGING_LEVEL));
-    Preferences.observe(PREF_LOGGING_LEVEL, LogManager.configure);
+    Services.prefs.addObserver(PREF_LOGGING_LEVEL, LogManager.configure);
     CleanupManager.addCleanupHandler(
-      () => Preferences.ignore(PREF_LOGGING_LEVEL, LogManager.configure),
+      () => Services.prefs.removeObserver(PREF_LOGGING_LEVEL, LogManager.configure),
     );
     log = LogManager.getLogger("bootstrap");
 
     // Initialize experiments first to avoid a race between initializing prefs
     // and recipes rolling back pref changes when experiments end.
     try {
       await PreferenceExperiments.init();
     } catch (err) {
@@ -74,17 +75,32 @@ this.ShieldRecipeClient = {
     await RecipeRunner.init();
   },
 
   shutdown(reason) {
     CleanupManager.cleanup();
   },
 
   setDefaultPrefs() {
-    for (const [key, val] of Object.entries(DEFAULT_PREFS)) {
+    for (const [key, [val, type]] of Object.entries(DEFAULT_PREFS)) {
       const fullKey = PREF_BRANCH + key;
       // If someone beat us to setting a default, don't overwrite it.
-      if (!Preferences.isSet(fullKey)) {
-        Preferences.set(fullKey, val);
+      if (!Services.prefs.prefHasUserValue(fullKey)) {
+        switch (type) {
+          case PREF_BOOL:
+            Services.prefs.setBoolPref(fullKey, val);
+            break;
+
+          case PREF_INT:
+            Services.prefs.setIntPref(fullKey, val);
+            break;
+
+          case PREF_STRING:
+            Services.prefs.setStringPref(fullKey, val);
+            break;
+
+          default:
+            throw new TypeError(`Unexpected type (${type}) for preference ${fullKey}.`)
+        }
       }
     }
   },
 };
--- a/browser/extensions/shield-recipe-client/test/browser/browser_PreferenceExperiments.js
+++ b/browser/extensions/shield-recipe-client/test/browser/browser_PreferenceExperiments.js
@@ -92,17 +92,17 @@ add_task(withMockExperiments(withMockPre
     branch: "branch",
     preferenceName: "fake.preference",
     preferenceValue: "newvalue",
     preferenceBranchType: "default",
     preferenceType: "string",
   });
   ok("test" in experiments, "start saved the experiment");
   ok(
-    startObserver.calledWith("test", "fake.preference", "newvalue"),
+    startObserver.calledWith("test", "fake.preference", "string", "newvalue"),
     "start registered an observer",
   );
 
   const expectedExperiment = {
     name: "test",
     branch: "branch",
     expired: false,
     preferenceName: "fake.preference",
@@ -139,17 +139,17 @@ add_task(withMockExperiments(withMockPre
     name: "test",
     branch: "branch",
     preferenceName: "fake.preference",
     preferenceValue: "newvalue",
     preferenceType: "string",
     preferenceBranchType: "user",
   });
   ok(
-    startObserver.calledWith("test", "fake.preference", "newvalue"),
+    startObserver.calledWith("test", "fake.preference", "string", "newvalue"),
     "start registered an observer",
   );
 
   const expectedExperiment = {
     name: "test",
     branch: "branch",
     expired: false,
     preferenceName: "fake.preference",
@@ -189,47 +189,55 @@ add_task(withMockPreferences(async funct
     "start threw error for incompatible preference type"
   );
 }));
 
 
 // startObserver should throw if an observer for the experiment is already
 // active.
 add_task(withMockExperiments(async function() {
-  PreferenceExperiments.startObserver("test", "fake.preference", "newvalue");
+  PreferenceExperiments.startObserver("test", "fake.preference", "string", "newvalue");
   Assert.throws(
-    () => PreferenceExperiments.startObserver("test", "another.fake", "othervalue"),
+    () => PreferenceExperiments.startObserver("test", "another.fake", "string", "othervalue"),
     "startObserver threw due to a conflicting active observer",
   );
   PreferenceExperiments.stopAllObservers();
 }));
 
 // startObserver should register an observer that calls stop when a preference
 // changes from its experimental value.
 add_task(withMockExperiments(withMockPreferences(async function(mockExperiments, mockPreferences) {
-  const stop = sinon.stub(PreferenceExperiments, "stop");
-  mockPreferences.set("fake.preference", "startvalue");
+  let tests = [
+    ["string", "startvalue", "experimentvalue", "newvalue"],
+    ["boolean", false, true, false],
+    ["integer", 1, 2, 42],
+  ];
 
-  // NOTE: startObserver does not modify the pref
-  PreferenceExperiments.startObserver("test", "fake.preference", "experimentvalue");
+  for (let [type, startvalue, experimentvalue, newvalue] of tests) {
+    const stop = sinon.stub(PreferenceExperiments, "stop");
+    mockPreferences.set("fake.preference" + type, startvalue);
 
-  // Setting it to the experimental value should not trigger the call.
-  Preferences.set("fake.preference", "experimentvalue");
-  ok(!stop.called, "Changing to the experimental pref value did not trigger the observer");
+    // NOTE: startObserver does not modify the pref
+    PreferenceExperiments.startObserver("test" + type, "fake.preference" + type, type, experimentvalue);
+
+    // Setting it to the experimental value should not trigger the call.
+    Preferences.set("fake.preference" + type, experimentvalue);
+    ok(!stop.called, "Changing to the experimental pref value did not trigger the observer");
 
-  // Setting it to something different should trigger the call.
-  Preferences.set("fake.preference", "newvalue");
-  ok(stop.called, "Changing to a different value triggered the observer");
+    // Setting it to something different should trigger the call.
+    Preferences.set("fake.preference" + type, newvalue);
+    ok(stop.called, "Changing to a different value triggered the observer");
 
-  PreferenceExperiments.stopAllObservers();
-  stop.restore();
+    PreferenceExperiments.stopAllObservers();
+    stop.restore();
+  }
 })));
 
 add_task(withMockExperiments(async function testHasObserver() {
-  PreferenceExperiments.startObserver("test", "fake.preference", "experimentValue");
+  PreferenceExperiments.startObserver("test", "fake.preference", "string", "experimentValue");
 
   ok(await PreferenceExperiments.hasObserver("test"), "hasObserver detects active observers");
   ok(
     !(await PreferenceExperiments.hasObserver("missing")),
     "hasObserver doesn't detect inactive observers",
   );
 
   PreferenceExperiments.stopAllObservers();
@@ -243,57 +251,57 @@ add_task(withMockExperiments(async funct
   );
 }));
 
 // stopObserver should cancel an active observer.
 add_task(withMockExperiments(withMockPreferences(async function(mockExperiments, mockPreferences) {
   const stop = sinon.stub(PreferenceExperiments, "stop");
   mockPreferences.set("fake.preference", "startvalue");
 
-  PreferenceExperiments.startObserver("test", "fake.preference", "experimentvalue");
+  PreferenceExperiments.startObserver("test", "fake.preference", "string", "experimentvalue");
   PreferenceExperiments.stopObserver("test");
 
   // Setting the preference now that the observer is stopped should not call
   // stop.
   Preferences.set("fake.preference", "newvalue");
   ok(!stop.called, "stopObserver successfully removed the observer");
 
   // Now that the observer is stopped, start should be able to start a new one
   // without throwing.
   try {
-    PreferenceExperiments.startObserver("test", "fake.preference", "experimentvalue");
+    PreferenceExperiments.startObserver("test", "fake.preference", "string", "experimentvalue");
   } catch (err) {
     ok(false, "startObserver did not throw an error for an observer that was already stopped");
   }
 
   PreferenceExperiments.stopAllObservers();
   stop.restore();
 })));
 
 // stopAllObservers
 add_task(withMockExperiments(withMockPreferences(async function(mockExperiments, mockPreferences) {
   const stop = sinon.stub(PreferenceExperiments, "stop");
   mockPreferences.set("fake.preference", "startvalue");
   mockPreferences.set("other.fake.preference", "startvalue");
 
-  PreferenceExperiments.startObserver("test", "fake.preference", "experimentvalue");
-  PreferenceExperiments.startObserver("test2", "other.fake.preference", "experimentvalue");
+  PreferenceExperiments.startObserver("test", "fake.preference", "string", "experimentvalue");
+  PreferenceExperiments.startObserver("test2", "other.fake.preference", "string", "experimentvalue");
   PreferenceExperiments.stopAllObservers();
 
   // Setting the preference now that the observers are stopped should not call
   // stop.
   Preferences.set("fake.preference", "newvalue");
   Preferences.set("other.fake.preference", "newvalue");
   ok(!stop.called, "stopAllObservers successfully removed all observers");
 
   // Now that the observers are stopped, start should be able to start new
   // observers without throwing.
   try {
-    PreferenceExperiments.startObserver("test", "fake.preference", "experimentvalue");
-    PreferenceExperiments.startObserver("test2", "other.fake.preference", "experimentvalue");
+    PreferenceExperiments.startObserver("test", "fake.preference", "string", "experimentvalue");
+    PreferenceExperiments.startObserver("test2", "other.fake.preference", "string", "experimentvalue");
   } catch (err) {
     ok(false, "startObserver did not throw an error for an observer that was already stopped");
   }
 
   PreferenceExperiments.stopAllObservers();
   stop.restore();
 })));
 
@@ -344,17 +352,17 @@ add_task(withMockExperiments(withMockPre
     name: "test",
     expired: false,
     preferenceName: "fake.preference",
     preferenceValue: "experimentvalue",
     preferenceType: "string",
     previousPreferenceValue: "oldvalue",
     preferenceBranchType: "default",
   });
-  PreferenceExperiments.startObserver("test", "fake.preference", "experimentvalue");
+  PreferenceExperiments.startObserver("test", "fake.preference", "string", "experimentvalue");
 
   await PreferenceExperiments.stop("test");
   ok(stopObserver.calledWith("test"), "stop removed an observer");
   is(experiments["test"].expired, true, "stop marked the experiment as expired");
   is(
     DefaultPreferences.get("fake.preference"),
     "oldvalue",
     "stop reverted the preference to its previous value",
@@ -372,17 +380,17 @@ add_task(withMockExperiments(withMockPre
     name: "test",
     expired: false,
     preferenceName: "fake.preference",
     preferenceValue: "experimentvalue",
     preferenceType: "string",
     previousPreferenceValue: "oldvalue",
     preferenceBranchType: "user",
   });
-  PreferenceExperiments.startObserver("test", "fake.preference", "experimentvalue");
+  PreferenceExperiments.startObserver("test", "fake.preference", "string", "experimentvalue");
 
   await PreferenceExperiments.stop("test");
   ok(stopObserver.calledWith("test"), "stop removed an observer");
   is(experiments["test"].expired, true, "stop marked the experiment as expired");
   is(
     Preferences.get("fake.preference"),
     "oldvalue",
     "stop reverted the preference to its previous value",
@@ -649,14 +657,14 @@ add_task(withMockExperiments(withMockPre
   experiments["test"] = experimentFactory({
     name: "test",
     preferenceName: "fake.preference",
     preferenceValue: "experiment value",
   });
   await PreferenceExperiments.init();
 
   ok(
-    startObserver.calledWith("test", "fake.preference", "experiment value"),
+    startObserver.calledWith("test", "fake.preference", "string", "experiment value"),
     "init registered an observer",
   );
 
   startObserver.restore();
 })));
--- a/dom/base/WebSocket.cpp
+++ b/dom/base/WebSocket.cpp
@@ -1691,17 +1691,20 @@ WebSocketImpl::Init(JSContext* aCx,
             break;
           }
 
           currentInnerWindow = parentWindow->GetCurrentInnerWindow();
           if (NS_WARN_IF(!currentInnerWindow)) {
             return NS_ERROR_DOM_SECURITY_ERR;
           }
 
-          MOZ_ASSERT(currentInnerWindow != innerWindow);
+          if (currentInnerWindow == innerWindow) {
+            // The opener may be the same outer window as the parent.
+            break;
+          }
         }
 
         innerWindow = currentInnerWindow;
 
         nsCOMPtr<nsIDocument> document = innerWindow->GetExtantDoc();
         if (NS_WARN_IF(!document)) {
           return NS_ERROR_DOM_SECURITY_ERR;
         }
--- a/dom/base/nsDOMWindowUtils.cpp
+++ b/dom/base/nsDOMWindowUtils.cpp
@@ -1821,16 +1821,49 @@ nsDOMWindowUtils::GetBoundsWithoutFlushi
     rect->SetLayoutRect(r);
   }
 
   rect.forget(aResult);
   return NS_OK;
 }
 
 NS_IMETHODIMP
+nsDOMWindowUtils::NeedsFlush(int32_t aFlushType, bool* aResult)
+{
+  MOZ_ASSERT(aResult);
+
+  nsCOMPtr<nsIDocument> doc = GetDocument();
+  NS_ENSURE_STATE(doc);
+
+  nsIPresShell* presShell = doc->GetShell();
+  NS_ENSURE_STATE(presShell);
+
+  FlushType flushType;
+  switch (aFlushType) {
+  case FLUSH_STYLE:
+    flushType = FlushType::Style;
+    break;
+
+  case FLUSH_LAYOUT:
+    flushType = FlushType::Layout;
+    break;
+
+  case FLUSH_DISPLAY:
+    flushType = FlushType::Display;
+    break;
+
+  default:
+    return NS_ERROR_INVALID_ARG;
+  }
+
+  *aResult = presShell->NeedFlush(flushType);
+  return NS_OK;
+}
+
+NS_IMETHODIMP
 nsDOMWindowUtils::GetRootBounds(nsIDOMClientRect** aResult)
 {
   nsIDocument* doc = GetDocument();
   NS_ENSURE_STATE(doc);
 
   nsRect bounds(0, 0, 0, 0);
   nsIPresShell* presShell = doc->GetShell();
   if (presShell) {
--- a/dom/base/nsGlobalWindow.cpp
+++ b/dom/base/nsGlobalWindow.cpp
@@ -7809,19 +7809,20 @@ nsGlobalWindow::PromptOuter(const nsAStr
   if (disallowDialog) {
     DisableDialogs();
   }
 
   if (aError.Failed()) {
     return;
   }
 
-  nsAdoptingString outValue(inoutValue);
-
-  if (ok && outValue) {
+  nsString outValue;
+  outValue.Adopt(inoutValue);
+
+  if (ok && inoutValue) {
     aReturn.Assign(outValue);
   }
 }
 
 void
 nsGlobalWindow::Prompt(const nsAString& aMessage, const nsAString& aInitial,
                        nsAString& aReturn,
                        nsIPrincipal& aSubjectPrincipal,
--- a/dom/base/nsINode.h
+++ b/dom/base/nsINode.h
@@ -1092,17 +1092,17 @@ public:
     virtual ~nsSlots();
 
     void Traverse(nsCycleCollectionTraversalCallback &cb);
     void Unlink();
 
     /**
      * A list of mutation observers
      */
-    nsTObserverArray<nsIMutationObserver*> mMutationObservers;
+    nsAutoTObserverArray<nsIMutationObserver*, 1> mMutationObservers;
 
     /**
      * An object implementing nsIDOMNodeList for this content (childNodes)
      * @see nsIDOMNodeList
      * @see nsGenericHTMLElement::GetChildNodes
      */
     RefPtr<nsChildContentList> mChildNodes;
 
@@ -1949,17 +1949,17 @@ protected:
   {
     if (!HasSlots()) {
       mSlots = CreateSlots();
       MOZ_ASSERT(mSlots);
     }
     return GetExistingSlots();
   }
 
-  nsTObserverArray<nsIMutationObserver*> *GetMutationObservers()
+  nsAutoTObserverArray<nsIMutationObserver*, 1> *GetMutationObservers()
   {
     return HasSlots() ? &GetExistingSlots()->mMutationObservers : nullptr;
   }
 
   bool IsEditableInternal() const;
   virtual bool IsEditableExternal() const
   {
     return IsEditableInternal();
--- a/dom/base/nsNodeUtils.cpp
+++ b/dom/base/nsNodeUtils.cpp
@@ -54,18 +54,18 @@ using mozilla::AutoJSContext;
   if (doc) {                                                      \
     doc->BindingManager()->func_ params_;                         \
   }                                                               \
   do {                                                            \
     nsINode::nsSlots* slots = node->GetExistingSlots();           \
     if (slots && !slots->mMutationObservers.IsEmpty()) {          \
       /* No need to explicitly notify the first observer first    \
          since that'll happen anyway. */                          \
-      NS_OBSERVER_ARRAY_NOTIFY_OBSERVERS(                         \
-        slots->mMutationObservers, nsIMutationObserver,           \
+      NS_OBSERVER_AUTO_ARRAY_NOTIFY_OBSERVERS(                    \
+        slots->mMutationObservers, nsIMutationObserver, 1,        \
         func_, params_);                                          \
     }                                                             \
     ShadowRoot* shadow = ShadowRoot::FromNode(node);              \
     if (shadow) {                                                 \
       node = shadow->GetPoolHost();                               \
     } else {                                                      \
       node = node->GetParentNode();                               \
     }                                                             \
@@ -82,18 +82,18 @@ using mozilla::AutoJSContext;
     nsDOMMutationObserver::EnterMutationHandling();               \
   }                                                               \
   nsINode* node = content_;                                       \
   do {                                                            \
     nsINode::nsSlots* slots = node->GetExistingSlots();           \
     if (slots && !slots->mMutationObservers.IsEmpty()) {          \
       /* No need to explicitly notify the first observer first    \
          since that'll happen anyway. */                          \
-      NS_OBSERVER_ARRAY_NOTIFY_OBSERVERS_WITH_QI(                 \
-        slots->mMutationObservers, nsIMutationObserver,           \
+      NS_OBSERVER_AUTO_ARRAY_NOTIFY_OBSERVERS_WITH_QI(            \
+        slots->mMutationObservers, nsIMutationObserver, 1,        \
         nsIAnimationObserver, func_, params_);                    \
     }                                                             \
     ShadowRoot* shadow = ShadowRoot::FromNode(node);              \
     if (shadow) {                                                 \
       node = shadow->GetPoolHost();                               \
     } else {                                                      \
       node = node->GetParentNode();                               \
     }                                                             \
@@ -287,19 +287,19 @@ nsNodeUtils::AnimationRemoved(Animation*
 }
 
 void
 nsNodeUtils::LastRelease(nsINode* aNode)
 {
   nsINode::nsSlots* slots = aNode->GetExistingSlots();
   if (slots) {
     if (!slots->mMutationObservers.IsEmpty()) {
-      NS_OBSERVER_ARRAY_NOTIFY_OBSERVERS(slots->mMutationObservers,
-                                         nsIMutationObserver,
-                                         NodeWillBeDestroyed, (aNode));
+      NS_OBSERVER_AUTO_ARRAY_NOTIFY_OBSERVERS(slots->mMutationObservers,
+                                              nsIMutationObserver, 1,
+                                              NodeWillBeDestroyed, (aNode));
     }
 
     if (aNode->IsElement()) {
       Element* elem = aNode->AsElement();
       FragmentOrElement::nsDOMSlots* domSlots =
         static_cast<FragmentOrElement::nsDOMSlots*>(slots);
       if (domSlots->mExtendedSlots) {
         for (auto iter = domSlots->mExtendedSlots->mRegisteredIntersectionObservers.Iter();
--- a/dom/base/nsNodeUtils.h
+++ b/dom/base/nsNodeUtils.h
@@ -132,20 +132,20 @@ public:
    * Send ParentChainChanged notifications to nsIMutationObservers
    * @param aContent  The piece of content that had its parent changed.
    * @see nsIMutationObserver::ParentChainChanged
    */
   static inline void ParentChainChanged(nsIContent *aContent)
   {
     nsINode::nsSlots* slots = aContent->GetExistingSlots();
     if (slots && !slots->mMutationObservers.IsEmpty()) {
-      NS_OBSERVER_ARRAY_NOTIFY_OBSERVERS(slots->mMutationObservers,
-                                         nsIMutationObserver,
-                                         ParentChainChanged,
-                                         (aContent));
+      NS_OBSERVER_AUTO_ARRAY_NOTIFY_OBSERVERS(slots->mMutationObservers,
+                                              nsIMutationObserver, 1,
+                                              ParentChainChanged,
+                                              (aContent));
     }
   }
 
   /**
    * Utility function to get the target (pseudo-)element associated with an
    * animation.
    * @param aAnimation The animation whose target is what we want.
    */
new file mode 100644
--- /dev/null
+++ b/dom/base/test/file_bug1384658.html
@@ -0,0 +1,19 @@
+<!DOCTYPE html>
+<html>
+<script>
+  onload = function() {
+    function done(success) {
+      var bc = new BroadcastChannel("test_channel");
+      bc.postMessage({success:success});
+      bc.close();
+    }
+    try {
+      new WebSocket("ws://mochi.test:8888/tests/dom/base/test/file_websocket_basic");
+      done(true); // no hang!
+    } catch (e) {
+      done(false);
+    }
+  }
+</script>
+</html>
+
--- a/dom/base/test/mochitest.ini
+++ b/dom/base/test/mochitest.ini
@@ -60,16 +60,17 @@ support-files =
   eventsource_redirect.resource
   eventsource_redirect.resource^headers^
   eventsource_redirect_to.resource
   eventsource_redirect_to.resource^headers^
   file_base_xbl.xml
   file_bug1091883_frame.html
   file_bug1091883_subframe.html
   file_bug1091883_target.html
+  file_bug1384658.html
   file_bug28293.sjs
   file_bug326337.xml
   file_bug326337_inner.html
   file_bug326337_outer.html
   file_bug372086.xml
   file_bug416317.xhtml
   file_bug426646-1.html
   file_bug426646-2.html
@@ -246,16 +247,17 @@ support-files =
   iframe7_bug431701.xml
   iframe1_bug426646.html
   iframe2_bug426646.html
   file1_setting_opener.html
   file2_setting_opener.html
   file3_setting_opener.html
   file4_setting_opener.html
   PASS.html
+  window_bug1384658.html
 
 [test_anchor_area_referrer.html]
 [test_anchor_area_referrer_changing.html]
 [test_anchor_area_referrer_invalid.html]
 [test_anchor_area_referrer_rel.html]
 [test_anonymousContent_api.html]
 [test_anonymousContent_append_after_reflow.html]
 [test_anonymousContent_canvas.html]
@@ -616,16 +618,18 @@ skip-if = toolkit == 'android'
 [test_bug1274806.html]
 [test_bug1281963.html]
 [test_bug1295852.html]
 [test_bug1307730.html]
 [test_bug1308069.html]
 [test_bug1314032.html]
 [test_bug1318303.html]
 [test_bug1375050.html]
+[test_bug1384658.html]
+skip-if = toolkit == 'android'
 [test_caretPositionFromPoint.html]
 [test_change_policy.html]
 [test_clearTimeoutIntervalNoArg.html]
 [test_constructor-assignment.html]
 [test_constructor.html]
 [test_copyimage.html]
 subsuite = clipboard
 skip-if = toolkit == 'android' #bug 904183
new file mode 100644
--- /dev/null
+++ b/dom/base/test/test_bug1384658.html
@@ -0,0 +1,37 @@
+<!DOCTYPE HTML>
+<html>
+<!--
+https://bugzilla.mozilla.org/show_bug.cgi?id=1384658
+-->
+<head>
+  <meta charset="utf-8">
+  <title>Test for Bug 1384658</title>
+  <script type="application/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
+  <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css"/>
+  <script type="application/javascript">
+
+  /** Test for Bug 1384658 **/
+
+  SimpleTest.waitForExplicitFinish();
+  var win = window.open("http://example.com/tests/dom/base/test/window_bug1384658.html",
+                        "_blank", "width=100,height=100");
+  var bc = new BroadcastChannel("test_channel");
+  bc.onmessage = ev => {
+    ok(ev.data.success, "We didn't hang");
+    bc.close();
+    win.close();
+    SimpleTest.finish();
+  };
+
+  </script>
+</head>
+<body>
+<a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=1384658">Mozilla Bug 1384658</a>
+<p id="display"></p>
+<div id="content" style="display: none">
+
+</div>
+<pre id="test">
+</pre>
+</body>
+</html>
new file mode 100644
--- /dev/null
+++ b/dom/base/test/window_bug1384658.html
@@ -0,0 +1,19 @@
+<!DOCTYPE html>
+<html>
+<head>
+<script>
+  onload = function() {
+    if (window.location.search == "") {
+      window.open("window_bug1384658.html?opened", "_top", "");
+    } else {
+      var iframeURL = "http://mochi.test:8888/tests/dom/base/test/file_bug1384658.html";
+      var iframe = document.createElement("iframe");
+      iframe.src = iframeURL;
+      document.body.appendChild(iframe);
+    }
+  };
+</script>
+</head>
+<body>
+</body>
+</html>
--- a/dom/interfaces/base/nsIDOMWindowUtils.idl
+++ b/dom/interfaces/base/nsIDOMWindowUtils.idl
@@ -990,16 +990,25 @@ interface nsIDOMWindowUtils : nsISupport
    */
   void getScrollbarSize(in boolean aFlushLayout, out long aWidth, out long aHeight);
 
   /**
    * Returns the given element's bounds without flushing pending layout changes.
    */
   nsIDOMClientRect getBoundsWithoutFlushing(in nsIDOMElement aElement);
 
+  const long FLUSH_STYLE = 0;
+  const long FLUSH_LAYOUT = 1;
+  const long FLUSH_DISPLAY = 2;
+
+  /**
+   * Returns true if a flush of the given type is needed.
+   */
+  bool needsFlush(in long aFlushtype);
+
   /**
    * Returns the bounds of the window's currently loaded document. This will
    * generally be (0, 0, pageWidth, pageHeight) but in some cases (e.g. RTL
    * documents) may have a negative left value.
    */
   nsIDOMClientRect getRootBounds();
 
   /**
--- a/dom/moz.build
+++ b/dom/moz.build
@@ -118,11 +118,11 @@ if CONFIG['MOZ_SECUREELEMENT']:
 
 DIRS += ['presentation']
 
 TEST_DIRS += [
     'tests',
     'imptests',
 ]
 
-if CONFIG['MOZ_WIDGET_TOOLKIT'] in ('gtk2', 'gtk3', 'cocoa', 'windows', 'android'):
+if CONFIG['MOZ_WIDGET_TOOLKIT'] in ('gtk2', 'gtk3', 'cocoa', 'windows'):
     TEST_DIRS += ['plugins/test']
 
--- a/dom/plugins/base/PluginPRLibrary.cpp
+++ b/dom/plugins/base/PluginPRLibrary.cpp
@@ -16,53 +16,20 @@
 // gNotOptimized exists so that the compiler will not optimize the alloca
 // below.
 static int gNotOptimized;
 #define CALLING_CONVENTION_HACK void* foo = _alloca(gNotOptimized);
 #else
 #define CALLING_CONVENTION_HACK
 #endif
 
-#ifdef MOZ_WIDGET_ANDROID
-#include "AndroidBridge.h"
-#include "android_npapi.h"
-#include <android/log.h>
-#undef ALOG
-#define ALOG(args...) __android_log_print(ANDROID_LOG_INFO, "GeckoJavaEnv", ## args)
-#endif
-
 using namespace mozilla::layers;
 
 namespace mozilla {
-#ifdef MOZ_WIDGET_ANDROID
-nsresult
-PluginPRLibrary::NP_Initialize(NPNetscapeFuncs* bFuncs,
-			       NPPluginFuncs* pFuncs, NPError* error)
-{
-  JNIEnv* env = jni::GetEnvForThread();
-
-  mozilla::AutoLocalJNIFrame jniFrame(env);
-
-  if (mNP_Initialize) {
-    *error = mNP_Initialize(bFuncs, pFuncs, env);
-  } else {
-    NP_InitializeFunc pfNP_Initialize = (NP_InitializeFunc)
-      PR_FindFunctionSymbol(mLibrary, "NP_Initialize");
-    if (!pfNP_Initialize)
-      return NS_ERROR_FAILURE;
-    *error = pfNP_Initialize(bFuncs, pFuncs, env);
-  }
-
-  // Save pointers to functions that get called through PluginLibrary itself.
-  mNPP_New = pFuncs->newp;
-  mNPP_ClearSiteData = pFuncs->clearsitedata;
-  mNPP_GetSitesWithData = pFuncs->getsiteswithdata;
-  return NS_OK;
-}
-#elif defined(XP_UNIX) && !defined(XP_MACOSX)
+#if defined(XP_UNIX) && !defined(XP_MACOSX)
 nsresult
 PluginPRLibrary::NP_Initialize(NPNetscapeFuncs* bFuncs,
                                NPPluginFuncs* pFuncs, NPError* error)
 {
   if (mNP_Initialize) {
     *error = mNP_Initialize(bFuncs, pFuncs);
   } else {
     NP_InitializeFunc pfNP_Initialize = (NP_InitializeFunc)
@@ -186,30 +153,28 @@ nsresult
 PluginPRLibrary::NPP_New(NPMIMEType pluginType, NPP instance,
 			 int16_t argc, char* argn[],
 			 char* argv[], NPSavedData* saved,
 			 NPError* error)
 {
   if (!mNPP_New)
     return NS_ERROR_FAILURE;
 
-  MAIN_THREAD_JNI_REF_GUARD;
   *error = mNPP_New(pluginType, instance, NP_EMBED, argc, argn, argv, saved);
   return NS_OK;
 }
 
 nsresult
 PluginPRLibrary::NPP_ClearSiteData(const char* site, uint64_t flags,
                                    uint64_t maxAge, nsCOMPtr<nsIClearSiteDataCallback> callback)
 {
   if (!mNPP_ClearSiteData) {
     return NS_ERROR_NOT_AVAILABLE;
   }
 
-  MAIN_THREAD_JNI_REF_GUARD;
   NPError result = mNPP_ClearSiteData(site, flags, maxAge);
 
   nsresult rv;
   switch (result) {
   case NPERR_NO_ERROR:
     rv = NS_OK;
     break;
   case NPERR_TIME_RANGE_NOT_SUPPORTED:
@@ -227,17 +192,16 @@ PluginPRLibrary::NPP_ClearSiteData(const
 
 nsresult
 PluginPRLibrary::NPP_GetSitesWithData(nsCOMPtr<nsIGetSitesWithDataCallback> callback)
 {
   if (!mNPP_GetSitesWithData) {
     return NS_ERROR_NOT_AVAILABLE;
   }
 
-  MAIN_THREAD_JNI_REF_GUARD;
   char** sites = mNPP_GetSitesWithData();
   if (!sites) {
     return NS_OK;
   }
   InfallibleTArray<nsCString> result;
   char** iterator = sites;
   while (*iterator) {
     result.AppendElement(*iterator);
deleted file mode 100644
--- a/dom/plugins/base/android/ANPAudio.cpp
+++ /dev/null
@@ -1,390 +0,0 @@
-/* -*- Mode: c++; c-basic-offset: 2; tab-width: 20; indent-tabs-mode: nil; -*-
- * This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-#include "base/basictypes.h"
-#include "AndroidBridge.h"
-
-#include <android/log.h>
-#include <stdlib.h>
-#include <time.h>
-
-#include "assert.h"
-#include "ANPBase.h"
-#include "nsIThread.h"
-#include "nsThreadUtils.h"
-#include "mozilla/Mutex.h"
-
-#define LOG(args...)  __android_log_print(ANDROID_LOG_INFO, "GeckoPluginsAudio" , ## args)
-#define ASSIGN(obj, name)   (obj)->name = anp_audio_##name
-
-/* android.media.AudioTrack */
-struct AudioTrack {
-  jclass    at_class;
-  jmethodID constructor;
-  jmethodID flush;
-  jmethodID pause;
-  jmethodID play;
-  jmethodID setvol;
-  jmethodID stop;
-  jmethodID write;
-  jmethodID getpos;
-  jmethodID getstate;
-  jmethodID release;
-};
-
-enum AudioTrackMode {
-  MODE_STATIC = 0,
-  MODE_STREAM = 1
-};
-
-/* android.media.AudioManager */
-enum AudioManagerStream {
-  STREAM_VOICE_CALL = 0,
-  STREAM_SYSTEM = 1,
-  STREAM_RING = 2,
-  STREAM_MUSIC = 3,
-  STREAM_ALARM = 4,
-  STREAM_NOTIFICATION = 5,
-  STREAM_DTMF = 8
-};
-
-/* android.media.AudioFormat */
-enum AudioFormatChannel {
-  CHANNEL_OUT_MONO = 4,
-  CHANNEL_OUT_STEREO = 12
-};
-
-enum AudioFormatEncoding {
-  ENCODING_PCM_16BIT = 2,
-  ENCODING_PCM_8BIT = 3
-};
-
-enum AudioFormatState {
-  STATE_UNINITIALIZED = 0,
-  STATE_INITIALIZED = 1,
-  STATE_NO_STATIC_DATA = 2
-};
-
-static struct AudioTrack at;
-
-static jclass
-init_jni_bindings(JNIEnv *jenv) {
-  jclass jc =
-    (jclass)jenv->NewGlobalRef(jenv->FindClass("android/media/AudioTrack"));
-
-  at.constructor = jenv->GetMethodID(jc, "<init>", "(IIIIII)V");
-  at.flush       = jenv->GetMethodID(jc, "flush", "()V");
-  at.pause       = jenv->GetMethodID(jc, "pause", "()V");
-  at.play        = jenv->GetMethodID(jc, "play",  "()V");
-  at.setvol      = jenv->GetMethodID(jc, "setStereoVolume",  "(FF)I");
-  at.stop        = jenv->GetMethodID(jc, "stop",  "()V");
-  at.write       = jenv->GetMethodID(jc, "write", "([BII)I");
-  at.getpos      = jenv->GetMethodID(jc, "getPlaybackHeadPosition", "()I");
-  at.getstate    = jenv->GetMethodID(jc, "getState", "()I");
-  at.release     = jenv->GetMethodID(jc, "release", "()V");
-
-  return jc;
-}
-
-struct ANPAudioTrack {
-  jobject output_unit;
-  jclass at_class;
-
-  unsigned int rate;
-  unsigned int channels;
-  unsigned int bufferSize;
-  unsigned int isStopped;
-  unsigned int keepGoing;
-
-  mozilla::Mutex lock;
-
-  void* user;
-  ANPAudioCallbackProc proc;
-  ANPSampleFormat format;
-
-  ANPAudioTrack() : lock("ANPAudioTrack") { }
-};
-
-class AudioRunnable : public mozilla::Runnable
-{
-public:
-  NS_DECL_NSIRUNNABLE
-
-  AudioRunnable(ANPAudioTrack* aAudioTrack) :
-    Runnable("AudioRunnable")
-  {
-    mTrack = aAudioTrack;
-  }
-
-  ANPAudioTrack* mTrack;
-};
-
-NS_IMETHODIMP
-AudioRunnable::Run()
-{
-  JNIEnv* const jenv = mozilla::jni::GetEnvForThread();
-
-  mozilla::AutoLocalJNIFrame autoFrame(jenv, 2);
-
-  jbyteArray bytearray = jenv->NewByteArray(mTrack->bufferSize);
-  if (!bytearray) {
-    LOG("AudioRunnable:: Run.  Could not create bytearray");
-    return NS_ERROR_FAILURE;
-  }
-
-  jbyte *byte = jenv->GetByteArrayElements(bytearray, nullptr);
-  if (!byte) {
-    LOG("AudioRunnable:: Run.  Could not create bytearray");
-    return NS_ERROR_FAILURE;
-  }
-
-  ANPAudioBuffer buffer;
-  buffer.channelCount = mTrack->channels;
-  buffer.format = mTrack->format;
-  buffer.bufferData = (void*) byte;
-
-  while (true)
-  {
-    // reset the buffer size
-    buffer.size = mTrack->bufferSize;
-
-    {
-      mozilla::MutexAutoLock lock(mTrack->lock);
-
-      if (!mTrack->keepGoing)
-        break;
-
-      // Get data from the plugin
-      mTrack->proc(kMoreData_ANPAudioEvent, mTrack->user, &buffer);
-    }
-
-    if (buffer.size == 0) {
-      LOG("%p - kMoreData_ANPAudioEvent", mTrack);
-      continue;
-    }
-
-    size_t wroteSoFar = 0;
-    jint retval;
-    do {
-      retval = jenv->CallIntMethod(mTrack->output_unit,
-                                   at.write,
-                                   bytearray,
-                                   wroteSoFar,
-                                   buffer.size - wroteSoFar);
-      if (retval < 0) {
-        LOG("%p - Write failed %d", mTrack, retval);
-        break;
-      }
-
-      wroteSoFar += retval;
-
-    } while(wroteSoFar < buffer.size);
-  }
-
-  jenv->CallVoidMethod(mTrack->output_unit, at.release);
-
-  jenv->DeleteGlobalRef(mTrack->output_unit);
-  jenv->DeleteGlobalRef(mTrack->at_class);
-
-  delete mTrack;
-
-  jenv->ReleaseByteArrayElements(bytearray, byte, 0);
-
-  return NS_OK;
-}
-
-ANPAudioTrack*
-anp_audio_newTrack(uint32_t sampleRate,    // sampling rate in Hz
-                   ANPSampleFormat format,
-                   int channelCount,       // MONO=1, STEREO=2
-                   ANPAudioCallbackProc proc,
-                   void* user)
-{
-  ANPAudioTrack *s = new ANPAudioTrack();
-  if (s == nullptr) {
-    return nullptr;
-  }
-
-  JNIEnv* const jenv = mozilla::jni::GetEnvForThread();
-
-  s->at_class = init_jni_bindings(jenv);
-  s->rate = sampleRate;
-  s->channels = channelCount;
-  s->bufferSize = s->rate * s->channels;
-  s->isStopped = true;
-  s->keepGoing = false;
-  s->user = user;
-  s->proc = proc;
-  s->format = format;
-
-  int jformat;
-  switch (format) {
-  case kPCM16Bit_ANPSampleFormat:
-    jformat = ENCODING_PCM_16BIT;
-    break;
-  case kPCM8Bit_ANPSampleFormat:
-    jformat = ENCODING_PCM_8BIT;
-    break;
-  default:
-    LOG("Unknown audio format.  defaulting to 16bit.");
-    jformat = ENCODING_PCM_16BIT;
-    break;
-  }
-
-  int jChannels;
-  switch (channelCount) {
-  case 1:
-    jChannels = CHANNEL_OUT_MONO;
-    break;
-  case 2:
-    jChannels = CHANNEL_OUT_STEREO;
-    break;
-  default:
-    LOG("Unknown channel count.  defaulting to mono.");
-    jChannels = CHANNEL_OUT_MONO;
-    break;
-  }
-
-  mozilla::AutoLocalJNIFrame autoFrame(jenv);
-
-  jobject obj = jenv->NewObject(s->at_class,
-                                at.constructor,
-                                STREAM_MUSIC,
-                                s->rate,
-                                jChannels,
-                                jformat,
-                                s->bufferSize,
-                                MODE_STREAM);
-
-  if (autoFrame.CheckForException() || obj == nullptr) {
-    jenv->DeleteGlobalRef(s->at_class);
-    delete s;
-    return nullptr;
-  }
-
-  jint state = jenv->CallIntMethod(obj, at.getstate);
-
-  if (autoFrame.CheckForException() || state == STATE_UNINITIALIZED) {
-    jenv->DeleteGlobalRef(s->at_class);
-    delete s;
-    return nullptr;
-  }
-
-  s->output_unit = jenv->NewGlobalRef(obj);
-  return s;
-}
-
-void
-anp_audio_deleteTrack(ANPAudioTrack* s)
-{
-  if (s == nullptr) {
-    return;
-  }
-
-  mozilla::MutexAutoLock lock(s->lock);
-  s->keepGoing = false;
-
-  // deallocation happens in the AudioThread.  There is a
-  // potential leak if anp_audio_start is never called, but
-  // we do not see that from flash.
-}
-
-void
-anp_audio_start(ANPAudioTrack* s)
-{
-  if (s == nullptr || s->output_unit == nullptr) {
-    return;
-  }
-
-  if (s->keepGoing) {
-    // we are already playing.  Ignore.
-    return;
-  }
-
-  JNIEnv* const jenv = mozilla::jni::GetEnvForThread();
-
-  mozilla::AutoLocalJNIFrame autoFrame(jenv, 0);
-  jenv->CallVoidMethod(s->output_unit, at.play);
-
-  if (autoFrame.CheckForException()) {
-    jenv->DeleteGlobalRef(s->at_class);
-    delete s;
-    return;
-  }
-
-  s->isStopped = false;
-  s->keepGoing = true;
-
-  // AudioRunnable now owns the ANPAudioTrack
-  RefPtr<AudioRunnable> runnable = new AudioRunnable(s);
-
-  nsCOMPtr<nsIThread> thread;
-  NS_NewNamedThread("Android Audio", getter_AddRefs(thread), runnable);
-}
-
-void
-anp_audio_pause(ANPAudioTrack* s)
-{
-  if (s == nullptr || s->output_unit == nullptr) {
-    return;
-  }
-
-  JNIEnv* const jenv = mozilla::jni::GetEnvForThread();
-
-  mozilla::AutoLocalJNIFrame autoFrame(jenv, 0);
-  jenv->CallVoidMethod(s->output_unit, at.pause);
-}
-
-void
-anp_audio_stop(ANPAudioTrack* s)
-{
-  if (s == nullptr || s->output_unit == nullptr) {
-    return;
-  }
-
-  s->isStopped = true;
-  JNIEnv* const jenv = mozilla::jni::GetEnvForThread();
-
-  mozilla::AutoLocalJNIFrame autoFrame(jenv, 0);
-  jenv->CallVoidMethod(s->output_unit, at.stop);
-}
-
-bool
-anp_audio_isStopped(ANPAudioTrack* s)
-{
-  return s->isStopped;
-}
-
-uint32_t
-anp_audio_trackLatency(ANPAudioTrack* s) {
-  // Hardcode an estimate of the system's audio latency. Flash hardcodes
-  // similar latency estimates for pre-Honeycomb devices that do not support
-  // ANPAudioTrackInterfaceV1's trackLatency(). The Android stock browser
-  // calls android::AudioTrack::latency(), an internal Android API that is
-  // not available in the public NDK:
-  // https://github.com/android/platform_external_webkit/commit/49bf866973cb3b2a6c74c0eab864e9562e4cbab1
-  return 100; // milliseconds
-}
-
-void InitAudioTrackInterfaceV0(ANPAudioTrackInterfaceV0 *i) {
-  _assert(i->inSize == sizeof(*i));
-  ASSIGN(i, newTrack);
-  ASSIGN(i, deleteTrack);
-  ASSIGN(i, start);
-  ASSIGN(i, pause);
-  ASSIGN(i, stop);
-  ASSIGN(i, isStopped);
-}
-
-void InitAudioTrackInterfaceV1(ANPAudioTrackInterfaceV1 *i) {
-  _assert(i->inSize == sizeof(*i));
-  ASSIGN(i, newTrack);
-  ASSIGN(i, deleteTrack);
-  ASSIGN(i, start);
-  ASSIGN(i, pause);
-  ASSIGN(i, stop);
-  ASSIGN(i, isStopped);
-  ASSIGN(i, trackLatency);
-}
deleted file mode 100644
--- a/dom/plugins/base/android/ANPBase.h
+++ /dev/null
@@ -1,36 +0,0 @@
-/* -*- Mode: IDL; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-#include <stdlib.h>
-#include "android_npapi.h"
-#include "nsISupportsImpl.h"
-
-#define NOT_IMPLEMENTED_FATAL() do {                                    \
-    __android_log_print(ANDROID_LOG_ERROR, "GeckoPlugins",              \
-                        "%s not implemented %s, %d",                    \
-                        __PRETTY_FUNCTION__, __FILE__, __LINE__);       \
-    abort();                                                            \
-  } while(0)
-
-#define NOT_IMPLEMENTED()                                               \
-    __android_log_print(ANDROID_LOG_ERROR, "GeckoPlugins",              \
-                        "!!!!!!!!!!!!!!  %s not implemented %s, %d",    \
-                        __PRETTY_FUNCTION__, __FILE__, __LINE__);       \
-
-void InitAudioTrackInterfaceV0(ANPAudioTrackInterfaceV0 *i);
-void InitAudioTrackInterfaceV1(ANPAudioTrackInterfaceV1* i);
-void InitCanvasInterface(ANPCanvasInterfaceV0 *i);
-void InitEventInterface(ANPEventInterfaceV0 *i);
-void InitLogInterface(ANPLogInterfaceV0 *i);
-void InitPaintInterface(ANPPaintInterfaceV0 *i);
-void InitSurfaceInterface(ANPSurfaceInterfaceV0 *i);
-void InitSystemInterfaceV1(ANPSystemInterfaceV1 *i);
-void InitSystemInterfaceV2(ANPSystemInterfaceV2 *i);
-void InitTypeFaceInterface(ANPTypefaceInterfaceV0 *i);
-void InitWindowInterface(ANPWindowInterfaceV0 *i);
-void InitWindowInterfaceV2(ANPWindowInterfaceV2 *i);
-void InitVideoInterfaceV1(ANPVideoInterfaceV1 *i);
-void InitOpenGLInterface(ANPOpenGLInterfaceV0 *i);
-void InitNativeWindowInterface(ANPNativeWindowInterfaceV0 *i);
deleted file mode 100644
--- a/dom/plugins/base/android/ANPEvent.cpp
+++ /dev/null
@@ -1,31 +0,0 @@
-/* -*- Mode: IDL; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-#include "assert.h"
-#include "ANPBase.h"
-#include <android/log.h>
-#include "nsThreadUtils.h"
-#include "nsNPAPIPluginInstance.h"
-#include "nsNPAPIPlugin.h"
-
-#define LOG(args...)  __android_log_print(ANDROID_LOG_INFO, "GeckoPlugins" , ## args)
-#define ASSIGN(obj, name)   (obj)->name = anp_event_##name
-
-void
-anp_event_postEvent(NPP instance, const ANPEvent* event)
-{
-  LOG("%s", __PRETTY_FUNCTION__);
-
-  nsNPAPIPluginInstance* pinst = static_cast<nsNPAPIPluginInstance*>(instance->ndata);
-  pinst->PostEvent((void*) event);
-
-  LOG("returning from %s", __PRETTY_FUNCTION__);
-}
-
-
-void InitEventInterface(ANPEventInterfaceV0 *i) {
-  _assert(i->inSize == sizeof(*i));
-  ASSIGN(i, postEvent);
-}
deleted file mode 100644
--- a/dom/plugins/base/android/ANPKeyCodes.h
+++ /dev/null
@@ -1,152 +0,0 @@
-/*
- * Copyright 2008, The Android Open Source Project
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *  * Redistributions of source code must retain the above copyright
- *    notice, this list of conditions and the following disclaimer.
- *  * Redistributions in binary form must reproduce the above copyright
- *    notice, this list of conditions and the following disclaimer in the
- *    documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef ANPKeyCodes_DEFINED
-#define ANPKeyCodes_DEFINED
-
-/*  List the key codes that are set to a plugin in the ANPKeyEvent.
-
-    These exactly match the values in android/view/KeyEvent.java and the
-    corresponding .h file android/keycodes.h.
-*/
-enum ANPKeyCodes {
-    kUnknown_ANPKeyCode = 0,
-
-    kSoftLeft_ANPKeyCode = 1,
-    kSoftRight_ANPKeyCode = 2,
-    kHome_ANPKeyCode = 3,
-    kBack_ANPKeyCode = 4,
-    kCall_ANPKeyCode = 5,
-    kEndCall_ANPKeyCode = 6,
-    k0_ANPKeyCode = 7,
-    k1_ANPKeyCode = 8,
-    k2_ANPKeyCode = 9,
-    k3_ANPKeyCode = 10,
-    k4_ANPKeyCode = 11,
-    k5_ANPKeyCode = 12,
-    k6_ANPKeyCode = 13,
-    k7_ANPKeyCode = 14,
-    k8_ANPKeyCode = 15,
-    k9_ANPKeyCode = 16,
-    kStar_ANPKeyCode = 17,
-    kPound_ANPKeyCode = 18,
-    kDpadUp_ANPKeyCode = 19,
-    kDpadDown_ANPKeyCode = 20,
-    kDpadLeft_ANPKeyCode = 21,
-    kDpadRight_ANPKeyCode = 22,
-    kDpadCenter_ANPKeyCode = 23,
-    kVolumeUp_ANPKeyCode = 24,
-    kVolumeDown_ANPKeyCode = 25,
-    kPower_ANPKeyCode = 26,
-    kCamera_ANPKeyCode = 27,
-    kClear_ANPKeyCode = 28,
-    kA_ANPKeyCode = 29,
-    kB_ANPKeyCode = 30,
-    kC_ANPKeyCode = 31,
-    kD_ANPKeyCode = 32,
-    kE_ANPKeyCode = 33,
-    kF_ANPKeyCode = 34,
-    kG_ANPKeyCode = 35,
-    kH_ANPKeyCode = 36,
-    kI_ANPKeyCode = 37,
-    kJ_ANPKeyCode = 38,
-    kK_ANPKeyCode = 39,
-    kL_ANPKeyCode = 40,
-    kM_ANPKeyCode = 41,
-    kN_ANPKeyCode = 42,
-    kO_ANPKeyCode = 43,
-    kP_ANPKeyCode = 44,
-    kQ_ANPKeyCode = 45,
-    kR_ANPKeyCode = 46,
-    kS_ANPKeyCode = 47,
-    kT_ANPKeyCode = 48,
-    kU_ANPKeyCode = 49,
-    kV_ANPKeyCode = 50,
-    kW_ANPKeyCode = 51,
-    kX_ANPKeyCode = 52,
-    kY_ANPKeyCode = 53,
-    kZ_ANPKeyCode = 54,
-    kComma_ANPKeyCode = 55,
-    kPeriod_ANPKeyCode = 56,
-    kAltLeft_ANPKeyCode = 57,
-    kAltRight_ANPKeyCode = 58,
-    kShiftLeft_ANPKeyCode = 59,
-    kShiftRight_ANPKeyCode = 60,
-    kTab_ANPKeyCode = 61,
-    kSpace_ANPKeyCode = 62,
-    kSym_ANPKeyCode = 63,
-    kExplorer_ANPKeyCode = 64,
-    kEnvelope_ANPKeyCode = 65,
-    kNewline_ANPKeyCode = 66,
-    kDel_ANPKeyCode = 67,
-    kGrave_ANPKeyCode = 68,
-    kMinus_ANPKeyCode = 69,
-    kEquals_ANPKeyCode = 70,
-    kLeftBracket_ANPKeyCode = 71,
-    kRightBracket_ANPKeyCode = 72,
-    kBackslash_ANPKeyCode = 73,
-    kSemicolon_ANPKeyCode = 74,
-    kApostrophe_ANPKeyCode = 75,
-    kSlash_ANPKeyCode = 76,
-    kAt_ANPKeyCode = 77,
-    kNum_ANPKeyCode = 78,
-    kHeadSetHook_ANPKeyCode = 79,
-    kFocus_ANPKeyCode = 80,
-    kPlus_ANPKeyCode = 81,
-    kMenu_ANPKeyCode = 82,
-    kNotification_ANPKeyCode = 83,
-    kSearch_ANPKeyCode = 84,
-    kMediaPlayPause_ANPKeyCode = 85,
-    kMediaStop_ANPKeyCode = 86,
-    kMediaNext_ANPKeyCode = 87,
-    kMediaPrevious_ANPKeyCode = 88,
-    kMediaRewind_ANPKeyCode = 89,
-    kMediaFastForward_ANPKeyCode = 90,
-    kMute_ANPKeyCode = 91,
-    kPageUp_ANPKeyCode = 92,
-    kPageDown_ANPKeyCode = 93,
-    kPictsymbols_ANPKeyCode = 94,
-    kSwitchCharset_ANPKeyCode = 95,
-    kButtonA_ANPKeyCode = 96,
-    kButtonB_ANPKeyCode = 97,
-    kButtonC_ANPKeyCode = 98,
-    kButtonX_ANPKeyCode = 99,
-    kButtonY_ANPKeyCode = 100,
-    kButtonZ_ANPKeyCode = 101,
-    kButtonL1_ANPKeyCode = 102,
-    kButtonR1_ANPKeyCode = 103,
-    kButtonL2_ANPKeyCode = 104,
-    kButtonR2_ANPKeyCode = 105,
-    kButtonThumbL_ANPKeyCode = 106,
-    kButtonThumbR_ANPKeyCode = 107,
-    kButtonStart_ANPKeyCode = 108,
-    kButtonSelect_ANPKeyCode = 109,
-    kButtonMode_ANPKeyCode = 110,
-
-    // NOTE: If you add a new keycode here you must also add it to several other files.
-    //       Refer to frameworks/base/core/java/android/view/KeyEvent.java for the full list.
-};
-
-#endif
deleted file mode 100644
--- a/dom/plugins/base/android/ANPLog.cpp
+++ /dev/null
@@ -1,26 +0,0 @@
-/* -*- Mode: IDL; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-#include "assert.h"
-#include "ANPBase.h"
-#include <android/log.h>
-
-#define LOG(args...)  __android_log_print(ANDROID_LOG_INFO, "GeckoPlugins" , ## args)
-#define ASSIGN(obj, name)   (obj)->name = anp_log_##name
-
-void
-anp_log_log(ANPLogType type, const char format[], ...) {
-
-  va_list argp;
-  va_start(argp,format);
-  __android_log_vprint(type == kError_ANPLogType ? ANDROID_LOG_ERROR : type == kWarning_ANPLogType ?
-                       ANDROID_LOG_WARN : ANDROID_LOG_INFO, "GeckoPluginLog", format, argp);
-  va_end(argp);
-}
-
-void InitLogInterface(ANPLogInterfaceV0 *i) {
-      _assert(i->inSize == sizeof(*i));
-      ASSIGN(i, log);
-}
deleted file mode 100644
--- a/dom/plugins/base/android/ANPNativeWindow.cpp
+++ /dev/null
@@ -1,39 +0,0 @@
-/* -*- Mode: IDL; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-// must include config.h first for webkit to fiddle with new/delete
-#include <android/log.h>
-#include "ANPBase.h"
-#include "nsIPluginInstanceOwner.h"
-#include "nsPluginInstanceOwner.h"
-#include "nsNPAPIPluginInstance.h"
-#include "gfxRect.h"
-
-using namespace mozilla;
-
-#define LOG(args...)  __android_log_print(ANDROID_LOG_INFO, "GeckoPlugins" , ## args)
-#define ASSIGN(obj, name)   (obj)->name = anp_native_window_##name
-
-static ANPNativeWindow anp_native_window_acquireNativeWindow(NPP instance) {
-  nsNPAPIPluginInstance* pinst = static_cast<nsNPAPIPluginInstance*>(instance->ndata);
-  return pinst->AcquireContentWindow();
-}
-
-static void anp_native_window_invertPluginContent(NPP instance, bool isContentInverted) {
-    // NativeWindow is TopLeft if uninverted.
-  gl::OriginPos newOriginPos = gl::OriginPos::TopLeft;
-  if (isContentInverted)
-    newOriginPos = gl::OriginPos::BottomLeft;
-
-  nsNPAPIPluginInstance* pinst = static_cast<nsNPAPIPluginInstance*>(instance->ndata);
-  pinst->SetOriginPos(newOriginPos);
-  pinst->RedrawPlugin();
-}
-
-
-void InitNativeWindowInterface(ANPNativeWindowInterfaceV0* i) {
-    ASSIGN(i, acquireNativeWindow);
-    ASSIGN(i, invertPluginContent);
-}
deleted file mode 100644
--- a/dom/plugins/base/android/ANPSurface.cpp
+++ /dev/null
@@ -1,266 +0,0 @@
-/* -*- Mode: IDL; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-#include <dlfcn.h>
-#include <android/log.h>
-#include "ANPBase.h"
-
-#define LOG(args...)  __android_log_print(ANDROID_LOG_INFO, "GeckoPlugins" , ## args)
-#define ASSIGN(obj, name)   (obj)->name = anp_surface_##name
-
-#define CLEAR_EXCEPTION(env) if (env->ExceptionOccurred()) env->ExceptionClear();
-
-#define ANDROID_REGION_SIZE 512
-
-enum {
-    PIXEL_FORMAT_RGBA_8888   = 1,
-    PIXEL_FORMAT_RGB_565     = 4,
-};
-
-struct SurfaceInfo {
-    uint32_t    w;
-    uint32_t    h;
-    uint32_t    s;
-    uint32_t    usage;
-    uint32_t    format;
-    unsigned char* bits;
-    uint32_t    reserved[2];
-};
-
-typedef struct ARect {
-    int32_t left;
-    int32_t top;
-    int32_t right;
-    int32_t bottom;
-} ARect;
-
-
-// used to cache JNI method and field IDs for Surface Objects
-static struct ANPSurfaceInterfaceJavaGlue {
-    bool        initialized;
-    jmethodID   getSurfaceHolder;
-    jmethodID   getSurface;
-    jfieldID    surfacePointer;
-} gSurfaceJavaGlue;
-
-static struct ANPSurfaceFunctions {
-    bool initialized;
-
-    int (* lock)(void*, SurfaceInfo*, void*);
-    int (* unlockAndPost)(void*);
-
-    void* (* regionConstructor)(void*);
-    void (* setRegion)(void*, ARect const&);
-} gSurfaceFunctions;
-
-
-static inline void* getSurface(JNIEnv* env, jobject view) {
-  if (!env || !view) {
-    return nullptr;
-  }
-
-  if (!gSurfaceJavaGlue.initialized) {
-
-    jclass surfaceViewClass = env->FindClass("android/view/SurfaceView");
-    gSurfaceJavaGlue.getSurfaceHolder = env->GetMethodID(surfaceViewClass, "getHolder", "()Landroid/view/SurfaceHolder;");
-
-    jclass surfaceHolderClass = env->FindClass("android/view/SurfaceHolder");
-    gSurfaceJavaGlue.getSurface = env->GetMethodID(surfaceHolderClass, "getSurface", "()Landroid/view/Surface;");
-
-    jclass surfaceClass = env->FindClass("android/view/Surface");
-    gSurfaceJavaGlue.surfacePointer = env->GetFieldID(surfaceClass,
-        "mSurfacePointer", "I");
-
-    if (!gSurfaceJavaGlue.surfacePointer) {
-      CLEAR_EXCEPTION(env);
-
-      // It was something else in 2.2.
-      gSurfaceJavaGlue.surfacePointer = env->GetFieldID(surfaceClass,
-          "mSurface", "I");
-
-      if (!gSurfaceJavaGlue.surfacePointer) {
-        CLEAR_EXCEPTION(env);
-
-        // And something else in 2.3+
-        gSurfaceJavaGlue.surfacePointer = env->GetFieldID(surfaceClass,
-            "mNativeSurface", "I");
-
-        CLEAR_EXCEPTION(env);
-      }
-    }
-
-    if (!gSurfaceJavaGlue.surfacePointer) {
-      LOG("Failed to acquire surface pointer");
-      return nullptr;
-    }
-
-    env->DeleteLocalRef(surfaceClass);
-    env->DeleteLocalRef(surfaceViewClass);
-    env->DeleteLocalRef(surfaceHolderClass);
-
-    gSurfaceJavaGlue.initialized = (gSurfaceJavaGlue.surfacePointer != nullptr);
-  }
-
-  jobject holder = env->CallObjectMethod(view, gSurfaceJavaGlue.getSurfaceHolder);
-  jobject surface = env->CallObjectMethod(holder, gSurfaceJavaGlue.getSurface);
-  jint surfacePointer = env->GetIntField(surface, gSurfaceJavaGlue.surfacePointer);
-
-  env->DeleteLocalRef(holder);
-  env->DeleteLocalRef(surface);
-
-  return reinterpret_cast<void*>(uintptr_t(surfacePointer));
-}
-
-static ANPBitmapFormat convertPixelFormat(int32_t format) {
-  switch (format) {
-    case PIXEL_FORMAT_RGBA_8888:  return kRGBA_8888_ANPBitmapFormat;
-    case PIXEL_FORMAT_RGB_565:    return kRGB_565_ANPBitmapFormat;
-    default:            return kUnknown_ANPBitmapFormat;
-  }
-}
-
-static int bytesPerPixel(int32_t format) {
-  switch (format) {
-    case PIXEL_FORMAT_RGBA_8888: return 4;
-    case PIXEL_FORMAT_RGB_565: return 2;
-    default: return -1;
-  }
-}
-
-static bool init() {
-  if (gSurfaceFunctions.initialized)
-    return true;
-
-  void* handle = dlopen("libsurfaceflinger_client.so", RTLD_LAZY);
-
-  if (!handle) {
-    LOG("Failed to open libsurfaceflinger_client.so");
-    return false;
-  }
-
-  gSurfaceFunctions.lock = (int (*)(void*, SurfaceInfo*, void*))dlsym(handle, "_ZN7android7Surface4lockEPNS0_11SurfaceInfoEPNS_6RegionEb");
-  gSurfaceFunctions.unlockAndPost = (int (*)(void*))dlsym(handle, "_ZN7android7Surface13unlockAndPostEv");
-
-
-  if (!gSurfaceFunctions.lock) {
-    // Stuff changed in 3.0/4.0
-    handle = dlopen("libgui.so", RTLD_LAZY);
-    gSurfaceFunctions.lock = (int (*)(void*, SurfaceInfo*, void*))dlsym(handle, "_ZN7android7Surface4lockEPNS0_11SurfaceInfoEPNS_6RegionE");
-    gSurfaceFunctions.unlockAndPost = (int (*)(void*))dlsym(handle, "_ZN7android7Surface13unlockAndPostEv");
-  }
-
-  handle = dlopen("libui.so", RTLD_LAZY);
-  if (!handle) {
-    LOG("Failed to open libui.so");
-    return false;
-  }
-
-  gSurfaceFunctions.regionConstructor = (void* (*)(void*))dlsym(handle, "_ZN7android6RegionC1Ev");
-  gSurfaceFunctions.setRegion = (void (*)(void*, ARect const&))dlsym(handle, "_ZN7android6Region3setERKNS_4RectE");
-
-  gSurfaceFunctions.initialized = (gSurfaceFunctions.lock && gSurfaceFunctions.unlockAndPost &&
-                                   gSurfaceFunctions.regionConstructor && gSurfaceFunctions.setRegion);
-  LOG("Initialized? %d\n", gSurfaceFunctions.initialized);
-  return gSurfaceFunctions.initialized;
-}
-
-// FIXME: All of this should be changed to use the equivalent things in AndroidBridge, bug 758612
-static bool anp_surface_lock(JNIEnv* env, jobject surfaceView, ANPBitmap* bitmap, ANPRectI* dirtyRect) {
-  if (!bitmap || !surfaceView) {
-    return false;
-  }
-
-  void* surface = getSurface(env, surfaceView);
-
-  if (!bitmap || !surface) {
-    return false;
-  }
-
-  if (!init()) {
-    return false;
-  }
-
-  void* region = nullptr;
-  if (dirtyRect) {
-    region = malloc(ANDROID_REGION_SIZE);
-    gSurfaceFunctions.regionConstructor(region);
-
-    ARect rect;
-    rect.left = dirtyRect->left;
-    rect.top = dirtyRect->top;
-    rect.right = dirtyRect->right;
-    rect.bottom = dirtyRect->bottom;
-
-    gSurfaceFunctions.setRegion(region, rect);
-  }
-
-  SurfaceInfo info;
-  int err = gSurfaceFunctions.lock(surface, &info, region);
-  if (err < 0) {
-    LOG("Failed to lock surface");
-    return false;
-  }
-
-  // the surface may have expanded the dirty region so we must to pass that
-  // information back to the plugin.
-  if (dirtyRect) {
-    ARect* dirtyBounds = (ARect*)region; // The bounds are the first member, so this should work!
-
-    dirtyRect->left = dirtyBounds->left;
-    dirtyRect->right = dirtyBounds->right;
-    dirtyRect->top = dirtyBounds->top;
-    dirtyRect->bottom = dirtyBounds->bottom;
-  }
-
-  if (region)
-    free(region);
-
-  int bpr = info.s * bytesPerPixel(info.format);
-
-  bitmap->format = convertPixelFormat(info.format);
-  bitmap->width = info.w;
-  bitmap->height = info.h;
-  bitmap->rowBytes = bpr;
-
-  if (info.w > 0 && info.h > 0) {
-    bitmap->baseAddr = info.bits;
-  } else {
-    bitmap->baseAddr = nullptr;
-    return false;
-  }
-
-  return true;
-}
-
-static void anp_surface_unlock(JNIEnv* env, jobject surfaceView) {
-  if (!surfaceView) {
-    return;
-  }
-
-  if (!init()) {
-    return;
-  }
-
-  void* surface = getSurface(env, surfaceView);
-
-  if (!surface) {
-    return;
-  }
-
-  gSurfaceFunctions.unlockAndPost(surface);
-}
-
-///////////////////////////////////////////////////////////////////////////////
-
-void InitSurfaceInterface(ANPSurfaceInterfaceV0* i) {
-  ASSIGN(i, lock);
-  ASSIGN(i, unlock);
-
-  // setup the java glue struct
-  gSurfaceJavaGlue.initialized = false;
-
-  // setup the function struct
-  gSurfaceFunctions.initialized = false;
-}
deleted file mode 100644
--- a/dom/plugins/base/android/ANPSystem.cpp
+++ /dev/null
@@ -1,88 +0,0 @@
-/* -*- Mode: IDL; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-#include "base/basictypes.h"
-
-#include "ANPBase.h"
-#include "GeneratedJNIWrappers.h"
-#include "PluginPRLibrary.h"
-#include "assert.h"
-#include "nsNPAPIPluginInstance.h"
-#include "nsNPAPIPlugin.h"
-
-#include <android/log.h>
-
-#define LOG(args...)  __android_log_print(ANDROID_LOG_INFO, "GeckoPlugins" , ## args)
-#define ASSIGN(obj, name)   (obj)->name = anp_system_##name
-
-const char*
-anp_system_getApplicationDataDirectory(NPP instance)
-{
-  static const char *dir = nullptr;
-  static const char *privateDir = nullptr;
-
-  bool isPrivate = false;
-
-  if (!dir) {
-    dir = getenv("ANDROID_PLUGIN_DATADIR");
-  }
-
-  if (!privateDir) {
-    privateDir = getenv("ANDROID_PLUGIN_DATADIR_PRIVATE");
-  }
-
-  if (!instance) {
-    return dir;
-  }
-
-  nsNPAPIPluginInstance* pinst = static_cast<nsNPAPIPluginInstance*>(instance->ndata);
-  if (pinst && NS_SUCCEEDED(pinst->IsPrivateBrowsing(&isPrivate)) && isPrivate) {
-    return privateDir;
-  }
-
-  return dir;
-}
-
-const char*
-anp_system_getApplicationDataDirectory()
-{
-  return anp_system_getApplicationDataDirectory(nullptr);
-}
-
-jclass anp_system_loadJavaClass(NPP instance, const char* className)
-{
-  LOG("%s", __PRETTY_FUNCTION__);
-
-  nsNPAPIPluginInstance* pinst = static_cast<nsNPAPIPluginInstance*>(instance->ndata);
-  mozilla::PluginPRLibrary* lib = static_cast<mozilla::PluginPRLibrary*>(pinst->GetPlugin()->GetLibrary());
-
-  nsCString libName;
-  lib->GetLibraryPath(libName);
-
-  return mozilla::java::GeckoAppShell::LoadPluginClass(className, libName).Forget();
-}
-
-void anp_system_setPowerState(NPP instance, ANPPowerState powerState)
-{
-  nsNPAPIPluginInstance* pinst = nsNPAPIPluginInstance::GetFromNPP(instance);
-
-  if (pinst) {
-    pinst->SetWakeLock(powerState == kScreenOn_ANPPowerState);
-  }
-}
-
-void InitSystemInterfaceV1(ANPSystemInterfaceV1 *i) {
-  _assert(i->inSize == sizeof(*i));
-  ASSIGN(i, getApplicationDataDirectory);
-  ASSIGN(i, loadJavaClass);
-  ASSIGN(i, setPowerState);
-}
-
-void InitSystemInterfaceV2(ANPSystemInterfaceV2 *i) {
-  _assert(i->inSize == sizeof(*i));
-  ASSIGN(i, getApplicationDataDirectory);
-  ASSIGN(i, loadJavaClass);
-  ASSIGN(i, setPowerState);
-}
deleted file mode 100644
--- a/dom/plugins/base/android/ANPVideo.cpp
+++ /dev/null
@@ -1,55 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-#include <android/log.h>
-#include "ANPBase.h"
-#include "nsIPluginInstanceOwner.h"
-#include "nsPluginInstanceOwner.h"
-#include "nsNPAPIPluginInstance.h"
-#include "gfxRect.h"
-
-#define LOG(args...)  __android_log_print(ANDROID_LOG_INFO, "GeckoPlugins" , ## args)
-#define ASSIGN(obj, name)   (obj)->name = anp_video_##name
-
-using namespace mozilla;
-
-typedef nsNPAPIPluginInstance::VideoInfo VideoInfo;
-
-static ANPNativeWindow anp_video_acquireNativeWindow(NPP instance) {
-  nsNPAPIPluginInstance* pinst = static_cast<nsNPAPIPluginInstance*>(instance->ndata);
-
-  return pinst->AcquireVideoWindow();
-}
-
-static void anp_video_setWindowDimensions(NPP instance, const ANPNativeWindow window,
-                                          const ANPRectF* dimensions) {
-  nsNPAPIPluginInstance* pinst = static_cast<nsNPAPIPluginInstance*>(instance->ndata);
-
-  gfxRect rect(dimensions->left, dimensions->top,
-               dimensions->right - dimensions->left,
-               dimensions->bottom - dimensions->top);
-
-  pinst->SetVideoDimensions(window, rect);
-  pinst->RedrawPlugin();
-}
-
-static void anp_video_releaseNativeWindow(NPP instance, ANPNativeWindow window) {
-  nsNPAPIPluginInstance* pinst = static_cast<nsNPAPIPluginInstance*>(instance->ndata);
-  pinst->ReleaseVideoWindow(window);
-  pinst->RedrawPlugin();
-}
-
-static void anp_video_setFramerateCallback(NPP instance, const ANPNativeWindow window, ANPVideoFrameCallbackProc callback) {
-  // Bug 722682
-  NOT_IMPLEMENTED();
-}
-
-///////////////////////////////////////////////////////////////////////////////
-
-void InitVideoInterfaceV1(ANPVideoInterfaceV1* i) {
-    ASSIGN(i, acquireNativeWindow);
-    ASSIGN(i, setWindowDimensions);
-    ASSIGN(i, releaseNativeWindow);
-    ASSIGN(i, setFramerateCallback);
-}
deleted file mode 100644
--- a/dom/plugins/base/android/ANPWindow.cpp
+++ /dev/null
@@ -1,152 +0,0 @@
-/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-#include "base/basictypes.h"
-#include "assert.h"
-#include "ANPBase.h"
-#include <android/log.h>
-#include "nsNPAPIPluginInstance.h"
-#include "nsPluginInstanceOwner.h"
-#include "nsWindow.h"
-#include "mozilla/dom/ScreenOrientation.h"
-
-#undef LOG
-#define LOG(args...)  __android_log_print(ANDROID_LOG_INFO, "GeckoPlugins" , ## args)
-#define ASSIGN(obj, name)   (obj)->name = anp_window_##name
-
-using namespace mozilla;
-using namespace mozilla::widget;
-using namespace mozilla::dom;
-
-void
-anp_window_setVisibleRects(NPP instance, const ANPRectI rects[], int32_t count)
-{
-  NOT_IMPLEMENTED();
-}
-
-void
-anp_window_clearVisibleRects(NPP instance)
-{
-  NOT_IMPLEMENTED();
-}
-
-void
-anp_window_showKeyboard(NPP instance, bool value)
-{
-  InputContext context;
-  context.mIMEState.mEnabled = value ? IMEState::PLUGIN : IMEState::DISABLED;
-  context.mIMEState.mOpen = value ? IMEState::OPEN : IMEState::CLOSED;
-  context.mActionHint.Assign(EmptyString());
-
-  InputContextAction action;
-  action.mCause = InputContextAction::CAUSE_UNKNOWN;
-  action.mFocusChange = InputContextAction::FOCUS_NOT_CHANGED;
-
-  nsWindow* window = nsWindow::TopWindow();
-  if (!window) {
-    LOG("Couldn't get top window?");
-    return;
-  }
-
-  window->SetInputContext(context, action);
-}
-
-void
-anp_window_requestFullScreen(NPP instance)
-{
-  nsNPAPIPluginInstance* inst = static_cast<nsNPAPIPluginInstance*>(instance->ndata);
-
-  RefPtr<nsPluginInstanceOwner> owner = inst->GetOwner();
-  if (!owner) {
-    return;
-  }
-
-  owner->RequestFullScreen();
-}
-
-void
-anp_window_exitFullScreen(NPP instance)
-{
-  nsNPAPIPluginInstance* inst = static_cast<nsNPAPIPluginInstance*>(instance->ndata);
-
-  RefPtr<nsPluginInstanceOwner> owner = inst->GetOwner();
-  if (!owner) {
-    return;
-  }
-
-  owner->ExitFullScreen();
-}
-
-void
-anp_window_requestCenterFitZoom(NPP instance)
-{
-  NOT_IMPLEMENTED();
-}
-
-ANPRectI
-anp_window_visibleRect(NPP instance)
-{
-  ANPRectI rect = { 0, 0, 0, 0 };
-
-  nsNPAPIPluginInstance* pinst = static_cast<nsNPAPIPluginInstance*>(instance->ndata);
-
-  nsIntSize currentSize = pinst->CurrentSize();
-  rect.left = rect.top = 0;
-  rect.right = currentSize.width;
-  rect.bottom = currentSize.height;
-
-  return rect;
-}
-
-void anp_window_requestFullScreenOrientation(NPP instance, ANPScreenOrientation orientation)
-{
-  short newOrientation;
-
-  // Convert to the ActivityInfo equivalent
-  switch (orientation) {
-    case kFixedLandscape_ANPScreenOrientation:
-      newOrientation = eScreenOrientation_LandscapePrimary;
-      break;
-    case kFixedPortrait_ANPScreenOrientation:
-      newOrientation = eScreenOrientation_PortraitPrimary;
-      break;
-    case kLandscape_ANPScreenOrientation:
-      newOrientation = eScreenOrientation_LandscapePrimary |
-                       eScreenOrientation_LandscapeSecondary;
-      break;
-    case kPortrait_ANPScreenOrientation:
-      newOrientation = eScreenOrientation_PortraitPrimary |
-                       eScreenOrientation_PortraitSecondary;
-      break;
-    default:
-      newOrientation = eScreenOrientation_None;
-      break;
-  }
-
-  nsNPAPIPluginInstance* pinst = static_cast<nsNPAPIPluginInstance*>(instance->ndata);
-  pinst->SetFullScreenOrientation(newOrientation);
-}
-
-void InitWindowInterface(ANPWindowInterfaceV0 *i) {
-  _assert(i->inSize == sizeof(*i));
-  ASSIGN(i, setVisibleRects);
-  ASSIGN(i, clearVisibleRects);
-  ASSIGN(i, showKeyboard);
-  ASSIGN(i, requestFullScreen);
-  ASSIGN(i, exitFullScreen);
-  ASSIGN(i, requestCenterFitZoom);
-}
-
-void InitWindowInterfaceV2(ANPWindowInterfaceV2 *i) {
-  _assert(i->inSize == sizeof(*i));
-  ASSIGN(i, setVisibleRects);
-  ASSIGN(i, clearVisibleRects);
-  ASSIGN(i, showKeyboard);
-  ASSIGN(i, requestFullScreen);
-  ASSIGN(i, exitFullScreen);
-  ASSIGN(i, requestCenterFitZoom);
-  ASSIGN(i, visibleRect);
-  ASSIGN(i, requestFullScreenOrientation);
-}
deleted file mode 100644
--- a/dom/plugins/base/android/android_npapi.h
+++ /dev/null
@@ -1,1027 +0,0 @@
-/*
- * Copyright 2009, The Android Open Source Project
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *  * Redistributions of source code must retain the above copyright
- *    notice, this list of conditions and the following disclaimer.
- *  * Redistributions in binary form must reproduce the above copyright
- *    notice, this list of conditions and the following disclaimer in the
- *    documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-/*  Defines the android-specific types and functions as part of npapi
-
-    In particular, defines the window and event types that are passed to
-    NPN_GetValue, NPP_SetWindow and NPP_HandleEvent.
-
-    To minimize what native libraries the plugin links against, some
-    functionality is provided via function-ptrs (e.g. time, sound)
- */
-
-#ifndef android_npapi_H
-#define android_npapi_H
-
-#include <stdint.h>
-#include <jni.h>
-#include "npapi.h"
-#include "GLDefs.h"
-
-///////////////////////////////////////////////////////////////////////////////
-// General types
-
-enum ANPBitmapFormats {
-    kUnknown_ANPBitmapFormat    = 0,
-    kRGBA_8888_ANPBitmapFormat  = 1,
-    kRGB_565_ANPBitmapFormat    = 2
-};
-typedef int32_t ANPBitmapFormat;
-
-struct ANPPixelPacking {
-    uint8_t AShift;
-    uint8_t ABits;
-    uint8_t RShift;
-    uint8_t RBits;
-    uint8_t GShift;
-    uint8_t GBits;
-    uint8_t BShift;
-    uint8_t BBits;
-};
-
-struct ANPBitmap {
-    void*           baseAddr;
-    ANPBitmapFormat format;
-    int32_t         width;
-    int32_t         height;
-    int32_t         rowBytes;
-};
-
-struct ANPRectF {
-    float   left;
-    float   top;
-    float   right;
-    float   bottom;
-};
-
-struct ANPRectI {
-    int32_t left;
-    int32_t top;
-    int32_t right;
-    int32_t bottom;
-};
-
-struct ANPCanvas;
-struct ANPMatrix;
-struct ANPPaint;
-struct ANPPath;
-struct ANPTypeface;
-
-///////////////////////////////////////////////////////////////////////////////
-// NPN_GetValue
-
-/** queries for a specific ANPInterface.
-
-    Maybe called with NULL for the NPP instance
-
-    NPN_GetValue(inst, interface_enum, ANPInterface*)
- */
-#define kLogInterfaceV0_ANPGetValue         ((NPNVariable)1000)
-#define kAudioTrackInterfaceV0_ANPGetValue  ((NPNVariable)1001)
-#define kCanvasInterfaceV0_ANPGetValue      ((NPNVariable)1002)
-#define kMatrixInterfaceV0_ANPGetValue      ((NPNVariable)1003)
-#define kPaintInterfaceV0_ANPGetValue       ((NPNVariable)1004)
-#define kPathInterfaceV0_ANPGetValue        ((NPNVariable)1005)
-#define kTypefaceInterfaceV0_ANPGetValue    ((NPNVariable)1006)
-#define kWindowInterfaceV0_ANPGetValue      ((NPNVariable)1007)
-#define kBitmapInterfaceV0_ANPGetValue      ((NPNVariable)1008)
-#define kSurfaceInterfaceV0_ANPGetValue     ((NPNVariable)1009)
-#define kSystemInterfaceV0_ANPGetValue      ((NPNVariable)1010)
-#define kEventInterfaceV0_ANPGetValue       ((NPNVariable)1011)
-
-#define kAudioTrackInterfaceV1_ANPGetValue  ((NPNVariable)1012)
-#define kOpenGLInterfaceV0_ANPGetValue      ((NPNVariable)1013)
-#define kWindowInterfaceV1_ANPGetValue      ((NPNVariable)1014)
-#define kVideoInterfaceV0_ANPGetValue       ((NPNVariable)1015)
-#define kSystemInterfaceV1_ANPGetValue      ((NPNVariable)1016)
-#define kSystemInterfaceV2_ANPGetValue      ((NPNVariable)1017)
-#define kWindowInterfaceV2_ANPGetValue      ((NPNVariable)1018)
-#define kNativeWindowInterfaceV0_ANPGetValue ((NPNVariable)1019)
-#define kVideoInterfaceV1_ANPGetValue       ((NPNVariable)1020)
-
-/** queries for the drawing models supported on this device.
-
-    NPN_GetValue(inst, kSupportedDrawingModel_ANPGetValue, uint32_t* bits)
- */
-#define kSupportedDrawingModel_ANPGetValue  ((NPNVariable)2000)
-
-/** queries for the context (android.content.Context) of the plugin. If no
-    instance is specified the application's context is returned. If the instance
-    is given then the context returned is identical to the context used to
-    create the webview in which that instance resides.
-
-    NOTE: Holding onto a non-application context after your instance has been
-    destroyed will cause a memory leak.  Refer to the android documentation to
-    determine what context is best suited for your particular scenario.
-
-    NPN_GetValue(inst, kJavaContext_ANPGetValue, jobject context)
- */
-#define kJavaContext_ANPGetValue            ((NPNVariable)2001)
-
-///////////////////////////////////////////////////////////////////////////////
-// NPN_SetValue
-
-/** Request to set the drawing model. SetValue will return false if the drawing
-    model is not supported or has insufficient information for configuration.
-
-    NPN_SetValue(inst, kRequestDrawingModel_ANPSetValue, (void*)foo_ANPDrawingModel)
- */
-#define kRequestDrawingModel_ANPSetValue    ((NPPVariable)1000)
-
-/** These are used as bitfields in ANPSupportedDrawingModels_EnumValue,
-    and as-is in ANPRequestDrawingModel_EnumValue. The drawing model determines
-    how to interpret the ANPDrawingContext provided in the Draw event and how
-    to interpret the NPWindow->window field.
- */
-enum ANPDrawingModels {
-    /** Draw into a bitmap from the browser thread in response to a Draw event.
-        NPWindow->window is reserved (ignore)
-     */
-    kBitmap_ANPDrawingModel  = 1 << 0,
-    /** Draw into a surface (e.g. raster, openGL, etc.) using the Java surface
-        interface. When this model is used the browser will invoke the Java
-        class specified in the plugin's apk manifest. From that class the browser
-        will invoke the appropriate method to return an an instance of a android
-        Java View. The instance is then embedded in the html. The plugin can then
-        manipulate the view as it would any normal Java View in android.
-
-        Unlike the bitmap model, a surface model is opaque so no html content
-        behind the plugin will be  visible. Unless the plugin needs to be
-        transparent the surface model should be chosen over the bitmap model as
-        it will have better performance.
-
-        Further, a plugin can manipulate some surfaces in native code using the
-        ANPSurfaceInterface.  This interface can be used to manipulate Java
-        objects that extend Surface.class by allowing them to access the
-        surface's underlying bitmap in native code.  For instance, if a raster
-        surface is used the plugin can lock, draw directly into the bitmap, and
-        unlock the surface in native code without making JNI calls to the Java
-        surface object.
-     */
-    kSurface_ANPDrawingModel = 1 << 1,
-    kOpenGL_ANPDrawingModel  = 1 << 2,
-};
-typedef int32_t ANPDrawingModel;
-
-/** Request to receive/disable events. If the pointer is NULL then all flags will
-    be disabled. Otherwise, the event type will be enabled iff its corresponding
-    bit in the EventFlags bit field is set.
-
-    NPN_SetValue(inst, ANPAcceptEvents, (void*)EventFlags)
- */
-#define kAcceptEvents_ANPSetValue           ((NPPVariable)1001)
-
-/** The EventFlags are a set of bits used to determine which types of events the
-    plugin wishes to receive. For example, if the value is 0x03 then both key
-    and touch events will be provided to the plugin.
- */
-enum ANPEventFlag {
-    kKey_ANPEventFlag               = 0x01,
-    kTouch_ANPEventFlag             = 0x02,
-};
-typedef uint32_t ANPEventFlags;
-
-///////////////////////////////////////////////////////////////////////////////
-// NPP_GetValue
-
-/** Requests that the plugin return a java surface to be displayed. This will
-    only be used if the plugin has choosen the kSurface_ANPDrawingModel.
-
-    NPP_GetValue(inst, kJavaSurface_ANPGetValue, jobject surface)
- */
-#define kJavaSurface_ANPGetValue            ((NPPVariable)2000)
-
-
-///////////////////////////////////////////////////////////////////////////////
-// ANDROID INTERFACE DEFINITIONS
-
-/** Interfaces provide additional functionality to the plugin via function ptrs.
-    Once an interface is retrieved, it is valid for the lifetime of the plugin
-    (just like browserfuncs).
-
-    All ANPInterfaces begin with an inSize field, which must be set by the
-    caller (plugin) with the number of bytes allocated for the interface.
-    e.g. SomeInterface si; si.inSize = sizeof(si); browser->getvalue(..., &si);
- */
-struct ANPInterface {
-    uint32_t    inSize;     // size (in bytes) of this struct
-};
-
-enum ANPLogTypes {
-    kError_ANPLogType   = 0,    // error
-    kWarning_ANPLogType = 1,    // warning
-    kDebug_ANPLogType   = 2     // debug only (informational)
-};
-typedef int32_t ANPLogType;
-
-struct ANPLogInterfaceV0 : ANPInterface {
-    /** dumps printf messages to the log file
-        e.g. interface->log(instance, kWarning_ANPLogType, "value is %d", value);
-     */
-    void (*log)(ANPLogType, const char format[], ...);
-};
-
-/** ANPColor is always defined to have the same packing on all platforms, and
-    it is always unpremultiplied.
-
-    This is in contrast to 32bit format(s) in bitmaps, which are premultiplied,
-    and their packing may vary depending on the platform, hence the need for
-    ANPBitmapInterface::getPixelPacking()
- */
-typedef uint32_t ANPColor;
-#define ANPColor_ASHIFT     24
-#define ANPColor_RSHIFT     16
-#define ANPColor_GSHIFT     8
-#define ANPColor_BSHIFT     0
-#define ANP_MAKE_COLOR(a, r, g, b)  \
-                   (((a) << ANPColor_ASHIFT) |  \
-                    ((r) << ANPColor_RSHIFT) |  \
-                    ((g) << ANPColor_GSHIFT) |  \
-                    ((b) << ANPColor_BSHIFT))
-
-enum ANPPaintFlag {
-    kAntiAlias_ANPPaintFlag         = 1 << 0,
-    kFilterBitmap_ANPPaintFlag      = 1 << 1,
-    kDither_ANPPaintFlag            = 1 << 2,
-    kUnderlineText_ANPPaintFlag     = 1 << 3,
-    kStrikeThruText_ANPPaintFlag    = 1 << 4,
-    kFakeBoldText_ANPPaintFlag      = 1 << 5,
-};
-typedef uint32_t ANPPaintFlags;
-
-enum ANPPaintStyles {
-    kFill_ANPPaintStyle             = 0,
-    kStroke_ANPPaintStyle           = 1,
-    kFillAndStroke_ANPPaintStyle    = 2
-};
-typedef int32_t ANPPaintStyle;
-
-enum ANPPaintCaps {
-    kButt_ANPPaintCap   = 0,
-    kRound_ANPPaintCap  = 1,
-    kSquare_ANPPaintCap = 2
-};
-typedef int32_t ANPPaintCap;
-
-enum ANPPaintJoins {
-    kMiter_ANPPaintJoin = 0,
-    kRound_ANPPaintJoin = 1,
-    kBevel_ANPPaintJoin = 2
-};
-typedef int32_t ANPPaintJoin;
-
-enum ANPPaintAligns {
-    kLeft_ANPPaintAlign     = 0,
-    kCenter_ANPPaintAlign   = 1,
-    kRight_ANPPaintAlign    = 2
-};
-typedef int32_t ANPPaintAlign;
-
-enum ANPTextEncodings {
-    kUTF8_ANPTextEncoding   = 0,
-    kUTF16_ANPTextEncoding  = 1,
-};
-typedef int32_t ANPTextEncoding;
-
-enum ANPTypefaceStyles {
-    kBold_ANPTypefaceStyle      = 1 << 0,
-    kItalic_ANPTypefaceStyle    = 1 << 1
-};
-typedef uint32_t ANPTypefaceStyle;
-
-typedef uint32_t ANPFontTableTag;
-
-struct ANPFontMetrics {
-    /** The greatest distance above the baseline for any glyph (will be <= 0) */
-    float   fTop;
-    /** The recommended distance above the baseline (will be <= 0) */
-    float   fAscent;
-    /** The recommended distance below the baseline (will be >= 0) */
-    float   fDescent;
-    /** The greatest distance below the baseline for any glyph (will be >= 0) */
-    float   fBottom;
-    /** The recommended distance to add between lines of text (will be >= 0) */
-    float   fLeading;
-};
-
-struct ANPTypefaceInterfaceV0 : ANPInterface {
-    /** Return a new reference to the typeface that most closely matches the
-        requested name and style. Pass null as the name to return
-        the default font for the requested style. Will never return null
-
-        The 5 generic font names "serif", "sans-serif", "monospace", "cursive",
-        "fantasy" are recognized, and will be mapped to their logical font
-        automatically by this call.
-
-        @param name     May be NULL. The name of the font family.
-        @param style    The style (normal, bold, italic) of the typeface.
-        @return reference to the closest-matching typeface. Caller must call
-                unref() when they are done with the typeface.
-     */
-    ANPTypeface* (*createFromName)(const char name[], ANPTypefaceStyle);
-
-    /** Return a new reference to the typeface that most closely matches the
-        requested typeface and specified Style. Use this call if you want to
-        pick a new style from the same family of the existing typeface.
-        If family is NULL, this selects from the default font's family.
-
-        @param family  May be NULL. The name of the existing type face.
-        @param s       The style (normal, bold, italic) of the type face.
-        @return reference to the closest-matching typeface. Call must call
-                unref() when they are done.
-     */
-    ANPTypeface* (*createFromTypeface)(const ANPTypeface* family,
-                                       ANPTypefaceStyle);
-
-    /** Return the owner count of the typeface. A newly created typeface has an
-        owner count of 1. When the owner count is reaches 0, the typeface is
-        deleted.
-     */
-    int32_t (*getRefCount)(const ANPTypeface*);
-
-    /** Increment the owner count on the typeface
-     */
-    void (*ref)(ANPTypeface*);
-
-    /** Decrement the owner count on the typeface. When the count goes to 0,
-        the typeface is deleted.
-     */
-    void (*unref)(ANPTypeface*);
-
-    /** Return the style bits for the specified typeface
-     */
-    ANPTypefaceStyle (*getStyle)(const ANPTypeface*);
-
-    /** Some fonts are stored in files. If that is true for the fontID, then
-        this returns the byte length of the full file path. If path is not null,
-        then the full path is copied into path (allocated by the caller), up to
-        length bytes. If index is not null, then it is set to the truetype
-        collection index for this font, or 0 if the font is not in a collection.
-
-        Note: getFontPath does not assume that path is a null-terminated string,
-        so when it succeeds, it only copies the bytes of the file name and
-        nothing else (i.e. it copies exactly the number of bytes returned by the
-        function. If the caller wants to treat path[] as a C string, it must be
-        sure that it is allocated at least 1 byte larger than the returned size,
-        and it must copy in the terminating 0.
-
-        If the fontID does not correspond to a file, then the function returns
-        0, and the path and index parameters are ignored.
-
-        @param fontID  The font whose file name is being queried
-        @param path    Either NULL, or storage for receiving up to length bytes
-                       of the font's file name. Allocated by the caller.
-        @param length  The maximum space allocated in path (by the caller).
-                       Ignored if path is NULL.
-        @param index   Either NULL, or receives the TTC index for this font.
-                       If the font is not a TTC, then will be set to 0.
-        @return The byte length of th font's file name, or 0 if the font is not
-                baked by a file.
-     */
-    int32_t (*getFontPath)(const ANPTypeface*, char path[], int32_t length,
-                           int32_t* index);
-
-    /** Return a UTF8 encoded path name for the font directory, or NULL if not
-        supported. If returned, this string address will be valid for the life
-        of the plugin instance. It will always end with a '/' character.
-     */
-    const char* (*getFontDirectoryPath)();
-};
-
-struct ANPPaintInterfaceV0 : ANPInterface {
-    /** Return a new paint object, which holds all of the color and style
-        attributes that affect how things (geometry, text, bitmaps) are drawn
-        in a ANPCanvas.
-
-        The paint that is returned is not tied to any particular plugin
-        instance, but it must only be accessed from one thread at a time.
-     */
-    ANPPaint*   (*newPaint)();
-    void        (*deletePaint)(ANPPaint*);
-
-    ANPPaintFlags (*getFlags)(const ANPPaint*);
-    void        (*setFlags)(ANPPaint*, ANPPaintFlags);
-
-    ANPColor    (*getColor)(const ANPPaint*);
-    void        (*setColor)(ANPPaint*, ANPColor);
-
-    ANPPaintStyle (*getStyle)(const ANPPaint*);
-    void        (*setStyle)(ANPPaint*, ANPPaintStyle);
-
-    float       (*getStrokeWidth)(const ANPPaint*);
-    float       (*getStrokeMiter)(const ANPPaint*);
-    ANPPaintCap (*getStrokeCap)(const ANPPaint*);
-    ANPPaintJoin (*getStrokeJoin)(const ANPPaint*);
-    void        (*setStrokeWidth)(ANPPaint*, float);
-    void        (*setStrokeMiter)(ANPPaint*, float);
-    void        (*setStrokeCap)(ANPPaint*, ANPPaintCap);
-    void        (*setStrokeJoin)(ANPPaint*, ANPPaintJoin);
-
-    ANPTextEncoding (*getTextEncoding)(const ANPPaint*);
-    ANPPaintAlign (*getTextAlign)(const ANPPaint*);
-    float       (*getTextSize)(const ANPPaint*);
-    float       (*getTextScaleX)(const ANPPaint*);
-    float       (*getTextSkewX)(const ANPPaint*);
-    void        (*setTextEncoding)(ANPPaint*, ANPTextEncoding);
-    void        (*setTextAlign)(ANPPaint*, ANPPaintAlign);
-    void        (*setTextSize)(ANPPaint*, float);
-    void        (*setTextScaleX)(ANPPaint*, float);
-    void        (*setTextSkewX)(ANPPaint*, float);
-
-    /** Return the typeface ine paint, or null if there is none. This does not
-        modify the owner count of the returned typeface.
-     */
-    ANPTypeface* (*getTypeface)(const ANPPaint*);
-
-    /** Set the paint's typeface. If the paint already had a non-null typeface,
-        its owner count is decremented. If the new typeface is non-null, its
-        owner count is incremented.
-     */
-    void (*setTypeface)(ANPPaint*, ANPTypeface*);
-
-    /** Return the width of the text. If bounds is not null, return the bounds
-        of the text in that rectangle.
-     */
-    float (*measureText)(ANPPaint*, const void* text, uint32_t byteLength,
-                         ANPRectF* bounds);
-
-    /** Return the number of unichars specifed by the text.
-        If widths is not null, returns the array of advance widths for each
-            unichar.
-        If bounds is not null, returns the array of bounds for each unichar.
-     */
-    int (*getTextWidths)(ANPPaint*, const void* text, uint32_t byteLength,
-                         float widths[], ANPRectF bounds[]);
-
-    /** Return in metrics the spacing values for text, respecting the paint's
-        typeface and pointsize, and return the spacing between lines
-        (descent - ascent + leading). If metrics is NULL, it will be ignored.
-     */
-    float (*getFontMetrics)(ANPPaint*, ANPFontMetrics* metrics);
-};
-
-struct ANPCanvasInterfaceV0 : ANPInterface {
-    /** Return a canvas that will draw into the specified bitmap. Note: the
-        canvas copies the fields of the bitmap, so it need not persist after
-        this call, but the canvas DOES point to the same pixel memory that the
-        bitmap did, so the canvas should not be used after that pixel memory
-        goes out of scope. In the case of creating a canvas to draw into the
-        pixels provided by kDraw_ANPEventType, those pixels are only while
-        handling that event.
-
-        The canvas that is returned is not tied to any particular plugin
-        instance, but it must only be accessed from one thread at a time.
-     */
-    ANPCanvas*  (*newCanvas)(const ANPBitmap*);
-    void        (*deleteCanvas)(ANPCanvas*);
-
-    void        (*save)(ANPCanvas*);
-    void        (*restore)(ANPCanvas*);
-    void        (*translate)(ANPCanvas*, float tx, float ty);
-    void        (*scale)(ANPCanvas*, float sx, float sy);
-    void        (*rotate)(ANPCanvas*, float degrees);
-    void        (*skew)(ANPCanvas*, float kx, float ky);
-    void        (*concat)(ANPCanvas*, const ANPMatrix*);
-    void        (*clipRect)(ANPCanvas*, const ANPRectF*);
-    void        (*clipPath)(ANPCanvas*, const ANPPath*);
-
-    /** Return the current matrix on the canvas
-     */
-    void        (*getTotalMatrix)(ANPCanvas*, ANPMatrix*);
-    /** Return the current clip bounds in local coordinates, expanding it to
-        account for antialiasing edge effects if aa is true. If the
-        current clip is empty, return false and ignore the bounds argument.
-     */
-    bool        (*getLocalClipBounds)(ANPCanvas*, ANPRectF* bounds, bool aa);
-    /** Return the current clip bounds in device coordinates in bounds. If the
-        current clip is empty, return false and ignore the bounds argument.
-     */
-    bool        (*getDeviceClipBounds)(ANPCanvas*, ANPRectI* bounds);
-
-    void        (*drawColor)(ANPCanvas*, ANPColor);
-    void        (*drawPaint)(ANPCanvas*, const ANPPaint*);
-    void        (*drawLine)(ANPCanvas*, float x0, float y0, float x1, float y1,
-                            const ANPPaint*);
-    void        (*drawRect)(ANPCanvas*, const ANPRectF*, const ANPPaint*);
-    void        (*drawOval)(ANPCanvas*, const ANPRectF*, const ANPPaint*);
-    void        (*drawPath)(ANPCanvas*, const ANPPath*, const ANPPaint*);
-    void        (*drawText)(ANPCanvas*, const void* text, uint32_t byteLength,
-                            float x, float y, const ANPPaint*);
-    void       (*drawPosText)(ANPCanvas*, const void* text, uint32_t byteLength,
-                               const float xy[], const ANPPaint*);
-    void        (*drawBitmap)(ANPCanvas*, const ANPBitmap*, float x, float y,
-                              const ANPPaint*);
-    void        (*drawBitmapRect)(ANPCanvas*, const ANPBitmap*,
-                                  const ANPRectI* src, const ANPRectF* dst,
-                                  const ANPPaint*);
-};
-
-struct ANPWindowInterfaceV0 : ANPInterface {
-    /** Registers a set of rectangles that the plugin would like to keep on
-        screen. The rectangles are listed in order of priority with the highest
-        priority rectangle in location rects[0].  The browser will attempt to keep
-        as many of the rectangles on screen as possible and will scroll them into
-        view in response to the invocation of this method and other various events.
-        The count specifies how many rectangles are in the array. If the count is
-        zero it signals the browser that any existing rectangles should be cleared
-        and no rectangles will be tracked.
-     */
-    void (*setVisibleRects)(NPP instance, const ANPRectI rects[], int32_t count);
-    /** Clears any rectangles that are being tracked as a result of a call to
-        setVisibleRects. This call is equivalent to setVisibleRect(inst, NULL, 0).
-     */
-    void    (*clearVisibleRects)(NPP instance);
-    /** Given a boolean value of true the device will be requested to provide
-        a keyboard. A value of false will result in a request to hide the
-        keyboard. Further, the on-screen keyboard will not be displayed if a
-        physical keyboard is active.
-     */
-    void    (*showKeyboard)(NPP instance, bool value);
-    /** Called when a plugin wishes to enter into full screen mode. The plugin's
-        Java class (defined in the plugin's apk manifest) will be called
-        asynchronously to provide a View object to be displayed full screen.
-     */
-    void    (*requestFullScreen)(NPP instance);
-    /** Called when a plugin wishes to exit from full screen mode. As a result,
-        the plugin's full screen view will be discarded by the view system.
-     */
-    void    (*exitFullScreen)(NPP instance);
-    /** Called when a plugin wishes to be zoomed and centered in the current view.
-     */
-    void    (*requestCenterFitZoom)(NPP instance);
-};
-
-enum ANPScreenOrientations {
-    /** No preference specified: let the system decide the best orientation.
-     */
-    kDefault_ANPScreenOrientation        = 0,
-    /** Would like to have the screen in a landscape orientation, but it will
-        not allow for 180 degree rotations.
-     */
-    kFixedLandscape_ANPScreenOrientation = 1,
-    /** Would like to have the screen in a portrait orientation, but it will
-        not allow for 180 degree rotations.
-     */
-    kFixedPortrait_ANPScreenOrientation  = 2,
-    /** Would like to have the screen in landscape orientation, but can use the
-        sensor to change which direction the screen is facing.
-     */
-    kLandscape_ANPScreenOrientation      = 3,
-    /** Would like to have the screen in portrait orientation, but can use the
-        sensor to change which direction the screen is facing.
-     */
-    kPortrait_ANPScreenOrientation       = 4
-};
-
-typedef int32_t ANPScreenOrientation;
-
-struct ANPWindowInterfaceV2 : ANPWindowInterfaceV0 {
-    /** Returns a rectangle representing the visible area of the plugin on
-        screen. The coordinates are relative to the size of the plugin in the
-        document and therefore will never be negative or exceed the plugin's size.
-     */
-    ANPRectI (*visibleRect)(NPP instance);
-
-    /** Called when the plugin wants to specify a particular screen orientation
-        when entering into full screen mode. The orientation must be set prior
-        to entering into full screen.  After entering full screen any subsequent
-        changes will be updated the next time the plugin goes full screen.
-     */
-    void (*requestFullScreenOrientation)(NPP instance, ANPScreenOrientation orientation);
-};
-
-///////////////////////////////////////////////////////////////////////////////
-
-enum ANPSampleFormats {
-    kUnknown_ANPSamleFormat     = 0,
-    kPCM16Bit_ANPSampleFormat   = 1,
-    kPCM8Bit_ANPSampleFormat    = 2
-};
-typedef int32_t ANPSampleFormat;
-
-/** The audio buffer is passed to the callback proc to request more samples.
-    It is owned by the system, and the callback may read it, but should not
-    maintain a pointer to it outside of the scope of the callback proc.
- */
-struct ANPAudioBuffer {
-    // RO - repeat what was specified in newTrack()
-    int32_t     channelCount;
-    // RO - repeat what was specified in newTrack()
-    ANPSampleFormat  format;
-    /** This buffer is owned by the caller. Inside the callback proc, up to
-        "size" bytes of sample data should be written into this buffer. The
-        address is only valid for the scope of a single invocation of the
-        callback proc.
-     */
-    void*       bufferData;
-    /** On input, specifies the maximum number of bytes that can be written
-        to "bufferData". On output, specifies the actual number of bytes that
-        the callback proc wrote into "bufferData".
-     */
-    uint32_t    size;
-};
-
-enum ANPAudioEvents {
-    /** This event is passed to the callback proc when the audio-track needs
-        more sample data written to the provided buffer parameter.
-     */
-    kMoreData_ANPAudioEvent = 0,
-    /** This event is passed to the callback proc if the audio system runs out
-        of sample data. In this event, no buffer parameter will be specified
-        (i.e. NULL will be passed to the 3rd parameter).
-     */
-    kUnderRun_ANPAudioEvent = 1
-};
-typedef int32_t ANPAudioEvent;
-
-/** Called to feed sample data to the track. This will be called in a separate
-    thread. However, you may call trackStop() from the callback (but you
-    cannot delete the track).
-
-    For example, when you have written the last chunk of sample data, you can
-    immediately call trackStop(). This will take effect after the current
-    buffer has been played.
-
-    The "user" parameter is the same value that was passed to newTrack()
- */
-typedef void (*ANPAudioCallbackProc)(ANPAudioEvent event, void* user,
-                                     ANPAudioBuffer* buffer);
-
-struct ANPAudioTrack;   // abstract type for audio tracks
-
-struct ANPAudioTrackInterfaceV0 : ANPInterface {
-    /** Create a new audio track, or NULL on failure. The track is initially in
-        the stopped state and therefore ANPAudioCallbackProc will not be called
-        until the track is started.
-     */
-    ANPAudioTrack*  (*newTrack)(uint32_t sampleRate,    // sampling rate in Hz
-                                ANPSampleFormat,
-                                int channelCount,       // MONO=1, STEREO=2
-                                ANPAudioCallbackProc,
-                                void* user);
-    /** Deletes a track that was created using newTrack.  The track can be
-        deleted in any state and it waits for the ANPAudioCallbackProc thread
-        to exit before returning.
-     */
-    void (*deleteTrack)(ANPAudioTrack*);
-
-    void (*start)(ANPAudioTrack*);
-    void (*pause)(ANPAudioTrack*);
-    void (*stop)(ANPAudioTrack*);
-    /** Returns true if the track is not playing (e.g. pause or stop was called,
-        or start was never called.
-     */
-    bool (*isStopped)(ANPAudioTrack*);
-};
-
-struct ANPAudioTrackInterfaceV1 : ANPAudioTrackInterfaceV0 {
-    /** Returns the track's latency in milliseconds. */
-    uint32_t (*trackLatency)(ANPAudioTrack*);
-};
-
-
-///////////////////////////////////////////////////////////////////////////////
-// DEFINITION OF VALUES PASSED THROUGH NPP_HandleEvent
-
-enum ANPEventTypes {
-    kNull_ANPEventType          = 0,
-    kKey_ANPEventType           = 1,
-    /** Mouse events are triggered by either clicking with the navigational pad
-        or by tapping the touchscreen (if the kDown_ANPTouchAction is handled by
-        the plugin then no mouse event is generated).  The kKey_ANPEventFlag has
-        to be set to true in order to receive these events.
-     */
-    kMouse_ANPEventType         = 2,
-    /** Touch events are generated when the user touches on the screen. The
-        kTouch_ANPEventFlag has to be set to true in order to receive these
-        events.
-     */
-    kTouch_ANPEventType         = 3,
-    /** Only triggered by a plugin using the kBitmap_ANPDrawingModel. This event
-        signals that the plugin needs to redraw itself into the provided bitmap.
-     */
-    kDraw_ANPEventType          = 4,
-    kLifecycle_ANPEventType     = 5,
-
-    /** This event type is completely defined by the plugin.
-        When creating an event, the caller must always set the first
-        two fields, the remaining data is optional.
-            ANPEvent evt;
-            evt.inSize = sizeof(ANPEvent);
-            evt.eventType = kCustom_ANPEventType
-            // other data slots are optional
-            evt.other[] = ...;
-        To post a copy of the event, call
-            eventInterface->postEvent(myNPPInstance, &evt);
-        That call makes a copy of the event struct, and post that on the event
-        queue for the plugin.
-     */
-    kCustom_ANPEventType   = 6,
-};
-typedef int32_t ANPEventType;
-
-enum ANPKeyActions {
-    kDown_ANPKeyAction  = 0,
-    kUp_ANPKeyAction    = 1,
-};
-typedef int32_t ANPKeyAction;
-
-#include "ANPKeyCodes.h"
-typedef int32_t ANPKeyCode;
-
-enum ANPKeyModifiers {
-    kAlt_ANPKeyModifier     = 1 << 0,
-    kShift_ANPKeyModifier   = 1 << 1,
-};
-// bit-field containing some number of ANPKeyModifier bits
-typedef uint32_t ANPKeyModifier;
-
-enum ANPMouseActions {
-    kDown_ANPMouseAction  = 0,
-    kUp_ANPMouseAction    = 1,
-};
-typedef int32_t ANPMouseAction;
-
-enum ANPTouchActions {
-    /** This occurs when the user first touches on the screen. As such, this
-        action will always occur prior to any of the other touch actions. If
-        the plugin chooses to not handle this action then no other events
-        related to that particular touch gesture will be generated.
-     */
-    kDown_ANPTouchAction        = 0,
-    kUp_ANPTouchAction          = 1,
-    kMove_ANPTouchAction        = 2,
-    kCancel_ANPTouchAction      = 3,
-    // The web view will ignore the return value from the following actions
-    kLongPress_ANPTouchAction   = 4,
-    kDoubleTap_ANPTouchAction   = 5,
-};
-typedef int32_t ANPTouchAction;
-
-enum ANPLifecycleActions {
-    /** The web view containing this plugin has been paused.  See documentation
-        on the android activity lifecycle for more information.
-     */
-    kPause_ANPLifecycleAction           = 0,
-    /** The web view containing this plugin has been resumed. See documentation
-        on the android activity lifecycle for more information.
-     */
-    kResume_ANPLifecycleAction          = 1,
-    /** The plugin has focus and is now the recipient of input events (e.g. key,
-        touch, etc.)
-     */
-    kGainFocus_ANPLifecycleAction       = 2,
-    /** The plugin has lost focus and will not receive any input events until it
-        regains focus. This event is always preceded by a GainFocus action.
-     */
-    kLoseFocus_ANPLifecycleAction       = 3,
-    /** The browser is running low on available memory and is requesting that
-        the plugin free any unused/inactive resources to prevent a performance
-        degradation.
-     */
-    kFreeMemory_ANPLifecycleAction      = 4,
-    /** The page has finished loading. This happens when the page's top level
-        frame reports that it has completed loading.
-     */
-    kOnLoad_ANPLifecycleAction          = 5,
-    /** The browser is honoring the plugin's request to go full screen. Upon
-        returning from this event the browser will resize the plugin's java
-        surface to full-screen coordinates.
-     */
-    kEnterFullScreen_ANPLifecycleAction = 6,
-    /** The browser has exited from full screen mode. Immediately prior to
-        sending this event the browser has resized the plugin's java surface to
-        its original coordinates.
-     */
-    kExitFullScreen_ANPLifecycleAction  = 7,
-    /** The plugin is visible to the user on the screen. This event will always
-        occur after a kOffScreen_ANPLifecycleAction event.
-     */
-    kOnScreen_ANPLifecycleAction        = 8,
-    /** The plugin is no longer visible to the user on the screen. This event
-        will always occur prior to an kOnScreen_ANPLifecycleAction event.
-     */
-    kOffScreen_ANPLifecycleAction       = 9,
-};
-typedef uint32_t ANPLifecycleAction;
-
-/* This is what is passed to NPP_HandleEvent() */
-struct ANPEvent {
-    uint32_t        inSize;  // size of this struct in bytes
-    ANPEventType    eventType;
-    // use based on the value in eventType
-    union {
-        struct {
-            ANPKeyAction    action;
-            ANPKeyCode      nativeCode;
-            int32_t         virtualCode;    // windows virtual key code
-            ANPKeyModifier  modifiers;
-            int32_t         repeatCount;    // 0 for initial down (or up)
-            int32_t         unichar;        // 0 if there is no value
-        } key;
-        struct {
-            ANPMouseAction  action;
-            int32_t         x;  // relative to your "window" (0...width)
-            int32_t         y;  // relative to your "window" (0...height)
-        } mouse;
-        struct {
-            ANPTouchAction  action;
-            ANPKeyModifier  modifiers;
-            int32_t         x;  // relative to your "window" (0...width)
-            int32_t         y;  // relative to your "window" (0...height)
-        } touch;
-        struct {
-            ANPLifecycleAction  action;
-        } lifecycle;
-        struct {
-            ANPDrawingModel model;
-            // relative to (0,0) in top-left of your plugin
-            ANPRectI        clip;
-            // use based on the value in model
-            union {
-                ANPBitmap   bitmap;
-                struct {
-                    int32_t width;
-                    int32_t height;
-                } surfaceSize;
-            } data;
-        } draw;
-    } data;
-};
-
-
-struct ANPEventInterfaceV0 : ANPInterface {
-    /** Post a copy of the specified event to the plugin. The event will be
-        delivered to the plugin in its main thread (the thread that receives
-        other ANPEvents). If, after posting before delivery, the NPP instance
-        is torn down, the event will be discarded.
-     */
-    void (*postEvent)(NPP inst, const ANPEvent* event);
-};
-
-struct ANPSurfaceInterfaceV0 : ANPInterface {
-  /** Locks the surface from manipulation by other threads and provides a bitmap
-        to be written to.  The dirtyRect param specifies which portion of the
-        bitmap will be written to.  If the dirtyRect is NULL then the entire
-        surface will be considered dirty.  If the lock was successful the function
-        will return true and the bitmap will be set to point to a valid bitmap.
-        If not the function will return false and the bitmap will be set to NULL.
-  */
-  bool (*lock)(JNIEnv* env, jobject surface, ANPBitmap* bitmap, ANPRectI* dirtyRect);
-  /** Given a locked surface handle (i.e. result of a successful call to lock)
-        the surface is unlocked and the contents of the bitmap, specifically
-        those inside the dirtyRect are written to the screen.
-  */
-  void (*unlock)(JNIEnv* env, jobject surface);
-};
-
-/**
- * TODO should we not use EGL and GL data types for ABI safety?
- */
-struct ANPTextureInfo {
-    GLuint      textureId;
-    uint32_t    width;
-    uint32_t    height;
-    GLenum      internalFormat;
-};
-
-typedef void* ANPEGLContext;
-
-struct ANPOpenGLInterfaceV0 : ANPInterface {
-    ANPEGLContext (*acquireContext)(NPP instance);
-
-    ANPTextureInfo (*lockTexture)(NPP instance);
-
-    void (*releaseTexture)(NPP instance, const ANPTextureInfo*);
-
-    /**
-     * Invert the contents of the plugin on the y-axis.
-     * default is to not be inverted (i.e. use OpenGL coordinates)
-     */
-    void (*invertPluginContent)(NPP instance, bool isContentInverted);
-};
-
-enum ANPPowerStates {
-    kDefault_ANPPowerState  = 0,
-    kScreenOn_ANPPowerState = 1
-};
-typedef int32_t ANPPowerState;
-
-struct ANPSystemInterfaceV1 : ANPInterface {
-    /** Return the path name for the current Application's plugin data directory,
-        or NULL if not supported
-     */
-    const char* (*getApplicationDataDirectory)();
-
-    /** A helper function to load java classes from the plugin's apk.  The
-        function looks for a class given the fully qualified and null terminated
-        string representing the className. For example,
-
-        const char* className = "com.android.mypackage.MyClass";
-
-        If the class cannot be found or there is a problem loading the class
-        NULL will be returned.
-     */
-    jclass (*loadJavaClass)(NPP instance, const char* className);
-
-    void (*setPowerState)(NPP instance, ANPPowerState powerState);
-};
-
-struct ANPSystemInterfaceV2 : ANPInterface {
-    /** Return the path name for the current Application's plugin data directory,
-        or NULL if not supported. This directory will change depending on whether
-        or not the plugin is found within an incognito tab.
-     */
-    const char* (*getApplicationDataDirectory)(NPP instance);
-
-    // redeclaration of existing features
-    jclass (*loadJavaClass)(NPP instance, const char* className);
-    void (*setPowerState)(NPP instance, ANPPowerState powerState);
-};
-
-typedef void* ANPNativeWindow;
-
-/** Called to notify the plugin that a video frame has been composited by the
-*  browser for display.  This will be called in a separate thread and as such
-*  you cannot call releaseNativeWindow from the callback.
-*
-*  The timestamp is in nanoseconds, and is monotonically increasing.
-*/
-typedef void (*ANPVideoFrameCallbackProc)(ANPNativeWindow* window, int64_t timestamp);
-
-struct ANPVideoInterfaceV1 : ANPInterface {
-
-    /**
-     * Constructs a new native window to be used for rendering video content.
-     *
-     * Subsequent calls will produce new windows, but may also return NULL after
-     * n attempts if the browser has reached it's limit. Further, if the browser
-     * is unable to acquire the window quickly it may also return NULL in order
-     * to not prevent the plugin from executing. A subsequent call will then
-     * return the window if it is avaiable.
-     *
-     * NOTE: The hardware may fail if you try to decode more than the allowable
-     * number of videos supported on that device.
-     */
-    ANPNativeWindow (*acquireNativeWindow)(NPP instance);
-
-    /**
-     * Sets the rectangle that specifies where the video content is to be drawn.
-     * The dimensions are in document space. Further, if the rect is NULL the
-     * browser will not attempt to draw the window, therefore do not set the
-     * dimensions until you queue the first buffer in the window.
-     */
-    void (*setWindowDimensions)(NPP instance, const ANPNativeWindow window, const ANPRectF* dimensions);
-
-    /**
-     */
-    void (*releaseNativeWindow)(NPP instance, ANPNativeWindow window);
-
-    /** Set a callback to be notified when an ANPNativeWindow is composited by
-     *  the browser.
-     */
-    void (*setFramerateCallback)(NPP instance, const ANPNativeWindow window, ANPVideoFrameCallbackProc);
-};
-
-struct ANPNativeWindowInterfaceV0 : ANPInterface {
-    /**
-     * Constructs a new native window to be used for rendering plugin content.
-     *
-     * Subsequent calls will return the original constructed window. Further, if
-     * the browser is unable to acquire the window quickly it may return NULL in
-     * order to not block the plugin indefinitely. A subsequent call will then
-     * return the window if it is available.
-     */
-    ANPNativeWindow (*acquireNativeWindow)(NPP instance);
-
-    /**
-     * Invert the contents of the plugin on the y-axis.
-     * default is to not be inverted (e.g. use OpenGL coordinates)
-     */
-    void (*invertPluginContent)(NPP instance, bool isContentInverted);
-};
-
-
-#endif
deleted file mode 100644
--- a/dom/plugins/base/android/moz.build
+++ /dev/null
@@ -1,35 +0,0 @@
-# -*- Mode: python; 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/.
-
-EXPORTS += [
-    'android_npapi.h',
-    'ANPKeyCodes.h',
-]
-
-SOURCES += [
-    'ANPAudio.cpp',
-    'ANPEvent.cpp',
-    'ANPLog.cpp',
-    'ANPNativeWindow.cpp',
-    'ANPSurface.cpp',
-    'ANPSystem.cpp',
-    'ANPVideo.cpp',
-    'ANPWindow.cpp',
-]
-
-include('/ipc/chromium/chromium-config.mozbuild')
-
-FINAL_LIBRARY = 'xul'
-LOCAL_INCLUDES += [
-    '/dom/plugins/base',
-    '/gfx/gl',
-    '/widget',
-    '/widget/android',
-]
-
-DEFINES['MOZ_APP_NAME'] = '"%s"' % CONFIG['MOZ_APP_NAME']
-
-CXXFLAGS += CONFIG['MOZ_CAIRO_CFLAGS']
--- a/dom/plugins/base/moz.build
+++ b/dom/plugins/base/moz.build
@@ -1,17 +1,14 @@
 # -*- Mode: python; 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/.
 
-if CONFIG['MOZ_WIDGET_TOOLKIT'] == 'android':
-    DIRS += ['android']
-
 XPIDL_SOURCES += [
     'nsIHTTPHeaderListener.idl',
     'nsIPluginDocument.idl',
     'nsIPluginHost.idl',
     'nsIPluginInputStream.idl',
     'nsIPluginInstanceOwner.idl',
     'nsIPluginTag.idl',
     'nspluginroot.idl',
@@ -75,34 +72,26 @@ else:
 
 LOCAL_INCLUDES += [
     '/dom/base',
     '/dom/plugins/ipc',
     '/layout/generic',
     '/layout/xul',
     '/netwerk/base',
     '/widget',
-    '/widget/android',
     '/widget/cocoa',
     '/xpcom/base',
 ]
 
-if CONFIG['MOZ_WIDGET_TOOLKIT'] == 'android':
-    LOCAL_INCLUDES += [
-        '/dom/plugins/base/android',
-    ]
-
 if CONFIG['OS_ARCH'] == 'WINNT':
     LOCAL_INCLUDES += [
         '/xpcom/base',
     ]
 
 include('/ipc/chromium/chromium-config.mozbuild')
 
-DEFINES['SK_BUILD_FOR_ANDROID_NDK'] = True
-
 FINAL_LIBRARY = 'xul'
 
 CXXFLAGS += CONFIG['MOZ_CAIRO_CFLAGS']
 CXXFLAGS += CONFIG['TK_CFLAGS']
 
 if CONFIG['GNU_CXX']:
     CXXFLAGS += ['-Wno-error=shadow']
--- a/dom/plugins/base/npfunctions.h
+++ b/dom/plugins/base/npfunctions.h
@@ -4,20 +4,16 @@
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #ifndef npfunctions_h_
 #define npfunctions_h_
 
 #include "npapi.h"
 #include "npruntime.h"
 
-#ifdef MOZ_WIDGET_ANDROID
-#include <jni.h>
-#endif
-
 typedef NPError      (* NPP_NewProcPtr)(NPMIMEType pluginType, NPP instance, uint16_t mode, int16_t argc, char* argn[], char* argv[], NPSavedData* saved);
 typedef NPError      (* NPP_DestroyProcPtr)(NPP instance, NPSavedData** save);
 typedef NPError      (* NPP_SetWindowProcPtr)(NPP instance, NPWindow* window);
 typedef NPError      (* NPP_NewStreamProcPtr)(NPP instance, NPMIMEType type, NPStream* stream, NPBool seekable, uint16_t* stype);
 typedef NPError      (* NPP_DestroyStreamProcPtr)(NPP instance, NPStream* stream, NPReason reason);
 typedef int32_t      (* NPP_WriteReadyProcPtr)(NPP instance, NPStream* stream);
 typedef int32_t      (* NPP_WriteProcPtr)(NPP instance, NPStream* stream, int32_t offset, int32_t len, void* buffer);
 typedef void         (* NPP_StreamAsFileProcPtr)(NPP instance, NPStream* stream, const char* fname);
@@ -256,24 +252,19 @@ NP_EXPORT(char*)       NP_GetPluginVersi
 typedef const char*    (*NP_GetMIMEDescriptionFunc)(void);
 NP_EXPORT(const char*) NP_GetMIMEDescription(void);
 #ifdef XP_MACOSX
 typedef NPError        (*NP_InitializeFunc)(NPNetscapeFuncs*);
 NP_EXPORT(NPError)     NP_Initialize(NPNetscapeFuncs* bFuncs);
 typedef NPError        (*NP_GetEntryPointsFunc)(NPPluginFuncs*);
 NP_EXPORT(NPError)     NP_GetEntryPoints(NPPluginFuncs* pFuncs);
 #else
-#ifdef MOZ_WIDGET_ANDROID
-typedef NPError    (*NP_InitializeFunc)(NPNetscapeFuncs*, NPPluginFuncs*, JNIEnv* pEnv);
-NP_EXPORT(NPError) NP_Initialize(NPNetscapeFuncs* bFuncs, NPPluginFuncs* pFuncs, JNIEnv* pEnv);
-#else
 typedef NPError    (*NP_InitializeFunc)(NPNetscapeFuncs*, NPPluginFuncs*);
 NP_EXPORT(NPError) NP_Initialize(NPNetscapeFuncs* bFuncs, NPPluginFuncs* pFuncs);
 #endif
-#endif
 typedef NPError        (*NP_ShutdownFunc)(void);
 NP_EXPORT(NPError)     NP_Shutdown(void);
 typedef NPError        (*NP_GetValueFunc)(void *, NPPVariable, void *);
 NP_EXPORT(NPError)     NP_GetValue(void *future, NPPVariable aVariable, void *aValue);
 #ifdef __cplusplus
 }
 #endif
 #endif
--- a/dom/plugins/base/nsNPAPIPlugin.cpp
+++ b/dom/plugins/base/nsNPAPIPlugin.cpp
@@ -91,26 +91,16 @@ using mozilla::plugins::PluginModuleCont
 #ifdef XP_WIN
 #include <windows.h>
 #include "mozilla/WindowsVersion.h"
 #ifdef ACCESSIBILITY
 #include "mozilla/a11y/Compatibility.h"
 #endif
 #endif
 
-#ifdef MOZ_WIDGET_ANDROID
-#include <android/log.h>
-#include "android_npapi.h"
-#include "ANPBase.h"
-#include "FennecJNIWrappers.h"
-#include "GeneratedJNIWrappers.h"
-#undef LOG
-#define LOG(args...)  __android_log_print(ANDROID_LOG_INFO, "GeckoPlugins" , ## args)
-#endif
-
 #include "nsIAudioChannelAgent.h"
 #include "AudioChannelService.h"
 
 using namespace mozilla;
 using namespace mozilla::plugins::parent;
 
 // We should make this const...
 static NPNetscapeFuncs sBrowserFuncs = {
@@ -231,21 +221,17 @@ nsNPAPIPlugin::PluginCrashed(const nsASt
 {
   RefPtr<nsPluginHost> host = nsPluginHost::GetInst();
   host->PluginCrashed(this, pluginDumpID, browserDumpID);
 }
 
 bool
 nsNPAPIPlugin::RunPluginOOP(const nsPluginTag *aPluginTag)
 {
-#ifdef MOZ_WIDGET_ANDROID
-  return false;
-#else
   return true;
-#endif
 }
 
 inline PluginLibrary*
 GetNewPluginLibrary(nsPluginTag *aPluginTag)
 {
   AUTO_PROFILER_LABEL("GetNewPluginLibrary", OTHER);
 
   if (!aPluginTag) {
@@ -277,17 +263,17 @@ nsNPAPIPlugin::CreatePlugin(nsPluginTag 
 
   RefPtr<nsNPAPIPlugin> plugin = new nsNPAPIPlugin();
 
   PluginLibrary* pluginLib = GetNewPluginLibrary(aPluginTag);
   if (!pluginLib) {
     return NS_ERROR_FAILURE;
   }
 
-#if defined(XP_MACOSX) || defined(MOZ_WIDGET_ANDROID)
+#if defined(XP_MACOSX)
   if (!pluginLib->HasRequiredFunctions()) {
     NS_WARNING("Not all necessary functions exposed by plugin, it will not load.");
     delete pluginLib;
     return NS_ERROR_FAILURE;
   }
 #endif
 
   plugin->mLibrary = pluginLib;
@@ -1777,169 +1763,16 @@ NPError
   case NPNVCSSZoomFactor: {
     nsNPAPIPluginInstance *inst =
       (nsNPAPIPluginInstance *) (npp ? npp->ndata : nullptr);
     double scaleFactor = inst ? inst->GetCSSZoomFactor() : 1.0;
     *(double*)result = scaleFactor;
     return NPERR_NO_ERROR;
   }
 
-#ifdef MOZ_WIDGET_ANDROID
-    case kLogInterfaceV0_ANPGetValue: {
-      LOG("get log interface");
-      ANPLogInterfaceV0 *i = (ANPLogInterfaceV0 *) result;
-      InitLogInterface(i);
-      return NPERR_NO_ERROR;
-    }
-
-    case kBitmapInterfaceV0_ANPGetValue: {
-      LOG("get bitmap interface");
-      return NPERR_GENERIC_ERROR;
-    }
-
-    case kMatrixInterfaceV0_ANPGetValue: {
-      LOG("get matrix interface");
-      return NPERR_GENERIC_ERROR;
-    }
-
-    case kPathInterfaceV0_ANPGetValue: {
-      LOG("get path interface");
-      return NPERR_GENERIC_ERROR;
-    }
-
-    case kTypefaceInterfaceV0_ANPGetValue: {
-      LOG("get typeface interface");
-      ANPTypefaceInterfaceV0 *i = (ANPTypefaceInterfaceV0 *) result;
-      InitTypeFaceInterface(i);
-      return NPERR_NO_ERROR;
-    }
-
-    case kPaintInterfaceV0_ANPGetValue: {
-      LOG("get paint interface");
-      ANPPaintInterfaceV0 *i = (ANPPaintInterfaceV0 *) result;
-      InitPaintInterface(i);
-      return NPERR_NO_ERROR;
-    }
-
-    case kCanvasInterfaceV0_ANPGetValue: {
-      LOG("get canvas interface");
-      ANPCanvasInterfaceV0 *i = (ANPCanvasInterfaceV0 *) result;
-      InitCanvasInterface(i);
-      return NPERR_NO_ERROR;
-    }
-
-    case kWindowInterfaceV0_ANPGetValue: {
-      LOG("get window interface");
-      ANPWindowInterfaceV0 *i = (ANPWindowInterfaceV0 *) result;
-      InitWindowInterface(i);
-      return NPERR_NO_ERROR;
-    }
-
-    case kAudioTrackInterfaceV0_ANPGetValue: {
-      LOG("get audio interface");
-      ANPAudioTrackInterfaceV0 *i = (ANPAudioTrackInterfaceV0 *) result;
-      InitAudioTrackInterfaceV0(i);
-      return NPERR_NO_ERROR;
-    }
-
-    case kEventInterfaceV0_ANPGetValue: {
-      LOG("get event interface");
-      ANPEventInterfaceV0 *i = (ANPEventInterfaceV0 *) result;
-      InitEventInterface(i);
-      return NPERR_NO_ERROR;
-    }
-
-    case kSystemInterfaceV0_ANPGetValue: {
-      LOG("get system interface");
-      return NPERR_GENERIC_ERROR;
-    }
-
-    case kSurfaceInterfaceV0_ANPGetValue: {
-      LOG("get surface interface");
-      ANPSurfaceInterfaceV0 *i = (ANPSurfaceInterfaceV0 *) result;
-      InitSurfaceInterface(i);
-      return NPERR_NO_ERROR;
-    }
-
-    case kSupportedDrawingModel_ANPGetValue: {
-      LOG("get supported drawing model");
-      return NPERR_GENERIC_ERROR;
-    }
-
-    case kJavaContext_ANPGetValue: {
-      LOG("get java context");
-
-      auto ret = npp && jni::IsFennec()
-          ? java::GeckoApp::GetPluginContext()
-          : java::GeckoAppShell::GetApplicationContext();
-      if (!ret) {
-        return NPERR_GENERIC_ERROR;
-      }
-      *static_cast<jobject*>(result) = ret.Forget();
-      return NPERR_NO_ERROR;
-    }
-
-    case kAudioTrackInterfaceV1_ANPGetValue: {
-      LOG("get audio interface v1");
-      ANPAudioTrackInterfaceV1 *i = (ANPAudioTrackInterfaceV1 *) result;
-      InitAudioTrackInterfaceV1(i);
-      return NPERR_NO_ERROR;
-    }
-
-    case kNativeWindowInterfaceV0_ANPGetValue: {
-      LOG("get native window interface v0");
-      ANPNativeWindowInterfaceV0* i = (ANPNativeWindowInterfaceV0 *) result;
-      InitNativeWindowInterface(i);
-      return NPERR_NO_ERROR;
-    }
-
-    case kOpenGLInterfaceV0_ANPGetValue: {
-      LOG("get openGL interface");
-      return NPERR_GENERIC_ERROR;
-    }
-
-    case kWindowInterfaceV1_ANPGetValue: {
-      LOG("get Window interface V1");
-      return NPERR_GENERIC_ERROR;
-    }
-
-    case kWindowInterfaceV2_ANPGetValue: {
-      LOG("get Window interface V2");
-      ANPWindowInterfaceV2 *i = (ANPWindowInterfaceV2 *) result;
-      InitWindowInterfaceV2(i);
-      return NPERR_NO_ERROR;
-    }
-
-    case kVideoInterfaceV0_ANPGetValue: {
-      LOG("get video interface V0");
-      return NPERR_GENERIC_ERROR;
-    }
-
-    case kVideoInterfaceV1_ANPGetValue: {
-      LOG("get video interface V1");
-      ANPVideoInterfaceV1 *i = (ANPVideoInterfaceV1*) result;
-      InitVideoInterfaceV1(i);
-      return NPERR_NO_ERROR;
-    }
-
-    case kSystemInterfaceV1_ANPGetValue: {
-      LOG("get system interface v1");
-      ANPSystemInterfaceV1* i = reinterpret_cast<ANPSystemInterfaceV1*>(result);
-      InitSystemInterfaceV1(i);
-      return NPERR_NO_ERROR;
-    }
-
-    case kSystemInterfaceV2_ANPGetValue: {
-      LOG("get system interface v2");
-      ANPSystemInterfaceV2* i = reinterpret_cast<ANPSystemInterfaceV2*>(result);
-      InitSystemInterfaceV2(i);
-      return NPERR_NO_ERROR;
-    }
-#endif
-
   // we no longer hand out any XPCOM objects
   case NPNVDOMElement:
   case NPNVDOMWindow:
   case NPNVserviceManager:
     // old XPCOM objects, no longer supported, but null out the out
     // param to avoid crashing plugins that still try to use this.
     *(nsISupports**)result = nullptr;
     MOZ_FALLTHROUGH;
@@ -2025,46 +1858,35 @@ NPError
         inst->NotifyStartedPlaying();
       } else {
         inst->NotifyStoppedPlaying();
       }
 
       return NPERR_NO_ERROR;
     }
 
-#ifndef MOZ_WIDGET_ANDROID
-    // On android, their 'drawing model' uses the same constant!
     case NPPVpluginDrawingModel: {
       if (inst) {
         inst->SetDrawingModel((NPDrawingModel)NS_PTR_TO_INT32(result));
         return NPERR_NO_ERROR;
       }
       return NPERR_GENERIC_ERROR;
     }
-#endif
 
 #ifdef XP_MACOSX
     case NPPVpluginEventModel: {
       if (inst) {
         inst->SetEventModel((NPEventModel)NS_PTR_TO_INT32(result));
         return NPERR_NO_ERROR;
       }
       else {
         return NPERR_GENERIC_ERROR;
       }
     }
 #endif
-#ifdef MOZ_WIDGET_ANDROID
-  case kRequestDrawingModel_ANPSetValue:
-    if (inst)
-      inst->SetANPDrawingModel(NS_PTR_TO_INT32(result));
-    return NPERR_NO_ERROR;
-  case kAcceptEvents_ANPSetValue:
-    return NPERR_NO_ERROR;
-#endif
     default:
       return NPERR_GENERIC_ERROR;
   }
 }
 
 NPError
 _requestread(NPStream *pstream, NPByteRange *rangeList)
 {
@@ -2291,23 +2113,17 @@ uint32_t
 void
 _unscheduletimer(NPP instance, uint32_t timerID)
 {
   if (!NS_IsMainThread()) {
     NPN_PLUGIN_LOG(PLUGIN_LOG_ALWAYS,("NPN_unscheduletimer called from the wrong thread\n"));
     return;
   }
 
-#ifdef MOZ_WIDGET_ANDROID
-  // Sometimes Flash calls this with a dead NPP instance. Ensure the one we have
-  // here is valid and maps to a nsNPAPIPluginInstance.
-  nsNPAPIPluginInstance *inst = nsNPAPIPluginInstance::GetFromNPP(instance);
-#else
   nsNPAPIPluginInstance *inst = (nsNPAPIPluginInstance *)instance->ndata;
-#endif
   if (!inst)
     return;
 
   inst->UnscheduleTimer(timerID);
 }
 
 NPError
 _popupcontextmenu(NPP instance, NPMenu* menu)
--- a/dom/plugins/base/nsNPAPIPluginInstance.cpp
+++ b/dom/plugins/base/nsNPAPIPluginInstance.cpp
@@ -1,20 +1,15 @@
 /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #include "mozilla/DebugOnly.h"
 
-#ifdef MOZ_WIDGET_ANDROID
-// For ScreenOrientation.h and Hal.h
-#include "base/basictypes.h"
-#endif
-
 #include "mozilla/Logging.h"
 #include "nscore.h"
 #include "prenv.h"
 
 #include "nsNPAPIPluginInstance.h"
 #include "nsNPAPIPlugin.h"
 #include "nsNPAPIPluginStreamListener.h"
 #include "nsPluginHost.h"
@@ -39,136 +34,54 @@
 #include "mozilla/Unused.h"
 #include "nsILoadContext.h"
 #include "mozilla/dom/HTMLObjectElementBinding.h"
 #include "AudioChannelService.h"
 
 using namespace mozilla;
 using namespace mozilla::dom;
 
-#ifdef MOZ_WIDGET_ANDROID
-#include "ANPBase.h"
-#include <android/log.h>
-#include "android_npapi.h"
-#include "mozilla/Mutex.h"
-#include "mozilla/CondVar.h"
-#include "mozilla/dom/ScreenOrientation.h"
-#include "mozilla/Hal.h"
-#include "GLContextProvider.h"
-#include "GLContext.h"
-#include "TexturePoolOGL.h"
-#include "SurfaceTypes.h"
-#include "EGLUtils.h"
-#include "GeneratedJNIWrappers.h"
-#include "GeneratedJNINatives.h"
-
-using namespace mozilla;
-using namespace mozilla::gl;
-
-typedef nsNPAPIPluginInstance::VideoInfo VideoInfo;
-
-class PluginEventRunnable : public Runnable
-{
-public:
-  PluginEventRunnable(nsNPAPIPluginInstance* instance, ANPEvent* event)
-    : Runnable("PluginEventRunnable"),
-      mInstance(instance),
-      mEvent(*event),
-      mCanceled(false)
-  {
-  }
-
-  virtual nsresult Run() {
-    if (mCanceled)
-      return NS_OK;
-
-    mInstance->HandleEvent(&mEvent, nullptr);
-    mInstance->PopPostedEvent(this);
-    return NS_OK;
-  }
-
-  void Cancel() { mCanceled = true; }
-private:
-  nsNPAPIPluginInstance* mInstance;
-  ANPEvent mEvent;
-  bool mCanceled;
-};
-
-static RefPtr<GLContext> sPluginContext = nullptr;
-
-static bool EnsureGLContext()
-{
-  if (!sPluginContext) {
-    const auto flags = CreateContextFlags::REQUIRE_COMPAT_PROFILE;
-    nsCString discardedFailureId;
-    sPluginContext = GLContextProvider::CreateHeadless(flags, &discardedFailureId);
-  }
-
-  return sPluginContext != nullptr;
-}
-
-static std::map<NPP, nsNPAPIPluginInstance*> sPluginNPPMap;
-
-#endif // MOZ_WIDGET_ANDROID
-
 using namespace mozilla;
 using namespace mozilla::plugins::parent;
 using namespace mozilla::layers;
 
 static NS_DEFINE_IID(kIOutputStreamIID, NS_IOUTPUTSTREAM_IID);
 
 NS_IMPL_ISUPPORTS(nsNPAPIPluginInstance, nsIAudioChannelAgentCallback)
 
 nsNPAPIPluginInstance::nsNPAPIPluginInstance()
   : mDrawingModel(kDefaultDrawingModel)
-#ifdef MOZ_WIDGET_ANDROID
-  , mANPDrawingModel(0)
-  , mFullScreenOrientation(dom::eScreenOrientation_LandscapePrimary)
-  , mWakeLocked(false)
-  , mFullScreen(false)
-  , mOriginPos(gl::OriginPos::TopLeft)
-#endif
   , mRunning(NOT_STARTED)
   , mWindowless(false)
   , mTransparent(false)
   , mCached(false)
   , mUsesDOMForCursor(false)
   , mInPluginInitCall(false)
   , mPlugin(nullptr)
   , mMIMEType(nullptr)
   , mOwner(nullptr)
 #ifdef XP_MACOSX
   , mCurrentPluginEvent(nullptr)
 #endif
-#ifdef MOZ_WIDGET_ANDROID
-  , mOnScreen(true)
-#endif
+  , mHaveJavaC2PJSObjectQuirk(false)
   , mCachedParamLength(0)
   , mCachedParamNames(nullptr)
   , mCachedParamValues(nullptr)
   , mMuted(false)
 {
   mNPP.pdata = nullptr;
   mNPP.ndata = this;
 
   PLUGIN_LOG(PLUGIN_LOG_BASIC, ("nsNPAPIPluginInstance ctor: this=%p\n",this));
-
-#ifdef MOZ_WIDGET_ANDROID
-  sPluginNPPMap[&mNPP] = this;
-#endif
 }
 
 nsNPAPIPluginInstance::~nsNPAPIPluginInstance()
 {
   PLUGIN_LOG(PLUGIN_LOG_BASIC, ("nsNPAPIPluginInstance dtor: this=%p\n",this));
 
-#ifdef MOZ_WIDGET_ANDROID
-  sPluginNPPMap.erase(&mNPP);
-#endif
-
   if (mMIMEType) {
     free(mMIMEType);
     mMIMEType = nullptr;
   }
 
   if (!mCachedParamValues || !mCachedParamNames) {
     return;
   }
@@ -195,29 +108,16 @@ nsNPAPIPluginInstance::~nsNPAPIPluginIns
 uint32_t nsNPAPIPluginInstance::gInUnsafePluginCalls = 0;
 
 void
 nsNPAPIPluginInstance::Destroy()
 {
   Stop();
   mPlugin = nullptr;
   mAudioChannelAgent = nullptr;
-
-#if MOZ_WIDGET_ANDROID
-  if (mContentSurface) {
-    java::SurfaceAllocator::DisposeSurface(mContentSurface);
-  }
-
-  std::map<void*, VideoInfo*>::iterator it;
-  for (it = mVideos.begin(); it != mVideos.end(); it++) {
-    delete it->second;
-  }
-  mVideos.clear();
-  SetWakeLock(false);
-#endif
 }
 
 TimeStamp
 nsNPAPIPluginInstance::StopTime()
 {
   return mStopTime;
 }
 
@@ -295,24 +195,16 @@ nsresult nsNPAPIPluginInstance::Stop()
     NS_TRY_SAFE_CALL_RETURN(error, (*pluginFunctions->destroy)(&mNPP, &sdata), this,
                             NS_PLUGIN_CALL_UNSAFE_TO_REENTER_GECKO);
 
     NPP_PLUGIN_LOG(PLUGIN_LOG_NORMAL,
                    ("NPP Destroy called: this=%p, npp=%p, return=%d\n", this, &mNPP, error));
   }
   mRunning = DESTROYED;
 
-#if MOZ_WIDGET_ANDROID
-  for (uint32_t i = 0; i < mPostedEvents.Length(); i++) {
-    mPostedEvents[i]->Cancel();
-  }
-
-  mPostedEvents.Clear();
-#endif
-
   nsJSNPRuntime::OnPluginDestroy(&mNPP);
 
   if (error != NPERR_NO_ERROR)
     return NS_ERROR_FAILURE;
   else
     return NS_OK;
 }
 
@@ -393,23 +285,18 @@ nsNPAPIPluginInstance::Start()
   mCachedParamNames = (char**)moz_xmalloc(sizeof(char*) * mCachedParamLength);
   mCachedParamValues = (char**)moz_xmalloc(sizeof(char*) * mCachedParamLength);
 
   for (uint32_t i = 0; i < attributes.Length(); i++) {
     mCachedParamNames[i] = ToNewUTF8String(attributes[i].mName);
     mCachedParamValues[i] = ToNewUTF8String(attributes[i].mValue);
   }
 
-  // Android expects and empty string instead of null.
   mCachedParamNames[attributes.Length()] = ToNewUTF8String(NS_LITERAL_STRING("PARAM"));
-  #ifdef MOZ_WIDGET_ANDROID
-    mCachedParamValues[attributes.Length()] = ToNewUTF8String(NS_LITERAL_STRING(""));
-  #else
-    mCachedParamValues[attributes.Length()] = nullptr;
-  #endif
+  mCachedParamValues[attributes.Length()] = nullptr;
 
   for (uint32_t i = 0, pos = attributes.Length() + 1; i < params.Length(); i ++) {
     mCachedParamNames[pos] = ToNewUTF8String(params[i].mName);
     mCachedParamValues[pos] = ToNewUTF8String(params[i].mValue);
     pos++;
   }
 
   const char*   mimetype;
@@ -589,17 +476,16 @@ nsresult nsNPAPIPluginInstance::HandleEv
   if (pluginFunctions->event) {
 #ifdef XP_MACOSX
     mCurrentPluginEvent = event;
 #endif
 #if defined(XP_WIN)
     NS_TRY_SAFE_CALL_RETURN(tmpResult, (*pluginFunctions->event)(&mNPP, event), this,
                             aSafeToReenterGecko);
 #else
-    MAIN_THREAD_JNI_REF_GUARD;
     tmpResult = (*pluginFunctions->event)(&mNPP, event);
 #endif
     NPP_PLUGIN_LOG(PLUGIN_LOG_NOISY,
       ("NPP HandleEvent called: this=%p, npp=%p, event=%p, return=%d\n",
       this, &mNPP, event, tmpResult));
 
     if (result)
       *result = tmpResult;
@@ -695,280 +581,16 @@ void nsNPAPIPluginInstance::SetEventMode
     NS_WARNING("Trying to set event model without a plugin instance owner!");
     return;
   }
 
   mOwner->SetEventModel(aModel);
 }
 #endif
 
-#if defined(MOZ_WIDGET_ANDROID)
-
-static void SendLifecycleEvent(nsNPAPIPluginInstance* aInstance, uint32_t aAction)
-{
-  ANPEvent event;
-  event.inSize = sizeof(ANPEvent);
-  event.eventType = kLifecycle_ANPEventType;
-  event.data.lifecycle.action = aAction;
-  aInstance->HandleEvent(&event, nullptr);
-}
-
-void nsNPAPIPluginInstance::NotifyForeground(bool aForeground)
-{
-  PLUGIN_LOG(PLUGIN_LOG_NORMAL, ("nsNPAPIPluginInstance::SetForeground this=%p\n foreground=%d",this, aForeground));
-  if (RUNNING != mRunning)
-    return;
-
-  SendLifecycleEvent(this, aForeground ? kResume_ANPLifecycleAction : kPause_ANPLifecycleAction);
-}
-
-void nsNPAPIPluginInstance::NotifyOnScreen(bool aOnScreen)
-{
-  PLUGIN_LOG(PLUGIN_LOG_NORMAL, ("nsNPAPIPluginInstance::SetOnScreen this=%p\n onScreen=%d",this, aOnScreen));
-  if (RUNNING != mRunning || mOnScreen == aOnScreen)
-    return;
-
-  mOnScreen = aOnScreen;
-  SendLifecycleEvent(this, aOnScreen ? kOnScreen_ANPLifecycleAction : kOffScreen_ANPLifecycleAction);
-}
-
-void nsNPAPIPluginInstance::MemoryPressure()
-{
-  PLUGIN_LOG(PLUGIN_LOG_NORMAL, ("nsNPAPIPluginInstance::MemoryPressure this=%p\n",this));
-  if (RUNNING != mRunning)
-    return;
-
-  SendLifecycleEvent(this, kFreeMemory_ANPLifecycleAction);
-}
-
-void nsNPAPIPluginInstance::NotifyFullScreen(bool aFullScreen)
-{
-  PLUGIN_LOG(PLUGIN_LOG_NORMAL, ("nsNPAPIPluginInstance::NotifyFullScreen this=%p\n",this));
-
-  if (RUNNING != mRunning || mFullScreen == aFullScreen)
-    return;
-
-  mFullScreen = aFullScreen;
-  SendLifecycleEvent(this, mFullScreen ? kEnterFullScreen_ANPLifecycleAction : kExitFullScreen_ANPLifecycleAction);
-
-  if (mFullScreen && mFullScreenOrientation != dom::eScreenOrientation_None) {
-    java::GeckoAppShell::LockScreenOrientation(mFullScreenOrientation);
-  }
-}
-
-void nsNPAPIPluginInstance::NotifySize(nsIntSize size)
-{
-  if (kOpenGL_ANPDrawingModel != GetANPDrawingModel() ||
-      size == mCurrentSize)
-    return;
-
-  mCurrentSize = size;
-
-  ANPEvent event;
-  event.inSize = sizeof(ANPEvent);
-  event.eventType = kDraw_ANPEventType;
-  event.data.draw.model = kOpenGL_ANPDrawingModel;
-  event.data.draw.data.surfaceSize.width = size.width;
-  event.data.draw.data.surfaceSize.height = size.height;
-
-  HandleEvent(&event, nullptr);
-}
-
-void nsNPAPIPluginInstance::SetANPDrawingModel(uint32_t aModel)
-{
-  mANPDrawingModel = aModel;
-}
-
-void* nsNPAPIPluginInstance::GetJavaSurface()
-{
-  void* surface = nullptr;
-  nsresult rv = GetValueFromPlugin(kJavaSurface_ANPGetValue, &surface);
-  if (NS_FAILED(rv))
-    return nullptr;
-
-  return surface;
-}
-
-void nsNPAPIPluginInstance::PostEvent(void* event)
-{
-  PluginEventRunnable *r = new PluginEventRunnable(this, (ANPEvent*)event);
-  mPostedEvents.AppendElement(RefPtr<PluginEventRunnable>(r));
-
-  NS_DispatchToMainThread(r);
-}
-
-void nsNPAPIPluginInstance::SetFullScreenOrientation(uint32_t orientation)
-{
-  if (mFullScreenOrientation == orientation)
-    return;
-
-  uint32_t oldOrientation = mFullScreenOrientation;
-  mFullScreenOrientation = orientation;
-
-  if (mFullScreen) {
-    // We're already fullscreen so immediately apply the orientation change
-
-    if (mFullScreenOrientation != dom::eScreenOrientation_None) {
-      java::GeckoAppShell::LockScreenOrientation(mFullScreenOrientation);
-    } else if (oldOrientation != dom::eScreenOrientation_None) {
-      // We applied an orientation when we entered fullscreen, but
-      // we don't want it anymore
-      java::GeckoAppShell::UnlockScreenOrientation();
-    }
-  }
-}
-
-void nsNPAPIPluginInstance::PopPostedEvent(PluginEventRunnable* r)
-{
-  mPostedEvents.RemoveElement(r);
-}
-
-void nsNPAPIPluginInstance::SetWakeLock(bool aLocked)
-{
-  if (aLocked == mWakeLocked)
-    return;
-
-  mWakeLocked = aLocked;
-  hal::ModifyWakeLock(NS_LITERAL_STRING("screen"),
-                      mWakeLocked ? hal::WAKE_LOCK_ADD_ONE : hal::WAKE_LOCK_REMOVE_ONE,
-                      hal::WAKE_LOCK_NO_CHANGE);
-}
-
-GLContext* nsNPAPIPluginInstance::GLContext()
-{
-  if (!EnsureGLContext())
-    return nullptr;
-
-  return sPluginContext;
-}
-
-class PluginTextureListener
-  : public java::SurfaceTextureListener::Natives<PluginTextureListener>
-{
-  using Base = java::SurfaceTextureListener::Natives<PluginTextureListener>;
-
-  const nsCOMPtr<nsIRunnable> mCallback;
-public:
-  using Base::AttachNative;
-  using Base::DisposeNative;
-
-  PluginTextureListener(nsIRunnable* aCallback) : mCallback(aCallback) {}
-
-  void OnFrameAvailable()
-  {
-    if (NS_IsMainThread()) {
-      mCallback->Run();
-      return;
-    }
-    NS_DispatchToMainThread(mCallback);
-  }
-};
-
-java::GeckoSurface::LocalRef nsNPAPIPluginInstance::CreateSurface()
-{
-  java::GeckoSurface::LocalRef surf = java::SurfaceAllocator::AcquireSurface(0, 0, false);
-  if (!surf) {
-    return nullptr;
-  }
-
-  nsCOMPtr<nsIRunnable> frameCallback = NewRunnableMethod("nsNPAPIPluginInstance::OnSurfaceTextureFrameAvailable",
-                                                          this, &nsNPAPIPluginInstance::OnSurfaceTextureFrameAvailable);
-
-  java::SurfaceTextureListener::LocalRef listener = java::SurfaceTextureListener::New();
-
-  PluginTextureListener::AttachNative(listener, MakeUnique<PluginTextureListener>(frameCallback.get()));
-
-  java::GeckoSurfaceTexture::LocalRef gst = java::GeckoSurfaceTexture::Lookup(surf->GetHandle());
-  if (!gst) {
-    return nullptr;
-  }
-
-  const auto& st = java::sdk::SurfaceTexture::Ref::From(gst);
-  st->SetOnFrameAvailableListener(listener);
-
-  return surf;
-}
-
-void nsNPAPIPluginInstance::OnSurfaceTextureFrameAvailable()
-{
-  if (mRunning == RUNNING && mOwner)
-    mOwner->Recomposite();
-}
-
-void* nsNPAPIPluginInstance::AcquireContentWindow()
-{
-  if (!mContentWindow.NativeWindow()) {
-    mContentSurface = CreateSurface();
-    if (!mContentSurface)
-      return nullptr;
-
-    mContentWindow = AndroidNativeWindow(mContentSurface);
-  }
-
-  return mContentWindow.NativeWindow();
-}
-
-java::GeckoSurface::Param
-nsNPAPIPluginInstance::AsSurface()
-{
-  return mContentSurface;
-}
-
-void* nsNPAPIPluginInstance::AcquireVideoWindow()
-{
-  java::GeckoSurface::LocalRef surface = CreateSurface();
-  VideoInfo* info = new VideoInfo(surface);
-
-  void* window = info->mNativeWindow.NativeWindow();
-  mVideos.insert(std::pair<void*, VideoInfo*>(window, info));
-
-  return window;
-}
-
-void nsNPAPIPluginInstance::ReleaseVideoWindow(void* window)
-{
-  std::map<void*, VideoInfo*>::iterator it = mVideos.find(window);
-  if (it == mVideos.end())
-    return;
-
-  delete it->second;
-  mVideos.erase(window);
-}
-
-void nsNPAPIPluginInstance::SetVideoDimensions(void* window, gfxRect aDimensions)
-{
-  std::map<void*, VideoInfo*>::iterator it;
-
-  it = mVideos.find(window);
-  if (it == mVideos.end())
-    return;
-
-  it->second->mDimensions = aDimensions;
-}
-
-void nsNPAPIPluginInstance::GetVideos(nsTArray<VideoInfo*>& aVideos)
-{
-  std::map<void*, VideoInfo*>::iterator it;
-  for (it = mVideos.begin(); it != mVideos.end(); it++)
-    aVideos.AppendElement(it->second);
-}
-
-nsNPAPIPluginInstance* nsNPAPIPluginInstance::GetFromNPP(NPP npp)
-{
-  std::map<NPP, nsNPAPIPluginInstance*>::iterator it;
-
-  it = sPluginNPPMap.find(npp);
-  if (it == sPluginNPPMap.end())
-    return nullptr;
-
-  return it->second;
-}
-
-#endif
-
 nsresult nsNPAPIPluginInstance::GetDrawingModel(int32_t* aModel)
 {
   *aModel = (int32_t)mDrawingModel;
   return NS_OK;
 }
 
 nsresult nsNPAPIPluginInstance::IsRemoteDrawingCoreAnimation(bool* aDrawing)
 {
@@ -1057,19 +679,18 @@ bool
 nsNPAPIPluginInstance::ShouldCache()
 {
   return mCached;
 }
 
 nsresult
 nsNPAPIPluginInstance::IsWindowless(bool* isWindowless)
 {
-#if defined(MOZ_WIDGET_ANDROID) || defined(XP_MACOSX)
+#if defined(XP_MACOSX)
   // All OS X plugins are windowless.
-  // On android, pre-honeycomb, all plugins are treated as windowless.
   *isWindowless = true;
 #else
   *isWindowless = mWindowless;
 #endif
   return NS_OK;
 }
 
 class MOZ_STACK_CLASS AutoPluginLibraryCall
@@ -1362,17 +983,16 @@ static void
 PluginTimerCallback(nsITimer *aTimer, void *aClosure)
 {
   nsNPAPITimer* t = (nsNPAPITimer*)aClosure;
   NPP npp = t->npp;
   uint32_t id = t->id;
 
   PLUGIN_LOG(PLUGIN_LOG_NOISY, ("nsNPAPIPluginInstance running plugin timer callback this=%p\n", npp->ndata));
 
-  MAIN_THREAD_JNI_REF_GUARD;
   // Some plugins (Flash on Android) calls unscheduletimer
   // from this callback.
   t->inCallback = true;
   (*(t->callback))(npp, id);
   t->inCallback = false;
 
   // Make sure we still have an instance and the timer is still alive
   // after the callback.
--- a/dom/plugins/base/nsNPAPIPluginInstance.h
+++ b/dom/plugins/base/nsNPAPIPluginInstance.h
@@ -13,24 +13,16 @@
 #include "nsITimer.h"
 #include "nsIPluginInstanceOwner.h"
 #include "nsIURI.h"
 #include "nsIChannel.h"
 #include "nsHashKeys.h"
 #include <prinrval.h>
 #include "js/TypeDecls.h"
 #include "nsIAudioChannelAgent.h"
-#ifdef MOZ_WIDGET_ANDROID
-#include "nsIRunnable.h"
-#include "GLContextTypes.h"
-#include "AndroidNativeWindow.h"
-#include "AndroidBridge.h"
-#include <map>
-class PluginEventRunnable;
-#endif
 
 #include "mozilla/EventForwards.h"
 #include "mozilla/TimeStamp.h"
 #include "mozilla/PluginLibrary.h"
 #include "mozilla/RefPtr.h"
 #include "mozilla/WeakPtr.h"
 
 class nsPluginStreamListenerPeer; // browser-initiated stream class
@@ -159,102 +151,16 @@ public:
 #ifdef XP_MACOSX
   void SetEventModel(NPEventModel aModel);
 
   void* GetCurrentEvent() {
     return mCurrentPluginEvent;
   }
 #endif
 
-#ifdef MOZ_WIDGET_ANDROID
-  void NotifyForeground(bool aForeground);
-  void NotifyOnScreen(bool aOnScreen);
-  void MemoryPressure();
-  void NotifyFullScreen(bool aFullScreen);
-  void NotifySize(nsIntSize size);
-
-  nsIntSize CurrentSize() { return mCurrentSize; }
-
-  bool IsOnScreen() {
-    return mOnScreen;
-  }
-
-  uint32_t GetANPDrawingModel() { return mANPDrawingModel; }
-  void SetANPDrawingModel(uint32_t aModel);
-
-  void* GetJavaSurface();
-
-  void PostEvent(void* event);
-
-  // These are really mozilla::dom::ScreenOrientation, but it's
-  // difficult to include that here
-  uint32_t FullScreenOrientation() { return mFullScreenOrientation; }
-  void SetFullScreenOrientation(uint32_t orientation);
-
-  void SetWakeLock(bool aLock);
-
-  mozilla::gl::GLContext* GLContext();
-
-  // For ANPOpenGL
-  class TextureInfo {
-  public:
-    TextureInfo() :
-      mTexture(0), mWidth(0), mHeight(0), mInternalFormat(0)
-    {
-    }
-
-    TextureInfo(GLuint aTexture, int32_t aWidth, int32_t aHeight, GLuint aInternalFormat) :
-      mTexture(aTexture), mWidth(aWidth), mHeight(aHeight), mInternalFormat(aInternalFormat)
-    {
-    }
-
-    GLuint mTexture;
-    int32_t mWidth;
-    int32_t mHeight;
-    GLuint mInternalFormat;
-  };
-
-  // For ANPNativeWindow
-  void* AcquireContentWindow();
-
-  mozilla::java::GeckoSurface::Param AsSurface();
-
-  // For ANPVideo
-  class VideoInfo {
-  public:
-    VideoInfo(mozilla::java::GeckoSurface::Param aSurface)
-      : mSurface(aSurface)
-      , mNativeWindow(aSurface)
-    {
-    }
-
-    ~VideoInfo()
-    {
-      mozilla::java::SurfaceAllocator::DisposeSurface(mSurface);
-    }
-
-    mozilla::java::GeckoSurface::GlobalRef mSurface;
-    mozilla::gl::AndroidNativeWindow mNativeWindow;
-    gfxRect mDimensions;
-  };
-
-  void* AcquireVideoWindow();
-  void ReleaseVideoWindow(void* aWindow);
-  void SetVideoDimensions(void* aWindow, gfxRect aDimensions);
-
-  void GetVideos(nsTArray<VideoInfo*>& aVideos);
-
-  void SetOriginPos(mozilla::gl::OriginPos aOriginPos) {
-    mOriginPos = aOriginPos;
-  }
-  mozilla::gl::OriginPos OriginPos() const { return mOriginPos; }
-
-  static nsNPAPIPluginInstance* GetFromNPP(NPP npp);
-#endif
-
   nsresult NewStreamListener(const char* aURL, void* notifyData,
                              nsNPAPIPluginStreamListener** listener);
 
   nsNPAPIPluginInstance();
 
   // To be called when an instance becomes orphaned, when
   // it's plugin is no longer guaranteed to be around.
   void Destroy();
@@ -337,34 +243,16 @@ protected:
   nsresult CreateAudioChannelAgentIfNeeded();
 
   // The structure used to communicate between the plugin instance and
   // the browser.
   NPP_t mNPP;
 
   NPDrawingModel mDrawingModel;
 
-#ifdef MOZ_WIDGET_ANDROID
-  uint32_t mANPDrawingModel;
-
-  friend class PluginEventRunnable;
-
-  nsTArray<RefPtr<PluginEventRunnable>> mPostedEvents;
-  void PopPostedEvent(PluginEventRunnable* r);
-  void OnSurfaceTextureFrameAvailable();
-
-  uint32_t mFullScreenOrientation;
-  bool mWakeLocked;
-  bool mFullScreen;
-  mozilla::gl::OriginPos mOriginPos;
-
-  mozilla::java::GeckoSurface::GlobalRef mContentSurface;
-  mozilla::gl::AndroidNativeWindow mContentWindow;
-#endif
-
   enum {
     NOT_STARTED,
     RUNNING,
     DESTROYING,
     DESTROYED
   } mRunning;
 
   // these are used to store the windowless properties
@@ -401,56 +289,41 @@ private:
   // non-null during a HandleEvent call
   void* mCurrentPluginEvent;
 #endif
 
   // Timestamp for the last time this plugin was stopped.
   // This is only valid when the plugin is actually stopped!
   mozilla::TimeStamp mStopTime;
 
-#ifdef MOZ_WIDGET_ANDROID
-  mozilla::java::GeckoSurface::LocalRef CreateSurface();
-  std::map<void*, VideoInfo*> mVideos;
-  bool mOnScreen;
-
-  nsIntSize mCurrentSize;
-#endif
+  // is this instance Java and affected by bug 750480?
+  bool mHaveJavaC2PJSObjectQuirk;
 
   static uint32_t gInUnsafePluginCalls;
 
   // The arrays can only be released when the plugin instance is destroyed,
   // because the plugin, in in-process mode, might keep a reference to them.
   uint32_t mCachedParamLength;
   char **mCachedParamNames;
   char **mCachedParamValues;
 
   nsCOMPtr<nsIAudioChannelAgent> mAudioChannelAgent;
   bool mMuted;
 };
 
-// On Android, we need to guard against plugin code leaking entries in the local
-// JNI ref table. See https://bugzilla.mozilla.org/show_bug.cgi?id=780831#c21
-#ifdef MOZ_WIDGET_ANDROID
-  #define MAIN_THREAD_JNI_REF_GUARD mozilla::AutoLocalJNIFrame jniFrame
-#else
-  #define MAIN_THREAD_JNI_REF_GUARD
-#endif
-
 void NS_NotifyBeginPluginCall(NSPluginCallReentry aReentryState);
 void NS_NotifyPluginCall(NSPluginCallReentry aReentryState);
 
 #define NS_TRY_SAFE_CALL_RETURN(ret, fun, pluginInst, pluginCallReentry) \
 PR_BEGIN_MACRO                                     \
-  MAIN_THREAD_JNI_REF_GUARD;                       \
   NS_NotifyBeginPluginCall(pluginCallReentry); \
   ret = fun;                                       \
   NS_NotifyPluginCall(pluginCallReentry); \
 PR_END_MACRO
 
 #define NS_TRY_SAFE_CALL_VOID(fun, pluginInst, pluginCallReentry) \
 PR_BEGIN_MACRO                                     \
-  MAIN_THREAD_JNI_REF_GUARD;                       \
   NS_NotifyBeginPluginCall(pluginCallReentry); \
   fun;                                             \
   NS_NotifyPluginCall(pluginCallReentry); \
 PR_END_MACRO
 
 #endif // nsNPAPIPluginInstance_h_
--- a/dom/plugins/base/nsNPAPIPluginStreamListener.cpp
+++ b/dom/plugins/base/nsNPAPIPluginStreamListener.cpp
@@ -836,17 +836,16 @@ nsNPAPIPluginStreamListener::HandleRedir
           mHTTPRedirectCallback = callback;
 
           NPP npp;
           mInst->GetNPP(&npp);
 #if defined(XP_WIN)
           NS_TRY_SAFE_CALL_VOID((*pluginFunctions->urlredirectnotify)(npp, spec.get(), static_cast<int32_t>(status), mNPStreamWrapper->mNPStream.notifyData), mInst,
                                 NS_PLUGIN_CALL_UNSAFE_TO_REENTER_GECKO);
 #else
-          MAIN_THREAD_JNI_REF_GUARD;
           (*pluginFunctions->urlredirectnotify)(npp, spec.get(), static_cast<int32_t>(status), mNPStreamWrapper->mNPStream.notifyData);
 #endif
           return true;
         }
       }
     }
   }
 
--- a/dom/plugins/base/nsPluginHost.cpp
+++ b/dom/plugins/base/nsPluginHost.cpp
@@ -98,21 +98,16 @@
 
 #if defined(XP_WIN)
 #include "nsIWindowMediator.h"
 #include "nsIBaseWindow.h"
 #include "windows.h"
 #include "winbase.h"
 #endif
 
-#ifdef ANDROID
-#include <android/log.h>
-#define LOG(args...)  __android_log_print(ANDROID_LOG_INFO, "GeckoPlugins" , ## args)
-#endif
-
 #if MOZ_CRASHREPORTER
 #include "nsExceptionHandler.h"
 #endif
 
 #include "npapi.h"
 
 using namespace mozilla;
 using mozilla::TimeStamp;
@@ -273,20 +268,16 @@ nsPluginHost::nsPluginHost()
 
   Preferences::AddStrongObserver(this, "plugin.disable");
 
   nsCOMPtr<nsIObserverService> obsService =
     mozilla::services::GetObserverService();
   if (obsService) {
     obsService->AddObserver(this, NS_XPCOM_SHUTDOWN_OBSERVER_ID, false);
     obsService->AddObserver(this, "blocklist-updated", false);
-#ifdef MOZ_WIDGET_ANDROID
-    obsService->AddObserver(this, "application-foreground", false);
-    obsService->AddObserver(this, "application-background", false);
-#endif
   }
 
 #ifdef PLUGIN_LOGGING
   MOZ_LOG(nsPluginLogging::gNPNLog, PLUGIN_LOG_ALWAYS,("NPN Logging Active!\n"));
   MOZ_LOG(nsPluginLogging::gPluginLog, PLUGIN_LOG_ALWAYS,("General Plugin Logging Active! (nsPluginHost::ctor)\n"));
   MOZ_LOG(nsPluginLogging::gNPPLog, PLUGIN_LOG_ALWAYS,("NPP Logging Active!\n"));
 
   PLUGIN_LOG(PLUGIN_LOG_ALWAYS,("nsPluginHost::ctor\n"));
@@ -872,22 +863,16 @@ nsPluginHost::TrySetUpPluginInstance(con
   }
 
   nsPluginTag* pluginTag = FindNativePluginForType(aMimeType, true);
 
   NS_ASSERTION(pluginTag, "Must have plugin tag here!");
 
   plugin->GetLibrary()->SetHasLocalInstance();
 
-#if defined(MOZ_WIDGET_ANDROID) && defined(MOZ_CRASHREPORTER)
-  if (pluginTag->mIsFlashPlugin) {
-    CrashReporter::AnnotateCrashReport(NS_LITERAL_CSTRING("FlashVersion"), pluginTag->Version());
-  }
-#endif
-
   RefPtr<nsNPAPIPluginInstance> instance = new nsNPAPIPluginInstance();
 
   // This will create the owning reference. The connection must be made between the
   // instance and the instance owner before initialization. Plugins can call into
   // the browser during initialization.
   aOwner->SetInstance(instance.get());
 
   // Add the instance to the instances list before we call NPP_New so that
@@ -2461,20 +2446,16 @@ nsresult nsPluginHost::FindPlugins(bool 
 
     // if we are just looking for possible changes,
     // no need to proceed if changes are detected
     if (!aCreatePluginList && *aPluginsChanged) {
       NS_ITERATIVE_UNREF_LIST(RefPtr<nsPluginTag>, mCachedPlugins, mNext);
       NS_ITERATIVE_UNREF_LIST(RefPtr<nsInvalidPluginTag>, mInvalidPlugins, mNext);
       return NS_OK;
     }
-  } else {
-#ifdef ANDROID
-    LOG("getting plugins dir failed");
-#endif
   }
 
   mPluginsLoaded = true; // at this point 'some' plugins have been loaded,
                             // the rest is optional
 
 #ifdef XP_WIN
   bool bScanPLIDs = Preferences::GetBool("plugin.scan.plid.all", false);
 
@@ -3055,24 +3036,16 @@ nsPluginHost::ReadPluginInfo()
     bool fromExtension = atoi(values[3]);
     if (!reader.NextLine())
       return rv;
 
     char *description = reader.LinePtr();
     if (!reader.NextLine())
       return rv;
 
-#if MOZ_WIDGET_ANDROID
-    // Flash on Android does not populate the version field, but it is tacked on to the description.
-    // For example, "Shockwave Flash 11.1 r115"
-    if (PL_strncmp("Shockwave Flash ", description, 16) == 0 && description[16]) {
-      version = &description[16];
-    }
-#endif
-
     const char *name = reader.LinePtr();
     if (!reader.NextLine())
       return rv;
 
     long mimetypecount = std::strtol(reader.LinePtr(), nullptr, 10);
     if (mimetypecount == LONG_MAX || mimetypecount == LONG_MIN ||
         mimetypecount >= PLUGIN_REG_MAX_MIMETYPES || mimetypecount < 0) {
       return NS_ERROR_FAILURE;
@@ -3128,18 +3101,16 @@ nsPluginHost::ReadPluginInfo()
     // Import flags from registry into prefs for old registry versions
     MOZ_LOG(nsPluginLogging::gPluginLog, PLUGIN_LOG_BASIC,
       ("LoadCachedPluginsInfo : Loading Cached plugininfo for %s\n", tag->FileName().get()));
 
     tag->mNext = mCachedPlugins;
     mCachedPlugins = tag;
   }
 
-// On Android we always want to try to load a plugin again (Flash). Bug 935676.
-#ifndef MOZ_WIDGET_ANDROID
   if (!ReadSectionHeader(reader, "INVALID")) {
     return rv;
   }
 
   while (reader.NextLine()) {
     const char *fullpath = reader.LinePtr();
     if (!reader.NextLine()) {
       return rv;
@@ -3151,17 +3122,16 @@ nsPluginHost::ReadPluginInfo()
     RefPtr<nsInvalidPluginTag> invalidTag = new nsInvalidPluginTag(fullpath, lastmod);
 
     invalidTag->mNext = mInvalidPlugins;
     if (mInvalidPlugins) {
       mInvalidPlugins->mPrev = invalidTag;
     }
     mInvalidPlugins = invalidTag;
   }
-#endif
 
   return NS_OK;
 }
 
 void
 nsPluginHost::RemoveCachedPluginsInfo(const char *filePath, nsPluginTag **result)
 {
   RefPtr<nsPluginTag> prev;
@@ -3483,34 +3453,16 @@ NS_IMETHODIMP nsPluginHost::Observe(nsIS
     // We update blocklists asynchronously by just sending a new plugin list to
     // content.
     if (XRE_IsParentProcess()) {
       // We'll need to repack our tags and send them to content again.
       IncrementChromeEpoch();
       SendPluginsToContent();
     }
   }
-#ifdef MOZ_WIDGET_ANDROID
-  if (!strcmp("application-background", aTopic)) {
-    for(uint32_t i = 0; i < mInstances.Length(); i++) {
-      mInstances[i]->NotifyForeground(false);
-    }
-  }
-  if (!strcmp("application-foreground", aTopic)) {
-    for(uint32_t i = 0; i < mInstances.Length(); i++) {
-      if (mInstances[i]->IsOnScreen())
-        mInstances[i]->NotifyForeground(true);
-    }
-  }
-  if (!strcmp("memory-pressure", aTopic)) {
-    for(uint32_t i = 0; i < mInstances.Length(); i++) {
-      mInstances[i]->MemoryPressure();
-    }
-  }
-#endif
   return NS_OK;
 }
 
 nsresult
 nsPluginHost::ParsePostBufferToFixHeaders(const char *inPostData, uint32_t inPostDataLen,
                                           char **outPostData, uint32_t *outPostDataLen)
 {
   if (!inPostData || !outPostData || !outPostDataLen)
--- a/dom/plugins/base/nsPluginInstanceOwner.cpp
+++ b/dom/plugins/base/nsPluginInstanceOwner.cpp
@@ -81,31 +81,16 @@ static NS_DEFINE_CID(kAppShellCID, NS_AP
 #include "nsIDOMXULCommandDispatcher.h"
 #endif
 
 #ifdef MOZ_WIDGET_GTK
 #include <gdk/gdk.h>
 #include <gtk/gtk.h>
 #endif
 
-#ifdef MOZ_WIDGET_ANDROID
-#include "ANPBase.h"
-#include "AndroidBridge.h"
-#include "ClientLayerManager.h"
-#include "FennecJNIWrappers.h"
-#include "nsWindow.h"
-
-static nsPluginInstanceOwner* sFullScreenInstance = nullptr;
-
-using namespace mozilla::dom;
-
-#include <android/log.h>
-#define LOG(args...)  __android_log_print(ANDROID_LOG_INFO, "GeckoPlugins" , ## args)
-#endif
-
 using namespace mozilla;
 using namespace mozilla::dom;
 using namespace mozilla::layers;
 
 // special class for handeling DOM context menu events because for
 // some reason it starves other mouse events if implemented on the
 // same class
 class nsPluginDOMContextMenuListener : public nsIDOMEventListener
@@ -158,40 +143,16 @@ nsPluginInstanceOwner::NotifyPaintWaiter
     nsCOMPtr<nsIRunnable> event = new AsyncPaintWaitEvent(content, false);
     // Run this event as soon as it's safe to do so, since listeners need to
     // receive it immediately
     nsContentUtils::AddScriptRunner(event);
     mWaitingForPaint = true;
   }
 }
 
-#if MOZ_WIDGET_ANDROID
-static void
-AttachToContainerAsSurface(ImageContainer* container,
-                           nsNPAPIPluginInstance* instance,
-                           const LayoutDeviceRect& rect,
-                           RefPtr<Image>* out_image)
-{
-  MOZ_ASSERT(out_image);
-  MOZ_ASSERT(!*out_image);
-
-  java::GeckoSurface::LocalRef surface = instance->AsSurface();
-  if (!surface) {
-    return;
-  }
-
-  RefPtr<Image> img = new SurfaceTextureImage(
-    surface->GetHandle(),
-    gfx::IntSize::Truncate(rect.width, rect.height),
-    true, // continuously update without a transaction
-    instance->OriginPos());
-  *out_image = img;
-}
-#endif
-
 bool
 nsPluginInstanceOwner::NeedsScrollImageLayer()
 {
 #if defined(XP_WIN)
   // If this is a windowed plugin and we're doing layout in the content
   // process, force the creation of an image layer for the plugin. We'll
   // paint to this when scrolling.
   return XRE_IsContentProcess() &&
@@ -205,47 +166,25 @@ nsPluginInstanceOwner::NeedsScrollImageL
 already_AddRefed<ImageContainer>
 nsPluginInstanceOwner::GetImageContainer()
 {
   if (!mInstance)
     return nullptr;
 
   RefPtr<ImageContainer> container;
 
-#if MOZ_WIDGET_ANDROID
-  LayoutDeviceRect r = GetPluginRect();
-
-  // NotifySize() causes Flash to do a bunch of stuff like ask for surfaces to render
-  // into, set y-flip flags, etc, so we do this at the beginning.
-  float resolution = mPluginFrame->PresContext()->PresShell()->GetCumulativeResolution();
-  ScreenSize screenSize = (r * LayoutDeviceToScreenScale(resolution)).Size();
-  mInstance->NotifySize(nsIntSize::Truncate(screenSize.width, screenSize.height));
-
-  container = LayerManager::CreateImageContainer();
-
-  if (r.width && r.height) {
-    // Try to get it as an EGLImage first.
-    RefPtr<Image> img;
-    AttachToContainerAsSurface(container, mInstance, r, &img);
-
-    if (img) {
-      container->SetCurrentImageInTransaction(img);
-    }
-  }
-#else
   if (NeedsScrollImageLayer()) {
     // windowed plugin under e10s
 #if defined(XP_WIN)
     mInstance->GetScrollCaptureContainer(getter_AddRefs(container));
 #endif
   } else {
     // async windowless rendering
     mInstance->GetImageContainer(getter_AddRefs(container));
   }
-#endif
 
   return container.forget();
 }
 
 void
 nsPluginInstanceOwner::DidComposite()
 {
   if (mInstance) {
@@ -352,21 +291,16 @@ nsPluginInstanceOwner::nsPluginInstanceO
 #else
   mEventModel = NPEventModelCocoa;
 #endif
   mUseAsyncRendering = false;
 #endif
 
   mWaitingForPaint = false;
 
-#ifdef MOZ_WIDGET_ANDROID
-  mFullScreen = false;
-  mJavaView = nullptr;
-#endif
-
 #ifdef XP_WIN
   mGotCompositionData = false;
   mSentStartComposition = false;
   mPluginDidNotHandleIMEComposition = false;
 #endif
 }
 
 nsPluginInstanceOwner::~nsPluginInstanceOwner()
@@ -381,20 +315,16 @@ nsPluginInstanceOwner::~nsPluginInstance
     }
   }
 
   mPluginFrame = nullptr;
 
   PLUG_DeletePluginNativeWindow(mPluginWindow);
   mPluginWindow = nullptr;
 
-#ifdef MOZ_WIDGET_ANDROID
-  RemovePluginView();
-#endif
-
   if (mInstance) {
     mInstance->SetOwner(nullptr);
   }
 }
 
 NS_IMPL_ISUPPORTS(nsPluginInstanceOwner,
                   nsIPluginInstanceOwner,
                   nsIDOMEventListener,
@@ -407,20 +337,16 @@ nsPluginInstanceOwner::SetInstance(nsNPA
 {
   NS_ASSERTION(!mInstance || !aInstance, "mInstance should only be set or unset!");
 
   // If we're going to null out mInstance after use, be sure to call
   // mInstance->SetOwner(nullptr) here, since it now won't be called
   // from our destructor.  This fixes bug 613376.
   if (mInstance && !aInstance) {
     mInstance->SetOwner(nullptr);
-
-#ifdef MOZ_WIDGET_ANDROID
-    RemovePluginView();
-#endif
   }
 
   mInstance = aInstance;
 
   nsCOMPtr<nsIDocument> doc;
   GetDocument(getter_AddRefs(doc));
   if (doc) {
     if (nsCOMPtr<nsPIDOMWindowOuter> domWindow = doc->GetWindow()) {
@@ -595,20 +521,19 @@ NS_IMETHODIMP nsPluginInstanceOwner::Inv
     nsCOMPtr<nsIRunnable> event = new AsyncPaintWaitEvent(content, true);
     NS_DispatchToMainThread(event);
     mWaitingForPaint = false;
   }
 
   if (!mPluginFrame || !invalidRect || !mWidgetVisible)
     return NS_ERROR_FAILURE;
 
-#if defined(XP_MACOSX) || defined(MOZ_WIDGET_ANDROID)
+#if defined(XP_MACOSX)
   // Each time an asynchronously-drawing plugin sends a new surface to display,
   // the image in the ImageContainer is updated and InvalidateRect is called.
-  // There are different side effects for (sync) Android plugins.
   RefPtr<ImageContainer> container;
   mInstance->GetImageContainer(getter_AddRefs(container));
 #endif
 
 #ifndef XP_MACOSX
   // Invalidate for windowed plugins needs to work.
   if (mWidget) {
     mWidget->Invalidate(
@@ -1480,219 +1405,18 @@ nsPluginInstanceOwner::GetEventloopNesti
   // we make sure we always tear the plugin down eventually.
   if (!currentLevel) {
     currentLevel++;
   }
 
   return currentLevel;
 }
 
-#ifdef MOZ_WIDGET_ANDROID
-
-// Modified version of nsFrame::GetOffsetToCrossDoc that stops when it
-// hits an element with a displayport (or runs out of frames). This is
-// not really the right thing to do, but it's better than what was here before.
-static nsPoint
-GetOffsetRootContent(nsIFrame* aFrame)
-{
-  // offset will hold the final offset
-  // docOffset holds the currently accumulated offset at the current APD, it
-  // will be converted and added to offset when the current APD changes.
-  nsPoint offset(0, 0), docOffset(0, 0);
-  const nsIFrame* f = aFrame;
-  int32_t currAPD = aFrame->PresContext()->AppUnitsPerDevPixel();
-  int32_t apd = currAPD;
-  while (f) {
-    if (f->GetContent() && nsLayoutUtils::HasDisplayPort(f->GetContent()))
-      break;
-
-    docOffset += f->GetPosition();
-    nsIFrame* parent = f->GetParent();
-    if (parent) {
-      f = parent;
-    } else {
-      nsPoint newOffset(0, 0);
-      f = nsLayoutUtils::GetCrossDocParentFrame(f, &newOffset);
-      int32_t newAPD = f ? f->PresContext()->AppUnitsPerDevPixel() : 0;
-      if (!f || newAPD != currAPD) {
-        // Convert docOffset to the right APD and add it to offset.
-        offset += docOffset.ScaleToOtherAppUnits(currAPD, apd);
-        docOffset.x = docOffset.y = 0;
-      }
-      currAPD = newAPD;
-      docOffset += newOffset;
-    }
-  }
-
-  offset += docOffset.ScaleToOtherAppUnits(currAPD, apd);
-
-  return offset;
-}
-
-LayoutDeviceRect nsPluginInstanceOwner::GetPluginRect()
-{
-  // Get the offset of the content relative to the page
-  nsRect bounds = mPluginFrame->GetContentRectRelativeToSelf() + GetOffsetRootContent(mPluginFrame);
-  LayoutDeviceIntRect rect = LayoutDeviceIntRect::FromAppUnitsToNearest(bounds, mPluginFrame->PresContext()->AppUnitsPerDevPixel());
-  return LayoutDeviceRect(rect);
-}
-
-bool nsPluginInstanceOwner::AddPluginView(const LayoutDeviceRect& aRect /* = LayoutDeviceRect(0, 0, 0, 0) */)
-{
-  if (!mJavaView) {
-    mJavaView = mInstance->GetJavaSurface();
-
-    if (!mJavaView)
-      return false;
-
-    mJavaView = (void*)jni::GetGeckoThreadEnv()->NewGlobalRef((jobject)mJavaView);
-  }
-
-  if (mFullScreen && jni::IsFennec()) {
-    java::GeckoApp::AddPluginView(jni::Object::Ref::From(jobject(mJavaView)));
-    sFullScreenInstance = this;
-  }
-
-  return true;
-}
-
-void nsPluginInstanceOwner::RemovePluginView()
-{
-  if (!mInstance || !mJavaView)
-    return;
-
-  if (mFullScreen && jni::IsFennec()) {
-    java::GeckoApp::RemovePluginView(jni::Object::Ref::From(jobject(mJavaView)));
-  }
-  jni::GetGeckoThreadEnv()->DeleteGlobalRef((jobject)mJavaView);
-  mJavaView = nullptr;
-
-  if (mFullScreen)
-    sFullScreenInstance = nullptr;
-}
-
-void
-nsPluginInstanceOwner::GetVideos(nsTArray<nsNPAPIPluginInstance::VideoInfo*>& aVideos)
-{
-  if (!mInstance)
-    return;
-
-  mInstance->GetVideos(aVideos);
-}
-
-already_AddRefed<ImageContainer>
-nsPluginInstanceOwner::GetImageContainerForVideo(nsNPAPIPluginInstance::VideoInfo* aVideoInfo)
-{
-  RefPtr<ImageContainer> container = LayerManager::CreateImageContainer();
-
-  if (aVideoInfo->mDimensions.width && aVideoInfo->mDimensions.height) {
-    RefPtr<Image> img = new SurfaceTextureImage(
-      aVideoInfo->mSurface->GetHandle(),
-      gfx::IntSize::Truncate(aVideoInfo->mDimensions.width, aVideoInfo->mDimensions.height),
-      true, /* continuous */
-      gl::OriginPos::BottomLeft);
-    container->SetCurrentImageInTransaction(img);
-  }
-
-  return container.forget();
-}
-
-void nsPluginInstanceOwner::Invalidate() {
-  NPRect rect;
-  rect.left = rect.top = 0;
-  rect.right = mPluginWindow->width;
-  rect.bottom = mPluginWindow->height;
-  InvalidateRect(&rect);
-}
-
-void nsPluginInstanceOwner::Recomposite() {
-  nsIWidget* const widget = mPluginFrame->GetNearestWidget();
-  NS_ENSURE_TRUE_VOID(widget);
-
-  LayerManager* const lm = widget->GetLayerManager();
-  NS_ENSURE_TRUE_VOID(lm);
-
-  ClientLayerManager* const clm = lm->AsClientLayerManager();
-  NS_ENSURE_TRUE_VOID(clm && clm->GetRoot());
-
-  clm->SendInvalidRegion(
-      clm->GetRoot()->GetLocalVisibleRegion().ToUnknownRegion().GetBounds());
-  clm->ScheduleComposite();
-}
-
-void nsPluginInstanceOwner::RequestFullScreen() {
-  if (mFullScreen)
-    return;
-
-  // Remove whatever view we currently have (if any, fullscreen or otherwise)
-  RemovePluginView();
-
-  mFullScreen = true;
-  AddPluginView();
-
-  mInstance->NotifyFullScreen(mFullScreen);
-}
-
-void nsPluginInstanceOwner::ExitFullScreen() {
-  if (!mFullScreen)
-    return;
-
-  RemovePluginView();
-
-  mFullScreen = false;
-
-  int32_t model = mInstance->GetANPDrawingModel();
-
-  if (model == kSurface_ANPDrawingModel) {
-    // We need to do this immediately, otherwise Flash
-    // sometimes causes a deadlock (bug 762407)
-    AddPluginView(GetPluginRect());
-  }
-
-  mInstance->NotifyFullScreen(mFullScreen);
-
-  // This will cause Paint() to be called, which is where
-  // we normally add/update views and layers
-  Invalidate();
-}
-
-void nsPluginInstanceOwner::ExitFullScreen(jobject view) {
-  JNIEnv* env = jni::GetGeckoThreadEnv();
-
-  if (sFullScreenInstance && sFullScreenInstance->mInstance &&
-      env->IsSameObject(view, (jobject)sFullScreenInstance->mInstance->GetJavaSurface())) {
-    sFullScreenInstance->ExitFullScreen();
-  }
-}
-
-#endif
-
 nsresult nsPluginInstanceOwner::DispatchFocusToPlugin(nsIDOMEvent* aFocusEvent)
 {
-#ifdef MOZ_WIDGET_ANDROID
-  if (mInstance) {
-    ANPEvent event;
-    event.inSize = sizeof(ANPEvent);
-    event.eventType = kLifecycle_ANPEventType;
-
-    nsAutoString eventType;
-    aFocusEvent->GetType(eventType);
-    if (eventType.EqualsLiteral("focus")) {
-      event.data.lifecycle.action = kGainFocus_ANPLifecycleAction;
-    }
-    else if (eventType.EqualsLiteral("blur")) {
-      event.data.lifecycle.action = kLoseFocus_ANPLifecycleAction;
-    }
-    else {
-      NS_ASSERTION(false, "nsPluginInstanceOwner::DispatchFocusToPlugin, wierd eventType");
-    }
-    mInstance->HandleEvent(&event, nullptr);
-  }
-#endif
-
 #ifndef XP_MACOSX
   if (!mPluginWindow || (mPluginWindow->type == NPWindowTypeWindow)) {
     // continue only for cases without child window
     return aFocusEvent->PreventDefault(); // consume event
   }
 #endif
 
   WidgetEvent* theEvent = aFocusEvent->WidgetEventPtr();
@@ -2743,106 +2467,16 @@ nsEventStatus nsPluginInstanceOwner::Pro
   event.send_event = False;
 
   int16_t response = kNPEventNotHandled;
   mInstance->HandleEvent(&pluginEvent, &response, NS_PLUGIN_CALL_SAFE_TO_REENTER_GECKO);
   if (response == kNPEventHandled)
     rv = nsEventStatus_eConsumeNoDefault;
 #endif
 
-#ifdef MOZ_WIDGET_ANDROID
-  // this code supports windowless plugins
-  {
-    // The plugin needs focus to receive keyboard and touch events
-    nsIFocusManager* fm = nsFocusManager::GetFocusManager();
-    if (fm) {
-      nsCOMPtr<nsIDOMElement> elem = do_QueryReferent(mContent);
-      fm->SetFocus(elem, 0);
-    }
-  }
-  switch(anEvent.mClass) {
-    case eMouseEventClass:
-      {
-        switch (anEvent.mMessage) {
-          case eMouseClick:
-          case eMouseDoubleClick:
-          case eMouseAuxClick:
-            // Button up/down events sent instead.
-            return rv;
-          default:
-            break;
-          }
-
-        // Get reference point relative to plugin origin.
-        const nsPresContext* presContext = mPluginFrame->PresContext();
-        nsPoint appPoint =
-          nsLayoutUtils::GetEventCoordinatesRelativeTo(&anEvent, mPluginFrame) -
-          mPluginFrame->GetContentRectRelativeToSelf().TopLeft();
-        nsIntPoint pluginPoint(presContext->AppUnitsToDevPixels(appPoint.x),
-                               presContext->AppUnitsToDevPixels(appPoint.y));
-
-        switch (anEvent.mMessage) {
-          case eMouseMove:
-            {
-              // are these going to be touch events?
-              // pluginPoint.x;
-              // pluginPoint.y;
-            }
-            break;
-          case eMouseDown:
-            {
-              ANPEvent event;
-              event.inSize = sizeof(ANPEvent);
-              event.eventType = kMouse_ANPEventType;
-              event.data.mouse.action = kDown_ANPMouseAction;
-              event.data.mouse.x = pluginPoint.x;
-              event.data.mouse.y = pluginPoint.y;
-              mInstance->HandleEvent(&event, nullptr, NS_PLUGIN_CALL_SAFE_TO_REENTER_GECKO);
-            }
-            break;
-          case eMouseUp:
-            {
-              ANPEvent event;
-              event.inSize = sizeof(ANPEvent);
-              event.eventType = kMouse_ANPEventType;
-              event.data.mouse.action = kUp_ANPMouseAction;
-              event.data.mouse.x = pluginPoint.x;
-              event.data.mouse.y = pluginPoint.y;
-              mInstance->HandleEvent(&event, nullptr, NS_PLUGIN_CALL_SAFE_TO_REENTER_GECKO);
-            }
-            break;
-          default:
-            break;
-          }
-      }
-      break;
-
-    case eKeyboardEventClass:
-     {
-       const WidgetKeyboardEvent& keyEvent = *anEvent.AsKeyboardEvent();
-       LOG("Firing eKeyboardEventClass %d %d\n",
-           keyEvent.mKeyCode, keyEvent.mCharCode);
-       // pluginEvent is initialized by nsWindow::InitKeyEvent().
-       const ANPEvent* pluginEvent = static_cast<const ANPEvent*>(keyEvent.mPluginEvent);
-       if (pluginEvent) {
-         MOZ_ASSERT(pluginEvent->inSize == sizeof(ANPEvent));
-         MOZ_ASSERT(pluginEvent->eventType == kKey_ANPEventType);
-         mInstance->HandleEvent(const_cast<ANPEvent*>(pluginEvent),
-                                nullptr,
-                                NS_PLUGIN_CALL_SAFE_TO_REENTER_GECKO);
-       }
-     }
-     break;
-
-    default:
-      break;
-    }
-    rv = nsEventStatus_eConsumeNoDefault;
-#endif
-
   return rv;
 }
 
 nsresult
 nsPluginInstanceOwner::Destroy()
 {
   SetFrame(nullptr);
 
@@ -2879,20 +2513,16 @@ nsPluginInstanceOwner::Destroy()
   content->RemoveEventListener(NS_LITERAL_STRING("dragstart"), this, true);
   content->RemoveEventListener(NS_LITERAL_STRING("dragend"), this, true);
   content->RemoveSystemEventListener(NS_LITERAL_STRING("compositionstart"),
                                      this, true);
   content->RemoveSystemEventListener(NS_LITERAL_STRING("compositionend"),
                                      this, true);
   content->RemoveSystemEventListener(NS_LITERAL_STRING("text"), this, true);
 
-#if MOZ_WIDGET_ANDROID
-  RemovePluginView();
-#endif
-
   if (mWidget) {
     if (mPluginWindow) {
       mPluginWindow->SetPluginWidget(nullptr);
     }
 
     nsCOMPtr<nsIPluginWidget> pluginWidget = do_QueryInterface(mWidget);
     if (pluginWidget) {
       pluginWidget->SetPluginInstanceOwner(nullptr);
@@ -2952,82 +2582,16 @@ void nsPluginInstanceOwner::Paint(const 
   NPEvent pluginEvent;
   pluginEvent.event = WM_PAINT;
   pluginEvent.wParam = WPARAM(aDC);
   pluginEvent.lParam = LPARAM(&aDirty);
   mInstance->HandleEvent(&pluginEvent, nullptr);
 }
 #endif
 
-#ifdef MOZ_WIDGET_ANDROID
-
-void nsPluginInstanceOwner::Paint(gfxContext* aContext,
-                                  const gfxRect& aFrameRect,
-                                  const gfxRect& aDirtyRect)
-{
-  if (!mInstance || !mPluginFrame || !mPluginDocumentActiveState || mFullScreen)
-    return;
-
-  int32_t model = mInstance->GetANPDrawingModel();
-
-  if (model == kSurface_ANPDrawingModel) {
-    if (!AddPluginView(GetPluginRect())) {
-      Invalidate();
-    }
-    return;
-  }
-
-  if (model != kBitmap_ANPDrawingModel)
-    return;
-
-#ifdef ANP_BITMAP_DRAWING_MODEL
-  static RefPtr<gfxImageSurface> pluginSurface;
-
-  if (pluginSurface == nullptr ||
-      aFrameRect.width  != pluginSurface->Width() ||
-      aFrameRect.height != pluginSurface->Height()) {
-
-    pluginSurface = new gfxImageSurface(gfx::IntSize(aFrameRect.width, aFrameRect.height),
-                                        SurfaceFormat::A8R8G8B8_UINT32);
-    if (!pluginSurface)
-      return;
-  }
-
-  // Clears buffer.  I think this is needed.
-  gfxUtils::ClearThebesSurface(pluginSurface);
-
-  ANPEvent event;
-  event.inSize = sizeof(ANPEvent);
-  event.eventType = 4;
-  event.data.draw.model = 1;
-
-  event.data.draw.clip.top     = 0;
-  event.data.draw.clip.left    = 0;
-  event.data.draw.clip.bottom  = aFrameRect.width;
-  event.data.draw.clip.right   = aFrameRect.height;
-
-  event.data.draw.data.bitmap.format   = kRGBA_8888_ANPBitmapFormat;
-  event.data.draw.data.bitmap.width    = aFrameRect.width;
-  event.data.draw.data.bitmap.height   = aFrameRect.height;
-  event.data.draw.data.bitmap.baseAddr = pluginSurface->Data();
-  event.data.draw.data.bitmap.rowBytes = aFrameRect.width * 4;
-
-  if (!mInstance)
-    return;
-
-  mInstance->HandleEvent(&event, nullptr);
-
-  aContext->SetOp(gfx::CompositionOp::OP_SOURCE);
-  aContext->SetSource(pluginSurface, gfxPoint(aFrameRect.x, aFrameRect.y));
-  aContext->Clip(aFrameRect);
-  aContext->Paint();
-#endif
-}
-#endif
-
 #if defined(MOZ_X11)
 void nsPluginInstanceOwner::Paint(gfxContext* aContext,
                                   const gfxRect& aFrameRect,
                                   const gfxRect& aDirtyRect)
 {
   if (!mInstance || !mPluginFrame)
     return;
 
@@ -3623,34 +3187,16 @@ nsPluginInstanceOwner::UpdateDocumentAct
 {
   AUTO_PROFILER_LABEL("nsPluginInstanceOwner::UpdateDocumentActiveState",
                       OTHER);
 
   mPluginDocumentActiveState = aIsActive;
 #ifndef XP_MACOSX
   UpdateWindowPositionAndClipRect(true);
 
-#ifdef MOZ_WIDGET_ANDROID
-  if (mInstance) {
-    if (!mPluginDocumentActiveState) {
-      RemovePluginView();
-    }
-
-    mInstance->NotifyOnScreen(mPluginDocumentActiveState);
-
-    // This is, perhaps, incorrect. It is supposed to be sent
-    // when "the webview has paused or resumed". The side effect
-    // is that Flash video players pause or resume (if they were
-    // playing before) based on the value here. I personally think
-    // we want that on Android when switching to another tab, so
-    // that's why we call it here.
-    mInstance->NotifyForeground(mPluginDocumentActiveState);
-  }
-#endif // #ifdef MOZ_WIDGET_ANDROID
-
   // We don't have a connection to PluginWidgetParent in the chrome
   // process when dealing with tab visibility changes, so this needs
   // to be forwarded over after the active state is updated. If we
   // don't hide plugin widgets in hidden tabs, the native child window
   // in chrome will remain visible after a tab switch.
   if (mWidget && XRE_IsContentProcess()) {
     mWidget->Show(aIsActive);
     mWidget->Enable(aIsActive);
--- a/dom/plugins/base/nsPluginInstanceOwner.h
+++ b/dom/plugins/base/nsPluginInstanceOwner.h
@@ -24,17 +24,17 @@
 #include <ApplicationServices/ApplicationServices.h>
 #endif
 
 class nsIInputStream;
 class nsPluginDOMContextMenuListener;
 class nsPluginFrame;
 class nsDisplayListBuilder;
 
-#if defined(MOZ_X11) || defined(ANDROID)
+#if defined(MOZ_X11)
 class gfxContext;
 #endif
 
 namespace mozilla {
 class TextComposition;
 namespace dom {
 struct MozPluginParameter;
 } // namespace dom
@@ -103,17 +103,17 @@ public:
   nsresult Destroy();
 
 #ifdef XP_WIN
   void Paint(const RECT& aDirty, HDC aDC);
 #elif defined(XP_MACOSX)
   void Paint(const gfxRect& aDirtyRect, CGContextRef cgContext);
   void RenderCoreAnimation(CGContextRef aCGContext, int aWidth, int aHeight);
   void DoCocoaEventDrawRect(const gfxRect& aDrawRect, CGContextRef cgContext);
-#elif defined(MOZ_X11) || defined(ANDROID)
+#elif defined(MOZ_X11)
   void Paint(gfxContext* aContext,
              const gfxRect& aFrameRect,
              const gfxRect& aDirtyRect);
 #endif
 
   //locals
 
   nsresult Init(nsIContent* aContent);
@@ -249,31 +249,16 @@ public:
   void SetBackgroundUnknown();
   already_AddRefed<DrawTarget> BeginUpdateBackground(const nsIntRect& aRect);
   void EndUpdateBackground(const nsIntRect& aRect);
 
   bool UseAsyncRendering();
 
   already_AddRefed<nsIURI> GetBaseURI() const;
 
-#ifdef MOZ_WIDGET_ANDROID
-  // Returns the image container for the specified VideoInfo
-  void GetVideos(nsTArray<nsNPAPIPluginInstance::VideoInfo*>& aVideos);
-  already_AddRefed<mozilla::layers::ImageContainer> GetImageContainerForVideo(nsNPAPIPluginInstance::VideoInfo* aVideoInfo);
-
-  void Invalidate();
-  void Recomposite();
-
-  void RequestFullScreen();
-  void ExitFullScreen();
-
-  // Called from nsAppShell when we removed the fullscreen view.
-  static void ExitFullScreen(jobject view);
-#endif
-
   bool GetCompositionString(uint32_t aIndex, nsTArray<uint8_t>* aString,
                             int32_t* aLength);
   bool SetCandidateWindow(
            const mozilla::widget::CandidateWindowPosition& aPosition);
   bool RequestCommitOrCancel(bool aCommitted);
 
   // See nsIKeyEventInPluginCallback
   virtual void HandledWindowedPluginKeyEvent(
@@ -297,25 +282,16 @@ private:
   // return FALSE if LayerSurface dirty (newly created and don't have valid plugin content yet)
   bool IsUpToDate()
   {
     nsIntSize size;
     return NS_SUCCEEDED(mInstance->GetImageSize(&size)) &&
     size == nsIntSize(mPluginWindow->width, mPluginWindow->height);
   }
 
-#ifdef MOZ_WIDGET_ANDROID
-  mozilla::LayoutDeviceRect GetPluginRect();
-  bool AddPluginView(const mozilla::LayoutDeviceRect& aRect = mozilla::LayoutDeviceRect(0, 0, 0, 0));
-  void RemovePluginView();
-
-  bool mFullScreen;
-  void* mJavaView;
-#endif
-
 #if defined(XP_WIN)
   nsIWidget* GetContainingWidgetIfOffset();
   already_AddRefed<mozilla::TextComposition> GetTextComposition();
   void HandleNoConsumedCompositionMessage(
     mozilla::WidgetCompositionEvent* aCompositionEvent,
     const NPEvent* aPluginEvent);
   bool mGotCompositionData;
   bool mSentStartComposition;
--- a/dom/plugins/base/nsPluginTags.cpp
+++ b/dom/plugins/base/nsPluginTags.cpp
@@ -690,21 +690,16 @@ nsPluginTag::GetNiceName(nsACString & aR
 {
   aResult = GetNiceFileName();
   return NS_OK;
 }
 
 NS_IMETHODIMP
 nsPluginTag::GetBlocklistState(uint32_t *aResult)
 {
-#if defined(MOZ_WIDGET_ANDROID)
-  *aResult = nsIBlocklistService::STATE_NOT_BLOCKED;
-  return NS_OK;
-#else
-
   // If we're in the content process, assume our cache state to always be valid,
   // as the only way it can be updated is via a plugin list push from the
   // parent process.
   if (!XRE_IsParentProcess()) {
     *aResult = mCachedBlocklistState;
     return NS_OK;
   }
 
@@ -720,17 +715,16 @@ nsPluginTag::GetBlocklistState(uint32_t 
                                                    EmptyString(), aResult))) {
     *aResult = nsIBlocklistService::STATE_NOT_BLOCKED;
   }
 
   MOZ_ASSERT(*aResult <= UINT16_MAX);
   mCachedBlocklistState = (uint16_t) *aResult;
   mCachedBlocklistStateValid = true;
   return NS_OK;
-#endif // defined(MOZ_WIDGET_ANDROID)
 }
 
 void
 nsPluginTag::SetBlocklistState(uint16_t aBlocklistState)
 {
   // We should only ever call this on content processes. Any calls in the parent
   // process should route through GetBlocklistState since we'll have the
   // blocklist service there.
--- a/dom/plugins/base/nsPluginsDirUnix.cpp
+++ b/dom/plugins/base/nsPluginsDirUnix.cpp
@@ -208,26 +208,16 @@ static void LoadExtraSharedLibs()
 /* nsPluginsDir implementation */
 
 bool nsPluginsDir::IsPluginFile(nsIFile* file)
 {
     nsAutoCString filename;
     if (NS_FAILED(file->GetNativeLeafName(filename)))
         return false;
 
-#ifdef ANDROID
-    // It appears that if you load
-    // 'libstagefright_honeycomb.so' on froyo, or
-    // 'libstagefright_froyo.so' on honeycomb, we will abort.
-    // Since these are just helper libs, we can ignore.
-    const char *cFile = filename.get();
-    if (strstr(cFile, "libstagefright") != nullptr)
-        return false;
-#endif
-
     NS_NAMED_LITERAL_CSTRING(dllSuffix, LOCAL_PLUGIN_DLL_SUFFIX);
     if (filename.Length() > dllSuffix.Length() &&
         StringEndsWith(filename, dllSuffix))
         return true;
 
 #ifdef LOCAL_PLUGIN_DLL_ALT_SUFFIX
     NS_NAMED_LITERAL_CSTRING(dllAltSuffix, LOCAL_PLUGIN_DLL_ALT_SUFFIX);
     if (filename.Length() > dllAltSuffix.Length() &&
--- a/dom/plugins/test/testplugin/testplugin.mozbuild
+++ b/dom/plugins/test/testplugin/testplugin.mozbuild
@@ -17,20 +17,16 @@ toolkit = CONFIG['MOZ_WIDGET_TOOLKIT']
 if toolkit == 'cocoa':
     UNIFIED_SOURCES += [
         'nptest_macosx.mm'
     ]
 elif toolkit in ('gtk2', 'gtk3'):
     UNIFIED_SOURCES += [
         'nptest_gtk2.cpp',
     ]
-elif toolkit == 'android':
-    UNIFIED_SOURCES += [
-        'nptest_droid.cpp',
-    ]
 elif toolkit == 'windows':
     UNIFIED_SOURCES += [
         'nptest_windows.cpp',
     ]
     OS_LIBS += [
         'msimg32',
         'imm32'
     ]
--- a/dom/security/test/gtest/TestCSPParser.cpp
+++ b/dom/security/test/gtest/TestCSPParser.cpp
@@ -14,18 +14,16 @@
 #define nsAString_h___
 #define nsString_h___
 #define nsStringFwd_h___
 #define nsReadableUtils_h___
 class nsACString;
 class nsAString;
 class nsString;
 class nsCString;
-class nsAdoptingString;
-class nsAdoptingCString;
 class nsXPIDLString;
 template<class T> class nsReadingIterator;
 #endif
 
 #include "nsIContentSecurityPolicy.h"
 #include "nsNetUtil.h"
 #include "nsIScriptSecurityManager.h"
 #include "mozilla/dom/nsCSPContext.h"
--- a/dom/svg/SVGFilterElement.cpp
+++ b/dom/svg/SVGFilterElement.cpp
@@ -128,20 +128,20 @@ SVGFilterElement::IsAttributeMapped(cons
   };
   return FindAttributeDependence(name, map) ||
     SVGFilterElementBase::IsAttributeMapped(name);
 }
 
 void
 SVGFilterElement::Invalidate()
 {
-  nsTObserverArray<nsIMutationObserver*> *observers = GetMutationObservers();
+  nsAutoTObserverArray<nsIMutationObserver*, 1> *observers = GetMutationObservers();
 
   if (observers && !observers->IsEmpty()) {
-    nsTObserverArray<nsIMutationObserver*>::ForwardIterator iter(*observers);
+    nsAutoTObserverArray<nsIMutationObserver*, 1>::ForwardIterator iter(*observers);
     while (iter.HasMore()) {
       nsCOMPtr<nsIMutationObserver> obs(iter.GetNext());
       nsCOMPtr<nsISVGFilterReference> filter = do_QueryInterface(obs);
       if (filter)
         filter->Invalidate();
     }
   }
 }
--- a/editor/libeditor/EditorBase.cpp
+++ b/editor/libeditor/EditorBase.cpp
@@ -123,17 +123,16 @@ using namespace dom;
 using namespace widget;
 
 /*****************************************************************************
  * mozilla::EditorBase
  *****************************************************************************/
 
 EditorBase::EditorBase()
   : mPlaceholderName(nullptr)
-  , mSelState(nullptr)
   , mModCount(0)
   , mFlags(0)
   , mUpdateCount(0)
   , mPlaceholderBatch(0)
   , mAction(EditAction::none)
   , mIMETextOffset(0)
   , mIMETextLength(0)
   , mDirection(eNone)
@@ -969,17 +968,17 @@ EditorBase::BeginPlaceHolderTransaction(
   if (!mPlaceholderBatch) {
     NotifyEditorObservers(eNotifyEditorObserversOfBefore);
     // time to turn on the batch
     BeginUpdateViewBatch();
     mPlaceholderTransaction = nullptr;
     mPlaceholderName = aName;
     RefPtr<Selection> selection = GetSelection();
     if (selection) {
-      mSelState = MakeUnique<SelectionState>();
+      mSelState.emplace();
       mSelState->SaveSelection(selection);
       // Composition transaction can modify multiple nodes and it merges text
       // node for ime into single text node.
       // So if current selection is into IME text node, it might be failed
       // to restore selection by UndoTransaction.
       // So we need update selection by range updater.
       if (mPlaceholderName == nsGkAtoms::IMETxnName) {
         mRangeUpdater.RegisterSelectionState(*mSelState);
@@ -1034,17 +1033,17 @@ EditorBase::EndPlaceHolderTransaction()
     }
 
     if (mSelState) {
       // we saved the selection state, but never got to hand it to placeholder
       // (else we ould have nulled out this pointer), so destroy it to prevent leaks.
       if (mPlaceholderName == nsGkAtoms::IMETxnName) {
         mRangeUpdater.DropSelectionState(*mSelState);
       }
-      mSelState = nullptr;
+      mSelState.reset();
     }
     // We might have never made a placeholder if no action took place.
     if (mPlaceholderTransaction) {
       mPlaceholderTransaction->EndPlaceHolderBatch();
       // notify editor observers of action but if composing, it's done by
       // compositionchange event handler.
       if (!mComposition) {
         NotifyEditorObservers(eNotifyEditorObserversOfEnd);
@@ -2718,21 +2717,17 @@ EditorBase::NotifyDocumentListeners(
 
   return rv;
 }
 
 nsresult
 EditorBase::SetTextImpl(Selection& aSelection, const nsAString& aString,
                         Text& aCharData)
 {
-  RefPtr<SetTextTransaction> transaction =
-    CreateTxnForSetText(aString, aCharData);
-  if (NS_WARN_IF(!transaction)) {
-    return NS_ERROR_FAILURE;
-  }
+  SetTextTransaction transaction(aCharData, aString, *this, &mRangeUpdater);
 
   uint32_t length = aCharData.Length();
 
   AutoRules beginRulesSniffing(this, EditAction::setText,
                                nsIEditor::eNext);
 
   // Let listeners know what's up
   {
@@ -2746,17 +2741,20 @@ EditorBase::SetTextImpl(Selection& aSele
       if (!aString.IsEmpty()) {
         listener->WillInsertText(
           static_cast<nsIDOMCharacterData*>(aCharData.AsDOMNode()), 0,
           aString);
       }
     }
   }
 
-  nsresult rv = DoTransaction(&aSelection, transaction);
+  // We don't support undo here, so we don't really need all of the transaction
+  // machinery, therefore we can run our transaction directly, breaking all of
+  // the rules!
+  nsresult rv = transaction.DoTransaction();
 
   // Let listeners know what happened
   {
     AutoActionListenerArray listeners(mActionListeners);
     for (auto& listener : listeners) {
       if (length) {
         listener->DidDeleteText(
           static_cast<nsIDOMCharacterData*>(aCharData.AsDOMNode()), 0,
@@ -2779,25 +2777,16 @@ EditorBase::CreateTxnForInsertText(const
                                    int32_t aOffset)
 {
   RefPtr<InsertTextTransaction> transaction =
     new InsertTextTransaction(aTextNode, aOffset, aStringToInsert, *this,
                               &mRangeUpdater);
   return transaction.forget();
 }
 
-already_AddRefed<SetTextTransaction>
-EditorBase::CreateTxnForSetText(const nsAString& aString,
-                                Text& aTextNode)
-{
-  RefPtr<SetTextTransaction> transaction =
-    new SetTextTransaction(aTextNode, aString, *this, &mRangeUpdater);
-  return transaction.forget();
-}
-
 nsresult
 EditorBase::DeleteText(nsGenericDOMDataNode& aCharData,
                        uint32_t aOffset,
                        uint32_t aLength)
 {
   RefPtr<DeleteTextTransaction> transaction =
     CreateTxnForDeleteText(aCharData, aOffset, aLength);
   NS_ENSURE_STATE(transaction);
--- a/editor/libeditor/EditorBase.h
+++ b/editor/libeditor/EditorBase.h
@@ -2,20 +2,20 @@
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #ifndef mozilla_EditorBase_h
 #define mozilla_EditorBase_h
 
 #include "mozilla/Assertions.h"         // for MOZ_ASSERT, etc.
+#include "mozilla/Maybe.h"              // for Maybe
 #include "mozilla/OwningNonNull.h"      // for OwningNonNull
 #include "mozilla/SelectionState.h"     // for RangeUpdater, etc.
 #include "mozilla/StyleSheet.h"         // for StyleSheet
-#include "mozilla/UniquePtr.h"
 #include "mozilla/WeakPtr.h"            // for WeakPtr
 #include "mozilla/dom/Text.h"
 #include "nsCOMPtr.h"                   // for already_AddRefed, nsCOMPtr
 #include "nsCycleCollectionParticipant.h"
 #include "nsGkAtoms.h"
 #include "nsIDocument.h"                // for nsIDocument
 #include "nsIEditor.h"                  // for nsIEditor, etc.
 #include "nsIObserver.h"                // for NS_DECL_NSIOBSERVER, etc.
@@ -428,19 +428,16 @@ protected:
   /**
    * Create a transaction for inserting aStringToInsert into aTextNode.  Never
    * returns null.
    */
   already_AddRefed<mozilla::InsertTextTransaction>
     CreateTxnForInsertText(const nsAString& aStringToInsert, Text& aTextNode,
                            int32_t aOffset);
 
-  already_AddRefed<SetTextTransaction>
-    CreateTxnForSetText(const nsAString& aString, Text& aTextNode);
-
   /**
    * Never returns null.
    */
   already_AddRefed<mozilla::CompositionTransaction>
     CreateTxnForComposition(const nsAString& aStringToInsert);
 
   /**
    * Create a transaction for adding a style sheet.
@@ -1131,17 +1128,17 @@ protected:
   // The form field as an event receiver.
   nsCOMPtr<dom::EventTarget> mEventTarget;
   nsCOMPtr<nsIDOMEventListener> mEventListener;
   // Strong reference to placeholder for begin/end batch purposes.
   RefPtr<PlaceholderTransaction> mPlaceholderTransaction;
   // Name of placeholder transaction.
   nsIAtom* mPlaceholderName;
   // Saved selection state for placeholder transaction batching.
-  mozilla::UniquePtr<SelectionState> mSelState;
+  mozilla::Maybe<SelectionState> mSelState;
   // IME composition this is not null between compositionstart and
   // compositionend.
   RefPtr<TextComposition> mComposition;
 
   // Listens to all low level actions on the doc.
   typedef AutoTArray<OwningNonNull<nsIEditActionListener>, 5>
             AutoActionListenerArray;
   AutoActionListenerArray mActionListeners;
--- a/editor/libeditor/PlaceholderTransaction.cpp
+++ b/editor/libeditor/PlaceholderTransaction.cpp
@@ -14,48 +14,44 @@
 
 namespace mozilla {
 
 using namespace dom;
 
 PlaceholderTransaction::PlaceholderTransaction(
                           EditorBase& aEditorBase,
                           nsIAtom* aName,
-                          UniquePtr<SelectionState> aSelState)
+                          Maybe<SelectionState>&& aSelState)
   : mAbsorb(true)
   , mForwarding(nullptr)
   , mCompositionTransaction(nullptr)
   , mCommitted(false)
-  , mStartSel(Move(aSelState))
+  , mStartSel(Move(*aSelState))
   , mEditorBase(&aEditorBase)
 {
   mName = aName;
 }
 
 PlaceholderTransaction::~PlaceholderTransaction()
 {
 }
 
 NS_IMPL_CYCLE_COLLECTION_CLASS(PlaceholderTransaction)
 
 NS_IMPL_CYCLE_COLLECTION_UNLINK_BEGIN_INHERITED(PlaceholderTransaction,
                                                 EditAggregateTransaction)
-  if (tmp->mStartSel) {
-    ImplCycleCollectionUnlink(*tmp->mStartSel);
-  }
   NS_IMPL_CYCLE_COLLECTION_UNLINK(mEditorBase);
+  NS_IMPL_CYCLE_COLLECTION_UNLINK(mStartSel);
   NS_IMPL_CYCLE_COLLECTION_UNLINK(mEndSel);
 NS_IMPL_CYCLE_COLLECTION_UNLINK_END
 
 NS_IMPL_CYCLE_COLLECTION_TRAVERSE_BEGIN_INHERITED(PlaceholderTransaction,
                                                   EditAggregateTransaction)
-  if (tmp->mStartSel) {
-    ImplCycleCollectionTraverse(cb, *tmp->mStartSel, "mStartSel", 0);
-  }
   NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mEditorBase);
+  NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mStartSel);
   NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mEndSel);
 NS_IMPL_CYCLE_COLLECTION_TRAVERSE_END
 
 NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION(PlaceholderTransaction)
   NS_INTERFACE_MAP_ENTRY(nsIAbsorbingTransaction)
 NS_INTERFACE_MAP_END_INHERITING(EditAggregateTransaction)
 
 NS_IMPL_ADDREF_INHERITED(PlaceholderTransaction, EditAggregateTransaction)
@@ -73,22 +69,20 @@ PlaceholderTransaction::UndoTransaction(
   if (NS_WARN_IF(!mEditorBase)) {
     return NS_ERROR_NOT_INITIALIZED;
   }
 
   // Undo transactions.
   nsresult rv = EditAggregateTransaction::UndoTransaction();
   NS_ENSURE_SUCCESS(rv, rv);
 
-  NS_ENSURE_TRUE(mStartSel, NS_ERROR_NULL_POINTER);
-
   // now restore selection
   RefPtr<Selection> selection = mEditorBase->GetSelection();
   NS_ENSURE_TRUE(selection, NS_ERROR_NULL_POINTER);
-  return mStartSel->RestoreSelection(selection);
+  return mStartSel.RestoreSelection(selection);
 }
 
 NS_IMETHODIMP
 PlaceholderTransaction::RedoTransaction()
 {
   if (NS_WARN_IF(!mEditorBase)) {
     return NS_ERROR_NOT_INITIALIZED;
   }
@@ -217,21 +211,21 @@ PlaceholderTransaction::GetTxnName(nsIAt
 
 NS_IMETHODIMP
 PlaceholderTransaction::StartSelectionEquals(SelectionState* aSelState,
                                              bool* aResult)
 {
   // determine if starting selection matches the given selection state.
   // note that we only care about collapsed selections.
   NS_ENSURE_TRUE(aResult && aSelState, NS_ERROR_NULL_POINTER);
-  if (!mStartSel->IsCollapsed() || !aSelState->IsCollapsed()) {
+  if (!mStartSel.IsCollapsed() || !aSelState->IsCollapsed()) {
     *aResult = false;
     return NS_OK;
   }
-  *aResult = mStartSel->IsEqual(aSelState);
+  *aResult = mStartSel.IsEqual(aSelState);
   return NS_OK;
 }
 
 NS_IMETHODIMP
 PlaceholderTransaction::EndPlaceHolderBatch()
 {
   mAbsorb = false;
 
--- a/editor/libeditor/PlaceholderTransaction.h
+++ b/editor/libeditor/PlaceholderTransaction.h
@@ -3,17 +3,17 @@
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #ifndef PlaceholderTransaction_h
 #define PlaceholderTransaction_h
 
 #include "EditAggregateTransaction.h"
 #include "mozilla/EditorUtils.h"
-#include "mozilla/UniquePtr.h"
+#include "mozilla/Maybe.h"
 #include "nsIAbsorbingTransaction.h"
 #include "nsIDOMNode.h"
 #include "nsCOMPtr.h"
 #include "nsWeakPtr.h"
 
 namespace mozilla {
 
 class CompositionTransaction;
@@ -28,17 +28,17 @@ class CompositionTransaction;
 class PlaceholderTransaction final
  : public EditAggregateTransaction
  , public nsIAbsorbingTransaction
 {
 public:
   NS_DECL_ISUPPORTS_INHERITED
 
   PlaceholderTransaction(EditorBase& aEditorBase, nsIAtom* aName,
-                         UniquePtr<SelectionState> aSelState);
+                         Maybe<SelectionState>&& aSelState);
 
   NS_DECL_CYCLE_COLLECTION_CLASS_INHERITED(PlaceholderTransaction,
                                            EditAggregateTransaction)
 // ------------ EditAggregateTransaction -----------------------
 
   NS_DECL_EDITTRANSACTIONBASE
 
   NS_IMETHOD RedoTransaction() override;
@@ -76,18 +76,17 @@ protected:
   // Do we stop auto absorbing any matching placeholder transactions?
   bool mCommitted;
 
   // These next two members store the state of the selection in a safe way.
   // Selection at the start of the transaction is stored, as is the selection
   // at the end.  This is so that UndoTransaction() and RedoTransaction() can
   // restore the selection properly.
 
-  // Use a pointer because this is constructed before we exist.
-  UniquePtr<SelectionState> mStartSel;
+  SelectionState mStartSel;
   SelectionState mEndSel;
 
   // The editor for this transaction.
   RefPtr<EditorBase> mEditorBase;
 };
 
 } // namespace mozilla
 
--- a/editor/libeditor/SetTextTransaction.cpp
+++ b/editor/libeditor/SetTextTransaction.cpp
@@ -9,51 +9,33 @@
 #include "mozilla/DebugOnly.h"          // DebugOnly
 #include "mozilla/EditorBase.h"         // mEditorBase
 #include "mozilla/SelectionState.h"     // RangeUpdater
 #include "mozilla/dom/Selection.h"      // Selection local var
 #include "mozilla/dom/Text.h"           // mTextNode
 #include "nsAString.h"                  // nsAString parameter
 #include "nsDebug.h"                    // for NS_ASSERTION, etc.
 #include "nsError.h"                    // for NS_OK, etc.
-#include "nsQueryObject.h"              // for do_QueryObject
 
 namespace mozilla {
 
 using namespace dom;
 
 SetTextTransaction::SetTextTransaction(Text& aTextNode,
                                        const nsAString& aStringToSet,
                                        EditorBase& aEditorBase,
                                        RangeUpdater* aRangeUpdater)
   : mTextNode(&aTextNode)
   , mStringToSet(aStringToSet)
   , mEditorBase(&aEditorBase)
   , mRangeUpdater(aRangeUpdater)
 {
 }
 
-SetTextTransaction::~SetTextTransaction()
-{
-}
-
-NS_IMPL_CYCLE_COLLECTION_INHERITED(SetTextTransaction, EditTransactionBase,
-                                   mEditorBase,
-                                   mTextNode)
-
-NS_IMPL_ADDREF_INHERITED(SetTextTransaction, EditTransactionBase)
-NS_IMPL_RELEASE_INHERITED(SetTextTransaction, EditTransactionBase)
-NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION(SetTextTransaction)
-  if (aIID.Equals(NS_GET_IID(SetTextTransaction))) {
-    foundInterface = static_cast<nsITransaction*>(this);
-  } else
-NS_INTERFACE_MAP_END_INHERITING(EditTransactionBase)
-
-
-NS_IMETHODIMP
+nsresult
 SetTextTransaction::DoTransaction()
 {
   if (NS_WARN_IF(!mEditorBase) || NS_WARN_IF(!mTextNode)) {
     return NS_ERROR_NOT_AVAILABLE;
   }
 
   nsresult rv = mTextNode->GetData(mPreviousData);
   if (NS_WARN_IF(NS_FAILED(rv))) {
@@ -77,33 +59,9 @@ SetTextTransaction::DoTransaction()
                  "Selection could not be collapsed after insert");
   }
   mRangeUpdater->SelAdjDeleteText(mTextNode, 0, mPreviousData.Length());
   mRangeUpdater->SelAdjInsertText(*mTextNode, 0, mStringToSet);
 
   return NS_OK;
 }
 
-NS_IMETHODIMP
-SetTextTransaction::UndoTransaction()
-{
-  return mTextNode->SetData(mPreviousData);
-}
-
-NS_IMETHODIMP
-SetTextTransaction::Merge(nsITransaction* aTransaction,
-                          bool* aDidMerge)
-{
-  // Set out param default value
-  *aDidMerge = false;
-
-  return NS_OK;
-}
-
-NS_IMETHODIMP
-SetTextTransaction::GetTxnDescription(nsAString& aString)
-{
-  aString.AssignLiteral("SetTextTransaction: ");
-  aString += mStringToSet;
-  return NS_OK;
-}
-
 } // namespace mozilla
--- a/editor/libeditor/SetTextTransaction.h
+++ b/editor/libeditor/SetTextTransaction.h
@@ -2,79 +2,60 @@
 /* vim: set ts=2 sw=2 et tw=78: */
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #ifndef mozilla_SetTextTransaction_h
 #define mozilla_SetTextTransaction_h
 
-#include "mozilla/EditTransactionBase.h"  // base class
-#include "nsCycleCollectionParticipant.h" // various macros
-#include "nsID.h"                       // NS_DECLARE_STATIC_IID_ACCESSOR
-#include "nsISupportsImpl.h"            // NS_DECL_ISUPPORTS_INHERITED
+#include "mozilla/Attributes.h"         // for MOZ_STACK_CLASS
 #include "nsString.h"                   // nsString members
 #include "nscore.h"                     // NS_IMETHOD, nsAString
 
-class nsITransaction;
-
-#define NS_SETTEXTTXN_IID \
-{ 0x568bac0b, 0xa42a, 0x4150, \
-  { 0xbd, 0x90, 0x34, 0xd0, 0x2f, 0x32, 0x74, 0x2e } }
-
 namespace mozilla {
 
 class EditorBase;
 class RangeUpdater;
 
 namespace dom {
 class Text;
 } // namespace dom
 
 /**
- * A transaction that inserts text into a content node.
+ * A fake transaction that inserts text into a content node.
+ *
+ * This class mimics a transaction class but it is not intended to be used as one.
  */
-class SetTextTransaction final : public EditTransactionBase
+class MOZ_STACK_CLASS SetTextTransaction final
 {
 public:
-  NS_DECLARE_STATIC_IID_ACCESSOR(NS_SETTEXTTXN_IID)
-
   /**
    * @param aTextNode       The text content node.
    * @param aString         The new text to insert.
    * @param aEditorBase     Used to get and set the selection.
    * @param aRangeUpdater   The range updater
    */
   SetTextTransaction(dom::Text& aTextNode,
                      const nsAString& aString, EditorBase& aEditorBase,
                      RangeUpdater* aRangeUpdater);
 
-  NS_DECL_ISUPPORTS_INHERITED
-  NS_DECL_CYCLE_COLLECTION_CLASS_INHERITED(SetTextTransaction,
-                                           EditTransactionBase)
-
-  NS_DECL_EDITTRANSACTIONBASE
-
-  NS_IMETHOD Merge(nsITransaction* aTransaction, bool* aDidMerge) override;
+  nsresult DoTransaction();
 
 private:
-  virtual ~SetTextTransaction();
-
   // The Text node to operate upon.
   RefPtr<dom::Text> mTextNode;
 
   // The text to insert into mTextNode at mOffset.
   nsString mStringToSet;
 
   // The previous text for undo
   nsString mPreviousData;
 
   // The editor, which we'll need to get the selection.
-  RefPtr<EditorBase> mEditorBase;
+  EditorBase* MOZ_NON_OWNING_REF mEditorBase;
 
   RangeUpdater* mRangeUpdater;
 };
 
-NS_DEFINE_STATIC_IID_ACCESSOR(SetTextTransaction, NS_SETTEXTTXN_IID)
-
 } // namespace mozilla
 
 #endif // #ifndef mozilla_SetTextTransaction_h
--- a/gfx/layers/LayerTreeInvalidation.cpp
+++ b/gfx/layers/LayerTreeInvalidation.cpp
@@ -416,20 +416,32 @@ public:
       aCallback(container, result);
     }
 
     if (childrenChanged) {
       container->SetChildrenChanged(true);
     }
 
     if (container->UseIntermediateSurface()) {
-      IntRect bounds = invalidateWholeLayer
-                       ? mLayer->GetLocalVisibleRegion().ToUnknownRegion().GetBounds()
-                       : result.GetBounds();
-      container->SetInvalidCompositeRect(bounds);
+      Maybe<IntRect> bounds;
+
+      if (!invalidateWholeLayer) {
+        bounds = Some(result.GetBounds());
+
+        // Process changes in the visible region.
+        IntRegion newVisible = mLayer->GetLocalVisibleRegion().ToUnknownRegion();
+        if (!newVisible.IsEqual(mVisibleRegion)) {
+          newVisible.XorWith(mVisibleRegion);
+          bounds = bounds->SafeUnion(newVisible.GetBounds());
+        }
+      }
+      if (!bounds) {
+        bounds = Some(mLayer->GetLocalVisibleRegion().GetBounds().ToUnknownRect());
+      }
+      container->SetInvalidCompositeRect(bounds.value());
     }
 
     if (!mLayer->Extend3DContext()) {
       // |result| contains invalid regions only of children.
       result.Transform(GetTransformForInvalidation(mLayer));
     }
     // else, effective transforms have applied on children.
 
--- a/gfx/layers/client/ClientPaintedLayer.cpp
+++ b/gfx/layers/client/ClientPaintedLayer.cpp
@@ -65,16 +65,22 @@ ClientPaintedLayer::CanRecordLayer(Readb
   }
 
   // If we have mask layers, we have to render those first
   // In this case, don't record for now.
   if (GetMaskLayer()) {
     return false;
   }
 
+  // Component alpha layers aren't supported yet since we have to
+  // hold onto both the front/back buffer of a texture client.
+  if (GetSurfaceMode() == SurfaceMode::SURFACE_COMPONENT_ALPHA) {
+    return false;
+  }
+
   return GetAncestorMaskLayerCount() == 0;
 }
 
 void
 ClientPaintedLayer::UpdateContentClient(PaintState& aState)
 {
   Mutated();
 
--- a/gfx/layers/d3d11/MLGDeviceD3D11.cpp
+++ b/gfx/layers/d3d11/MLGDeviceD3D11.cpp
@@ -8,16 +8,17 @@
 #include "mozilla/Telemetry.h"
 #include "mozilla/WindowsVersion.h"
 #include "mozilla/gfx/GPUParent.h"
 #include "mozilla/gfx/StackArray.h"
 #include "mozilla/layers/DiagnosticsD3D11.h"
 #include "mozilla/layers/LayerMLGPU.h"
 #include "mozilla/layers/MemoryReportingMLGPU.h"
 #include "mozilla/layers/ShaderDefinitionsMLGPU.h"
+#include "mozilla/layers/UtilityMLGPU.h"
 #include "mozilla/widget/CompositorWidget.h"
 #include "mozilla/widget/WinCompositorWidget.h"
 #include "MLGShaders.h"
 #include "TextureD3D11.h"
 #include "gfxConfig.h"
 #include "gfxPrefs.h"
 
 namespace mozilla {
--- a/gfx/layers/d3d11/mlgshaders/common-vs.hlsl
+++ b/gfx/layers/d3d11/mlgshaders/common-vs.hlsl
@@ -8,17 +8,17 @@
 
 #include "common.hlsl"
 
 cbuffer VSBufSimple : register(b0)
 {
   float4x4 WorldTransform;
   float2 RenderTargetOffset;
   int SortIndexOffset;
-  float padding;
+  uint DebugFrameNumber;
 };
 
 struct Layer {
   float4x4 transform;
   float4 clipRect;
   uint4 info;
 };
 
--- a/gfx/layers/mlgpu/ContainerLayerMLGPU.cpp
+++ b/gfx/layers/mlgpu/ContainerLayerMLGPU.cpp
@@ -14,32 +14,36 @@
 #include "UtilityMLGPU.h"
 
 namespace mozilla {
 namespace layers {
 
 using namespace gfx;
 
 ContainerLayerMLGPU::ContainerLayerMLGPU(LayerManagerMLGPU* aManager)
-  : ContainerLayer(aManager, nullptr)
-  , LayerMLGPU(aManager)
+ : ContainerLayer(aManager, nullptr),
+   LayerMLGPU(aManager),
+   mInvalidateEntireSurface(false)
 {
 }
 
 ContainerLayerMLGPU::~ContainerLayerMLGPU()
 {
   while (mFirstChild) {
     RemoveChild(mFirstChild);
   }
 }
 
 bool
 ContainerLayerMLGPU::OnPrepareToRender(FrameBuilder* aBuilder)
 {
   if (!UseIntermediateSurface()) {
+    // Set this so we invalidate the entire cached render target (if any)
+    // if our container uses an intermediate surface again later.
+    mInvalidateEntireSurface = true;
     return true;
   }
 
   if ((!mRenderTarget || mChildrenChanged) &&
       gfxPrefs::AdvancedLayersEnableContainerResizing())
   {
     // Try to compute a more accurate visible region.
     AL_LOG("Computing new surface size for container %p:\n", GetLayer());
@@ -59,23 +63,29 @@ ContainerLayerMLGPU::OnPrepareToRender(F
   mTargetOffset = GetIntermediateSurfaceRect().TopLeft().ToUnknownPoint();
   mTargetSize = GetIntermediateSurfaceRect().Size().ToUnknownSize();
 
   if (mRenderTarget && mRenderTarget->GetSize() != mTargetSize) {
     mRenderTarget = nullptr;
   }
 
   gfx::IntRect viewport(gfx::IntPoint(0, 0), mTargetSize);
-  if (!mRenderTarget || !gfxPrefs::AdvancedLayersUseInvalidation()) {
+  if (!mRenderTarget ||
+      !gfxPrefs::AdvancedLayersUseInvalidation() ||
+      mInvalidateEntireSurface)
+  {
     // Fine-grained invalidation is disabled, invalidate everything.
     mInvalidRect = viewport;
   } else {
     // Clamp the invalid rect to the viewport.
+    mInvalidRect -= mTargetOffset;
     mInvalidRect = mInvalidRect.Intersect(viewport);
   }
+
+  mInvalidateEntireSurface = false;
   return true;
 }
 
 static IntRect
 GetTransformedBounds(Layer* aLayer)
 {
   IntRect bounds = aLayer->GetLocalVisibleRegion().GetBounds().ToUnknownRect();
   if (bounds.IsEmpty()) {
@@ -178,26 +188,26 @@ ContainerLayerMLGPU::UpdateRenderTarget(
 
   return mRenderTarget;
 }
 
 void
 ContainerLayerMLGPU::SetInvalidCompositeRect(const gfx::IntRect& aRect)
 {
   // For simplicity we only track the bounds of the invalid area, since regions
-  // are expensive. We can adjust this in the future if needed.
-  gfx::IntRect bounds = aRect;
-  bounds.MoveBy(-GetTargetOffset());
-
+  // are expensive.
+  //
   // Note we add the bounds to the invalid rect from the last frame, since we
-  // only clear the area that we actually paint.
-  if (Maybe<gfx::IntRect> result = mInvalidRect.SafeUnion(bounds)) {
+  // only clear the area that we actually paint. If this overflows we use the
+  // last render target size, since if that changes we'll invalidate everything
+  // anyway.
+  if (Maybe<gfx::IntRect> result = mInvalidRect.SafeUnion(aRect)) {
     mInvalidRect = result.value();
   } else {
-    mInvalidRect = gfx::IntRect(gfx::IntPoint(0, 0), GetTargetSize());
+    mInvalidateEntireSurface = true;
   }
 }
 
 void
 ContainerLayerMLGPU::ClearCachedResources()
 {
   mRenderTarget = nullptr;
 }
--- a/gfx/layers/mlgpu/ContainerLayerMLGPU.h
+++ b/gfx/layers/mlgpu/ContainerLayerMLGPU.h
@@ -62,16 +62,18 @@ protected:
 private:
   RefPtr<MLGRenderTarget> mRenderTarget;
 
   // We cache these since occlusion culling can change the visible region.
   gfx::IntPoint mTargetOffset;
   gfx::IntSize mTargetSize;
 
   // The region of the container that needs to be recomposited if visible. We
-  // store this as a rectangle instead of an nsIntRegion for efficiency.
+  // store this as a rectangle instead of an nsIntRegion for efficiency. This
+  // is in layer coordinates.
   gfx::IntRect mInvalidRect;
+  bool mInvalidateEntireSurface;
 };
 
 } // namespace layers
 } // namespace mozilla
 
 #endif // mozilla_gfx_layers_mlgpu_ContainerLayerMLGPU_h
--- a/gfx/layers/mlgpu/FrameBuilder.cpp
+++ b/gfx/layers/mlgpu/FrameBuilder.cpp
@@ -157,16 +157,17 @@ FrameBuilder::ProcessContainerLayer(Cont
 
   // If the container is not part of the invalid region, we don't draw it
   // or traverse it. Note that we do not pass the geometry here. Otherwise
   // we could decide the particular split is not visible, and because of the
   // check above, never bother traversing the container again.
   gfx::IntRect boundingBox = layer->GetClippedBoundingBox(aView, Nothing());
   const gfx::IntRect& invalidRect = aView->GetInvalidRect();
   if (boundingBox.IsEmpty() || !invalidRect.Intersects(boundingBox)) {
+    AL_LOG("Culling ContainerLayer %p that does not need painting\n", aContainer);
     return false;
   }
 
   if (!aContainer->UseIntermediateSurface()) {
     // In case the layer previously required an intermediate surface, we
     // clear any intermediate render targets here.
     layer->ClearCachedResources();
 
--- a/gfx/layers/mlgpu/LayerManagerMLGPU.cpp
+++ b/gfx/layers/mlgpu/LayerManagerMLGPU.cpp
@@ -39,17 +39,18 @@ static const int kDebugOverlayX = 2;
 static const int kDebugOverlayY = 5;
 static const int kDebugOverlayMaxWidth = 600;
 static const int kDebugOverlayMaxHeight = 96;
 
 LayerManagerMLGPU::LayerManagerMLGPU(widget::CompositorWidget* aWidget)
  : mWidget(aWidget),
    mDrawDiagnostics(false),
    mUsingInvalidation(false),
-   mCurrentFrame(nullptr)
+   mCurrentFrame(nullptr),
+   mDebugFrameNumber(0)
 {
   if (!aWidget) {
     return;
   }
 
 #ifdef WIN32
   mDevice = DeviceManagerDx::Get()->GetMLGDevice();
 #endif
@@ -261,16 +262,19 @@ LayerManagerMLGPU::EndTransaction(const 
         hexa(windowSize.width) << "," << hexa(windowSize.height) << ")";
       return;
     }
   }
 
   // Don't draw the diagnostic overlay if we want to snapshot the output.
   mDrawDiagnostics = gfxPrefs::LayersDrawFPS() && !mTarget;
   mUsingInvalidation = gfxPrefs::AdvancedLayersUseInvalidation();
+  mDebugFrameNumber++;
+
+  AL_LOG("--- Compositing frame %d ---\n", mDebugFrameNumber);
 
   // Compute transforms - and the changed area, if enabled.
   mRoot->ComputeEffectiveTransforms(Matrix4x4());
   ComputeInvalidRegion();
 
   // Build and execute draw commands, and present.
   if (PreRender()) {
     Composite();
--- a/gfx/layers/mlgpu/LayerManagerMLGPU.h
+++ b/gfx/layers/mlgpu/LayerManagerMLGPU.h
@@ -91,16 +91,19 @@ public:
   }
 
   TimeStamp GetLastCompositionEndTime() const {
     return mLastCompositionEndTime;
   }
   const nsIntRegion& GetRegionToClear() const {
     return mRegionToClear;
   }
+  uint32_t GetDebugFrameNumber() const {
+    return mDebugFrameNumber;
+  }
 
 private:
   void Composite();
   void ComputeInvalidRegion();
   void RenderLayers();
   void DrawDebugOverlay();
   bool PreRender();
   void PostRender();
@@ -125,15 +128,19 @@ private:
   IntSize mWindowSize;
   TimeStamp mCompositionStartTime;
   TimeStamp mLastCompositionEndTime;
 
   RefPtr<DrawTarget> mTarget;
   gfx::IntRect mTargetRect;
   FrameBuilder* mCurrentFrame;
 
+  // The debug frame number is incremented every frame and is included in the
+  // WorldConstants bound to vertex shaders. This allows us to correlate
+  // a frame in RenderDoc to spew in the console.
+  uint32_t mDebugFrameNumber;
   RefPtr<MLGBuffer> mDiagnosticVertices;
 };
 
 } // namespace layers
 } // namespace mozilla
 
 #endif
--- a/gfx/layers/mlgpu/MLGDevice.cpp
+++ b/gfx/layers/mlgpu/MLGDevice.cpp
@@ -349,10 +349,47 @@ MLGDevice::DrawClearRegion(const ClearRe
   // Otherwise, if we have a normal rect list, we wanted to use the faster
   // ClearView.
   if (!aHelper.mRects.IsEmpty()) {
     Color color(0.0, 0.0, 0.0, 0.0);
     ClearView(mCurrentRT, color, aHelper.mRects.Elements(), aHelper.mRects.Length());
   }
 }
 
+void
+MLGDevice::WriteAsPNG(MLGTexture* aTexture, const char* aPath)
+{
+  MLGMappedResource map;
+  if (!Map(aTexture, MLGMapType::READ, &map)) {
+    return;
+  }
+
+  RefPtr<DataSourceSurface> surface = Factory::CreateWrappingDataSourceSurface(
+    map.mData,
+    map.mStride,
+    aTexture->GetSize(),
+    SurfaceFormat::B8G8R8A8);
+  gfxUtils::WriteAsPNG(surface, aPath);
+
+  Unmap(aTexture);
+}
+
+RefPtr<MLGTexture>
+MLGDevice::CopyAndCreateReadbackTexture(MLGTexture* aTexture)
+{
+  RefPtr<MLGTexture> copy = CreateTexture(
+    aTexture->GetSize(),
+    SurfaceFormat::B8G8R8A8,
+    MLGUsage::Staging,
+    MLGTextureFlags::None);
+  if (!copy) {
+    return nullptr;
+  }
+  CopyTexture(
+    copy,
+    IntPoint(0, 0),
+    aTexture,
+    IntRect(IntPoint(0, 0), aTexture->GetSize()));
+  return copy;
+}
+
 } // namespace layers
 } // namespace mozilla
--- a/gfx/layers/mlgpu/MLGDevice.h
+++ b/gfx/layers/mlgpu/MLGDevice.h
@@ -425,16 +425,22 @@ public:
   }
 
   // Helper function for unbinding textures since SetPSTexture is overloaded.
   void UnsetPSTexture(uint32_t aSlot) {
     TextureSource* nullTexture = nullptr;
     SetPSTexture(aSlot, nullTexture);
   }
 
+  // Debugging helper function for dumping an MLGTexture to a file.
+  void WriteAsPNG(MLGTexture* aTexture, const char* aPath);
+
+  // Debugging helper function for copying a texture for later dumping to a file.
+  RefPtr<MLGTexture> CopyAndCreateReadbackTexture(MLGTexture* aTexture);
+
 protected:
   virtual ~MLGDevice();
 
   virtual void SetPrimitiveTopology(MLGPrimitiveTopology aTopology) = 0;
 
   // Optionally run a runtime test to determine if constant buffer offset
   // binding works.
   virtual bool VerifyConstantBufferOffsetting() {
--- a/gfx/layers/mlgpu/RenderViewMLGPU.cpp
+++ b/gfx/layers/mlgpu/RenderViewMLGPU.cpp
@@ -353,16 +353,17 @@ RenderViewMLGPU::Prepare()
     projection.PreScale(2.0 / float(mTarget->GetSize().width),
                         2.0 / float(mTarget->GetSize().height),
                         1.0f);
     projection.PreScale(1.0f, -1.0f, 1.0f);
 
     memcpy(vsConstants.projection, &projection._11, 64);
     vsConstants.targetOffset = Point(mTargetOffset);
     vsConstants.sortIndexOffset = PrepareDepthBuffer();
+    vsConstants.debugFrameNumber = mBuilder->GetManager()->GetDebugFrameNumber();
 
     SharedConstantBuffer* shared = mDevice->GetSharedVSBuffer();
     if (!shared->Allocate(&mWorldConstants, vsConstants)) {
       return;
     }
   }
 
   // Prepare back-to-front passes. In depth buffer mode, these contain draw
--- a/gfx/layers/mlgpu/ShaderDefinitionsMLGPU.h
+++ b/gfx/layers/mlgpu/ShaderDefinitionsMLGPU.h
@@ -47,17 +47,17 @@ static const uint32_t kMaxPixelShaderCon
 // Maximum depth in the depth buffer. This must match common-vs.hlsl.
 static const int32_t kDepthLimit = 1000000;
 
 struct WorldConstants
 {
   float projection[4][4];
   gfx::Point targetOffset;
   int sortIndexOffset;
-  float padding;
+  unsigned debugFrameNumber;
 };
 
 struct ClearConstants
 {
   explicit ClearConstants(int aDepth) : depth(aDepth)
   {}
   int depth;
   int padding[3];
--- a/gfx/thebes/DeviceManagerDx.cpp
+++ b/gfx/thebes/DeviceManagerDx.cpp
@@ -125,16 +125,21 @@ ProcessOwnsCompositor()
 bool
 DeviceManagerDx::CreateCompositorDevices()
 {
   MOZ_ASSERT(ProcessOwnsCompositor());
 
   FeatureState& d3d11 = gfxConfig::GetFeature(Feature::D3D11_COMPOSITING);
   MOZ_ASSERT(d3d11.IsEnabled());
 
+  if (int32_t sleepSec = gfxPrefs::Direct3D11SleepOnCreateDevice()) {
+    printf_stderr("Attach to PID: %d\n", GetCurrentProcessId());
+    Sleep(sleepSec * 1000);
+  }
+
   if (!LoadD3D11()) {
     return false;
   }
 
   CreateCompositorDevice(d3d11);
 
   if (!d3d11.IsEnabled()) {
     MOZ_ASSERT(!mCompositorDevice);
--- a/gfx/thebes/gfxPrefs.cpp
+++ b/gfx/thebes/gfxPrefs.cpp
@@ -192,17 +192,17 @@ float gfxPrefs::PrefGet(const char* aPre
   MOZ_ASSERT(IsPrefsServiceAvailable());
   return Preferences::GetFloat(aPref, aDefault);
 }
 
 std::string gfxPrefs::PrefGet(const char* aPref, std::string aDefault)
 {
   MOZ_ASSERT(IsPrefsServiceAvailable());
 
-  nsAdoptingCString result;
+  nsAutoCString result;
   Preferences::GetCString(aPref, result);
 
   if (result.IsEmpty()) {
     return aDefault;
   }
 
   return result.get();
 }
--- a/gfx/thebes/gfxPrefs.h
+++ b/gfx/thebes/gfxPrefs.h
@@ -436,16 +436,17 @@ private:
 
   DECL_GFX_PREF(Once, "gfx.direct2d.disabled",                 Direct2DDisabled, bool, false);
   DECL_GFX_PREF(Once, "gfx.direct2d.force-enabled",            Direct2DForceEnabled, bool, false);
   DECL_GFX_PREF(Live, "gfx.direct3d11.reuse-decoder-device",   Direct3D11ReuseDecoderDevice, int32_t, -1);
   DECL_GFX_PREF(Live, "gfx.direct3d11.allow-keyed-mutex",      Direct3D11AllowKeyedMutex, bool, true);
   DECL_GFX_PREF(Live, "gfx.direct3d11.use-double-buffering",   Direct3D11UseDoubleBuffering, bool, false);
   DECL_GFX_PREF(Once, "gfx.direct3d11.enable-debug-layer",     Direct3D11EnableDebugLayer, bool, false);
   DECL_GFX_PREF(Once, "gfx.direct3d11.break-on-error",         Direct3D11BreakOnError, bool, false);
+  DECL_GFX_PREF(Once, "gfx.direct3d11.sleep-on-create-device", Direct3D11SleepOnCreateDevice, int32_t, 0);
   DECL_GFX_PREF(Live, "gfx.downloadable_fonts.keep_variation_tables", KeepVariationTables, bool, false);
   DECL_GFX_PREF(Live, "gfx.downloadable_fonts.otl_validation", ValidateOTLTables, bool, true);
   DECL_GFX_PREF(Live, "gfx.draw-color-bars",                   CompositorDrawColorBars, bool, false);
   DECL_GFX_PREF(Once, "gfx.e10s.hide-plugins-for-scroll",      HidePluginsForScroll, bool, true);
   DECL_GFX_PREF(Live, "gfx.layerscope.enabled",                LayerScopeEnabled, bool, false);
   DECL_GFX_PREF(Live, "gfx.layerscope.port",                   LayerScopePort, int32_t, 23456);
   // Note that        "gfx.logging.level" is defined in Logging.h.
   DECL_GFX_PREF(Live, "gfx.logging.level",                     GfxLoggingLevel, int32_t, mozilla::gfx::LOG_DEFAULT);
--- a/intl/uconv/nsTextToSubURI.cpp
+++ b/intl/uconv/nsTextToSubURI.cpp
@@ -147,17 +147,17 @@ NS_IMETHODIMP  nsTextToSubURI::UnEscapeU
                 PromiseFlatCString(aCharset), unescapedSpec, _retval)
       != NS_OK) {
     // assume UTF-8 instead of ASCII  because hostname (IDN) may be in UTF-8
     CopyUTF8toUTF16(aURIFragment, _retval);
   }
 
   // If there are any characters that are unsafe for URIs, reescape those.
   if (mUnsafeChars.IsEmpty()) {
-    nsAdoptingString blacklist;
+    nsAutoString blacklist;
     nsresult rv = mozilla::Preferences::GetString("network.IDN.blacklist_chars",
                                                   blacklist);
     if (NS_SUCCEEDED(rv)) {
       // we allow SPACE and IDEOGRAPHIC SPACE in this method
       blacklist.StripChars(u" \u3000");
       mUnsafeChars.AppendElements(static_cast<const char16_t*>(blacklist.Data()),
                                   blacklist.Length());
     } else {
--- a/js/public/HashTable.h
+++ b/js/public/HashTable.h
@@ -1767,17 +1767,19 @@ class HashTable : private AllocPolicy
     }
 
     MOZ_ALWAYS_INLINE AddPtr lookupForAdd(const Lookup& l) const
     {
         mozilla::ReentrancyGuard g(*this);
         if (!EnsureHash<HashPolicy>(l))
             return AddPtr();
         HashNumber keyHash = prepareHash(l);
-        return AddPtr(lookup(l, keyHash, sCollisionBit), *this, keyHash);
+        Entry& entry = lookup(l, keyHash, sCollisionBit);
+        AddPtr p(entry, *this, keyHash);
+        return p;
     }
 
     template <typename... Args>
     MOZ_MUST_USE bool add(AddPtr& p, Args&&... args)
     {
         mozilla::ReentrancyGuard g(*this);
         MOZ_ASSERT(table);
         MOZ_ASSERT_IF(p.isValid(), p.table_ == this);
--- a/layout/generic/nsPluginFrame.cpp
+++ b/layout/generic/nsPluginFrame.cpp
@@ -75,21 +75,16 @@
 using mozilla::DefaultXDisplay;
 #endif
 
 #ifdef XP_WIN
 #include <wtypes.h>
 #include <winuser.h>
 #endif
 
-#ifdef MOZ_WIDGET_ANDROID
-#include "AndroidBridge.h"
-#include "GLContext.h"
-#endif
-
 #include "mozilla/dom/TabChild.h"
 
 #ifdef CreateEvent // Thank you MS.
 #undef CreateEvent
 #endif
 
 static mozilla::LazyLogModule sPluginFrameLog("nsPluginFrame");
 
@@ -933,65 +928,16 @@ GetDisplayItemBounds(nsDisplayListBuilde
 
 nsRect
 nsDisplayPluginReadback::GetBounds(nsDisplayListBuilder* aBuilder, bool* aSnap)
 {
   *aSnap = false;
   return GetDisplayItemBounds(aBuilder, this, mFrame);
 }
 
-#ifdef MOZ_WIDGET_ANDROID
-
-class nsDisplayPluginVideo : public nsDisplayItem {
-public:
-  nsDisplayPluginVideo(nsDisplayListBuilder* aBuilder, nsIFrame* aFrame, nsNPAPIPluginInstance::VideoInfo* aVideoInfo)
-    : nsDisplayItem(aBuilder, aFrame), mVideoInfo(aVideoInfo)
-  {
-    MOZ_COUNT_CTOR(nsDisplayPluginVideo);
-  }
-#ifdef NS_BUILD_REFCNT_LOGGING
-  virtual ~nsDisplayPluginVideo() {
-    MOZ_COUNT_DTOR(nsDisplayPluginVideo);
-  }
-#endif
-
-  virtual nsRect GetBounds(nsDisplayListBuilder* aBuilder,
-                           bool* aSnap) override;
-
-  NS_DISPLAY_DECL_NAME("PluginVideo", TYPE_PLUGIN_VIDEO)
-
-  virtual already_AddRefed<Layer> BuildLayer(nsDisplayListBuilder* aBuilder,
-                                             LayerManager* aManager,
-                                             const ContainerLayerParameters& aContainerParameters) override
-  {
-    return static_cast<nsPluginFrame*>(mFrame)->BuildLayer(aBuilder, aManager, this, aContainerParameters);
-  }
-
-  virtual LayerState GetLayerState(nsDisplayListBuilder* aBuilder,
-                                   LayerManager* aManager,
-                                   const ContainerLayerParameters& aParameters) override
-  {
-    return LAYER_ACTIVE;
-  }
-
-  nsNPAPIPluginInstance::VideoInfo* VideoInfo() { return mVideoInfo; }
-
-private:
-  nsNPAPIPluginInstance::VideoInfo* mVideoInfo;
-};
-
-nsRect
-nsDisplayPluginVideo::GetBounds(nsDisplayListBuilder* aBuilder, bool* aSnap)
-{
-  *aSnap = false;
-  return GetDisplayItemBounds(aBuilder, this, mFrame);
-}
-
-#endif
-
 nsRect
 nsDisplayPlugin::GetBounds(nsDisplayListBuilder* aBuilder, bool* aSnap)
 {
   *aSnap = true;
   return GetDisplayItemBounds(aBuilder, this, mFrame);
 }
 
 void
@@ -1131,19 +1077,16 @@ nsPluginFrame::DidSetWidgetGeometry()
 #endif
 }
 
 bool
 nsPluginFrame::IsOpaque() const
 {
 #if defined(XP_MACOSX)
   return false;
-#elif defined(MOZ_WIDGET_ANDROID)
-  // We don't know, so just assume transparent
-  return false;
 #else
 
   if (mInstanceOwner && mInstanceOwner->UseAsyncRendering()) {
     return false;
   }
   return !IsTransparentMode();
 #endif
 }
@@ -1233,39 +1176,22 @@ nsPluginFrame::BuildDisplayList(nsDispla
       nsDisplayGeneric(aBuilder, this, PaintPrintPlugin, "PrintPlugin",
                        nsDisplayItem::TYPE_PRINT_PLUGIN));
   } else {
     LayerState state = GetLayerState(aBuilder, nullptr);
     if (state == LAYER_INACTIVE &&
         nsDisplayItem::ForceActiveLayers()) {
       state = LAYER_ACTIVE;
     }
-    // We don't need this on Android, and it just confuses things
-#if !MOZ_WIDGET_ANDROID
     if (aBuilder->IsPaintingToWindow() &&
         state == LAYER_ACTIVE &&
         IsTransparentMode()) {
       aLists.Content()->AppendNewToTop(new (aBuilder)
         nsDisplayPluginReadback(aBuilder, this));
     }
-#endif
-
-#if MOZ_WIDGET_ANDROID
-    if (aBuilder->IsPaintingToWindow() &&
-        state == LAYER_ACTIVE) {
-
-      nsTArray<nsNPAPIPluginInstance::VideoInfo*> videos;
-      mInstanceOwner->GetVideos(videos);
-
-      for (uint32_t i = 0; i < videos.Length(); i++) {
-        aLists.Content()->AppendNewToTop(new (aBuilder)
-          nsDisplayPluginVideo(aBuilder, this, videos[i]));
-      }
-    }
-#endif
 
     aLists.Content()->AppendNewToTop(new (aBuilder)
       nsDisplayPlugin(aBuilder, this));
   }
 }
 
 void
 nsPluginFrame::PrintPlugin(gfxContext& aRenderingContext,
@@ -1391,30 +1317,25 @@ nsPluginFrame::GetPaintedRect(nsDisplayP
 
 LayerState
 nsPluginFrame::GetLayerState(nsDisplayListBuilder* aBuilder,
                              LayerManager* aManager)
 {
   if (!mInstanceOwner)
     return LAYER_NONE;
 
-#ifdef MOZ_WIDGET_ANDROID
-  // We always want a layer on Honeycomb and later
-  return LAYER_ACTIVE;
-#else
   if (mInstanceOwner->NeedsScrollImageLayer()) {
     return LAYER_ACTIVE;
   }
 
   if (!mInstanceOwner->UseAsyncRendering()) {
     return LAYER_NONE;
   }
 
   return LAYER_ACTIVE_FORCE;
-#endif
 }
 
 class PluginFrameDidCompositeObserver final : public DidCompositeObserver
 {
 public:
   PluginFrameDidCompositeObserver(nsPluginInstanceOwner* aOwner, LayerManager* aLayerManager)
     : mInstanceOwner(aOwner),
       mLayerManager(aLayerManager)
@@ -1521,42 +1442,16 @@ nsPluginFrame::BuildLayer(nsDisplayListB
         mInstanceOwner->UseAsyncRendering())
     {
       RefPtr<LayerManager> lm = aBuilder->GetWidgetLayerManager();
       if (!mDidCompositeObserver || !mDidCompositeObserver->IsValid(lm)) {
         mDidCompositeObserver = MakeUnique<PluginFrameDidCompositeObserver>(mInstanceOwner, lm);
       }
       lm->AddDidCompositeObserver(mDidCompositeObserver.get());
     }
-#ifdef MOZ_WIDGET_ANDROID
-  } else if (aItem->GetType() == nsDisplayItem::TYPE_PLUGIN_VIDEO) {
-    nsDisplayPluginVideo* videoItem = reinterpret_cast<nsDisplayPluginVideo*>(aItem);
-    nsNPAPIPluginInstance::VideoInfo* videoInfo = videoItem->VideoInfo();
-
-    RefPtr<ImageContainer> container = mInstanceOwner->GetImageContainerForVideo(videoInfo);
-    if (!container)
-      return nullptr;
-
-    if (!layer) {
-      // Initialize ImageLayer
-      layer = aManager->CreateImageLayer();
-      if (!layer)
-        return nullptr;
-    }
-
-    ImageLayer* imglayer = static_cast<ImageLayer*>(layer.get());
-    imglayer->SetContainer(container);
-
-    layer->SetContentFlags(IsOpaque() ? Layer::CONTENT_OPAQUE : 0);
-
-    // Set the offset and size according to the video dimensions
-    r.MoveBy(videoInfo->mDimensions.TopLeft());
-    size.width = videoInfo->mDimensions.width;
-    size.height = videoInfo->mDimensions.height;
-#endif
   } else {
     NS_ASSERTION(aItem->GetType() == nsDisplayItem::TYPE_PLUGIN_READBACK,
                  "Unknown item type");
     MOZ_ASSERT(!IsOpaque(), "Opaque plugins don't use backgrounds");
 
     if (!layer) {
       layer = aManager->CreateReadbackLayer();
       if (!layer)
@@ -1595,37 +1490,25 @@ nsPluginFrame::BuildLayer(nsDisplayListB
   return layer.forget();
 }
 
 void
 nsPluginFrame::PaintPlugin(nsDisplayListBuilder* aBuilder,
                            gfxContext& aRenderingContext,
                            const nsRect& aDirtyRect, const nsRect& aPluginRect)
 {
-#if defined(MOZ_WIDGET_ANDROID)
-  if (mInstanceOwner) {
-    gfxRect frameGfxRect =
-      PresContext()->AppUnitsToGfxUnits(aPluginRect);
-    gfxRect dirtyGfxRect =
-      PresContext()->AppUnitsToGfxUnits(aDirtyRect);
-
-    mInstanceOwner->Paint(&aRenderingContext, frameGfxRect, dirtyGfxRect);
-    return;
-  }
-#else
-# if defined(DEBUG)
+#if defined(DEBUG)
   // On Desktop, we should have built a layer as we no longer support in-process
   // plugins or synchronous painting. We can only get here for windowed plugins
   // (which draw themselves), or via some error/unload state.
   if (mInstanceOwner) {
     NPWindow *window = nullptr;
     mInstanceOwner->GetWindow(window);
     MOZ_ASSERT(!window || window->type == NPWindowTypeWindow);
   }
-# endif
 #endif
 }
 
 nsresult
 nsPluginFrame::HandleEvent(nsPresContext* aPresContext,
                            WidgetGUIEvent* anEvent,
                            nsEventStatus* anEventStatus)
 {
--- a/layout/painting/FrameLayerBuilder.cpp
+++ b/layout/painting/FrameLayerBuilder.cpp
@@ -4099,17 +4099,17 @@ ContainerState::ProcessDisplayItems(nsDi
     nsIntRect itemDrawRect = ScaleToOutsidePixels(itemContent, snap);
     bool prerenderedTransform = itemType == nsDisplayItem::TYPE_TRANSFORM &&
         static_cast<nsDisplayTransform*>(item)->MayBeAnimated(mBuilder);
     ParentLayerIntRect clipRect;
     const DisplayItemClip& itemClip = item->GetClip();
     if (itemClip.HasClip()) {
       itemContent.IntersectRect(itemContent, itemClip.GetClipRect());
       clipRect = ViewAs<ParentLayerPixel>(ScaleToNearestPixels(itemClip.GetClipRect()));
-      if (!prerenderedTransform) {
+      if (!prerenderedTransform && !IsScrollThumbLayer(item)) {
         itemDrawRect.IntersectRect(itemDrawRect, clipRect.ToUnknownRect());
       }
       clipRect.MoveBy(ViewAs<ParentLayerPixel>(mParameters.mOffset));
     }
 #ifdef DEBUG
     nsRect bounds = itemContent;
     bool dummy;
     if (itemType == nsDisplayItem::TYPE_LAYER_EVENT_REGIONS) {
--- a/layout/xul/nsSliderFrame.cpp
+++ b/layout/xul/nsSliderFrame.cpp
@@ -452,16 +452,19 @@ nsSliderFrame::BuildDisplayListForChildr
       masterList.AppendToTop(tempLists.Floats());
       masterList.AppendToTop(tempLists.Content());
       masterList.AppendToTop(tempLists.PositionedDescendants());
       masterList.AppendToTop(tempLists.Outlines());
 
       // Restore the saved clip so it applies to the thumb container layer.
       thumbContentsClipState.Restore();
 
+      nsDisplayListBuilder::AutoBuildingDisplayList
+        buildingDisplayList(aBuilder, this, dirty, false);
+
       // Wrap the list to make it its own layer.
       const ActiveScrolledRoot* ownLayerASR = contASRTracker.GetContainerASR();
       aLists.Content()->AppendNewToTop(new (aBuilder)
         nsDisplayOwnLayer(aBuilder, this, &masterList, ownLayerASR,
                           flags, scrollTargetId,
                           ScrollThumbData{scrollDirection,
                                           GetThumbRatio(),
                                           thumbStart,
--- a/mobile/android/app/mobile.js
+++ b/mobile/android/app/mobile.js
@@ -442,25 +442,19 @@ pref("ui.mouse.radius.reposition", true)
 // manipulation is allowed.
 pref("browser.ui.scroll-toolbar-threshold", 10);
 
 // Maximum distance from the point where the user pressed where we still
 // look for text to select
 pref("browser.ui.selection.distance", 250);
 
 // plugins
-pref("plugin.disable", false);
+pref("plugin.disable", true);
 pref("dom.ipc.plugins.enabled", false);
 
-// This pref isn't actually used anymore, but we're leaving this here to avoid changing
-// the default so that we can migrate a user-set pref. See bug 885357.
-pref("plugins.click_to_play", true);
-// The default value for nsIPluginTag.enabledState (STATE_CLICKTOPLAY = 1)
-pref("plugin.default.state", 1);
-
 // product URLs
 // The breakpad report server to link to in about:crashes
 pref("breakpad.reportURL", "https://crash-stats.mozilla.com/report/index/");
 
 pref("app.support.baseURL", "https://support.mozilla.org/1/mobile/%VERSION%/%OS%/%LOCALE%/");
 pref("app.supportURL", "https://support.mozilla.org/1/mobile/%VERSION%/%OS%/%LOCALE%/mobile-help");
 pref("app.faqURL", "https://support.mozilla.org/1/mobile/%VERSION%/%OS%/%LOCALE%/faq");
 
--- a/mobile/android/app/src/main/res/layout/gecko_app.xml
+++ b/mobile/android/app/src/main/res/layout/gecko_app.xml
@@ -26,21 +26,16 @@
                         android:layout_below="@+id/tablet_tab_strip"
                         android:layout_above="@+id/find_in_page">
 
             <org.mozilla.gecko.GeckoView android:id="@+id/layer_view"
                                          android:layout_width="match_parent"
                                          android:layout_height="match_parent"
                                          android:scrollbars="none"/>
 
-            <AbsoluteLayout android:id="@+id/plugin_container"
-                            android:background="@android:color/transparent"
-                            android:layout_width="match_parent"
-                            android:layout_height="match_parent"/>
-
             <org.mozilla.gecko.FormAssistPopup android:id="@+id/form_assist_popup"
                                                android:layout_width="match_parent"
                                                android:layout_height="match_parent"
                                                android:visibility="gone"/>
 
             <view class="org.mozilla.gecko.media.VideoPlayer" android:id="@+id/video_player"
                          android:layout_height="match_parent"
                          android:layout_width="match_parent">
--- a/mobile/android/app/src/main/res/values/arrays.xml
+++ b/mobile/android/app/src/main/res/values/arrays.xml
@@ -8,26 +8,16 @@
     <string-array name="pref_home_updates_entries">
         <item>@string/pref_home_updates_enabled</item>
         <item>@string/pref_home_updates_wifi</item>
     </string-array>
     <string-array name="pref_home_updates_values">
         <item>0</item>
         <item>1</item>
     </string-array>
-    <string-array name="pref_plugins_entries">
-        <item>@string/pref_plugins_enabled</item>
-        <item>@string/pref_plugins_tap_to_play</item>
-        <item>@string/pref_plugins_disabled</item>
-    </string-array>
-    <string-array name="pref_plugins_values">
-        <item>1</item>
-        <item>2</item>
-        <item>0</item>
-    </string-array>
     <string-array name="pref_char_encoding_entries">
         <item>@string/pref_char_encoding_on</item>
         <item>@string/pref_char_encoding_off</item>
     </string-array>
     <string-array name="pref_char_encoding_values">
         <item>true</item>
         <item>false</item>
     </string-array>
--- a/mobile/android/app/src/main/res/xml/preferences_advanced.xml
+++ b/mobile/android/app/src/main/res/xml/preferences_advanced.xml
@@ -49,22 +49,16 @@
         <SwitchPreference android:key="browser.display.use_document_fonts"
                           android:title="@string/pref_show_web_fonts"
                           android:summary="@string/pref_show_web_fonts_summary"/>
 
     </PreferenceCategory>
 
     <PreferenceCategory android:title="@string/pref_category_media">
 
-        <ListPreference android:key="plugin.enable"
-                        android:title="@string/pref_plugins"
-                        android:entries="@array/pref_plugins_entries"
-                        android:entryValues="@array/pref_plugins_values"
-                        android:persistent="false" />
-
         <SwitchPreference android:key="media.autoplay.enabled"
                           android:title="@string/pref_media_autoplay_enabled"
                           android:summary="@string/pref_media_autoplay_enabled_summary" />
 
     </PreferenceCategory>
 
     <PreferenceCategory android:title="@string/pref_category_developer_tools">
 
--- a/mobile/android/base/java/org/mozilla/gecko/GeckoApp.java
+++ b/mobile/android/base/java/org/mozilla/gecko/GeckoApp.java
@@ -189,19 +189,16 @@ public abstract class GeckoApp extends G
     private PromptService mPromptService;
     protected TextSelection mTextSelection;
 
     protected DoorHangerPopup mDoorHangerPopup;
     protected FormAssistPopup mFormAssistPopup;
 
     protected GeckoView mLayerView;
 
-    private FullScreenHolder mFullScreenPluginContainer;
-    private View mFullScreenPluginView;
-
     protected boolean mLastSessionCrashed;
     protected boolean mShouldRestore;
     private boolean mSessionRestoreParsingFinished = false;
 
     private boolean foregrounded = false;
 
     private static final class LastSessionParser extends SessionParser {
         private JSONArray tabs;
@@ -804,21 +801,16 @@ public abstract class GeckoApp extends G
             UpdateServiceHelper.checkForUpdate(this);
 
         } else if ("Update:Download".equals(event)) {
             UpdateServiceHelper.downloadUpdate(this);
 
         } else if ("Update:Install".equals(event)) {
             UpdateServiceHelper.applyUpdate(this);
 
-        } else if ("PluginHelper:playFlash".equals(event)) {
-            final SharedPreferences prefs = getSharedPreferences();
-            int count = prefs.getInt(PREFS_FLASH_USAGE, 0);
-            prefs.edit().putInt(PREFS_FLASH_USAGE, ++count).apply();
-
         } else if ("Mma:reader_available".equals(event)) {
             MmaDelegate.track(READER_AVAILABLE);
 
         } else if ("Mma:web_save_media".equals(event) || "Mma:web_save_image".equals(event)) {
             MmaDelegate.track(DOWNLOAD_MEDIA_SAVED_IMAGE);
 
         }
 
@@ -912,123 +904,16 @@ public abstract class GeckoApp extends G
                     clearButton.setEnabled(false);
                 } else {
                     clearButton.setEnabled(true);
                 }
             }
         });
     }
 
-    /* package */ void addFullScreenPluginView(View view) {
-        if (mFullScreenPluginView != null) {
-            Log.w(LOGTAG, "Already have a fullscreen plugin view");
-            return;
-        }
-
-        setFullScreen(true);
-
-        view.setWillNotDraw(false);
-        if (view instanceof SurfaceView) {
-            ((SurfaceView) view).setZOrderOnTop(true);
-        }
-
-        mFullScreenPluginContainer = new FullScreenHolder(this);
-
-        FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams(
-                            ViewGroup.LayoutParams.MATCH_PARENT,
-                            ViewGroup.LayoutParams.MATCH_PARENT,
-                            Gravity.CENTER);
-        mFullScreenPluginContainer.addView(view, layoutParams);
-
-
-        FrameLayout decor = (FrameLayout)getWindow().getDecorView();
-        decor.addView(mFullScreenPluginContainer, layoutParams);
-
-        mFullScreenPluginView = view;
-    }
-
-    @WrapForJNI(calledFrom = "gecko")
-    private static void addPluginView(final View view) {
-        final Activity activity = GeckoActivityMonitor.getInstance().getCurrentActivity();
-        if (!(activity instanceof GeckoApp)) {
-            return;
-        }
-
-        final GeckoApp geckoApp = (GeckoApp) activity;
-        if (ThreadUtils.isOnUiThread()) {
-            geckoApp.addFullScreenPluginView(view);
-        } else {
-            ThreadUtils.postToUiThread(new Runnable() {
-                @Override
-                public void run() {
-                    geckoApp.addFullScreenPluginView(view);
-                }
-            });
-        }
-    }
-
-    /* package */ void removeFullScreenPluginView(View view) {
-        if (mFullScreenPluginView == null) {
-            Log.w(LOGTAG, "Don't have a fullscreen plugin view");
-            return;
-        }
-
-        if (mFullScreenPluginView != view) {
-            Log.w(LOGTAG, "Passed view is not the current full screen view");
-            return;
-        }
-
-        mFullScreenPluginContainer.removeView(mFullScreenPluginView);
-
-        // We need do do this on the next iteration in order to avoid
-        // a deadlock, see comment below in FullScreenHolder
-        ThreadUtils.postToUiThread(new Runnable() {
-            @Override
-            public void run() {
-                mLayerView.showSurface();
-            }
-        });
-
-        FrameLayout decor = (FrameLayout)getWindow().getDecorView();
-        decor.removeView(mFullScreenPluginContainer);
-
-        mFullScreenPluginView = null;
-
-        GeckoScreenOrientation.getInstance().unlock();
-        setFullScreen(false);
-    }
-
-    @WrapForJNI(calledFrom = "gecko")
-    private static void removePluginView(final View view) {
-        final Activity activity = GeckoActivityMonitor.getInstance().getCurrentActivity();
-        if (!(activity instanceof GeckoApp)) {
-            return;
-        }
-
-        final GeckoApp geckoApp = (GeckoApp) activity;
-        if (ThreadUtils.isOnUiThread()) {
-            geckoApp.removeFullScreenPluginView(view);
-        } else {
-            ThreadUtils.postToUiThread(new Runnable() {
-                @Override
-                public void run() {
-                    geckoApp.removeFullScreenPluginView(view);
-                }
-            });
-        }
-    }
-
-    @WrapForJNI(calledFrom = "ui", dispatchTo = "gecko")
-    private static native void onFullScreenPluginHidden(View view);
-
-    @WrapForJNI(calledFrom = "gecko")
-    private static Context getPluginContext() {
-        return GeckoActivityMonitor.getInstance().getCurrentActivity();
-    }
-
     private void showSetImageResult(final boolean success, final int message, final String path) {
         ThreadUtils.postToUiThread(new Runnable() {
             @Override
             public void run() {
                 if (!success) {
                     SnackbarBuilder.builder(GeckoApp.this)
                             .message(message)
                             .duration(Snackbar.LENGTH_LONG)
@@ -1298,17 +1183,16 @@ public abstract class GeckoApp extends G
                 GeckoThread.speculativeConnect(uri);
             }
         }
 
         // To prevent races, register startup events before launching the Gecko thread.
         EventDispatcher.getInstance().registerGeckoThreadListener(this,
             "Accessibility:Ready",
             "Gecko:Ready",
-            "PluginHelper:playFlash",
             null);
 
         EventDispatcher.getInstance().registerUiThreadListener(this,
             "Update:Check",
             "Update:Download",
             "Update:Install",
             null);
 
@@ -2325,17 +2209,16 @@ public abstract class GeckoApp extends G
             // We did not initialize anything, so skip cleaning up.
             super.onDestroy();
             return;
         }
 
         EventDispatcher.getInstance().unregisterGeckoThreadListener(this,
             "Accessibility:Ready",
             "Gecko:Ready",
-            "PluginHelper:playFlash",
             null);
 
         EventDispatcher.getInstance().unregisterUiThreadListener(this,
             "Update:Check",
             "Update:Download",
             "Update:Install",
             null);
 
@@ -2540,22 +2423,16 @@ public abstract class GeckoApp extends G
             return;
         }
 
         if (mDoorHangerPopup != null && mDoorHangerPopup.isShowing()) {
             mDoorHangerPopup.dismiss();
             return;
         }
 
-        if (mFullScreenPluginView != null) {
-            onFullScreenPluginHidden(mFullScreenPluginView);
-            removeFullScreenPluginView(mFullScreenPluginView);
-            return;
-        }
-
         if (mLayerView != null && mLayerView.isFullScreen()) {
             EventDispatcher.getInstance().dispatch("FullScreen:Exit", null);
             return;
         }
 
         final Tabs tabs = Tabs.getInstance();
         final Tab tab = tabs.getSelectedTab();
         if (tab == null) {
@@ -2678,81 +2555,16 @@ public abstract class GeckoApp extends G
         public void setDrawingCacheEnabled(boolean enabled) {
             // Instead of setting drawing cache in the view itself, we simply
             // enable drawing caching on its children. This is mainly used in
             // animations (see PropertyAnimator)
             super.setChildrenDrawnWithCacheEnabled(enabled);
         }
     }
 
-    private class FullScreenHolder extends FrameLayout {
-
-        public FullScreenHolder(Context ctx) {
-            super(ctx);
-            setBackgroundColor(0xff000000);
-        }
-
-        @Override
-        public void addView(View view, int index) {
-            /**
-             * This normally gets called when Flash adds a separate SurfaceView
-             * for the video. It is unhappy if we have the LayerView underneath
-             * it for some reason so we need to hide that. Hiding the LayerView causes
-             * its surface to be destroyed, which causes a pause composition
-             * event to be sent to Gecko. We synchronously wait for that to be
-             * processed. Simultaneously, however, Flash is waiting on a mutex so
-             * the post() below is an attempt to avoid a deadlock.
-             */
-            super.addView(view, index);
-
-            ThreadUtils.postToUiThread(new Runnable() {
-                @Override
-                public void run() {
-                    mLayerView.hideSurface();
-                }
-            });
-        }
-
-        /**
-         * The methods below are simply copied from what Android WebKit does.
-         * It wasn't ever called in my testing, but might as well
-         * keep it in case it is for some reason. The methods
-         * all return true because we don't want any events
-         * leaking out from the fullscreen view.
-         */
-        @Override
-        public boolean onKeyDown(int keyCode, KeyEvent event) {
-            if (event.isSystem()) {
-                return super.onKeyDown(keyCode, event);
-            }
-            mFullScreenPluginView.onKeyDown(keyCode, event);
-            return true;
-        }
-
-        @Override
-        public boolean onKeyUp(int keyCode, KeyEvent event) {
-            if (event.isSystem()) {
-                return super.onKeyUp(keyCode, event);
-            }
-            mFullScreenPluginView.onKeyUp(keyCode, event);
-            return true;
-        }
-
-        @Override
-        public boolean onTouchEvent(MotionEvent event) {
-            return true;
-        }
-
-        @Override
-        public boolean onTrackballEvent(MotionEvent event) {
-            mFullScreenPluginView.onTrackballEvent(event);
-            return true;
-        }
-    }
-
     private int getVersionCode() {
         int versionCode = 0;
         try {
             versionCode = getPackageManager().getPackageInfo(getPackageName(), 0).versionCode;
         } catch (NameNotFoundException e) {
             Log.wtf(LOGTAG, getPackageName() + " not found", e);
         }
         return versionCode;
--- a/mobile/android/base/java/org/mozilla/gecko/Tab.java
+++ b/mobile/android/base/java/org/mozilla/gecko/Tab.java
@@ -64,17 +64,16 @@ public class Tab {
     private volatile int mParentId;
     // Indicates the url was loaded from a source external to the app. This will be cleared
     // when the user explicitly loads a new url (e.g. clicking a link is not explicit).
     private final boolean mExternal;
     private boolean mBookmark;
     private int mFaviconLoadId;
     private String mContentType;
     private boolean mHasTouchListeners;
-    private final ArrayList<View> mPluginViews;
     private int mState;
     private Bitmap mThumbnailBitmap;
     private boolean mDesktopMode;
     private boolean mEnteringReaderMode;
     private final Context mAppContext;
     private ErrorType mErrorType = ErrorType.NONE;
     private volatile int mLoadProgress;
     private volatile int mRecordingCount;
@@ -124,17 +123,16 @@ public class Tab {
         mUrl = url;
         mBaseDomain = "";
         mUserRequested = "";
         mExternal = external;
         mParentId = parentId;
         mTitle = title == null ? "" : title;
         mSiteIdentity = new SiteIdentity();
         mContentType = "";
-        mPluginViews = new ArrayList<View>();
         mState = shouldShowProgress(url) ? STATE_LOADING : STATE_SUCCESS;
         mLoadProgress = LOAD_PROGRESS_INIT;
         mIconRequestBuilder = Icons.with(mAppContext).pageUrl(mUrl);
 
         updateBookmark();
     }
 
     private ContentResolver getContentResolver() {
@@ -731,28 +729,16 @@ public class Tab {
 
             // Passing in a null thumbnail will delete the stored thumbnail for this url
             db.updateThumbnailForUrl(getContentResolver(), url, null);
         } catch (Exception e) {
             // ignore
         }
     }
 
-    public void addPluginView(View view) {
-        mPluginViews.add(view);
-    }
-
-    public void removePluginView(View view) {
-        mPluginViews.remove(view);
-    }
-
-    public View[] getPluginViews() {
-        return mPluginViews.toArray(new View[mPluginViews.size()]);
-    }
-
     public void setDesktopMode(boolean enabled) {
         mDesktopMode = enabled;
     }
 
     public boolean getDesktopMode() {
         return mDesktopMode;
     }
 
--- a/mobile/android/base/locales/en-US/android_strings.dtd
+++ b/mobile/android/base/locales/en-US/android_strings.dtd
@@ -356,20 +356,16 @@
 <!ENTITY pref_char_encoding_off "Don\'t show menu">
 <!ENTITY pref_clear_private_data2 "Clear private data">
 <!-- Localization note (pref_clear_private_data_now_tablet): This action to clear private data is only shown on tablets.
      The action is shown below a header saying "Clear private data"; See pref_clear_private_data -->
 <!ENTITY pref_clear_private_data_now_tablet "Clear now">
 <!ENTITY pref_clear_on_exit_title3 "Clear private data on exit">
 <!ENTITY pref_clear_on_exit_summary2 "&brandShortName; will automatically clear your data whenever you select \u0022Quit\u0022 from the main menu">
 <!ENTITY pref_clear_on_exit_dialog_title "Select which data to clear">
-<!ENTITY pref_plugins "Plugins">
-<!ENTITY pref_plugins_enabled "Enabled">
-<!ENTITY pref_plugins_tap_to_play2 "Touch to play">
-<!ENTITY pref_plugins_disabled "Disabled">
 <!ENTITY pref_restore_tabs "Restore tabs">
 <!ENTITY pref_restore_always "Always restore">
 <!ENTITY pref_restore_quit "Don\'t restore after quitting &brandShortName;">
 
 <!-- Localization note (pref_use_system_font_size, pref_use_system_font_size_summary):
      Font size here refers to the name of the corresponding Android system setting. -->
 <!ENTITY pref_use_system_font_size "Use system font size">
 <!ENTITY pref_use_system_font_size_summary "Scale web content according to the system font size">
--- a/mobile/android/base/strings.xml.in
+++ b/mobile/android/base/strings.xml.in
@@ -256,20 +256,16 @@
   <string name="pref_char_encoding">&pref_char_encoding;</string>
   <string name="pref_char_encoding_on">&pref_char_encoding_on;</string>
   <string name="pref_char_encoding_off">&pref_char_encoding_off;</string>
   <string name="pref_clear_private_data_now">&pref_clear_private_data2;</string>
   <string name="pref_clear_private_data_now_tablet">&pref_clear_private_data_now_tablet;</string>
   <string name="pref_clear_on_exit_title">&pref_clear_on_exit_title3;</string>
   <string name="pref_clear_on_exit_summary2">&pref_clear_on_exit_summary2;</string>
   <string name="pref_clear_on_exit_dialog_title">&pref_clear_on_exit_dialog_title;</string>
-  <string name="pref_plugins">&pref_plugins;</string>
-  <string name="pref_plugins_enabled">&pref_plugins_enabled;</string>
-  <string name="pref_plugins_tap_to_play">&pref_plugins_tap_to_play2;</string>
-  <string name="pref_plugins_disabled">&pref_plugins_disabled;</string>
   <string name="pref_use_system_font_size">&pref_use_system_font_size;</string>
   <string name="pref_use_system_font_size_summary">&pref_use_system_font_size_summary;</string>
   <string name="pref_media_autoplay_enabled">&pref_media_autoplay_enabled;</string>
   <string name="pref_media_autoplay_enabled_summary">&pref_media_autoplay_enabled_summary;</string>
   <string name="pref_zoom_force_enabled">&pref_zoom_force_enabled;</string>
   <string name="pref_zoom_force_enabled_summary">&pref_zoom_force_enabled_summary;</string>
   <string name="pref_voice_input">&pref_voice_input;</string>
   <string name="pref_voice_input_summary">&pref_voice_input_summary2;</string>
--- a/mobile/android/chrome/content/browser.js
+++ b/mobile/android/chrome/content/browser.js
@@ -124,17 +124,16 @@ XPCOMUtils.defineLazyServiceGetter(this,
   "@mozilla.org/gfx/fontenumerator;1",
   "nsIFontEnumerator");
 
 var GlobalEventDispatcher = EventDispatcher.instance;
 var WindowEventDispatcher = EventDispatcher.for(window);
 
 var lazilyLoadedBrowserScripts = [
   ["MasterPassword", "chrome://browser/content/MasterPassword.js"],
-  ["PluginHelper", "chrome://browser/content/PluginHelper.js"],
   ["OfflineApps", "chrome://browser/content/OfflineApps.js"],
   ["Linkifier", "chrome://browser/content/Linkify.js"],
   ["CastingApps", "chrome://browser/content/CastingApps.js"],
   ["RemoteDebugger", "chrome://browser/content/RemoteDebugger.js"],
 ];
 if (!AppConstants.RELEASE_OR_BETA) {
   lazilyLoadedBrowserScripts.push(
     ["WebcompatReporter", "chrome://browser/content/WebcompatReporter.js"]);
@@ -1009,23 +1008,16 @@ var BrowserApp = {
   _migrateUI: function() {
     const UI_VERSION = 3;
     let currentUIVersion = Services.prefs.getIntPref("browser.migration.version", 0);
     if (currentUIVersion >= UI_VERSION) {
       return;
     }
 
     if (currentUIVersion < 1) {
-      // Migrate user-set "plugins.click_to_play" pref. See bug 884694.
-      // Because the default value is true, a user-set pref means that the pref was set to false.
-      if (Services.prefs.prefHasUserValue("plugins.click_to_play")) {
-        Services.prefs.setIntPref("plugin.default.state", Ci.nsIPluginTag.STATE_ENABLED);
-        Services.prefs.clearUserPref("plugins.click_to_play");
-      }
-
       // Migrate the "privacy.donottrackheader.value" pref. See bug 1042135.
       if (Services.prefs.prefHasUserValue("privacy.donottrackheader.value")) {
         // Make sure the doNotTrack value conforms to the conversion from
         // three-state to two-state. (This reverts a setting of "please track me"
         // to the default "don't say anything").
         if (Services.prefs.getBoolPref("privacy.donottrackheader.enabled") &&
             (Services.prefs.getIntPref("privacy.donottrackheader.value") != 1)) {
           Services.prefs.clearUserPref("privacy.donottrackheader.enabled");
@@ -1950,22 +1942,16 @@ var BrowserApp = {
 
       case "android-get-pref": {
         // These pref names are not "real" pref names. They are used in the
         // setting menu, and these are passed when initializing the setting
         // menu. aSubject is a nsIWritableVariant to hold the pref value.
         aSubject.QueryInterface(Ci.nsIWritableVariant);
 
         switch (aData) {
-          // The plugin pref is actually two separate prefs, so
-          // we need to handle it differently
-          case "plugin.enable":
-            aSubject.setAsAString(PluginHelper.getPluginPreference());
-            break;
-
           // Handle master password
           case "privacy.masterpassword.enabled":
             aSubject.setAsBool(MasterPassword.enabled);
             break;
 
           case "privacy.trackingprotection.state": {
             aSubject.setAsAString(this.getTrackingProtectionState());
             break;
@@ -1986,23 +1972,16 @@ var BrowserApp = {
 
       case "android-set-pref": {
         // Pseudo-prefs. aSubject is an nsIWritableVariant that holds the pref
         // value. Set to empty to signal the pref was handled.
         aSubject.QueryInterface(Ci.nsIWritableVariant);
         let value = aSubject.QueryInterface(Ci.nsIVariant);
 
         switch (aData) {
-          // The plugin pref is actually two separate prefs, so we need to
-          // handle it differently.
-          case "plugin.enable":
-            PluginHelper.setPluginPreference(value);
-            aSubject.setAsEmpty();
-            break;
-
           // MasterPassword pref is not real, we just need take action and leave
           case "privacy.masterpassword.enabled":
             if (MasterPassword.enabled) {
               MasterPassword.removePassword(value);
             } else {
               MasterPassword.setPassword(value);
             }
             aSubject.setAsEmpty();
@@ -3468,19 +3447,16 @@ nsBrowserAccess.prototype = {
 
 function Tab(aURL, aParams) {
   this.filter = null;
   this.browser = null;
   this.id = 0;
   this._parentId = -1;
   this.lastTouchedAt = Date.now();
   this.contentDocumentIsDisplayed = true;
-  this.pluginDoorhangerTimeout = null;
-  this.shouldShowPluginDoorhanger = true;
-  this.clickToPlayPluginsActivated = false;
   this.desktopMode = false;
   this.originalURI = null;
   this.hasTouchListener = false;
   this.playingAudio = false;
 
   this.create(aURL, aParams);
 }
 
@@ -3638,17 +3614,16 @@ Tab.prototype = {
     this.browser.addEventListener("DOMAutoComplete", this, true);
     this.browser.addEventListener("blur", this, true);
     this.browser.addEventListener("pageshow", this, true);
     this.browser.addEventListener("MozApplicationManifest", this, true);
     this.browser.addEventListener("TabPreZombify", this, true);
     this.browser.addEventListener("DOMWindowFocus", this, true);
 
     // Note that the XBL binding is untrusted
-    this.browser.addEventListener("PluginBindingAttached", this, true, true);
     this.browser.addEventListener("VideoBindingAttached", this, true, true);
     this.browser.addEventListener("VideoBindingCast", this, true, true);
 
     Services.obs.addObserver(this, "audioFocusChanged", false);
     Services.obs.addObserver(this, "before-first-paint");
     Services.obs.addObserver(this, "media-playback");
 
     // Always initialise new tabs with basic session store data to avoid
@@ -3753,17 +3728,16 @@ Tab.prototype = {
     this.browser.removeEventListener("DOMWillOpenModalDialog", this, true);
     this.browser.removeEventListener("DOMAutoComplete", this, true);
     this.browser.removeEventListener("blur", this, true);
     this.browser.removeEventListener("pageshow", this, true);
     this.browser.removeEventListener("MozApplicationManifest", this, true);
     this.browser.removeEventListener("TabPreZombify", this, true);
     this.browser.removeEventListener("DOMWindowFocus", this, true);
 
-    this.browser.removeEventListener("PluginBindingAttached", this, true, true);
     this.browser.removeEventListener("VideoBindingAttached", this, true, true);
     this.browser.removeEventListener("VideoBindingCast", this, true, true);
 
     Services.obs.removeObserver(this, "audioFocusChanged");
     Services.obs.removeObserver(this, "before-first-paint");
     Services.obs.removeObserver(this, "media-playback");
 
     // Make sure the previously selected panel remains selected. The selected panel of a deck is
@@ -4266,21 +4240,16 @@ Tab.prototype = {
       }
 
       case "DOMAutoComplete":
       case "blur": {
         LoginManagerContent.onUsernameInput(aEvent);
         break;
       }
 
-      case "PluginBindingAttached": {
-        PluginHelper.handlePluginBindingAttached(this, aEvent);
-        break;
-      }
-
       case "VideoBindingAttached": {
         CastingApps.handleVideoBindingAttached(this, aEvent);
         break;
       }
 
       case "VideoBindingCast": {
         CastingApps.handleVideoBindingCast(this, aEvent);
         break;
@@ -4449,22 +4418,16 @@ Tab.prototype = {
 
     // Let the reader logic know about same document changes because we won't get a DOMContentLoaded
     // or pageshow event, but we'll still want to update the reader view button to account for this change.
     // This mirrors the desktop logic in TabsProgressListener.
     if (aFlags & Ci.nsIWebProgressListener.LOCATION_CHANGE_SAME_DOCUMENT) {
       this.browser.messageManager.sendAsyncMessage("Reader:PushState", {isArticle: this.browser.isArticle});
     }
 
-    // Reset state of click-to-play plugin notifications.
-    clearTimeout(this.pluginDoorhangerTimeout);
-    this.pluginDoorhangerTimeout = null;
-    this.shouldShowPluginDoorhanger = true;
-    this.clickToPlayPluginsActivated = false;
-
     let baseDomain = "";
     // For recognized scheme, get base domain from host.
     let principalURI = contentWin.document.nodePrincipal.URI;
     if (principalURI && ["http", "https", "ftp"].includes(principalURI.scheme) && principalURI.host) {
       try {
         baseDomain = Services.eTLD.getBaseDomainFromHost(principalURI.host);
         if (!principalURI.host.endsWith(baseDomain)) {
           // getBaseDomainFromHost converts its resultant to ACE.
@@ -5914,17 +5877,17 @@ var IdentityHandler = {
       return this.IDENTITY_MODE_VERIFIED;
     }
 
     if (aState & Ci.nsIWebProgressListener.STATE_IS_SECURE) {
       return this.IDENTITY_MODE_IDENTIFIED;
     }
 
     // We also allow "about:" by allowing the selector to be empty (i.e. '(|.....|...|...)'
-    let whitelist = /^about:($|about|accounts|addons|buildconfig|cache|config|crashes|devices|downloads|fennec|firefox|feedback|healthreport|home|license|logins|logo|memory|mozilla|networking|plugins|privatebrowsing|rights|serviceworkers|support|telemetry|webrtc)($|\?)/i;
+    let whitelist = /^about:($|about|accounts|addons|buildconfig|cache|config|crashes|devices|downloads|fennec|firefox|feedback|healthreport|home|license|logins|logo|memory|mozilla|networking|privatebrowsing|rights|serviceworkers|support|telemetry|webrtc)($|\?)/i;
     if (uri.schemeIs("about") && whitelist.test(uri.spec)) {
         return this.IDENTITY_MODE_CHROMEUI;
     }
 
     return this.IDENTITY_MODE_UNKNOWN;
   },
 
   getMixedDisplayMode: function getMixedDisplayMode(aState) {
--- a/mobile/android/components/PromptService.js
+++ b/mobile/android/components/PromptService.js
@@ -51,18 +51,18 @@ PromptService.prototype = {
         if (!this.selectHelper) {
           this.selectHelper = this.loadSubscript(
               "SelectHelper", "chrome://browser/content/SelectHelper.js");
         }
         if (!this.inputWidgetHelper) {
           this.inputWidgetHelper = this.loadSubscript(
               "InputWidgetHelper", "chrome://browser/content/InputWidgetHelper.js");
         }
-        win.addEventListener("click", this.selectHelper); // non-capture
-        win.addEventListener("click", this.inputWidgetHelper); // non-capture
+        win.addEventListener("click", this.selectHelper, /* capture */ true);
+        win.addEventListener("click", this.inputWidgetHelper, /* capture */ true);
         break;
       }
     }
   },
 
   /* ----------  nsIPromptFactory  ---------- */
   // XXX Copied from nsPrompter.js.
   getPrompt: function getPrompt(domWin, iid) {
--- a/mobile/android/geckoview/src/main/java/org/mozilla/gecko/GeckoAppShell.java
+++ b/mobile/android/geckoview/src/main/java/org/mozilla/gecko/GeckoAppShell.java
@@ -1402,239 +1402,16 @@ public class GeckoAppShell
                                        Settings.System.TEXT_SHOW_PASSWORD, 1);
             return (showPassword > 0);
         }
         catch (Exception e) {
             return true;
         }
     }
 
-    /**
-     * A plugin that wish to be loaded in the WebView must provide this permission
-     * in their AndroidManifest.xml.
-     */
-    public static final String PLUGIN_ACTION = "android.webkit.PLUGIN";
-    public static final String PLUGIN_PERMISSION = "android.webkit.permission.PLUGIN";
-
-    private static final String PLUGIN_SYSTEM_LIB = "/system/lib/plugins/";
-
-    private static final String PLUGIN_TYPE = "type";
-    private static final String TYPE_NATIVE = "native";
-    public static final ArrayList<PackageInfo> mPackageInfoCache = new ArrayList<>();
-
-    // Returns null if plugins are blocked on the device.
-    static String[] getPluginDirectories() {
-
-        // Block on Pixel C.
-        if ((new File("/system/lib/hw/power.dragon.so")).exists()) {
-            Log.w(LOGTAG, "Blocking plugins because of Pixel C device (bug 1255122)");
-            return null;
-        }
-        // An awful hack to detect Tegra devices. Easiest way to do it without spinning up a EGL context.
-        boolean isTegra = (new File("/system/lib/hw/gralloc.tegra.so")).exists() ||
-                          (new File("/system/lib/hw/gralloc.tegra3.so")).exists() ||
-                          (new File("/sys/class/nvidia-gpu")).exists();
-        if (isTegra) {
-            // disable on KitKat (bug 957694)
-            if (Build.VERSION.SDK_INT >= 19) {
-                Log.w(LOGTAG, "Blocking plugins because of Tegra (bug 957694)");
-                return null;
-            }
-
-            // disable Flash on Tegra ICS with CM9 and other custom firmware (bug 736421)
-            final File vfile = new File("/proc/version");
-            try {
-                if (vfile.canRead()) {
-                    final BufferedReader reader = new BufferedReader(new FileReader(vfile));
-                    try {
-                        final String version = reader.readLine();
-                        if (version.indexOf("CM9") != -1 ||
-                            version.indexOf("cyanogen") != -1 ||
-                            version.indexOf("Nova") != -1) {
-                            Log.w(LOGTAG, "Blocking plugins because of Tegra 2 + unofficial ICS bug (bug 736421)");
-                            return null;
-                        }
-                    } finally {
-                      reader.close();
-                    }
-                }
-            } catch (IOException ex) {
-                // Do nothing.
-            }
-        }
-
-        ArrayList<String> directories = new ArrayList<String>();
-        PackageManager pm = getApplicationContext().getPackageManager();
-        List<ResolveInfo> plugins = pm.queryIntentServices(new Intent(PLUGIN_ACTION),
-                PackageManager.GET_META_DATA);
-
-        synchronized (mPackageInfoCache) {
-
-            // clear the list of existing packageInfo objects
-            mPackageInfoCache.clear();
-
-
-            for (ResolveInfo info : plugins) {
-
-                // retrieve the plugin's service information
-                ServiceInfo serviceInfo = info.serviceInfo;
-                if (serviceInfo == null) {
-                    Log.w(LOGTAG, "Ignoring bad plugin.");
-                    continue;
-                }
-
-                // Blacklist HTC's flash lite.
-                // See bug #704516 - We're not quite sure what Flash Lite does,
-                // but loading it causes Flash to give errors and fail to draw.
-                if (serviceInfo.packageName.equals("com.htc.flashliteplugin")) {
-                    Log.w(LOGTAG, "Skipping HTC's flash lite plugin");
-                    continue;
-                }
-
-
-                // Retrieve information from the plugin's manifest.
-                PackageInfo pkgInfo;
-                try {
-                    pkgInfo = pm.getPackageInfo(serviceInfo.packageName,
-                                    PackageManager.GET_PERMISSIONS
-                                    | PackageManager.GET_SIGNATURES);
-                } catch (Exception e) {
-                    Log.w(LOGTAG, "Can't find plugin: " + serviceInfo.packageName);
-                    continue;
-                }
-
-                if (pkgInfo == null) {
-                    Log.w(LOGTAG, "Not loading plugin: " + serviceInfo.packageName + ". Could not load package information.");
-                    continue;
-                }
-
-                /*
-                 * find the location of the plugin's shared library. The default
-                 * is to assume the app is either a user installed app or an
-                 * updated system app. In both of these cases the library is
-                 * stored in the app's data directory.
-                 */
-                String directory = pkgInfo.applicationInfo.dataDir + "/lib";
-                final int appFlags = pkgInfo.applicationInfo.flags;
-                final int updatedSystemFlags = ApplicationInfo.FLAG_SYSTEM |
-                                               ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
-
-                // preloaded system app with no user updates
-                if ((appFlags & updatedSystemFlags) == ApplicationInfo.FLAG_SYSTEM) {
-                    directory = PLUGIN_SYSTEM_LIB + pkgInfo.packageName;
-                }
-
-                // check if the plugin has the required permissions
-                String permissions[] = pkgInfo.requestedPermissions;
-                if (permissions == null) {
-                    Log.w(LOGTAG, "Not loading plugin: " + serviceInfo.packageName + ". Does not have required permission.");
-                    continue;
-                }
-                boolean permissionOk = false;
-                for (String permit : permissions) {
-                    if (PLUGIN_PERMISSION.equals(permit)) {
-                        permissionOk = true;
-                        break;
-                    }
-                }
-                if (!permissionOk) {
-                    Log.w(LOGTAG, "Not loading plugin: " + serviceInfo.packageName + ". Does not have required permission (2).");
-                    continue;
-                }
-
-                // check to ensure the plugin is properly signed
-                Signature signatures[] = pkgInfo.signatures;
-                if (signatures == null) {
-                    Log.w(LOGTAG, "Not loading plugin: " + serviceInfo.packageName + ". Not signed.");
-                    continue;
-                }
-
-                // determine the type of plugin from the manifest
-                if (serviceInfo.metaData == null) {
-                    Log.e(LOGTAG, "The plugin '" + serviceInfo.name + "' has no defined type.");
-                    continue;
-                }
-
-                String pluginType = serviceInfo.metaData.getString(PLUGIN_TYPE);
-                if (!TYPE_NATIVE.equals(pluginType)) {
-                    Log.e(LOGTAG, "Unrecognized plugin type: " + pluginType);
-                    continue;
-                }
-
-                try {
-                    Class<?> cls = getPluginClass(serviceInfo.packageName, serviceInfo.name);
-
-                    //TODO implement any requirements of the plugin class here!
-                    boolean classFound = true;
-
-                    if (!classFound) {
-                        Log.e(LOGTAG, "The plugin's class' " + serviceInfo.name + "' does not extend the appropriate class.");
-                        continue;
-                    }
-
-                } catch (NameNotFoundException e) {
-                    Log.e(LOGTAG, "Can't find plugin: " + serviceInfo.packageName);
-                    continue;
-                } catch (ClassNotFoundException e) {
-                    Log.e(LOGTAG, "Can't find plugin's class: " + serviceInfo.name);
-                    continue;
-                }
-
-                // if all checks have passed then make the plugin available
-                mPackageInfoCache.add(pkgInfo);
-                directories.add(directory);
-            }
-        }
-
-        return directories.toArray(new String[directories.size()]);
-    }
-
-    static String getPluginPackage(String pluginLib) {
-
-        if (pluginLib == null || pluginLib.length() == 0) {
-            return null;
-        }
-
-        synchronized (mPackageInfoCache) {
-            for (PackageInfo pkgInfo : mPackageInfoCache) {
-                if (pluginLib.contains(pkgInfo.packageName)) {
-                    return pkgInfo.packageName;
-                }
-            }
-        }
-
-        return null;
-    }
-
-    static Class<?> getPluginClass(String packageName, String className)
-            throws NameNotFoundException, ClassNotFoundException {
-        Context pluginContext = getApplicationContext().createPackageContext(packageName,
-                Context.CONTEXT_INCLUDE_CODE |
-                Context.CONTEXT_IGNORE_SECURITY);
-        ClassLoader pluginCL = pluginContext.getClassLoader();
-        return pluginCL.loadClass(className);
-    }
-
-    @WrapForJNI
-    private static Class<?> loadPluginClass(String className, String libName) {
-        try {
-            final String packageName = getPluginPackage(libName);
-            final int contextFlags = Context.CONTEXT_INCLUDE_CODE | Context.CONTEXT_IGNORE_SECURITY;
-            final Context pluginContext = getApplicationContext().createPackageContext(
-                    packageName, contextFlags);
-            return pluginContext.getClassLoader().loadClass(className);
-        } catch (java.lang.ClassNotFoundException cnfe) {
-            Log.w(LOGTAG, "Couldn't find plugin class " + className, cnfe);
-            return null;
-        } catch (android.content.pm.PackageManager.NameNotFoundException nnfe) {
-            Log.w(LOGTAG, "Couldn't find package.", nnfe);
-            return null;
-        }
-    }
-
     private static Context sApplicationContext;
 
     @WrapForJNI
     public static Context getApplicationContext() {
         return sApplicationContext;
     }
 
     public static void setApplicationContext(final Context context) {
--- a/mobile/android/geckoview/src/main/java/org/mozilla/gecko/GeckoThread.java
+++ b/mobile/android/geckoview/src/main/java/org/mozilla/gecko/GeckoThread.java
@@ -254,25 +254,18 @@ public class GeckoThread extends Thread 
         if (locale.toString().equalsIgnoreCase("zh_hk")) {
             final Locale mappedLocale = Locale.TRADITIONAL_CHINESE;
             Locale.setDefault(mappedLocale);
             Configuration config = res.getConfiguration();
             config.locale = mappedLocale;
             res.updateConfiguration(config, null);
         }
 
-        String[] pluginDirs = null;
-        try {
-            pluginDirs = GeckoAppShell.getPluginDirectories();
-        } catch (Exception e) {
-            Log.w(LOGTAG, "Caught exception getting plugin dirs.", e);
-        }
-
         final String resourcePath = context.getPackageResourcePath();
-        GeckoLoader.setupGeckoEnvironment(context, pluginDirs, context.getFilesDir().getPath());
+        GeckoLoader.setupGeckoEnvironment(context, context.getFilesDir().getPath());
 
         try {
             loadGeckoLibs(context, resourcePath);
 
         } catch (final Exception e) {
             // Cannot load libs; try clearing the cached files.
             Log.w(LOGTAG, "Clearing cache after load libs exception", e);
             FileUtils.delTree(GeckoLoader.getCacheDir(context),
--- a/mobile/android/geckoview/src/main/java/org/mozilla/gecko/mozglue/GeckoLoader.java
+++ b/mobile/android/geckoview/src/main/java/org/mozilla/gecko/mozglue/GeckoLoader.java
@@ -52,44 +52,16 @@ public final class GeckoLoader {
 
     public static File getGREDir(Context context) {
         if (sGREDir == null) {
             sGREDir = new File(context.getApplicationInfo().dataDir);
         }
         return sGREDir;
     }
 
-    private static void setupPluginEnvironment(Context context, String[] pluginDirs) {
-        // setup plugin path directories
-        try {
-            // Check to see if plugins were blocked.
-            if (pluginDirs == null) {
-                putenv("MOZ_PLUGINS_BLOCKED=1");
-                putenv("MOZ_PLUGIN_PATH=");
-                return;
-            }
-
-            StringBuilder pluginSearchPath = new StringBuilder();
-            for (int i = 0; i < pluginDirs.length; i++) {
-                pluginSearchPath.append(pluginDirs[i]);
-                pluginSearchPath.append(":");
-            }
-            putenv("MOZ_PLUGIN_PATH=" + pluginSearchPath);
-
-            File pluginDataDir = context.getDir("plugins", 0);
-            putenv("ANDROID_PLUGIN_DATADIR=" + pluginDataDir.getPath());
-
-            File pluginPrivateDataDir = context.getDir("plugins_private", 0);
-            putenv("ANDROID_PLUGIN_DATADIR_PRIVATE=" + pluginPrivateDataDir.getPath());
-
-        } catch (Exception ex) {
-            Log.w(LOGTAG, "Caught exception getting plugin dirs.", ex);
-        }
-    }
-
     private static void setupDownloadEnvironment(final Context context) {
         try {
             File downloadDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
             File updatesDir  = context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS);
             if (downloadDir == null) {
                 downloadDir = new File(Environment.getExternalStorageDirectory().getPath(), "download");
             }
             if (updatesDir == null) {
@@ -129,17 +101,17 @@ public final class GeckoLoader {
     public static void addEnvironmentToIntent(Intent intent) {
         if (sEnvList != null) {
             for (int ix = 0; ix < sEnvList.length; ix++) {
                 intent.putExtra("env" + ix, sEnvList[ix]);
             }
         }
     }
 
-    public static void setupGeckoEnvironment(Context context, String[] pluginDirs, String profilePath) {
+    public static void setupGeckoEnvironment(Context context, String profilePath) {
         // if we have an intent (we're being launched by an activity)
         // read in any environmental variables from it here
         final SafeIntent intent = sIntent;
         if (intent != null) {
             final ArrayList<String> envList = new ArrayList<String>();
             String env = intent.getStringExtra("env0");
             Log.d(LOGTAG, "Gecko environment env0: " + env);
             for (int c = 1; env != null; c++) {
@@ -150,17 +122,16 @@ public final class GeckoLoader {
             }
             if (envList.size() > 0) {
               sEnvList = envList.toArray(new String[envList.size()]);
             }
         }
 
         putenv("MOZ_ANDROID_PACKAGE_NAME=" + context.getPackageName());
 
-        setupPluginEnvironment(context, pluginDirs);
         setupDownloadEnvironment(context);
 
         // profile home path
         putenv("HOME=" + profilePath);
 
         // setup the tmp path
         File f = getTmpDir(context);
         if (!f.exists()) {
deleted file mode 100644
--- a/mobile/android/tests/browser/robocop/robocop_adobe_flash.html
+++ /dev/null
@@ -1,17 +0,0 @@
-<html style="margin: 0; padding: 0">
-<head>
- <title>Adobe Flash Test</title>
- <meta name="viewport" content="width=device-width,initial-scale=1.0"/>
- <meta charset="utf-8">
-</head>
-<body style="margin: 0; padding: 0">
-	<object width="100" height="100"
-	classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000"
-	codebase="http://fpdownload.macromedia.com/
-	pub/shockwave/cabs/flash/swflash.cab#version=8,0,0,0">
-		<param name="SRC" value="green.swf">
-		<embed src="green.swf" width="100" height="100">
-		</embed>
-	</object>
-</body>
-</html>
--- a/mobile/android/tests/browser/robocop/src/org/mozilla/gecko/tests/StringHelper.java
+++ b/mobile/android/tests/browser/robocop/src/org/mozilla/gecko/tests/StringHelper.java
@@ -76,17 +76,16 @@ public class StringHelper {
     public final String ROBOCOP_GEOLOCATION_URL = "/robocop/robocop_geolocation.html";
     public final String ROBOCOP_LOGIN_01_URL= "/robocop/robocop_login_01.html";
     public final String ROBOCOP_LOGIN_02_URL= "/robocop/robocop_login_02.html";
     public final String ROBOCOP_POPUP_URL = "/robocop/robocop_popup.html";
     public final String ROBOCOP_OFFLINE_STORAGE_URL = "/robocop/robocop_offline_storage.html";
     public final String ROBOCOP_PICTURE_LINK_URL = "/robocop/robocop_picture_link.html";
     public final String ROBOCOP_SEARCH_URL = "/robocop/robocop_search.html";
     public final String ROBOCOP_TEXT_PAGE_URL = "/robocop/robocop_text_page.html";
-    public final String ROBOCOP_ADOBE_FLASH_URL = "/robocop/robocop_adobe_flash.html";
     public final String ROBOCOP_INPUT_URL = "/robocop/robocop_input.html";
     public final String ROBOCOP_READER_MODE_BASIC_ARTICLE = "/robocop/reader_mode_pages/basic_article.html";
     public final String ROBOCOP_LINK_TO_SLOW_LOADING = "/robocop/robocop_link_to_slow_loading.html";
     public final String ROBOCOP_MEDIA_PLAYBACK_JS_URL = "/robocop/robocop_media_playback_js.html";
     public final String ROBOCOP_MEDIA_PLAYBACK_LOOP_URL = "/robocop/robocop_media_playback_loop.html";
 
     private final String ROBOCOP_JS_HARNESS_URL = "/robocop/robocop_javascript.html";
 
@@ -213,18 +212,16 @@ public class StringHelper {
 
     // Notifications Settings
     public final String NEW_IN_FIREFOX_LABEL;
 
     // Advanced Settings
     public final String ADVANCED;
     public final String DONT_SHOW_MENU;
     public final String SHOW_MENU;
-    public final String DISABLED;
-    public final String TAP_TO_PLAY;
     public final String HIDE_TITLE_BAR;
     public final String RESTORE_TABS_LABEL;
 
     // Clear Private Data Section
     public final String SITE_SETTINGS_LABEL;
 
     // Mozilla Firefox Section
     public final String FAQS_LABEL;
@@ -396,18 +393,16 @@ public class StringHelper {
 
         // Notification Settings
         NEW_IN_FIREFOX_LABEL = res.getString(R.string.pref_whats_new_notification);
 
         // Advanced Settings
         ADVANCED = res.getString(R.string.pref_category_advanced);
         DONT_SHOW_MENU = res.getString(R.string.pref_char_encoding_off);
         SHOW_MENU = res.getString(R.string.pref_char_encoding_on);
-        DISABLED = res.getString(R.string.pref_plugins_disabled );
-        TAP_TO_PLAY = res.getString(R.string.pref_plugins_tap_to_play);
         HIDE_TITLE_BAR = res.getString(R.string.pref_scroll_title_bar_summary );
         RESTORE_TABS_LABEL = res.getString(R.string.pref_restore);
 
         // Clear Private Data Settings
         SITE_SETTINGS_LABEL = res.getString(R.string.pref_private_data_siteSettings);
 
         // Mozilla Firefox Settings
         FAQS_LABEL = res.getString(R.string.pref_vendor_faqs);
deleted file mode 100644
--- a/mobile/android/tests/browser/robocop/src/org/mozilla/gecko/tests/testAdobeFlash.java
+++ /dev/null
@@ -1,33 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-package org.mozilla.gecko.tests;
-
-import org.json.JSONObject;
-import org.mozilla.gecko.PaintedSurface;
-
-import android.os.Build;
-
-/**
- * Tests that Flash is working
- * - loads a page containing a Flash plugin
- * - verifies it rendered properly
- */
-public class testAdobeFlash extends PixelTest {
-    public void testLoad() {
-        // Enable plugins
-        setPreferenceAndWaitForChange("plugin.enable", "1");
-
-        blockForGeckoReady();
-
-        String url = getAbsoluteUrl(mStringHelper.ROBOCOP_ADOBE_FLASH_URL);
-        PaintedSurface painted = loadAndGetPainted(url);
-
-        mAsserter.ispixel(painted.getPixelAt(0, 0), 0, 0xff, 0, "Pixel at 0, 0");
-        mAsserter.ispixel(painted.getPixelAt(50, 50), 0, 0xff, 0, "Pixel at 50, 50");
-        mAsserter.ispixel(painted.getPixelAt(101, 0), 0xff, 0xff, 0xff, "Pixel at 101, 0");
-        mAsserter.ispixel(painted.getPixelAt(0, 101), 0xff, 0xff, 0xff, "Pixel at 0, 101");
-
-    }
-}
--- a/modules/libpref/init/all.js
+++ b/modules/libpref/init/all.js
@@ -5728,22 +5728,21 @@ pref("layout.css.servo.enabled", true);
 #else
 pref("layout.css.servo.enabled", false);
 #endif
 #endif
 
 // HSTS Priming
 // If a request is mixed-content, send an HSTS priming request to attempt to
 // see if it is available over HTTPS.
-#ifdef RELEASE
 // Don't change the order of evaluation of mixed-content and HSTS upgrades in
-// order to be most compatible with current standards
+// order to be most compatible with current standards in Release
 pref("security.mixed_content.send_hsts_priming", false);
 pref("security.mixed_content.use_hsts", false);
-#else
+#ifdef EARLY_BETA_OR_EARLIER
 // Change the order of evaluation so HSTS upgrades happen before
 // mixed-content blocking
 pref("security.mixed_content.send_hsts_priming", true);
 pref("security.mixed_content.use_hsts", true);
 #endif
 // Approximately 1 week default cache for HSTS priming failures, in seconds
 pref("security.mixed_content.hsts_priming_cache_timeout", 604800);
 // Force the channel to timeout in 2 seconds if we have not received
--- a/netwerk/base/nsFileStreams.cpp
+++ b/netwerk/base/nsFileStreams.cpp
@@ -327,17 +327,17 @@ nsFileStreamBase::DoOpen()
 
     if (mOpenParams.ioFlags & PR_CREATE_FILE) {
         nsCOMPtr<nsIFile> parent;
         mOpenParams.localFile->GetParent(getter_AddRefs(parent));
 
         // Result doesn't need to be checked. If the file's parent path does not
         // exist, make it. If it does exist, do nothing.
         if (parent) {
-            Unused << parent->Create(nsIFile::DIRECTORY_TYPE, 0644);
+            Unused << parent->Create(nsIFile::DIRECTORY_TYPE, 0755);
         }
     }
 
 #ifdef XP_WIN
     if (mBehaviorFlags & nsIFileInputStream::SHARE_DELETE) {
       nsCOMPtr<nsILocalFileWin> file = do_QueryInterface(mOpenParams.localFile);
       MOZ_ASSERT(file);
 
--- a/netwerk/base/nsStandardURL.cpp
+++ b/netwerk/base/nsStandardURL.cpp
@@ -1406,29 +1406,63 @@ nsStandardURL::GetSpecIgnoringRef(nsACSt
     // URI without ref is 0 to one char before ref
     if (mRef.mLen < 0) {
         return GetSpec(result);
     }
 
     URLSegment noRef(0, mRef.mPos - 1);
     result = Segment(noRef);
 
-    if (!gPunycodeHost && mCheckedIfHostA && !mDisplayHost.IsEmpty()) {
+    CheckIfHostIsAscii();
+    MOZ_ASSERT(mCheckedIfHostA);
+    if (!gPunycodeHost && !mDisplayHost.IsEmpty()) {
         result.Replace(mHost.mPos, mHost.mLen, mDisplayHost);
     }
 
     CALL_RUST_GETTER_STR(result, GetSpecIgnoringRef, result);
     return NS_OK;
 }
 
+nsresult
+nsStandardURL::CheckIfHostIsAscii()
+{
+    nsresult rv;
+    if (mCheckedIfHostA) {
+        return NS_OK;
+    }
+
+    mCheckedIfHostA = true;
+
+    // If the hostname doesn't begin with `xn--` we are sure it is ASCII.
+    if (!StringBeginsWith(Host(), NS_LITERAL_CSTRING("xn--"))) {
+        return NS_OK;
+    }
+
+    if (!gIDN) {
+        return NS_ERROR_NOT_INITIALIZED;
+    }
+
+    bool isAscii;
+    rv = gIDN->ConvertToDisplayIDN(Host(), &isAscii, mDisplayHost);
+    if (NS_FAILED(rv)) {
+        mDisplayHost.Truncate();
+        mCheckedIfHostA = false;
+        return rv;
+    }
+
+    return NS_OK;
+}
+
 NS_IMETHODIMP
 nsStandardURL::GetDisplaySpec(nsACString &aUnicodeSpec)
 {
+    CheckIfHostIsAscii();
     aUnicodeSpec.Assign(mSpec);
-    if (mCheckedIfHostA && !mDisplayHost.IsEmpty()) {
+    MOZ_ASSERT(mCheckedIfHostA);
+    if (!mDisplayHost.IsEmpty()) {
         aUnicodeSpec.Replace(mHost.mPos, mHost.mLen, mDisplayHost);
     }
 
     return NS_OK;
 }
 
 NS_IMETHODIMP
 nsStandardURL::GetDisplayHostPort(nsACString &aUnicodeHostPort)
@@ -1453,49 +1487,35 @@ nsStandardURL::GetDisplayHostPort(nsACSt
         aUnicodeHostPort += Substring(mSpec, pos, mPath.mPos - pos);
 
     return NS_OK;
 }
 
 NS_IMETHODIMP
 nsStandardURL::GetDisplayHost(nsACString &aUnicodeHost)
 {
-    if (mCheckedIfHostA) {
-        if (mDisplayHost.IsEmpty()) {
-            return GetAsciiHost(aUnicodeHost);
-        } else {
-            aUnicodeHost = mDisplayHost;
-            return NS_OK;
-        }
-    }
-
-    if (!gIDN) {
-        return NS_ERROR_NOT_INITIALIZED;
+    CheckIfHostIsAscii();
+    MOZ_ASSERT(mCheckedIfHostA);
+    if (mDisplayHost.IsEmpty()) {
+        return GetAsciiHost(aUnicodeHost);
     }
 
-    nsresult rv = gIDN->ConvertACEtoUTF8(Host(), aUnicodeHost);
-    if (NS_FAILED(rv)) {
-        return rv;
-    }
-
-    mCheckedIfHostA = true;
-    if (aUnicodeHost != Host()) {
-        mDisplayHost = aUnicodeHost;
-    }
-
+    aUnicodeHost = mDisplayHost;
     return NS_OK;
 }
 
 
 // result may contain unescaped UTF-8 characters
 NS_IMETHODIMP
 nsStandardURL::GetPrePath(nsACString &result)
 {
     result = Prepath();
-    if (!gPunycodeHost && mCheckedIfHostA && !mDisplayHost.IsEmpty()) {
+    CheckIfHostIsAscii();
+    MOZ_ASSERT(mCheckedIfHostA);
+    if (!gPunycodeHost && !mDisplayHost.IsEmpty()) {
         result.Replace(mHost.mPos, mHost.mLen, mDisplayHost);
     }
     CALL_RUST_GETTER_STR(result, GetPrePath, result);
     return NS_OK;
 }
 
 // result is strictly US-ASCII
 NS_IMETHODIMP
--- a/netwerk/base/nsStandardURL.h
+++ b/netwerk/base/nsStandardURL.h
@@ -184,16 +184,17 @@ private:
 
     void     ReplacePortInSpec(int32_t aNewPort);
     void     Clear();
     void     InvalidateCache(bool invalidateCachedFile = true);
 
     bool     ValidIPv6orHostname(const char *host, uint32_t aLen);
     static bool     IsValidOfBase(unsigned char c, const uint32_t base);
     nsresult NormalizeIDN(const nsACString& host, nsCString& result);
+    nsresult CheckIfHostIsAscii();
     void     CoalescePath(netCoalesceFlags coalesceFlag, char *path);
 
     uint32_t AppendSegmentToBuf(char *, uint32_t, const char *,
                                 const URLSegment &input, URLSegment &output,
                                 const nsCString *esc=nullptr,
                                 bool useEsc = false, int32_t* diff = nullptr);
     uint32_t AppendToBuf(char *, uint32_t, const char *, uint32_t);
 
--- a/netwerk/dns/nsDNSService2.cpp
+++ b/netwerk/dns/nsDNSService2.cpp
@@ -542,19 +542,19 @@ nsDNSService::Init()
     uint32_t defaultGracePeriod = 60; // seconds
     bool     disableIPv6      = false;
     bool     offlineLocalhost = true;
     bool     disablePrefetch  = false;
     bool     blockDotOnion    = true;
     int      proxyType        = nsIProtocolProxyService::PROXYCONFIG_DIRECT;
     bool     notifyResolution = false;
 
-    nsAdoptingCString ipv4OnlyDomains;
-    nsAdoptingCString localDomains;
-    nsAdoptingCString forceResolve;
+    nsCString ipv4OnlyDomains;
+    nsCString localDomains;
+    nsCString forceResolve;
 
     // read prefs
     nsCOMPtr<nsIPrefBranch> prefs = do_GetService(NS_PREFSERVICE_CONTRACTID);
     if (prefs) {
         int32_t val;
         if (NS_SUCCEEDED(prefs->GetIntPref(kPrefDnsCacheEntries, &val)))
             maxCacheEntries = (uint32_t) val;
         if (NS_SUCCEEDED(prefs->GetIntPref(kPrefDnsCacheExpiration, &val)))
@@ -613,28 +613,28 @@ nsDNSService::Init()
                                          defaultCacheLifetime,
                                          defaultGracePeriod,
                                          getter_AddRefs(res));
     if (NS_SUCCEEDED(rv)) {
         // now, set all of our member variables while holding the lock
         MutexAutoLock lock(mLock);
         mResolver = res;
         mIDN = idn;
-        mIPv4OnlyDomains = ipv4OnlyDomains; // exchanges buffer ownership
+        mIPv4OnlyDomains = ipv4OnlyDomains;
         mOfflineLocalhost = offlineLocalhost;
         mDisableIPv6 = disableIPv6;
         mBlockDotOnion = blockDotOnion;
         mForceResolve = forceResolve;
         mForceResolveOn = !mForceResolve.IsEmpty();
 
         // Disable prefetching either by explicit preference or if a manual proxy is configured
         mDisablePrefetch = disablePrefetch || (proxyType == nsIProtocolProxyService::PROXYCONFIG_MANUAL);
 
         mLocalDomains.Clear();
-        if (localDomains) {
+        if (!localDomains.IsVoid()) {
             nsCCharSeparatedTokenizer tokenizer(localDomains, ',',
                                                 nsCCharSeparatedTokenizer::SEPARATOR_OPTIONAL);
 
             while (tokenizer.hasMoreTokens()) {
                 mLocalDomains.PutEntry(tokenizer.nextToken());
             }
         }
         mNotifyResolution = notifyResolution;
--- a/netwerk/dns/nsDNSService2.h
+++ b/netwerk/dns/nsDNSService2.h
@@ -54,18 +54,18 @@ private:
     nsCOMPtr<nsIIDNService>   mIDN;
 
     // mLock protects access to mResolver and mIPv4OnlyDomains
     mozilla::Mutex            mLock;
 
     // mIPv4OnlyDomains is a comma-separated list of domains for which only
     // IPv4 DNS lookups are performed. This allows the user to disable IPv6 on
     // a per-domain basis and work around broken DNS servers. See bug 68796.
-    nsAdoptingCString                         mIPv4OnlyDomains;
-    nsAdoptingCString                         mForceResolve;
+    nsCString                                 mIPv4OnlyDomains;
+    nsCString                                 mForceResolve;
     bool                                      mDisableIPv6;
     bool                                      mDisablePrefetch;
     bool                                      mBlockDotOnion;
     bool                                      mFirstTime;
     bool                                      mNotifyResolution;
     bool                                      mOfflineLocalhost;
     bool                                      mForceResolveOn;
     nsTHashtable<nsCStringHashKey>            mLocalDomains;
--- a/netwerk/protocol/http/nsHttpConnection.cpp
+++ b/netwerk/protocol/http/nsHttpConnection.cpp
@@ -139,17 +139,17 @@ nsHttpConnection::Init(nsHttpConnectionI
                        PRIntervalTime rtt)
 {
     LOG(("nsHttpConnection::Init this=%p", this));
     NS_ENSURE_ARG_POINTER(info);
     NS_ENSURE_TRUE(!mConnInfo, NS_ERROR_ALREADY_INITIALIZED);
 
     mConnectedTransport = connectedTransport;
     mConnInfo = info;
-    MOZ_DIAGNOSTIC_ASSERT(mConnInfo);
+    MOZ_ASSERT(mConnInfo);
     mLastWriteTime = mLastReadTime = PR_IntervalNow();
     mRtt = rtt;
     mMaxHangTime = PR_SecondsToInterval(maxHangTime);
 
     mSocketTransport = transport;
     mSocketIn = instream;
     mSocketOut = outstream;
 
@@ -310,17 +310,17 @@ nsHttpConnection::StartSpdy(uint8_t spdy
     bool spdyProxy = mConnInfo->UsingHttpsProxy() && !mTLSFilter;
     if (spdyProxy) {
         RefPtr<nsHttpConnectionInfo> wildCardProxyCi;
         rv = mConnInfo->CreateWildCard(getter_AddRefs(wildCardProxyCi));
         MOZ_ASSERT(NS_SUCCEEDED(rv));
         gHttpHandler->ConnMgr()->MoveToWildCardConnEntry(mConnInfo,
                                                          wildCardProxyCi, this);
         mConnInfo = wildCardProxyCi;
-        MOZ_DIAGNOSTIC_ASSERT(mConnInfo);
+        MOZ_ASSERT(mConnInfo);
     }
 
     if (!mDid0RTTSpdy) {
         rv = MoveTransactionsToSpdy(status, list);
         if (NS_FAILED(rv)) {
             return;
         }
     }
@@ -1936,17 +1936,17 @@ nsHttpConnection::SetupSecondaryTLS()
 
     nsHttpConnectionInfo *ci = nullptr;
     if (mTransaction) {
         ci = mTransaction->ConnectionInfo();
     }
     if (!ci) {
         ci = mConnInfo;
     }
-    MOZ_DIAGNOSTIC_ASSERT(ci);
+    MOZ_ASSERT(ci);
 
     mTLSFilter = new TLSFilterTransaction(mTransaction,
                                           ci->Origin(), ci->OriginPort(), this, this);
 
     if (mTransaction) {
         mTransaction = mTLSFilter;
     }
 }
--- a/netwerk/protocol/http/nsHttpConnectionMgr.cpp
+++ b/netwerk/protocol/http/nsHttpConnectionMgr.cpp
@@ -614,17 +614,16 @@ nsHttpConnectionMgr::ClearConnectionHist
         RefPtr<nsConnectionEntry> ent = iter.Data();
         if (ent->mIdleConns.Length()    == 0 &&
             ent->mActiveConns.Length()  == 0 &&
             ent->mHalfOpens.Length()    == 0 &&
             ent->mUrgentStartQ.Length() == 0 &&
             ent->PendingQLength()       == 0 &&
             ent->mHalfOpenFastOpenBackups.Length() == 0 &&
             !ent->mDoNotDestroy) {
-            ent->mHowItWasRemoved = nsConnectionEntry::CONN_ENTRY_CLEAR_CONNECTION_HISTORY;
             iter.Remove();
         }
     }
 
     return NS_OK;
 }
 
 nsresult
@@ -783,19 +782,18 @@ nsHttpConnectionMgr::FindCoalescableConn
 
 void
 nsHttpConnectionMgr::UpdateCoalescingForNewConn(nsHttpConnection *newConn,
                                                 nsConnectionEntry *ent)
 {
     MOZ_ASSERT(OnSocketThread(), "not on socket thread");
     MOZ_ASSERT(newConn);
     MOZ_ASSERT(newConn->ConnectionInfo());
-    MOZ_DIAGNOSTIC_ASSERT(ent);
+    MOZ_ASSERT(ent);
     MOZ_ASSERT(mCT.GetWeak(newConn->ConnectionInfo()->HashKey()) == ent);
-    CheckConnEntryMustBeInmCT(ent);
 
     nsHttpConnection *existingConn = FindCoalescableConnection(ent, true);
     if (existingConn) {
         LOG(("UpdateCoalescingForNewConn() found existing active conn that could have served newConn "
              "graceful close of newConn=%p to migrate to existingConn %p\n", newConn, existingConn));
         newConn->DontReuse();
         return;
     }
@@ -822,21 +820,16 @@ nsHttpConnectionMgr::UpdateCoalescingFor
 
     // Cancel any other pending connections - their associated transactions
     // are in the pending queue and will be dispatched onto this new connection
     for (int32_t index = ent->mHalfOpens.Length() - 1; index >= 0; --index) {
         RefPtr<nsHalfOpenSocket> half = ent->mHalfOpens[index];
         LOG(("UpdateCoalescingForNewConn() forcing halfopen abandon %p\n",
              half.get()));
         ent->mHalfOpens[index]->Abandon();
-        MOZ_DIAGNOSTIC_ASSERT(!half->mBackupTransport);
-        MOZ_DIAGNOSTIC_ASSERT(!half->mBackupStreamOut);
-        MOZ_DIAGNOSTIC_ASSERT(!half->mBackupStreamIn);
-        MOZ_DIAGNOSTIC_ASSERT(!half->mSynTimer);
-        MOZ_DIAGNOSTIC_ASSERT(!half->mEnt);
     }
 
     if (ent->mActiveConns.Length() > 1) {
         // this is a new connection that can be coalesced onto. hooray!
         // if there are other connection to this entry (e.g.
         // some could still be handshaking, shutting down, etc..) then close
         // them down after any transactions that are on them are complete.
         // This probably happened due to the parallel connection algorithm
@@ -852,21 +845,16 @@ nsHttpConnectionMgr::UpdateCoalescingFor
     }
 
     for (int32_t index = ent->mHalfOpenFastOpenBackups.Length() - 1; index >= 0; --index) {
         LOG(("UpdateCoalescingForNewConn() shutting down connection in fast "
              "open state (%p) because new spdy connection (%p) takes "
              "precedence\n", ent->mHalfOpenFastOpenBackups[index].get(), newConn));
         RefPtr<nsHalfOpenSocket> half = ent->mHalfOpenFastOpenBackups[index];
         half->CancelFastOpenConnection();
-        MOZ_DIAGNOSTIC_ASSERT(!half->mBackupTransport);
-        MOZ_DIAGNOSTIC_ASSERT(!half->mBackupStreamOut);
-        MOZ_DIAGNOSTIC_ASSERT(!half->mBackupStreamIn);
-        MOZ_DIAGNOSTIC_ASSERT(!half->mSynTimer);
-        MOZ_DIAGNOSTIC_ASSERT(!half->mEnt);
     }
 }
 
 // This function lets a connection, after completing the NPN phase,
 // report whether or not it is using spdy through the usingSpdy
 // argument. It would not be necessary if NPN were driven out of
 // the connection manager. The connection entry associated with the
 // connection is then updated to indicate whether or not we want to use
@@ -1248,35 +1236,31 @@ nsHttpConnectionMgr::AtActiveConnectionL
     bool result = (totalCount >= maxPersistConns);
     LOG(("AtActiveConnectionLimit result: %s", result ? "true" : "false"));
     return result;
 }
 
 void
 nsHttpConnectionMgr::ClosePersistentConnections(nsConnectionEntry *ent)
 {
-    CheckConnEntryMustBeInmCT(ent);
     LOG(("nsHttpConnectionMgr::ClosePersistentConnections [ci=%s]\n",
          ent->mConnInfo->HashKey().get()));
     while (ent->mIdleConns.Length()) {
         RefPtr<nsHttpConnection> conn(ent->mIdleConns[0]);
         ent->mIdleConns.RemoveElementAt(0);
         mNumIdleConns--;
         conn->Close(NS_ERROR_ABORT);
     }
 
     int32_t activeCount = ent->mActiveConns.Length();
     for (int32_t i=0; i < activeCount; i++)
         ent->mActiveConns[i]->DontReuse();
     for (int32_t index = ent->mHalfOpenFastOpenBackups.Length() - 1; index >= 0; --index) {
         RefPtr<nsHalfOpenSocket> half = ent->mHalfOpenFastOpenBackups[index];
         half->CancelFastOpenConnection();
-        MOZ_DIAGNOSTIC_ASSERT(!half->mBackupTransport);
-        MOZ_DIAGNOSTIC_ASSERT(!half->mSynTimer);
-        MOZ_DIAGNOSTIC_ASSERT(!half->mEnt);
     }
 }
 
 bool
 nsHttpConnectionMgr::RestrictConnections(nsConnectionEntry *ent)
 {
     MOZ_ASSERT(OnSocketThread(), "not on socket thread");
 
@@ -1657,17 +1641,16 @@ nsHttpConnectionMgr::TryDispatchTransact
     return NS_ERROR_NOT_AVAILABLE;                /* queue it */
 }
 
 nsresult
 nsHttpConnectionMgr::DispatchTransaction(nsConnectionEntry *ent,
                                          nsHttpTransaction *trans,
                                          nsHttpConnection *conn)
 {
-    CheckConnEntryMustBeInmCT(ent);
     uint32_t caps = trans->Caps();
     int32_t priority = trans->Priority();
     nsresult rv;
 
     LOG(("nsHttpConnectionMgr::DispatchTransaction "
          "[ent-ci=%s %p trans=%p caps=%x conn=%p priority=%d]\n",
          ent->mConnInfo->HashKey().get(), ent, trans, caps, conn, priority));
 
@@ -1752,18 +1735,18 @@ NS_IMPL_ISUPPORTS0(ConnectionHandle)
 // concrete nsHttpTransaction
 nsresult
 nsHttpConnectionMgr::DispatchAbstractTransaction(nsConnectionEntry *ent,
                                                  nsAHttpTransaction *aTrans,
                                                  uint32_t caps,
                                                  nsHttpConnection *conn,
                                                  int32_t priority)
 {
-    MOZ_DIAGNOSTIC_ASSERT(ent);
-    CheckConnEntryMustBeInmCT(ent);
+    MOZ_ASSERT(ent);
+
     nsresult rv;
     MOZ_ASSERT(!conn->UsingSpdy(),
                "Spdy Must Not Use DispatchAbstractTransaction");
     LOG(("nsHttpConnectionMgr::DispatchAbstractTransaction "
          "[ci=%s trans=%p caps=%x conn=%p]\n",
          ent->mConnInfo->HashKey().get(), aTrans, caps, conn));
 
     RefPtr<nsAHttpTransaction> transaction(aTrans);
@@ -1829,17 +1812,17 @@ nsHttpConnectionMgr::ProcessNewTransacti
     }
 
     nsresult rv = NS_OK;
     nsHttpConnectionInfo *ci = trans->ConnectionInfo();
     MOZ_ASSERT(ci);
 
     nsConnectionEntry *ent =
         GetOrCreateConnectionEntry(ci, !!trans->TunnelProvider());
-    MOZ_DIAGNOSTIC_ASSERT(ent);
+    MOZ_ASSERT(ent);
 
     ReportProxyTelemetry(ent);
 
     // Check if the transaction already has a sticky reference to a connection.
     // If so, then we can just use it directly by transferring its reference
     // to the new connection variable instead of searching for a new one
 
     nsAHttpConnection *wrappedConnection = trans->Connection();
@@ -1902,17 +1885,16 @@ nsHttpConnectionMgr::ProcessNewTransacti
     return rv;
 }
 
 
 void
 nsHttpConnectionMgr::AddActiveConn(nsHttpConnection *conn,
                                    nsConnectionEntry *ent)
 {
-    CheckConnEntryMustBeInmCT(ent);
     ent->mActiveConns.AppendElement(conn);
     mNumActiveConns++;
     ActivateTimeoutTick();
 }
 
 void
 nsHttpConnectionMgr::DecrementActiveConnCount(nsHttpConnection *conn)
 {
@@ -2090,18 +2072,17 @@ nsHttpConnectionMgr::OnMsgProcessAllSpdy
 }
 
 // Given a connection entry, return an active h2 connection
 // that can be directly activated or null
 nsHttpConnection *
 nsHttpConnectionMgr::GetSpdyActiveConn(nsConnectionEntry *ent)
 {
     MOZ_ASSERT(OnSocketThread(), "not on socket thread");
-    MOZ_DIAGNOSTIC_ASSERT(ent);
-    CheckConnEntryMustBeInmCT(ent);
+    MOZ_ASSERT(ent);
 
     nsHttpConnection *experienced = nullptr;
     nsHttpConnection *noExperience = nullptr;
     uint32_t activeLen = ent->mActiveConns.Length();
     nsHttpConnectionInfo *ci = ent->mConnInfo;
     uint32_t index;
 
     // activeLen should generally be 1.. this is a setup race being resolved
@@ -2128,22 +2109,16 @@ nsHttpConnectionMgr::GetSpdyActiveConn(n
         }
         for (int32_t index = ent->mHalfOpenFastOpenBackups.Length() - 1; index >= 0; --index) {
              LOG(("GetSpdyActiveConn() shutting down connection in fast "
                  "open state (%p) because we have an experienced spdy "
                  "connection (%p).\n",
                  ent->mHalfOpenFastOpenBackups[index].get(), experienced));
              RefPtr<nsHalfOpenSocket> half = ent->mHalfOpenFastOpenBackups[index];
              half->CancelFastOpenConnection();
-
-             MOZ_DIAGNOSTIC_ASSERT(!half->mBackupTransport);
-             MOZ_DIAGNOSTIC_ASSERT(!half->mBackupStreamOut);
-             MOZ_DIAGNOSTIC_ASSERT(!half->mBackupStreamIn);
-             MOZ_DIAGNOSTIC_ASSERT(!half->mSynTimer);
-             MOZ_DIAGNOSTIC_ASSERT(!half->mEnt);
         }
 
         LOG(("GetSpdyActiveConn() request for ent %p %s "
              "found an active experienced connection %p in native connection entry\n",
              ent, ci->HashKey().get(), experienced));
         return experienced;
     }
 
@@ -2226,19 +2201,18 @@ nsHttpConnectionMgr::OnMsgShutdown(int32
         }
         ent->mPendingTransactionTable.Clear();
 
         // Close all half open tcp connections.
         for (int32_t i = int32_t(ent->mHalfOpens.Length()) - 1; i >= 0; i--) {
             ent->mHalfOpens[i]->Abandon();
         }
 
-        MOZ_DIAGNOSTIC_ASSERT(ent->mHalfOpenFastOpenBackups.Length() == 0 &&
-                              !ent->mDoNotDestroy);
-        ent->mHowItWasRemoved = nsConnectionEntry::CONN_ENTRY_REMOVED_SHUTDOWN;
+        MOZ_ASSERT(ent->mHalfOpenFastOpenBackups.Length() == 0 &&
+                   !ent->mDoNotDestroy);
         iter.Remove();
     }
 
     if (mTimeoutTick) {
         mTimeoutTick->Cancel();
         mTimeoutTick = nullptr;
         mTimeoutTickArmed = false;
     }
@@ -2413,17 +2387,16 @@ nsHttpConnectionMgr::OnMsgCancelTransact
         // so we want to cancel any null transactions related to this connection
         // entry. They are just optimizations, but they aren't hooked up to
         // anything that might get canceled from the rest of gecko, so best
         // to assume that's what was meant by the cancel we did receive if
         // it only applied to something in the queue.
         for (uint32_t index = 0;
              ent && (index < ent->mActiveConns.Length());
              ++index) {
-            CheckConnEntryMustBeInmCT(ent);
             nsHttpConnection *activeConn = ent->mActiveConns[index];
             nsAHttpTransaction *liveTransaction = activeConn->Transaction();
             if (liveTransaction && liveTransaction->IsNullTransaction()) {
                 LOG(("nsHttpConnectionMgr::OnMsgCancelTransaction [trans=%p] "
                      "also canceling Null Transaction %p on conn %p\n",
                      trans, liveTransaction, activeConn));
                 activeConn->CloseTransaction(liveTransaction, closeCode);
             }
@@ -2708,17 +2681,17 @@ nsHttpConnectionMgr::OnMsgReclaimConnect
     nsHttpConnection *conn = static_cast<nsHttpConnection *>(param);
 
     //
     // 1) remove the connection from the active list
     // 2) if keep-alive, add connection to idle list
     // 3) post event to process the pending transaction queue
     //
 
-    MOZ_DIAGNOSTIC_ASSERT(conn);
+    MOZ_ASSERT(conn);
     nsConnectionEntry *ent = conn->ConnectionInfo() ?
         mCT.GetWeak(conn->ConnectionInfo()->HashKey()) : nullptr;
 
     if (!ent) {
         // this can happen if the connection is made outside of the
         // connection manager and is being "reclaimed" for use with
         // future transactions. HTTP/2 tunnels work like this.
         ent = GetOrCreateConnectionEntry(conn->ConnectionInfo(), true);
@@ -2863,23 +2836,23 @@ nsHttpConnectionMgr::OnMsgUpdateParam(in
     }
 }
 
 // nsHttpConnectionMgr::nsConnectionEntry
 nsHttpConnectionMgr::nsConnectionEntry::~nsConnectionEntry()
 {
     LOG(("nsConnectionEntry::~nsConnectionEntry this=%p", this));
 
-    MOZ_DIAGNOSTIC_ASSERT(!mIdleConns.Length());
-    MOZ_DIAGNOSTIC_ASSERT(!mActiveConns.Length());
-    MOZ_DIAGNOSTIC_ASSERT(!mHalfOpens.Length());
-    MOZ_DIAGNOSTIC_ASSERT(!mUrgentStartQ.Length());
-    MOZ_DIAGNOSTIC_ASSERT(!PendingQLength());
-    MOZ_DIAGNOSTIC_ASSERT(!mHalfOpenFastOpenBackups.Length());
-    MOZ_DIAGNOSTIC_ASSERT(!mDoNotDestroy);
+    MOZ_ASSERT(!mIdleConns.Length());
+    MOZ_ASSERT(!mActiveConns.Length());
+    MOZ_ASSERT(!mHalfOpens.Length());
+    MOZ_ASSERT(!mUrgentStartQ.Length());
+    MOZ_ASSERT(!PendingQLength());
+    MOZ_ASSERT(!mHalfOpenFastOpenBackups.Length());
+    MOZ_ASSERT(!mDoNotDestroy);
 
     MOZ_COUNT_DTOR(nsConnectionEntry);
 }
 
 // Read Timeout Tick handlers
 
 void
 nsHttpConnectionMgr::ActivateTimeoutTick()
@@ -3694,40 +3667,40 @@ nsHalfOpenSocket::nsHalfOpenSocket(nsCon
         ++totalSpeculativeConn;
 
         if (isFromPredictor) {
           Telemetry::AutoCounter<Telemetry::PREDICTOR_TOTAL_PRECONNECTS_CREATED> totalPreconnectsCreated;
           ++totalPreconnectsCreated;
         }
     }
 
-    MOZ_DIAGNOSTIC_ASSERT(mEnt);
+    MOZ_ASSERT(mEnt);
 }
 
 nsHttpConnectionMgr::nsHalfOpenSocket::~nsHalfOpenSocket()
 {
-    MOZ_DIAGNOSTIC_ASSERT(!mStreamOut);
-    MOZ_DIAGNOSTIC_ASSERT(!mBackupStreamOut);
-    MOZ_DIAGNOSTIC_ASSERT(!mSynTimer);
+    MOZ_ASSERT(!mStreamOut);
+    MOZ_ASSERT(!mBackupStreamOut);
+    MOZ_ASSERT(!mSynTimer);
     LOG(("Destroying nsHalfOpenSocket [this=%p]\n", this));
 
     if (mEnt)
         mEnt->RemoveHalfOpen(this);
 }
 
 nsresult
 nsHttpConnectionMgr::
 nsHalfOpenSocket::SetupStreams(nsISocketTransport **transport,
                                nsIAsyncInputStream **instream,
                                nsIAsyncOutputStream **outstream,
                                bool isBackup)
 {
     MOZ_ASSERT(OnSocketThread(), "not on socket thread");
 
-    MOZ_DIAGNOSTIC_ASSERT(mEnt);
+    MOZ_ASSERT(mEnt);
     nsresult rv;
     const char *socketTypes[1];
     uint32_t typeCount = 0;
     const nsHttpConnectionInfo *ci = mEnt->mConnInfo;
     if (ci->FirstHopSSL()) {
         socketTypes[typeCount++] = "ssl";
     } else {
         socketTypes[typeCount] = gHttpHandler->DefaultSocketType();
@@ -3902,19 +3875,19 @@ nsHttpConnectionMgr::nsHalfOpenSocket::S
         mBackupTransport = nullptr;
     }
     return rv;
 }
 
 void
 nsHttpConnectionMgr::nsHalfOpenSocket::SetupBackupTimer()
 {
-    MOZ_DIAGNOSTIC_ASSERT(mEnt);
+    MOZ_ASSERT(mEnt);
     uint16_t timeout = gHttpHandler->GetIdleSynTimeout();
-    MOZ_DIAGNOSTIC_ASSERT(!mSynTimer, "timer already initd");
+    MOZ_ASSERT(!mSynTimer, "timer already initd");
     if (!timeout && mFastOpenInProgress) {
         timeout = 250;
     }
     // When using Fast Open the correct transport will be setup for sure (it is
     // guaranteed), but it can be that it will happened a bit later.
     if (mFastOpenInProgress ||
         (timeout && !mSpeculative)) {
         // Setup the timer that will establish a backup socket
@@ -4019,21 +3992,21 @@ nsHttpConnectionMgr::nsHalfOpenSocket::D
     return (epoch - mPrimarySynStarted).ToMilliseconds();
 }
 
 
 NS_IMETHODIMP // method for nsITimerCallback
 nsHttpConnectionMgr::nsHalfOpenSocket::Notify(nsITimer *timer)
 {
     MOZ_ASSERT(OnSocketThread(), "not on socket thread");
-    MOZ_DIAGNOSTIC_ASSERT(timer == mSynTimer, "wrong timer");
-
-    MOZ_DIAGNOSTIC_ASSERT(!mBackupTransport);
-    MOZ_DIAGNOSTIC_ASSERT(mSynTimer);
-    MOZ_DIAGNOSTIC_ASSERT(mEnt);
+    MOZ_ASSERT(timer == mSynTimer, "wrong timer");
+
+    MOZ_ASSERT(!mBackupTransport);
+    MOZ_ASSERT(mSynTimer);
+    MOZ_ASSERT(mEnt);
 
     DebugOnly<nsresult> rv = SetupBackupStreams();
     MOZ_ASSERT(NS_SUCCEEDED(rv));
 
     mSynTimer = nullptr;
     return NS_OK;
 }
 
@@ -4066,29 +4039,20 @@ nsHalfOpenSocket::FindTransactionHelper(
 }
 
 // method for nsIAsyncOutputStreamCallback
 NS_IMETHODIMP
 nsHttpConnectionMgr::
 nsHalfOpenSocket::OnOutputStreamReady(nsIAsyncOutputStream *out)
 {
     MOZ_ASSERT(OnSocketThread(), "not on socket thread");
-    MOZ_DIAGNOSTIC_ASSERT(mStreamOut || mBackupStreamOut);
-    MOZ_DIAGNOSTIC_ASSERT(out == mStreamOut || out == mBackupStreamOut,
+    MOZ_ASSERT(mStreamOut || mBackupStreamOut);
+    MOZ_ASSERT(out == mStreamOut || out == mBackupStreamOut,
                           "stream mismatch");
-    MOZ_DIAGNOSTIC_ASSERT(mEnt);
-    if (out == mStreamOut) {
-        LOG(("nsHalfOpenSocket::OnOutputStreamReady [this=%p ent=%s %s]\n",
-             this, mEnt->mConnInfo->Origin(), "primary"));
-        gHttpHandler->ConnMgr()->CheckConnEntryMustBeInmCT(mEnt);
-    } else {
-        LOG(("nsHalfOpenSocket::OnOutputStreamReady [this=%p ent=%s %s]\n",
-             this, mEnt->mConnInfo->Origin(), "backup"));
-        gHttpHandler->ConnMgr()->CheckConnEntryMustBeInmCT(mEnt);
-    }
+    MOZ_ASSERT(mEnt);
 
     LOG(("nsHalfOpenSocket::OnOutputStreamReady [this=%p ent=%s %s]\n",
          this, mEnt->mConnInfo->Origin(),
          out == mStreamOut ? "primary" : "backup"));
 
     mEnt->mDoNotDestroy = true;
     gHttpHandler->ConnMgr()->RecvdConnect();
 
@@ -4138,34 +4102,30 @@ nsHalfOpenSocket::OnOutputStreamReady(ns
             gHttpHandler->IncrementFastOpenConsecutiveFailureCounter();
             mEnt->mUseFastOpen = false;
         }
 
         mFastOpenInProgress = false;
         mConnectionNegotiatingFastOpen = nullptr;
     }
 
-    MOZ_DIAGNOSTIC_ASSERT(mEnt);
-    gHttpHandler->ConnMgr()->CheckConnEntryMustBeInmCT(mEnt);
     nsresult rv =  SetupConn(out, false);
     if (mEnt) {
         mEnt->mDoNotDestroy = false;
     }
     return rv;
 }
 
 bool
 nsHttpConnectionMgr::
 nsHalfOpenSocket::FastOpenEnabled()
 {
     LOG(("nsHalfOpenSocket::FastOpenEnabled [this=%p]\n", this));
 
-    MOZ_DIAGNOSTIC_ASSERT(mEnt);
-
-    gHttpHandler->ConnMgr()->CheckConnEntryMustBeInmCT(mEnt);
+    MOZ_ASSERT(mEnt);
 
     if (!mEnt) {
         return false;
     }
 
     // If mEnt is present this HalfOpen must be in the mHalfOpens,
     // but we want to be sure!!!
     if (!mEnt->mHalfOpens.Contains(this)) {
@@ -4205,21 +4165,19 @@ nsHalfOpenSocket::FastOpenEnabled()
 
     return true;
 }
 
 nsresult
 nsHttpConnectionMgr::
 nsHalfOpenSocket::StartFastOpen()
 {
-    MOZ_DIAGNOSTIC_ASSERT(mStreamOut);
-    MOZ_DIAGNOSTIC_ASSERT(!mBackupTransport);
-    MOZ_DIAGNOSTIC_ASSERT(mEnt);
-
-    gHttpHandler->ConnMgr()->CheckConnEntryMustBeInmCT(mEnt);
+    MOZ_ASSERT(mStreamOut);
+    MOZ_ASSERT(!mBackupTransport);
+    MOZ_ASSERT(mEnt);
 
     LOG(("nsHalfOpenSocket::StartFastOpen [this=%p]\n",
          this));
 
     RefPtr<nsHalfOpenSocket> deleteProtector(this);
 
     mFastOpenInProgress = true;
     mEnt->mDoNotDestroy = true;
@@ -4263,18 +4221,16 @@ nsHalfOpenSocket::StartFastOpen()
 
         // The connection is responsible to take care of the halfOpen so we
         // need to clean it up.
         Abandon();
     } else {
         LOG(("nsHalfOpenSocket::StartFastOpen [this=%p conn=%p]\n",
              this, mConnectionNegotiatingFastOpen.get()));
 
-        gHttpHandler->ConnMgr()->CheckConnEntryMustBeInmCT(mEnt);
-
         mEnt->mHalfOpenFastOpenBackups.AppendElement(this);
         // SetupBackupTimer should setup timer which will hold a ref to this
         // halfOpen. It will failed only if it cannot create timer. Anyway just
         // to be sure I will add this deleteProtector!!!
         if (!mSynTimer) {
             // For Fast Open we will setup backup timer also for
             // NullTransaction.
             // So maybe it is not set and we need to set it here.
@@ -4286,20 +4242,18 @@ nsHalfOpenSocket::StartFastOpen()
     }
     return rv;
 }
 
 void
 nsHttpConnectionMgr::
 nsHalfOpenSocket::SetFastOpenConnected(nsresult aError, bool aWillRetry)
 {
-    MOZ_DIAGNOSTIC_ASSERT(mFastOpenInProgress);
-    MOZ_DIAGNOSTIC_ASSERT(mEnt);
-
-    gHttpHandler->ConnMgr()->CheckConnEntryMustBeInmCT(mEnt);
+    MOZ_ASSERT(mFastOpenInProgress);
+    MOZ_ASSERT(mEnt);
 
     LOG(("nsHalfOpenSocket::SetFastOpenConnected [this=%p conn=%p error=%x]\n",
          this, mConnectionNegotiatingFastOpen.get(),
          static_cast<uint32_t>(aError)));
 
     // mConnectionNegotiatingFastOpen is set after a StartFastOpen creates
     // and activates a nsHttpConnection successfully (SetupConn calls
     // DispatchTransaction and DispatchAbstractTransaction which calls
@@ -4351,17 +4305,16 @@ nsHalfOpenSocket::SetFastOpenConnected(n
             }
         }