Merge draft head draft
authorGregory Szorc <gregory.szorc@gmail.com>
Thu, 25 Jan 2018 00:45:19 -0800
changeset 744071 addbc3e3da8f1a7986f88405bfc8885711fb9a97
parent 744070 91b81345780c578b058633d66cd976af53b99cc9 (diff)
parent 712522 dc7edf4c175d1fe3adc74c0a21f13e1cdc0bd2d1 (current diff)
child 744072 7bd28d87776de480c68b85136ae833b61f88ccff
push id96834
push usergszorc@mozilla.com
push dateThu, 25 Jan 2018 17:14:24 +0000
milestone60.0a1
Merge draft head
--- a/.cargo/config.in
+++ b/.cargo/config.in
@@ -1,11 +1,18 @@
+# Note: if you add more configure substitutions here with required values
+# you will also need to fix the sed commands in:
+# taskcluster/scripts/builder/build-sm-mozjs-crate.sh
+# taskcluster/scripts/builder/build-sm-rust-bindings.sh
+
 [source.crates-io]
 registry = 'https://github.com/rust-lang/crates.io-index'
 replace-with = 'vendored-sources'
 
 [source."https://github.com/gankro/serde"]
 git = "https://github.com/gankro/serde"
-branch = "deserialize_from_enums3"
+branch = "deserialize_from_enums4"
 replace-with = "vendored-sources"
 
 [source.vendored-sources]
 directory = '@top_srcdir@/third_party/rust'
+
+@WIN64_CARGO_LINKER_CONFIG@
--- a/.clang-format-ignore
+++ b/.clang-format-ignore
@@ -2,16 +2,17 @@
 build/clang-plugin/.*
 # The two templates cannot be formatted
 config/gcc-stl-wrapper.template.h
 config/msvc-stl-wrapper.template.h
 dom/base/test/.*
 dom/bindings/test/.*
 dom/media/gtest/.*
 gfx/testsd/.*
+.*/gtest/ExampleStylesheet.h
 image/test/.*
 ipc/ipdl/test/.*
 ipc/testshell/.*
 js/src/jsapi-tests/.*
 # See bug 1395584
 js/src/vm/Opcodes.h
 # Ignored because of bug 1342657
 layout/style/nsCSSPropAliasList.h
--- a/.eslintignore
+++ b/.eslintignore
@@ -72,29 +72,34 @@ browser/branding/**/firefox-branding.js
 # Gzipped test file.
 browser/base/content/test/general/gZipOfflineChild.html
 browser/base/content/test/urlbar/file_blank_but_not_blank.html
 # New tab is likely to be replaced soon.
 browser/base/content/newtab/**
 # Test files that are really json not js, and don't need to be linted.
 browser/components/sessionstore/test/unit/data/sessionstore_valid.js
 browser/components/sessionstore/test/unit/data/sessionstore_invalid.js
+# This file is split into two in order to keep it as a valid json file
+# for documentation purposes (policies.json) but to be accessed by the
+# code as a .jsm (schema.jsm)
+browser/components/enterprisepolicies/schemas/schema.jsm
 # generated & special files in cld2
 browser/components/translation/cld2/**
 # Screenshots and Follow-on search are imported as a system add-on and have
 # their own lint rules currently.
 browser/extensions/followonsearch/**
 browser/extensions/screenshots/**
 browser/extensions/pdfjs/content/build**
 browser/extensions/pdfjs/content/web**
 # generated or library files in pocket
 browser/extensions/pocket/content/panels/js/tmpl.js
 browser/extensions/pocket/content/panels/js/vendor/**
 # generated or library files in activity-stream
 browser/extensions/activity-stream/data/content/activity-stream.bundle.js
+browser/extensions/activity-stream/test/**
 browser/extensions/activity-stream/vendor/**
 # The only file in browser/locales/ is pre-processed.
 browser/locales/**
 # imported from chromium
 browser/extensions/mortar/**
 # Generated data files
 browser/extensions/formautofill/phonenumberutils/PhoneNumberMetaData.jsm
 
--- a/.eslintrc.js
+++ b/.eslintrc.js
@@ -23,26 +23,21 @@ module.exports = {
     "files": "**/*.*html",
     "rules": {
       "eol-last": "off",
     }
   }, {
     // XXX Bug 1421969. These files/directories are still being fixed,
     // so turn off mozilla/use-services for them for now.
     "files": [
-      "accessible/**",
       // Browser: Bug 1421379
       "browser/extensions/shield-recipe-client/test/browser/head.js",
       "browser/modules/offlineAppCache.jsm",
       "devtools/**",
-      "dom/indexedDB/**",
-      "dom/media/**",
       "extensions/pref/**",
       "mobile/android/**",
-      "security/**",
       "testing/**",
-      "tools/profiler/**",
     ],
     "rules": {
       "mozilla/use-services": "off",
     }
   }]
 };
--- a/.gitignore
+++ b/.gitignore
@@ -99,16 +99,20 @@ testing/web-platform/products/
 # Android Gradle artifacts.
 mobile/android/gradle/.gradle
 
 # XCode project cruft
 /*.xcodeproj/
 embedding/ios/GeckoEmbed/GeckoEmbed.xcodeproj/project.xcworkspace/xcuserdata
 embedding/ios/GeckoEmbed/GeckoEmbed.xcodeproj/xcuserdata
 
+# Rust port of mozbase are libraries
+testing/mozbase/rust/*/target
+testing/mozbase/rust/*/Cargo.lock
+
 # Ignore mozharness execution files
 testing/mozharness/.tox/
 testing/mozharness/build/
 testing/mozharness/logs/
 testing/mozharness/.coverage
 testing/mozharness/nosetests.xml
 
 # Ignore ESLint node_modules
--- a/.hgignore
+++ b/.hgignore
@@ -106,16 +106,20 @@ GPATH
 # Android Gradle artifacts.
 ^mobile/android/gradle/.gradle
 
 # XCode project cruft
 ^[^/]*\.xcodeproj/
 ^embedding/ios/GeckoEmbed/GeckoEmbed.xcodeproj/project.xcworkspace/xcuserdata
 ^embedding/ios/GeckoEmbed/GeckoEmbed.xcodeproj/xcuserdata
 
+# Rust port of mozbase are Rust libraries
+^testing/mozbase/rust/.*/target
+^testing/mozbase/rust/.*/Cargo.lock
+
 # Ignore mozharness execution files
 ^testing/mozharness/.tox/
 ^testing/mozharness/build/
 ^testing/mozharness/logs/
 ^testing/mozharness/.coverage
 ^testing/mozharness/nosetests.xml
 
 # Ignore tox generated dir
@@ -140,20 +144,20 @@ GPATH
 ^testing/talos/talos/tests/tp5n
 ^testing/talos/talos/tests/devtools/damp.manifest.develop
 ^talos-venv
 ^py3venv
 ^testing/talos/talos/mitmproxy/mitmdump
 ^testing/talos/talos/mitmproxy/mitmproxy
 ^testing/talos/talos/mitmproxy/mitmweb
 
-# Ignore talos speedometer files; source is copied from in-tree /third_party
-# into testing/talos/talos/tests/webkit/PerformanceTests/Speedometer when
-# talos speedometer test is run locally
-^testing/talos/talos/tests/webkit/PerformanceTests/Speedometer
+# Ignore talos webkit benchmark files; source is copied from in-tree /third_party
+# into testing/talos/talos/tests/webkit/PerformanceTests/ when run locally
+# i.e. speedometer, motionmark, stylebench
+^testing/talos/talos/tests/webkit/PerformanceTests
 
 # Ignore toolchains.json created by tooltool.
 ^toolchains\.json
 
 # Ignore files created when running a reftest.
 ^lextab.py$
 
 # tup database
--- a/.hgtags
+++ b/.hgtags
@@ -133,8 +133,9 @@ 1196bf3032e1bce1fb07a01fd9082a767426c5fb
 f80dc9fc34680105b714a49b4704bb843f5f7004 FIREFOX_AURORA_53_BASE
 6583496f169cd8a13c531ed16e98e8bf313eda8e FIREFOX_AURORA_54_BASE
 f9605772a0c9098ed1bcaa98089b2c944ed69e9b FIREFOX_BETA_55_BASE
 320642944e42a889db13c6c55b404e32319d4de6 FIREFOX_BETA_56_BASE
 8e818b5e9b6bef0fc1a5c527ecf30b0d56a02f14 FIREFOX_BETA_57_BASE
 f7e9777221a34f9f23c2e4933307eb38b621b679 FIREFOX_NIGHTLY_57_END
 40a14ca1cf04499f398e4cb8ba359b39eae4e216 FIREFOX_BETA_58_BASE
 1f91961bb79ad06fd4caef9e5dfd546afd5bf42c FIREFOX_NIGHTLY_58_END
+5faab9e619901b1513fd4ca137747231be550def FIREFOX_NIGHTLY_59_END
--- a/.taskcluster.yml
+++ b/.taskcluster.yml
@@ -53,22 +53,20 @@ tasks:
 
       routes:
         $if: 'tasks_for == "hg-push"'
         then:
           - "index.gecko.v2.${repository.project}.latest.firefox.decision"
           - "index.gecko.v2.${repository.project}.revision.${push.revision}.firefox.decision"
           - "index.gecko.v2.${repository.project}.pushlog-id.${push.pushlog_id}.decision"
           - "tc-treeherder.v2.${repository.project}.${push.revision}.${push.pushlog_id}"
-          - "tc-treeherder-stage.v2.${repository.project}.${push.revision}.${push.pushlog_id}"
           - "notify.email.${ownerEmail}.on-failed"
           - "notify.email.${ownerEmail}.on-exception"
         else:
           - "tc-treeherder.v2.${repository.project}.${push.revision}.${push.pushlog_id}"
-          - "tc-treeherder-stage.v2.${repository.project}.${push.revision}.${push.pushlog_id}"
           - $if: 'tasks_for == "action"'
             then: "index.gecko.v2.${repository.project}.pushlog-id.${push.pushlog_id}.actions.${ownTaskId}"
             else: "index.gecko.v2.${repository.project}.latest.firefox.decision-${cron.job_name}"
 
       scopes:
         $if: 'tasks_for == "hg-push"'
         then:
           - 'assume:repo:${repoUrl[8:]}:*'
@@ -95,17 +93,17 @@ tasks:
               GECKO_HEAD_REPOSITORY: '${repoUrl}'
               GECKO_HEAD_REF: '${push.revision}'
               GECKO_HEAD_REV: '${push.revision}'
               GECKO_COMMIT_MSG: {$if: 'tasks_for != "action"', then: '${push.comment}'}
               HG_STORE_PATH: /builds/worker/checkouts/hg-store
               TASKCLUSTER_CACHES: /builds/worker/checkouts
             - $if: 'tasks_for == "action"'
               then:
-                ACTION_TASK_GROUP_ID: '${action.taskGroupId}'
+                ACTION_TASK_GROUP_ID: '${ownTaskId}'
                 ACTION_TASK_ID: {$json: {$eval: 'taskId'}}
                 ACTION_TASK: {$json: {$eval: 'task'}}
                 ACTION_INPUT: {$json: {$eval: 'input'}}
                 ACTION_CALLBACK: '${action.cb_name}'
                 ACTION_PARAMETERS: {$json: {$eval: 'parameters'}}
 
         cache:
           level-${repository.level}-checkouts-sparse-v1: /builds/worker/checkouts
@@ -182,8 +180,12 @@ tasks:
               parent: '${action.taskGroupId}'
               action:
                 name: '${action.name}'
                 context:
                   taskGroupId: '${action.taskGroupId}'
                   taskId: {$eval: 'taskId'}
                   input: {$eval: 'input'}
                   parameters: {$eval: 'parameters'}
+          - $if: 'tasks_for == "cron"'
+            then:
+              cron: {$json: {$eval: 'cron'}}
+          - tasks_for: '${tasks_for}'
--- a/CLOBBER
+++ b/CLOBBER
@@ -17,9 +17,9 @@
 #
 # Modifying this file will now automatically clobber the buildbot machines \o/
 #
 
 # Are you updating CLOBBER because you think it's needed for your WebIDL
 # changes to stick? As of bug 928195, this shouldn't be necessary! Please
 # don't change CLOBBER for WebIDL changes any more.
 
-Bug 1416465 - Old track files may cause problems if they have wildcards.
+Merge day clobber
--- a/accessible/atk/Platform.cpp
+++ b/accessible/atk/Platform.cpp
@@ -14,17 +14,17 @@
 #include "prenv.h"
 #include "prlink.h"
 
 #ifdef MOZ_ENABLE_DBUS
 #include <dbus/dbus.h>
 #endif
 #include <gtk/gtk.h>
 
-#if (MOZ_WIDGET_GTK == 3)
+#ifdef MOZ_WIDGET_GTK
 extern "C" __attribute__((weak,visibility("default"))) int atk_bridge_adaptor_init(int*, char **[]);
 #endif
 
 using namespace mozilla;
 using namespace mozilla::a11y;
 
 int atkMajorVersion = 1, atkMinorVersion = 12, atkMicroVersion = 0;
 
@@ -64,24 +64,16 @@ static GnomeAccessibilityModule sAtkBrid
     "libatk-bridge.a(libatk-bridge.so.0)", nullptr,
 #else
     "libatk-bridge.so", nullptr,
 #endif
     "gnome_accessibility_module_init", nullptr,
     "gnome_accessibility_module_shutdown", nullptr
 };
 
-#if (MOZ_WIDGET_GTK == 2)
-static GnomeAccessibilityModule sGail = {
-    "libgail.so", nullptr,
-    "gnome_accessibility_module_init", nullptr,
-    "gnome_accessibility_module_shutdown", nullptr
-};
-#endif
-
 static nsresult
 LoadGtkModule(GnomeAccessibilityModule& aModule)
 {
     NS_ENSURE_ARG(aModule.libName);
 
     if (!(aModule.lib = PR_LoadLibrary(aModule.libName))) {
         //try to load the module with "gtk-2.0/modules" appended
         char *curLibPath = PR_GetLibraryPath();
@@ -97,21 +89,17 @@ LoadGtkModule(GnomeAccessibilityModule& 
         int16_t subLen = 0;
         while (loc2 >= 0) {
             loc2 = libPath.FindChar(':', loc1);
             if (loc2 < 0)
                 subLen = libPath.Length() - loc1;
             else
                 subLen = loc2 - loc1;
             nsAutoCString sub(Substring(libPath, loc1, subLen));
-#if (MOZ_WIDGET_GTK == 2)
-            sub.AppendLiteral("/gtk-2.0/modules/");
-#else
             sub.AppendLiteral("/gtk-3.0/modules/");
-#endif
             sub.Append(aModule.libName);
             aModule.lib = PR_LoadLibrary(sub.get());
             if (aModule.lib)
                 break;
 
             loc1 = loc2+1;
         }
         if (!aModule.lib)
@@ -171,29 +159,22 @@ a11y::PlatformInit()
       if (atkMajorVersion != 0L) {
         atkMinorVersion = strtol(endPtr + 1, &endPtr, 10);
         if (atkMinorVersion != 0L)
           atkMicroVersion = strtol(endPtr + 1, &endPtr, 10);
       }
     }
   }
 
-#if (MOZ_WIDGET_GTK == 2)
-  // Load and initialize gail library.
-  nsresult rv = LoadGtkModule(sGail);
-  if (NS_SUCCEEDED(rv))
-    (*sGail.init)();
-#endif
-
   // Initialize the MAI Utility class, it will overwrite gail_util.
   g_type_class_unref(g_type_class_ref(mai_util_get_type()));
 
   // Init atk-bridge now
   PR_SetEnv("NO_AT_BRIDGE=0");
-#if (MOZ_WIDGET_GTK == 3)
+#ifdef MOZ_WIDGET_GTK
   if (atk_bridge_adaptor_init) {
     atk_bridge_adaptor_init(nullptr, nullptr);
   } else
 #endif
   {
     nsresult rv = LoadGtkModule(sAtkBridge);
     if (NS_SUCCEEDED(rv)) {
       (*sAtkBridge.init)();
@@ -231,29 +212,16 @@ a11y::PlatformShutdown()
         // an exit function registered will take care of it
         // if (sAtkBridge.shutdown)
         //     (*sAtkBridge.shutdown)();
         // PR_UnloadLibrary(sAtkBridge.lib);
         sAtkBridge.lib = nullptr;
         sAtkBridge.init = nullptr;
         sAtkBridge.shutdown = nullptr;
     }
-#if (MOZ_WIDGET_GTK == 2)
-    if (sGail.lib) {
-        // Do not shutdown gail because
-        // 1) Maybe it's not init-ed by us. e.g. GtkEmbed
-        // 2) We need it to avoid assert in spi_atk_tidy_windows
-        // if (sGail.shutdown)
-        //   (*sGail.shutdown)();
-        // PR_UnloadLibrary(sGail.lib);
-        sGail.lib = nullptr;
-        sGail.init = nullptr;
-        sGail.shutdown = nullptr;
-    }
-#endif
     // if (sATKLib) {
     //     PR_UnloadLibrary(sATKLib);
     //     sATKLib = nullptr;
     // }
 }
 
   static const char sAccEnv [] = "GNOME_ACCESSIBILITY";
 #ifdef MOZ_ENABLE_DBUS
--- a/accessible/base/ARIAMap.cpp
+++ b/accessible/base/ARIAMap.cpp
@@ -612,16 +612,47 @@ static const nsRoleMapEntry sWAIRoleMaps
     roles::FORM,
     kUseMapRole,
     eNoValue,
     eNoAction,
     eNoLiveAttr,
     eLandmark,
     kNoReqStates
   },
+  { // graphics-document
+    &nsGkAtoms::graphicsDocument,
+    roles::DOCUMENT,
+    kUseMapRole,
+    eNoValue,
+    eNoAction,
+    eNoLiveAttr,
+    kGenericAccType,
+    kNoReqStates,
+    eReadonlyUntilEditable
+  },
+  { // graphics-object
+    &nsGkAtoms::graphicsObject,
+    roles::GROUPING,
+    kUseMapRole,
+    eNoValue,
+    eNoAction,
+    eNoLiveAttr,
+    kGenericAccType,
+    kNoReqStates
+  },
+  { // graphics-symbol
+    &nsGkAtoms::graphicsSymbol,
+    roles::GRAPHIC,
+    kUseMapRole,
+    eNoValue,
+    eNoAction,
+    eNoLiveAttr,
+    kGenericAccType,
+    kNoReqStates
+  },
   { // grid
     &nsGkAtoms::grid,
     roles::TABLE,
     kUseMapRole,
     eNoValue,
     eNoAction,
     eNoLiveAttr,
     eSelect | eTable,
@@ -1370,18 +1401,20 @@ aria::AttrCharacteristicsFor(nsAtom* aAt
   return 0;
 }
 
 bool
 aria::HasDefinedARIAHidden(nsIContent* aContent)
 {
   return aContent &&
     nsAccUtils::HasDefinedARIAToken(aContent, nsGkAtoms::aria_hidden) &&
-    !aContent->AttrValueIs(kNameSpaceID_None, nsGkAtoms::aria_hidden,
-                           nsGkAtoms::_false, eCaseMatters);
+    !aContent->AsElement()->AttrValueIs(kNameSpaceID_None,
+                                        nsGkAtoms::aria_hidden,
+                                        nsGkAtoms::_false,
+                                        eCaseMatters);
 }
 
 ////////////////////////////////////////////////////////////////////////////////
 // AttrIterator class
 
 bool
 AttrIterator::Next(nsAString& aAttrName, nsAString& aAttrValue)
 {
--- a/accessible/base/ARIAStateMap.cpp
+++ b/accessible/base/ARIAStateMap.cpp
@@ -18,17 +18,17 @@ using namespace mozilla::a11y::aria;
  * Used to store state map rule data for ARIA attribute of enum type.
  */
 struct EnumTypeData
 {
   // ARIA attribute name.
   nsStaticAtom* const mAttrName;
 
   // States if the attribute value is matched to the enum value. Used as
-  // nsIContent::AttrValuesArray, last item must be nullptr.
+  // Element::AttrValuesArray, last item must be nullptr.
   nsStaticAtom* const* const mValues[4];
 
   // States applied if corresponding enum values are matched.
   const uint64_t mStates[3];
 
   // States to clear in case of match.
   const uint64_t mClearState;
 };
--- a/accessible/base/AccIterator.cpp
+++ b/accessible/base/AccIterator.cpp
@@ -80,17 +80,18 @@ RelatedAccIterator::
   mDocument(aDocument), mRelAttr(aRelAttr), mProviders(nullptr),
   mBindingParent(nullptr), mIndex(0)
 {
   mBindingParent = aDependentContent->GetBindingParent();
   nsAtom* IDAttr = mBindingParent ?
     nsGkAtoms::anonid : nsGkAtoms::id;
 
   nsAutoString id;
-  if (aDependentContent->GetAttr(kNameSpaceID_None, IDAttr, id))
+  if (aDependentContent->IsElement() &&
+      aDependentContent->AsElement()->GetAttr(kNameSpaceID_None, IDAttr, id))
     mProviders = mDocument->mDependentIDsHash.Get(id);
 }
 
 Accessible*
 RelatedAccIterator::Next()
 {
   if (!mProviders)
     return nullptr;
@@ -160,17 +161,17 @@ HTMLLabelIterator::Next()
 
   // Go up tree to get a name of ancestor label if there is one (an ancestor
   // <label> implicitly points to us). Don't go up farther than form or
   // document.
   Accessible* walkUp = mAcc->Parent();
   while (walkUp && !walkUp->IsDoc()) {
     nsIContent* walkUpEl = walkUp->GetContent();
     if (IsLabel(walkUp) &&
-        !walkUpEl->HasAttr(kNameSpaceID_None, nsGkAtoms::_for)) {
+        !walkUpEl->AsElement()->HasAttr(kNameSpaceID_None, nsGkAtoms::_for)) {
       mLabelFilter = eSkipAncestorLabel; // prevent infinite loop
       return walkUp;
     }
 
     if (walkUpEl->IsHTMLElement(nsGkAtoms::form))
       break;
 
     walkUp = walkUp->Parent();
@@ -252,18 +253,18 @@ XULDescriptionIterator::Next()
 // IDRefsIterator
 ////////////////////////////////////////////////////////////////////////////////
 
 IDRefsIterator::
   IDRefsIterator(DocAccessible* aDoc, nsIContent* aContent,
                  nsAtom* aIDRefsAttr) :
   mContent(aContent), mDoc(aDoc), mCurrIdx(0)
 {
-  if (mContent->IsInUncomposedDoc())
-    mContent->GetAttr(kNameSpaceID_None, aIDRefsAttr, mIDs);
+  if (mContent->IsInUncomposedDoc() && mContent->IsElement())
+    mContent->AsElement()->GetAttr(kNameSpaceID_None, aIDRefsAttr, mIDs);
 }
 
 const nsDependentSubstring
 IDRefsIterator::NextID()
 {
   for (; mCurrIdx < mIDs.Length(); mCurrIdx++) {
     if (!NS_IsAsciiWhitespace(mIDs[mCurrIdx]))
       break;
--- a/accessible/base/Logging.cpp
+++ b/accessible/base/Logging.cpp
@@ -829,17 +829,17 @@ logging::Node(const char* aDescr, nsINod
   }
 
   if (aNode->IsNodeOfType(nsINode::eDOCUMENT)) {
     printf("%s: %p, document\n", aDescr, static_cast<void*>(aNode));
     return;
   }
 
   nsINode* parentNode = aNode->GetParentNode();
-  int32_t idxInParent = parentNode ? parentNode->IndexOf(aNode) : - 1;
+  int32_t idxInParent = parentNode ? parentNode->ComputeIndexOf(aNode) : - 1;
 
   if (aNode->IsNodeOfType(nsINode::eTEXT)) {
     printf("%s: %p, text node, idx in parent: %d\n",
            aDescr, static_cast<void*>(aNode), idxInParent);
     return;
   }
 
   if (!aNode->IsElement()) {
--- a/accessible/base/NotificationController.cpp
+++ b/accessible/base/NotificationController.cpp
@@ -414,33 +414,33 @@ NotificationController::ScheduleChildDoc
   ScheduleProcessing();
 }
 
 void
 NotificationController::ScheduleContentInsertion(Accessible* aContainer,
                                                  nsIContent* aStartChildNode,
                                                  nsIContent* aEndChildNode)
 {
-  nsTArray<nsCOMPtr<nsIContent>>* list =
-    mContentInsertions.LookupOrAdd(aContainer);
+  nsTArray<nsCOMPtr<nsIContent>> list;
 
   bool needsProcessing = false;
   nsIContent* node = aStartChildNode;
   while (node != aEndChildNode) {
     // Notification triggers for content insertion even if no content was
     // actually inserted, check if the given content has a frame to discard
     // this case early.
     if (node->GetPrimaryFrame()) {
-      if (list->AppendElement(node))
+      if (list.AppendElement(node))
         needsProcessing = true;
     }
     node = node->GetNextSibling();
   }
 
   if (needsProcessing) {
+    mContentInsertions.LookupOrAdd(aContainer)->AppendElements(list);
     ScheduleProcessing();
   }
 }
 
 void
 NotificationController::ScheduleProcessing()
 {
   // If notification flush isn't planed yet start notification flush
@@ -454,21 +454,41 @@ NotificationController::ScheduleProcessi
 ////////////////////////////////////////////////////////////////////////////////
 // NotificationCollector: protected
 
 bool
 NotificationController::IsUpdatePending()
 {
   return mPresShell->IsLayoutFlushObserver() ||
     mObservingState == eRefreshProcessingForUpdate ||
+    WaitingForParent() ||
     mContentInsertions.Count() != 0 || mNotifications.Length() != 0 ||
     mTextHash.Count() != 0 ||
     !mDocument->HasLoadState(DocAccessible::eTreeConstructed);
 }
 
+bool
+NotificationController::WaitingForParent()
+{
+  DocAccessible* parentdoc = mDocument->ParentDocument();
+  if (!parentdoc) {
+    return false;
+  }
+
+  NotificationController* parent = parentdoc->mNotificationController;
+  if (!parent || parent == this) {
+    // Do not wait for nothing or ourselves
+    return false;
+  }
+
+  // Wait for parent's notifications processing
+  return parent->mContentInsertions.Count() != 0 ||
+         parent->mNotifications.Length() != 0;
+}
+
 void
 NotificationController::ProcessMutationEvents()
 {
   // there is no reason to fire a hide event for a child of a show event
   // target.  That can happen if something is inserted into the tree and
   // removed before the next refresh driver tick, but it should not be
   // observable outside gecko so it should be safe to coalesce away any such
   // events.  This means that it should be fine to fire all of the hide events
@@ -587,16 +607,18 @@ NotificationController::ProcessMutationE
 }
 
 ////////////////////////////////////////////////////////////////////////////////
 // NotificationCollector: private
 
 void
 NotificationController::WillRefresh(mozilla::TimeStamp aTime)
 {
+  Telemetry::AutoTimer<Telemetry::A11Y_TREE_UPDATE_TIMING_MS> timer;
+
   AUTO_PROFILER_LABEL("NotificationController::WillRefresh", OTHER);
 
   // If the document accessible that notification collector was created for is
   // now shut down, don't process notifications anymore.
   NS_ASSERTION(mDocument,
                "The document was shut down while refresh observer is attached!");
   if (!mDocument)
     return;
@@ -604,16 +626,25 @@ NotificationController::WillRefresh(mozi
   // Wait until an update, we have started, or an interruptible reflow is
   // finished.
   if (mObservingState == eRefreshProcessing ||
       mObservingState == eRefreshProcessingForUpdate ||
       mPresShell->IsReflowInterrupted()) {
     return;
   }
 
+  // Process parent's notifications before ours, to get proper ordering between
+  // e.g. tab event and content event.
+  if (WaitingForParent()) {
+    mDocument->ParentDocument()->mNotificationController->WillRefresh(aTime);
+    if (!mDocument) {
+      return;
+    }
+  }
+
   // Any generic notifications should be queued if we're processing content
   // insertions or generic notifications.
   mObservingState = eRefreshProcessingForUpdate;
 
   // Initial accessible tree construction.
   if (!mDocument->HasLoadState(DocAccessible::eTreeConstructed)) {
     // If document is not bound to parent at this point then the document is not
     // ready yet (process notifications later).
@@ -644,19 +675,18 @@ NotificationController::WillRefresh(mozi
   for (auto iter = mTextHash.Iter(); !iter.Done(); iter.Next()) {
     nsCOMPtrHashKey<nsIContent>* entry = iter.Get();
     nsIContent* textNode = entry->GetKey();
     Accessible* textAcc = mDocument->GetAccessible(textNode);
 
     // If the text node is not in tree or doesn't have a frame, or placed in
     // another document, then this case should have been handled already by
     // content removal notifications.
-    nsINode* containerNode = textNode->GetParentNode();
-    if (!containerNode ||
-        textNode->GetOwnerDocument() != mDocument->DocumentNode()) {
+    nsINode* containerNode = textNode->GetFlattenedTreeParentNode();
+    if (!containerNode || textNode->OwnerDoc() != mDocument->DocumentNode()) {
       MOZ_ASSERT(!textAcc,
                  "Text node was removed but accessible is kept alive!");
       continue;
     }
 
     nsIFrame* textFrame = textNode->GetPrimaryFrame();
     if (!textFrame) {
       MOZ_ASSERT(!textAcc,
--- a/accessible/base/NotificationController.h
+++ b/accessible/base/NotificationController.h
@@ -269,16 +269,22 @@ protected:
   nsCycleCollectingAutoRefCnt mRefCnt;
   NS_DECL_OWNINGTHREAD
 
   /**
    * Return true if the accessible tree state update is pending.
    */
   bool IsUpdatePending();
 
+  /**
+   * Return true if we should wait for processing from the parent before we can
+   * process our own queue.
+   */
+  bool WaitingForParent();
+
 private:
   NotificationController(const NotificationController&);
   NotificationController& operator = (const NotificationController&);
 
   // nsARefreshObserver
   virtual void WillRefresh(mozilla::TimeStamp aTime) override;
 
   /**
--- a/accessible/base/TextAttrs.cpp
+++ b/accessible/base/TextAttrs.cpp
@@ -296,23 +296,23 @@ TextAttrsMgr::InvalidTextAttr::
 
 bool
 TextAttrsMgr::InvalidTextAttr::
   GetValue(nsIContent* aElm, uint32_t* aValue)
 {
   nsIContent* elm = aElm;
   do {
     if (nsAccUtils::HasDefinedARIAToken(elm, nsGkAtoms::aria_invalid)) {
-      static nsIContent::AttrValuesArray tokens[] =
+      static Element::AttrValuesArray tokens[] =
         { &nsGkAtoms::_false, &nsGkAtoms::grammar, &nsGkAtoms::spelling,
           nullptr };
 
-      int32_t idx = elm->FindAttrValueIn(kNameSpaceID_None,
-                                         nsGkAtoms::aria_invalid, tokens,
-                                         eCaseMatters);
+      int32_t idx = elm->AsElement()->FindAttrValueIn(kNameSpaceID_None,
+                                                      nsGkAtoms::aria_invalid,
+                                                      tokens, eCaseMatters);
       switch (idx) {
         case 0:
           *aValue = eFalse;
           return true;
         case 1:
           *aValue = eGrammar;
           return true;
         case 2:
--- a/accessible/base/TreeWalker.cpp
+++ b/accessible/base/TreeWalker.cpp
@@ -71,16 +71,18 @@ TreeWalker::~TreeWalker()
 
 Accessible*
 TreeWalker::Scope(nsIContent* aAnchorNode)
 {
   Reset();
 
   mAnchorNode = aAnchorNode;
 
+  mFlags |= eScoped;
+
   bool skipSubtree = false;
   Accessible* acc = AccessibleFor(aAnchorNode, 0, &skipSubtree);
   if (acc) {
     mPhase = eAtEnd;
     return acc;
   }
 
   return skipSubtree ? nullptr : Next();
@@ -107,16 +109,18 @@ TreeWalker::Seek(nsIContent* aChildNode)
 
     if (!parentNode || !parentNode->IsElement()) {
       return false;
     }
 
     // If ARIA owned child.
     Accessible* child = mDoc->GetAccessible(childNode);
     if (child && child->IsRelocated()) {
+      MOZ_ASSERT(!(mFlags & eScoped),
+        "Walker should not be scoped when seeking into relocated children");
       if (child->Parent() != mContext) {
         return false;
       }
 
       Accessible* ownedChild = nullptr;
       while ((ownedChild = mDoc->ARIAOwnedAt(mContext, mARIAOwnsIdx++)) &&
              ownedChild != child);
 
@@ -144,22 +148,26 @@ Accessible*
 TreeWalker::Next()
 {
   if (mStateStack.IsEmpty()) {
     if (mPhase == eAtEnd) {
       return nullptr;
     }
 
     if (mPhase == eAtDOM || mPhase == eAtARIAOwns) {
-      mPhase = eAtARIAOwns;
-      Accessible* child = mDoc->ARIAOwnedAt(mContext, mARIAOwnsIdx);
-      if (child) {
-        mARIAOwnsIdx++;
-        return child;
+      if (!(mFlags & eScoped)) {
+        mPhase = eAtARIAOwns;
+        Accessible* child = mDoc->ARIAOwnedAt(mContext, mARIAOwnsIdx);
+        if (child) {
+          mARIAOwnsIdx++;
+          return child;
+        }
       }
+      MOZ_ASSERT(!(mFlags & eScoped) || mPhase != eAtARIAOwns,
+        "Don't walk relocated children in scoped mode");
       mPhase = eAtEnd;
       return nullptr;
     }
 
     if (!mAnchorNode) {
       mPhase = eAtEnd;
       return nullptr;
     }
@@ -225,21 +233,27 @@ TreeWalker::Prev()
 {
   if (mStateStack.IsEmpty()) {
     if (mPhase == eAtStart || mPhase == eAtDOM) {
       mPhase = eAtStart;
       return nullptr;
     }
 
     if (mPhase == eAtEnd) {
-      mARIAOwnsIdx = mDoc->ARIAOwnedCount(mContext);
-      mPhase = eAtARIAOwns;
+      if (mFlags & eScoped) {
+        mPhase = eAtDOM;
+      } else {
+        mPhase = eAtARIAOwns;
+        mARIAOwnsIdx = mDoc->ARIAOwnedCount(mContext);
+      }
     }
 
     if (mPhase == eAtARIAOwns) {
+      MOZ_ASSERT(!(mFlags & eScoped),
+        "Should not walk relocated children in scoped mode");
       if (mARIAOwnsIdx > 0) {
         return mDoc->ARIAOwnedAt(mContext, --mARIAOwnsIdx);
       }
 
       if (!mAnchorNode) {
         mPhase = eAtStart;
         return nullptr;
       }
--- a/accessible/base/TreeWalker.h
+++ b/accessible/base/TreeWalker.h
@@ -24,17 +24,18 @@ class DocAccessible;
  */
 class TreeWalker final
 {
 public:
   enum {
     // used to walk the existing tree of the given node
     eWalkCache = 1,
     // used to walk the context tree starting from given node
-    eWalkContextTree = 2 | eWalkCache
+    eWalkContextTree = 2 | eWalkCache,
+    eScoped = 4
   };
 
   /**
    * Used to navigate and create if needed the accessible children.
    */
   explicit TreeWalker(Accessible* aContext);
 
   /**
--- a/accessible/base/nsAccUtils.cpp
+++ b/accessible/base/nsAccUtils.cpp
@@ -136,83 +136,90 @@ nsAccUtils::SetLiveContainerAttributes(n
 {
   nsAutoString live, relevant, busy;
   nsIContent* ancestor = aStartContent;
   while (ancestor) {
 
     // container-relevant attribute
     if (relevant.IsEmpty() &&
         HasDefinedARIAToken(ancestor, nsGkAtoms::aria_relevant) &&
-        ancestor->GetAttr(kNameSpaceID_None, nsGkAtoms::aria_relevant, relevant))
+        ancestor->AsElement()->GetAttr(kNameSpaceID_None,
+                                       nsGkAtoms::aria_relevant, relevant))
       SetAccAttr(aAttributes, nsGkAtoms::containerRelevant, relevant);
 
     // container-live, and container-live-role attributes
     if (live.IsEmpty()) {
       const nsRoleMapEntry* role = nullptr;
       if (ancestor->IsElement()) {
         role = aria::GetRoleMap(ancestor->AsElement());
       }
       if (HasDefinedARIAToken(ancestor, nsGkAtoms::aria_live)) {
-        ancestor->GetAttr(kNameSpaceID_None, nsGkAtoms::aria_live, live);
+        ancestor->AsElement()->GetAttr(kNameSpaceID_None, nsGkAtoms::aria_live, live);
       } else if (role) {
         GetLiveAttrValue(role->liveAttRule, live);
       }
       if (!live.IsEmpty()) {
         SetAccAttr(aAttributes, nsGkAtoms::containerLive, live);
         if (role) {
           SetAccAttr(aAttributes, nsGkAtoms::containerLiveRole,
                      role->ARIARoleString());
         }
       }
     }
 
     // container-atomic attribute
-    if (ancestor->AttrValueIs(kNameSpaceID_None, nsGkAtoms::aria_atomic,
-                              nsGkAtoms::_true, eCaseMatters)) {
+    if (ancestor->IsElement() &&
+        ancestor->AsElement()->AttrValueIs(kNameSpaceID_None,
+                                           nsGkAtoms::aria_atomic,
+                                           nsGkAtoms::_true, eCaseMatters)) {
       SetAccAttr(aAttributes, nsGkAtoms::containerAtomic,
                  NS_LITERAL_STRING("true"));
     }
 
     // container-busy attribute
     if (busy.IsEmpty() &&
         HasDefinedARIAToken(ancestor, nsGkAtoms::aria_busy) &&
-        ancestor->GetAttr(kNameSpaceID_None, nsGkAtoms::aria_busy, busy))
+        ancestor->AsElement()->GetAttr(kNameSpaceID_None, nsGkAtoms::aria_busy, busy))
       SetAccAttr(aAttributes, nsGkAtoms::containerBusy, busy);
 
     if (ancestor == aTopEl)
       break;
 
     ancestor = ancestor->GetParent();
     if (!ancestor)
       ancestor = aTopEl; // Use <body>/<frameset>
   }
 }
 
 bool
 nsAccUtils::HasDefinedARIAToken(nsIContent *aContent, nsAtom *aAtom)
 {
   NS_ASSERTION(aContent, "aContent is null in call to HasDefinedARIAToken!");
 
-  if (!aContent->HasAttr(kNameSpaceID_None, aAtom) ||
-      aContent->AttrValueIs(kNameSpaceID_None, aAtom,
-                            nsGkAtoms::_empty, eCaseMatters) ||
-      aContent->AttrValueIs(kNameSpaceID_None, aAtom,
-                            nsGkAtoms::_undefined, eCaseMatters)) {
+  if (!aContent->IsElement())
+    return false;
+
+  Element* element = aContent->AsElement();
+  if (!element->HasAttr(kNameSpaceID_None, aAtom) ||
+      element->AttrValueIs(kNameSpaceID_None, aAtom, nsGkAtoms::_empty,
+                           eCaseMatters) ||
+      element->AttrValueIs(kNameSpaceID_None, aAtom, nsGkAtoms::_undefined,
+                           eCaseMatters)) {
         return false;
   }
   return true;
 }
 
 nsAtom*
 nsAccUtils::GetARIAToken(dom::Element* aElement, nsAtom* aAttr)
 {
   if (!HasDefinedARIAToken(aElement, aAttr))
     return nsGkAtoms::_empty;
 
-  static nsIContent::AttrValuesArray tokens[] =
+  static Element::AttrValuesArray tokens[] =
     { &nsGkAtoms::_false, &nsGkAtoms::_true,
       &nsGkAtoms::mixed, nullptr};
 
   int32_t idx = aElement->FindAttrValueIn(kNameSpaceID_None,
                                           aAttr, tokens, eCaseMatters);
   if (idx >= 0)
     return *(tokens[idx]);
 
@@ -234,17 +241,19 @@ nsAccUtils::GetSelectableContainer(Acces
       return nullptr;
   }
   return parent;
 }
 
 bool
 nsAccUtils::IsARIASelected(Accessible* aAccessible)
 {
-  return aAccessible->GetContent()->
+  if (!aAccessible->GetContent()->IsElement())
+    return false;
+  return aAccessible->GetContent()->AsElement()->
     AttrValueIs(kNameSpaceID_None, nsGkAtoms::aria_selected,
                 nsGkAtoms::_true, eCaseMatters);
 }
 
 Accessible*
 nsAccUtils::TableFor(Accessible* aRow)
 {
   if (aRow) {
@@ -354,17 +363,17 @@ nsAccUtils::GetScreenCoordsForParent(Acc
   if (!parent)
     return nsIntPoint(0, 0);
 
   nsIFrame *parentFrame = parent->GetFrame();
   if (!parentFrame)
     return nsIntPoint(0, 0);
 
   nsRect rect = parentFrame->GetScreenRectInAppUnits();
-  return nsPoint(rect.x, rect.y).
+  return nsPoint(rect.X(), rect.Y()).
     ToNearestPixels(parentFrame->PresContext()->AppUnitsPerDevPixel());
 }
 
 bool
 nsAccUtils::GetLiveAttrValue(uint32_t aRule, nsAString& aValue)
 {
   switch (aRule) {
     case eOffLiveAttr:
--- a/accessible/base/nsAccessibilityService.cpp
+++ b/accessible/base/nsAccessibilityService.cpp
@@ -204,30 +204,35 @@ New_HTMLDefinition(nsIContent* aContent,
   return nullptr;
 }
 
 static Accessible* New_HTMLLabel(nsIContent* aContent, Accessible* aContext)
   { return new HTMLLabelAccessible(aContent, aContext->Document()); }
 
 static Accessible* New_HTMLInput(nsIContent* aContent, Accessible* aContext)
 {
-  if (aContent->AttrValueIs(kNameSpaceID_None, nsGkAtoms::type,
-                            nsGkAtoms::checkbox, eIgnoreCase)) {
+  if (!aContent->IsElement()) {
+    return nullptr;
+  }
+
+  Element* element = aContent->AsElement();
+  if (element->AttrValueIs(kNameSpaceID_None, nsGkAtoms::type,
+                           nsGkAtoms::checkbox, eIgnoreCase)) {
     return new HTMLCheckboxAccessible(aContent, aContext->Document());
   }
-  if (aContent->AttrValueIs(kNameSpaceID_None, nsGkAtoms::type,
-                            nsGkAtoms::radio, eIgnoreCase)) {
+  if (element->AttrValueIs(kNameSpaceID_None, nsGkAtoms::type,
+                           nsGkAtoms::radio, eIgnoreCase)) {
     return new HTMLRadioButtonAccessible(aContent, aContext->Document());
   }
-  if (aContent->AttrValueIs(kNameSpaceID_None, nsGkAtoms::type,
-                            nsGkAtoms::time, eIgnoreCase)) {
+  if (element->AttrValueIs(kNameSpaceID_None, nsGkAtoms::type,
+                           nsGkAtoms::time, eIgnoreCase)) {
     return new EnumRoleAccessible<roles::GROUPING>(aContent, aContext->Document());
   }
-  if (aContent->AttrValueIs(kNameSpaceID_None, nsGkAtoms::type,
-                            nsGkAtoms::date, eIgnoreCase)) {
+  if (element->AttrValueIs(kNameSpaceID_None, nsGkAtoms::type,
+                           nsGkAtoms::date, eIgnoreCase)) {
     return new EnumRoleAccessible<roles::DATE_EDITOR>(aContent, aContext->Document());
   }
   return nullptr;
 }
 
 static Accessible* New_HTMLOutput(nsIContent* aContent, Accessible* aContext)
   { return new HTMLOutputAccessible(aContent, aContext->Document()); }
 
@@ -256,32 +261,35 @@ New_HTMLTableHeaderCell(nsIContent* aCon
     return new HTMLTableHeaderCellAccessibleWrap(aContent, aContext->Document());
   return nullptr;
 }
 
 static Accessible*
 New_HTMLTableHeaderCellIfScope(nsIContent* aContent, Accessible* aContext)
 {
   if (aContext->IsTableRow() && aContext->GetContent() == aContent->GetParent() &&
-      aContent->HasAttr(kNameSpaceID_None, nsGkAtoms::scope))
+      aContent->IsElement() &&
+      aContent->AsElement()->HasAttr(kNameSpaceID_None, nsGkAtoms::scope))
     return new HTMLTableHeaderCellAccessibleWrap(aContent, aContext->Document());
   return nullptr;
 }
 
 #ifdef MOZ_XUL
 static Accessible*
 New_MaybeImageOrToolbarButtonAccessible(nsIContent* aContent,
                                         Accessible* aContext)
 {
-  if (aContent->HasAttr(kNameSpaceID_None, nsGkAtoms::onclick)) {
+  if (aContent->IsElement() &&
+      aContent->AsElement()->HasAttr(kNameSpaceID_None, nsGkAtoms::onclick)) {
     return new XULToolbarButtonAccessible(aContent, aContext->Document());
   }
 
   // Don't include nameless images in accessible tree.
-  if (!aContent->HasAttr(kNameSpaceID_None, nsGkAtoms::tooltiptext)) {
+  if (!aContent->IsElement() ||
+      !aContent->AsElement()->HasAttr(kNameSpaceID_None, nsGkAtoms::tooltiptext)) {
     return nullptr;
   }
 
   return new ImageAccessibleWrap(aContent, aContext->Document());
 }
 static Accessible*
 New_MenuSeparator(nsIContent* aContent, Accessible* aContext)
   { return new XULMenuSeparatorAccessible(aContent, aContext->Document()); }
@@ -469,17 +477,17 @@ class PluginTimerCallBack final : public
 {
   ~PluginTimerCallBack() {}
 
 public:
   explicit PluginTimerCallBack(nsIContent* aContent) : mContent(aContent) {}
 
   NS_DECL_ISUPPORTS
 
-  NS_IMETHOD Notify(nsITimer* aTimer) final
+  NS_IMETHOD Notify(nsITimer* aTimer) final override
   {
     if (!mContent->IsInUncomposedDoc())
       return NS_OK;
 
     nsIPresShell* ps = mContent->OwnerDoc()->GetShell();
     if (ps) {
       DocAccessible* doc = ps->GetDocAccessible();
       if (doc) {
@@ -493,17 +501,17 @@ public:
 
     // We couldn't get a doc accessible so presumably the document went away.
     // In this case don't leak our ref to the content or timer.
     sPendingPlugins->RemoveElement(mContent);
     sPluginTimers->RemoveElement(aTimer);
     return NS_OK;
   }
 
-  NS_IMETHOD GetName(nsACString& aName) final
+  NS_IMETHOD GetName(nsACString& aName) final override
   {
     aName.AssignLiteral("PluginTimerCallBack");
     return NS_OK;
   }
 
 private:
   nsCOMPtr<nsIContent> mContent;
 };
@@ -1329,19 +1337,16 @@ nsAccessibilityService::Init()
 
 #if defined(XP_WIN)
   // This information needs to be initialized before the observer fires.
   if (XRE_IsParentProcess()) {
     Compatibility::Init();
   }
 #endif // defined(XP_WIN)
 
-  static const char16_t kInitIndicator[] = { '1', 0 };
-  observerService->NotifyObservers(nullptr, "a11y-init-or-shutdown", kInitIndicator);
-
   // Subscribe to EventListenerService.
   nsCOMPtr<nsIEventListenerService> eventListenerService =
     do_GetService("@mozilla.org/eventlistenerservice;1");
   if (!eventListenerService)
     return false;
 
   eventListenerService->AddListenerChangeListener(this);
 
@@ -1393,16 +1398,19 @@ nsAccessibilityService::Init()
 #endif
 
   // Now its safe to start platform accessibility.
   if (XRE_IsParentProcess())
     PlatformInit();
 
   statistics::A11yInitialized();
 
+  static const char16_t kInitIndicator[] = { '1', 0 };
+  observerService->NotifyObservers(nullptr, "a11y-init-or-shutdown", kInitIndicator);
+
   return true;
 }
 
 void
 nsAccessibilityService::Shutdown()
 {
   // Application is going to be closed, shutdown accessibility and mark
   // accessibility service as shutdown to prevent calls of its methods.
@@ -1412,19 +1420,16 @@ nsAccessibilityService::Shutdown()
   MOZ_ASSERT(gConsumers, "Accessibility was shutdown already");
   UnsetConsumers(eXPCOM | eMainProcess | ePlatformAPI);
 
   // Remove observers.
   nsCOMPtr<nsIObserverService> observerService =
       mozilla::services::GetObserverService();
   if (observerService) {
     observerService->RemoveObserver(this, NS_XPCOM_SHUTDOWN_OBSERVER_ID);
-
-    static const char16_t kShutdownIndicator[] = { '0', 0 };
-    observerService->NotifyObservers(nullptr, "a11y-init-or-shutdown", kShutdownIndicator);
   }
 
   // Stop accessible document loader.
   DocManager::Shutdown();
 
   SelectionManager::Shutdown();
 
 #ifdef XP_WIN
@@ -1444,16 +1449,21 @@ nsAccessibilityService::Shutdown()
   NS_RELEASE(gApplicationAccessible);
   gApplicationAccessible = nullptr;
 
   NS_IF_RELEASE(gXPCApplicationAccessible);
   gXPCApplicationAccessible = nullptr;
 
   NS_RELEASE(gAccessibilityService);
   gAccessibilityService = nullptr;
+
+  if (observerService) {
+    static const char16_t kShutdownIndicator[] = { '0', 0 };
+    observerService->NotifyObservers(nullptr, "a11y-init-or-shutdown", kShutdownIndicator);
+  }
 }
 
 already_AddRefed<Accessible>
 nsAccessibilityService::CreateAccessibleByType(nsIContent* aContent,
                                                DocAccessible* aDoc)
 {
   nsAutoString role;
   nsCoreUtils::XBLBindingRole(aContent, role);
@@ -1546,18 +1556,20 @@ nsAccessibilityService::CreateAccessible
 #endif
 
     accessible = new XULMenupopupAccessible(aContent, aDoc);
 
   } else if(role.EqualsLiteral("xul:pane")) {
     accessible = new EnumRoleAccessible<roles::PANE>(aContent, aDoc);
 
   } else if (role.EqualsLiteral("xul:panel")) {
-    if (aContent->AttrValueIs(kNameSpaceID_None, nsGkAtoms::noautofocus,
-                              nsGkAtoms::_true, eCaseMatters))
+    if (aContent->IsElement() &&
+        aContent->AsElement()->AttrValueIs(kNameSpaceID_None,
+                                           nsGkAtoms::noautofocus,
+                                           nsGkAtoms::_true, eCaseMatters))
       accessible = new XULAlertAccessible(aContent, aDoc);
     else
       accessible = new EnumRoleAccessible<roles::PANE>(aContent, aDoc);
 
   } else if (role.EqualsLiteral("xul:progressmeter")) {
     accessible = new XULProgressMeterAccessible(aContent, aDoc);
 
   } else if (role.EqualsLiteral("xul:scale")) {
@@ -1760,25 +1772,32 @@ nsAccessibilityService::MarkupAttributes
 
   for (uint32_t i = 0; i < ArrayLength(markupMap->attrs); i++) {
     const MarkupAttrInfo* info = markupMap->attrs + i;
     if (!info->name)
       break;
 
     if (info->DOMAttrName) {
       if (info->DOMAttrValue) {
-        if (aContent->AttrValueIs(kNameSpaceID_None, *info->DOMAttrName,
-                                  *info->DOMAttrValue, eCaseMatters)) {
+        if (aContent->IsElement() &&
+            aContent->AsElement()->AttrValueIs(kNameSpaceID_None,
+                                               *info->DOMAttrName,
+                                               *info->DOMAttrValue,
+                                               eCaseMatters)) {
           nsAccUtils::SetAccAttr(aAttributes, *info->name, *info->DOMAttrValue);
         }
         continue;
       }
 
       nsAutoString value;
-      aContent->GetAttr(kNameSpaceID_None, *info->DOMAttrName, value);
+
+      if (aContent->IsElement()) {
+        aContent->AsElement()->GetAttr(kNameSpaceID_None, *info->DOMAttrName, value);
+      }
+
       if (!value.IsEmpty())
         nsAccUtils::SetAccAttr(aAttributes, *info->name, value);
 
       continue;
     }
 
     nsAccUtils::SetAccAttr(aAttributes, *info->name, *info->value);
   }
--- a/accessible/base/nsAccessiblePivot.cpp
+++ b/accessible/base/nsAccessiblePivot.cpp
@@ -581,18 +581,17 @@ nsAccessiblePivot::MoveToPoint(nsIAccess
     if (filtered & nsIAccessibleTraversalRule::FILTER_IGNORE_SUBTREE)
       match = nullptr;
 
     // Match if no node below this is a match
     if ((filtered & nsIAccessibleTraversalRule::FILTER_MATCH) && !match) {
       nsIntRect childRect = child->Bounds();
       // Double-check child's bounds since the deepest child may have been out
       // of bounds. This assures we don't return a false positive.
-      if (aX >= childRect.x && aX < childRect.x + childRect.width &&
-          aY >= childRect.y && aY < childRect.y + childRect.height)
+      if (childRect.Contains(aX, aY))
         match = child;
     }
 
     child = child->Parent();
   }
 
   if (match || !aIgnoreNoMatch)
     *aResult = MovePivotInternal(match, nsIAccessiblePivot::REASON_POINT,
--- a/accessible/base/nsCoreUtils.cpp
+++ b/accessible/base/nsCoreUtils.cpp
@@ -179,32 +179,33 @@ nsCoreUtils::DispatchTouchEvent(EventMes
 }
 
 uint32_t
 nsCoreUtils::GetAccessKeyFor(nsIContent* aContent)
 {
   // Accesskeys are registered by @accesskey attribute only. At first check
   // whether it is presented on the given element to avoid the slow
   // EventStateManager::GetRegisteredAccessKey() method.
-  if (!aContent->HasAttr(kNameSpaceID_None, nsGkAtoms::accesskey))
+  if (!aContent->IsElement() ||
+      !aContent->AsElement()->HasAttr(kNameSpaceID_None, nsGkAtoms::accesskey))
     return 0;
 
   nsIPresShell* presShell = aContent->OwnerDoc()->GetShell();
   if (!presShell)
     return 0;
 
   nsPresContext *presContext = presShell->GetPresContext();
   if (!presContext)
     return 0;
 
   EventStateManager *esm = presContext->EventStateManager();
   if (!esm)
     return 0;
 
-  return esm->GetRegisteredAccessKey(aContent);
+  return esm->GetRegisteredAccessKey(aContent->AsElement());
 }
 
 nsIContent *
 nsCoreUtils::GetDOMElementFor(nsIContent *aContent)
 {
   if (aContent->IsElement())
     return aContent;
 
@@ -220,17 +221,17 @@ nsCoreUtils::GetDOMNodeFromDOMPoint(nsIN
   if (aNode && aNode->IsElement()) {
     uint32_t childCount = aNode->GetChildCount();
     NS_ASSERTION(aOffset <= childCount, "Wrong offset of the DOM point!");
 
     // The offset can be after last child of container node that means DOM point
     // is placed immediately after the last child. In this case use the DOM node
     // from the given DOM point is used as result node.
     if (aOffset != childCount)
-      return aNode->GetChildAt(aOffset);
+      return aNode->GetChildAt_Deprecated(aOffset);
   }
 
   return aNode;
 }
 
 bool
 nsCoreUtils::IsAncestorOf(nsINode *aPossibleAncestorNode,
                           nsINode *aPossibleDescendantNode,
@@ -296,17 +297,17 @@ nsCoreUtils::ScrollFrameToPoint(nsIFrame
 {
   nsIScrollableFrame* scrollableFrame = do_QueryFrame(aScrollableFrame);
   if (!scrollableFrame)
     return;
 
   nsPoint point =
     ToAppUnits(aPoint, aFrame->PresContext()->AppUnitsPerDevPixel());
   nsRect frameRect = aFrame->GetScreenRectInAppUnits();
-  nsPoint deltaPoint(point.x - frameRect.x, point.y - frameRect.y);
+  nsPoint deltaPoint = point - frameRect.TopLeft();
 
   nsPoint scrollPoint = scrollableFrame->GetScrollPosition();
   scrollPoint -= deltaPoint;
 
   scrollableFrame->ScrollTo(scrollPoint, nsIScrollableFrame::INSTANT);
 }
 
 void
@@ -450,24 +451,28 @@ nsCoreUtils::IsErrorPage(nsIDocument *aD
   NS_NAMED_LITERAL_CSTRING(certerror, "certerror");
 
   return StringBeginsWith(path, neterror) || StringBeginsWith(path, certerror);
 }
 
 bool
 nsCoreUtils::GetID(nsIContent *aContent, nsAString& aID)
 {
-  return aContent->GetAttr(kNameSpaceID_None, nsGkAtoms::id, aID);
+  return aContent->IsElement() &&
+    aContent->AsElement()->GetAttr(kNameSpaceID_None, nsGkAtoms::id, aID);
 }
 
 bool
 nsCoreUtils::GetUIntAttr(nsIContent *aContent, nsAtom *aAttr, int32_t *aUInt)
 {
   nsAutoString value;
-  aContent->GetAttr(kNameSpaceID_None, aAttr, value);
+  if (!aContent->IsElement()) {
+    return false;
+  }
+  aContent->AsElement()->GetAttr(kNameSpaceID_None, aAttr, value);
   if (!value.IsEmpty()) {
     nsresult error = NS_OK;
     int32_t integer = value.ToInteger(&error);
     if (NS_SUCCEEDED(error) && integer > 0) {
       *aUInt = integer;
       return true;
     }
   }
@@ -478,17 +483,18 @@ nsCoreUtils::GetUIntAttr(nsIContent *aCo
 void
 nsCoreUtils::GetLanguageFor(nsIContent *aContent, nsIContent *aRootContent,
                             nsAString& aLanguage)
 {
   aLanguage.Truncate();
 
   nsIContent *walkUp = aContent;
   while (walkUp && walkUp != aRootContent &&
-         !walkUp->GetAttr(kNameSpaceID_None, nsGkAtoms::lang, aLanguage))
+         (!walkUp->IsElement() ||
+          !walkUp->AsElement()->GetAttr(kNameSpaceID_None, nsGkAtoms::lang, aLanguage)))
     walkUp = walkUp->GetParent();
 }
 
 already_AddRefed<nsIBoxObject>
 nsCoreUtils::GetTreeBodyBoxObject(nsITreeBoxObject *aTreeBoxObj)
 {
   nsCOMPtr<nsIDOMElement> tcElm;
   aTreeBoxObj->GetTreeBody(getter_AddRefs(tcElm));
@@ -612,17 +618,17 @@ nsCoreUtils::GetPreviousSensibleColumn(n
   return prevColumn.forget();
 }
 
 bool
 nsCoreUtils::IsColumnHidden(nsITreeColumn *aColumn)
 {
   nsCOMPtr<nsIDOMElement> element;
   aColumn->GetElement(getter_AddRefs(element));
-  nsCOMPtr<nsIContent> content = do_QueryInterface(element);
+  nsCOMPtr<Element> content = do_QueryInterface(element);
   return content->AttrValueIs(kNameSpaceID_None, nsGkAtoms::hidden,
                               nsGkAtoms::_true, eCaseMatters);
 }
 
 void
 nsCoreUtils::ScrollTo(nsIPresShell* aPresShell, nsIContent* aContent,
                       uint32_t aScrollType)
 {
@@ -672,14 +678,14 @@ nsCoreUtils::DispatchAccEvent(RefPtr<nsI
   obsService->NotifyObservers(event, NS_ACCESSIBLE_EVENT_TOPIC, nullptr);
 }
 
 void
 nsCoreUtils::XBLBindingRole(const nsIContent* aEl, nsAString& aRole)
 {
   for (const nsXBLBinding* binding = aEl->GetXBLBinding(); binding;
        binding = binding->GetBaseBinding()) {
-    nsIContent* bindingElm = binding->PrototypeBinding()->GetBindingElement();
+    Element* bindingElm = binding->PrototypeBinding()->GetBindingElement();
     bindingElm->GetAttr(kNameSpaceID_None, nsGkAtoms::role, aRole);
     if (!aRole.IsEmpty())
       break;
   }
 }
--- a/accessible/base/nsCoreUtils.h
+++ b/accessible/base/nsCoreUtils.h
@@ -2,16 +2,17 @@
 /* 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 nsCoreUtils_h_
 #define nsCoreUtils_h_
 
 #include "mozilla/EventForwards.h"
+#include "mozilla/dom/Element.h"
 #include "nsIAccessibleEvent.h"
 #include "nsIContent.h"
 #include "nsIDocument.h" // for GetShell()
 #include "nsIPresShell.h"
 
 #include "nsPoint.h"
 #include "nsTArray.h"
 
@@ -286,17 +287,18 @@ public:
                        uint32_t aScrollType);
 
   /**
    * Return true if the given node is table header element.
    */
   static bool IsHTMLTableHeader(nsIContent *aContent)
   {
     return aContent->NodeInfo()->Equals(nsGkAtoms::th) ||
-      aContent->HasAttr(kNameSpaceID_None, nsGkAtoms::scope);
+      (aContent->IsElement() &&
+       aContent->AsElement()->HasAttr(kNameSpaceID_None, nsGkAtoms::scope));
   }
 
   /**
    * Returns true if the given string is empty or contains whitespace symbols
    * only. In contrast to nsWhitespaceTokenizer class it takes into account
    * non-breaking space (0xa0).
    */
   static bool IsWhitespaceString(const nsAString& aString);
--- a/accessible/base/nsTextEquivUtils.cpp
+++ b/accessible/base/nsTextEquivUtils.cpp
@@ -308,22 +308,22 @@ nsTextEquivUtils::AppendFromDOMNode(nsIC
     nsCOMPtr<nsIDOMXULLabeledControlElement> labeledEl =
       do_QueryInterface(aContent);
 
     if (labeledEl) {
       labeledEl->GetLabel(textEquivalent);
     } else {
       if (aContent->NodeInfo()->Equals(nsGkAtoms::label,
                                        kNameSpaceID_XUL))
-        aContent->GetAttr(kNameSpaceID_None, nsGkAtoms::value,
-                          textEquivalent);
+        aContent->AsElement()->GetAttr(kNameSpaceID_None, nsGkAtoms::value,
+                                       textEquivalent);
 
       if (textEquivalent.IsEmpty())
-        aContent->GetAttr(kNameSpaceID_None,
-                          nsGkAtoms::tooltiptext, textEquivalent);
+        aContent->AsElement()->GetAttr(kNameSpaceID_None,
+                                       nsGkAtoms::tooltiptext, textEquivalent);
     }
 
     AppendString(aString, textEquivalent);
   }
 
   return AppendFromDOMChildren(aContent, aString);
 }
 
--- a/accessible/generic/ARIAGridAccessible.cpp
+++ b/accessible/generic/ARIAGridAccessible.cpp
@@ -636,21 +636,20 @@ ARIAGridCellAccessible::ApplyARIAState(u
     return;
 
   // Check aria-selected="true" on the row.
   Accessible* row = Parent();
   if (!row || row->Role() != roles::ROW)
     return;
 
   nsIContent *rowContent = row->GetContent();
-  if (nsAccUtils::HasDefinedARIAToken(rowContent,
-                                      nsGkAtoms::aria_selected) &&
-      !rowContent->AttrValueIs(kNameSpaceID_None,
-                               nsGkAtoms::aria_selected,
-                               nsGkAtoms::_false, eCaseMatters))
+  if (nsAccUtils::HasDefinedARIAToken(rowContent, nsGkAtoms::aria_selected) &&
+      !rowContent->AsElement()->AttrValueIs(kNameSpaceID_None,
+                                            nsGkAtoms::aria_selected,
+                                            nsGkAtoms::_false, eCaseMatters))
     *aState |= states::SELECTABLE | states::SELECTED;
 }
 
 already_AddRefed<nsIPersistentProperties>
 ARIAGridCellAccessible::NativeAttributes()
 {
   nsCOMPtr<nsIPersistentProperties> attributes =
     HyperTextAccessibleWrap::NativeAttributes();
--- a/accessible/generic/Accessible-inl.h
+++ b/accessible/generic/Accessible-inl.h
@@ -71,18 +71,18 @@ Accessible::SetRoleMapEntry(const nsRole
 }
 
 inline bool
 Accessible::IsSearchbox() const
 {
   const nsRoleMapEntry* roleMapEntry = ARIARoleMap();
   return (roleMapEntry && roleMapEntry->Is(nsGkAtoms::searchbox)) ||
     (mContent->IsHTMLElement(nsGkAtoms::input) &&
-     mContent->AttrValueIs(kNameSpaceID_None, nsGkAtoms::type,
-                           nsGkAtoms::search, eCaseMatters));
+     mContent->AsElement()->AttrValueIs(kNameSpaceID_None, nsGkAtoms::type,
+                                        nsGkAtoms::search, eCaseMatters));
 }
 
 inline bool
 Accessible::HasGenericType(AccGenericType aType) const
 {
   const nsRoleMapEntry* roleMapEntry = ARIARoleMap();
   return (mGenericTypes & aType) ||
     (roleMapEntry && roleMapEntry->IsOfType(aType));
--- a/accessible/generic/Accessible.cpp
+++ b/accessible/generic/Accessible.cpp
@@ -148,22 +148,22 @@ Accessible::Name(nsString& aName)
   }
 
   ENameValueFlag nameFlag = NativeName(aName);
   if (!aName.IsEmpty())
     return nameFlag;
 
   // In the end get the name from tooltip.
   if (mContent->IsHTMLElement()) {
-    if (mContent->GetAttr(kNameSpaceID_None, nsGkAtoms::title, aName)) {
+    if (mContent->AsElement()->GetAttr(kNameSpaceID_None, nsGkAtoms::title, aName)) {
       aName.CompressWhitespace();
       return eNameFromTooltip;
     }
   } else if (mContent->IsXULElement()) {
-    if (mContent->GetAttr(kNameSpaceID_None, nsGkAtoms::tooltiptext, aName)) {
+    if (mContent->AsElement()->GetAttr(kNameSpaceID_None, nsGkAtoms::tooltiptext, aName)) {
       aName.CompressWhitespace();
       return eNameFromTooltip;
     }
   } else if (mContent->IsSVGElement()) {
     // If user agents need to choose among multiple ‘desc’ or ‘title’ elements
     // for processing, the user agent shall choose the first one.
     for (nsIContent* childElm = mContent->GetFirstChild(); childElm;
          childElm = childElm->GetNextSibling()) {
@@ -197,19 +197,19 @@ Accessible::Description(nsString& aDescr
                            aDescription);
 
   if (aDescription.IsEmpty()) {
     NativeDescription(aDescription);
 
     if (aDescription.IsEmpty()) {
       // Keep the Name() method logic.
       if (mContent->IsHTMLElement()) {
-        mContent->GetAttr(kNameSpaceID_None, nsGkAtoms::title, aDescription);
+        mContent->AsElement()->GetAttr(kNameSpaceID_None, nsGkAtoms::title, aDescription);
       } else if (mContent->IsXULElement()) {
-        mContent->GetAttr(kNameSpaceID_None, nsGkAtoms::tooltiptext, aDescription);
+        mContent->AsElement()->GetAttr(kNameSpaceID_None, nsGkAtoms::tooltiptext, aDescription);
       } else if (mContent->IsSVGElement()) {
         for (nsIContent* childElm = mContent->GetFirstChild(); childElm;
              childElm = childElm->GetNextSibling()) {
           if (childElm->IsSVGElement(nsGkAtoms::desc)) {
             nsTextEquivUtils::AppendTextEquivFromContent(this, childElm,
                                                          &aDescription);
             break;
           }
@@ -446,17 +446,17 @@ Accessible::NativeState()
         else
           state |= states::HORIZONTAL;
       }
     }
   }
 
   // Check if a XUL element has the popup attribute (an attached popup menu).
   if (HasOwnContent() && mContent->IsXULElement() &&
-      mContent->HasAttr(kNameSpaceID_None, nsGkAtoms::popup))
+      mContent->AsElement()->HasAttr(kNameSpaceID_None, nsGkAtoms::popup))
     state |= states::HASPOPUP;
 
   // Bypass the link states specialization for non links.
   const nsRoleMapEntry* roleMapEntry = ARIARoleMap();
   if (!roleMapEntry || roleMapEntry->roleRule == kUseNativeRole ||
       roleMapEntry->role == roles::LINK)
     state |= NativeLinkState();
 
@@ -486,18 +486,19 @@ Accessible::NativeLinkState() const
 }
 
 bool
 Accessible::NativelyUnavailable() const
 {
   if (mContent->IsHTMLElement())
     return mContent->AsElement()->State().HasState(NS_EVENT_STATE_DISABLED);
 
-  return mContent->AttrValueIs(kNameSpaceID_None, nsGkAtoms::disabled,
-                               nsGkAtoms::_true, eCaseMatters);
+  return mContent->IsElement() &&
+    mContent->AsElement()->AttrValueIs(kNameSpaceID_None, nsGkAtoms::disabled,
+                                       nsGkAtoms::_true, eCaseMatters);
 }
 
 Accessible*
 Accessible::FocusedChild()
 {
   Accessible* focus = FocusMgr()->FocusedAccessible();
   if (focus && (focus == this || focus->Parent() == this))
     return focus;
@@ -508,18 +509,17 @@ Accessible::FocusedChild()
 Accessible*
 Accessible::ChildAtPoint(int32_t aX, int32_t aY,
                          EWhichChildAtPoint aWhichChild)
 {
   // If we can't find the point in a child, we will return the fallback answer:
   // we return |this| if the point is within it, otherwise nullptr.
   Accessible* fallbackAnswer = nullptr;
   nsIntRect rect = Bounds();
-  if (aX >= rect.x && aX < rect.x + rect.width &&
-      aY >= rect.y && aY < rect.y + rect.height)
+  if (rect.Contains(aX, aY))
     fallbackAnswer = this;
 
   if (nsAccUtils::MustPrune(this))  // Do not dig any further
     return fallbackAnswer;
 
   // Search an accessible at the given point starting from accessible document
   // because containing block (see CSS2) for out of flow element (for example,
   // absolutely positioned element) may be different from its DOM parent and
@@ -537,17 +537,17 @@ Accessible::ChildAtPoint(int32_t aX, int
   // Check whether the point is at popup content.
   nsIWidget* rootWidget = rootFrame->GetView()->GetNearestWidget(nullptr);
   NS_ENSURE_TRUE(rootWidget, nullptr);
 
   LayoutDeviceIntRect rootRect = rootWidget->GetScreenBounds();
 
   WidgetMouseEvent dummyEvent(true, eMouseMove, rootWidget,
                               WidgetMouseEvent::eSynthesized);
-  dummyEvent.mRefPoint = LayoutDeviceIntPoint(aX - rootRect.x, aY - rootRect.y);
+  dummyEvent.mRefPoint = LayoutDeviceIntPoint(aX - rootRect.X(), aY - rootRect.Y());
 
   nsIFrame* popupFrame = nsLayoutUtils::
     GetPopupFrameForEventCoordinates(accDocument->PresContext()->GetRootPresContext(),
                                      &dummyEvent);
   if (popupFrame) {
     // If 'this' accessible is not inside the popup then ignore the popup when
     // searching an accessible at point.
     DocAccessible* popupDoc =
@@ -559,18 +559,18 @@ Accessible::ChildAtPoint(int32_t aX, int
       popupChild = popupChild->Parent();
 
     if (popupChild == popupAcc)
       startFrame = popupFrame;
   }
 
   nsPresContext* presContext = startFrame->PresContext();
   nsRect screenRect = startFrame->GetScreenRectInAppUnits();
-    nsPoint offset(presContext->DevPixelsToAppUnits(aX) - screenRect.x,
-                   presContext->DevPixelsToAppUnits(aY) - screenRect.y);
+  nsPoint offset(presContext->DevPixelsToAppUnits(aX) - screenRect.X(),
+                 presContext->DevPixelsToAppUnits(aY) - screenRect.Y());
   nsIFrame* foundFrame = nsLayoutUtils::GetFrameForPoint(startFrame, offset);
 
   nsIContent* content = nullptr;
   if (!foundFrame || !(content = foundFrame->GetContent()))
     return fallbackAnswer;
 
   // Get accessible for the node with the point or the first accessible in
   // the DOM parent chain.
@@ -611,18 +611,17 @@ Accessible::ChildAtPoint(int32_t aX, int
   // where layout won't walk into things for us, such as image map areas and
   // sub documents (XXX: subdocuments should be handled by methods of
   // OuterDocAccessibles).
   uint32_t childCount = accessible->ChildCount();
   for (uint32_t childIdx = 0; childIdx < childCount; childIdx++) {
     Accessible* child = accessible->GetChildAt(childIdx);
 
     nsIntRect childRect = child->Bounds();
-    if (aX >= childRect.x && aX < childRect.x + childRect.width &&
-        aY >= childRect.y && aY < childRect.y + childRect.height &&
+    if (childRect.Contains(aX, aY) &&
         (child->State() & states::INVISIBLE) == 0) {
 
       if (aWhichChild == eDeepestChild)
         return child->ChildAtPoint(aX, aY, eDeepestChild);
 
       return child;
     }
   }
@@ -675,27 +674,26 @@ Accessible::Bounds() const
 {
   nsIFrame* boundingFrame = nullptr;
   nsRect unionRectTwips = RelativeBounds(&boundingFrame);
   if (!boundingFrame)
     return nsIntRect();
 
   nsIntRect screenRect;
   nsPresContext* presContext = mDoc->PresContext();
-  screenRect.x = presContext->AppUnitsToDevPixels(unionRectTwips.x);
-  screenRect.y = presContext->AppUnitsToDevPixels(unionRectTwips.y);
-  screenRect.width = presContext->AppUnitsToDevPixels(unionRectTwips.width);
-  screenRect.height = presContext->AppUnitsToDevPixels(unionRectTwips.height);
+  screenRect.SetRect(presContext->AppUnitsToDevPixels(unionRectTwips.X()),
+                     presContext->AppUnitsToDevPixels(unionRectTwips.Y()),
+                     presContext->AppUnitsToDevPixels(unionRectTwips.Width()),
+                     presContext->AppUnitsToDevPixels(unionRectTwips.Height()));
 
   // We have the union of the rectangle, now we need to put it in absolute
   // screen coords.
   nsIntRect orgRectPixels = boundingFrame->GetScreenRectInAppUnits().
     ToNearestPixels(presContext->AppUnitsPerDevPixel());
-  screenRect.x += orgRectPixels.x;
-  screenRect.y += orgRectPixels.y;
+  screenRect.MoveBy(orgRectPixels.X(), orgRectPixels.Y());
 
   return screenRect;
 }
 
 void
 Accessible::SetSelected(bool aSelect)
 {
   if (!HasOwnContent())
@@ -822,19 +820,20 @@ Accessible::XULElmName(DocAccessible* aD
 
   // Can get text from title of <toolbaritem> if we're a child of a <toolbaritem>
   nsIContent *bindingParent = aElm->GetBindingParent();
   nsIContent* parent =
     bindingParent? bindingParent->GetParent() : aElm->GetParent();
   nsAutoString ancestorTitle;
   while (parent) {
     if (parent->IsXULElement(nsGkAtoms::toolbaritem) &&
-        parent->GetAttr(kNameSpaceID_None, nsGkAtoms::title, ancestorTitle)) {
+        parent->AsElement()->GetAttr(kNameSpaceID_None, nsGkAtoms::title, ancestorTitle)) {
       // Before returning this, check if the element itself has a tooltip:
-      if (aElm->GetAttr(kNameSpaceID_None, nsGkAtoms::tooltiptext, aName)) {
+      if (aElm->IsElement() &&
+          aElm->AsElement()->GetAttr(kNameSpaceID_None, nsGkAtoms::tooltiptext, aName)) {
         aName.CompressWhitespace();
         return;
       }
 
       aName.Assign(ancestorTitle);
       aName.CompressWhitespace();
       return;
     }
@@ -939,17 +938,17 @@ Accessible::Attributes()
   // 'xml-roles' attribute for landmark.
   nsAtom* landmark = LandmarkRole();
   if (landmark) {
     nsAccUtils::SetAccAttr(attributes, nsGkAtoms::xmlroles, landmark);
 
   } else {
     // 'xml-roles' attribute coming from ARIA.
     nsAutoString xmlRoles;
-    if (mContent->GetAttr(kNameSpaceID_None, nsGkAtoms::role, xmlRoles))
+    if (mContent->AsElement()->GetAttr(kNameSpaceID_None, nsGkAtoms::role, xmlRoles))
       nsAccUtils::SetAccAttr(attributes, nsGkAtoms::xmlroles, xmlRoles);
   }
 
   // Expose object attributes from ARIA attributes.
   nsAutoString unused;
   aria::AttrIterator attribIter(mContent);
   nsAutoString name, value;
   while(attribIter.Next(name, value))
@@ -1060,17 +1059,17 @@ Accessible::NativeAttributes()
     return attributes.forget();
 
   nsAutoString id;
   if (nsCoreUtils::GetID(mContent, id))
     attributes->SetStringProperty(NS_LITERAL_CSTRING("id"), id, unused);
 
   // Expose class because it may have useful microformat information.
   nsAutoString _class;
-  if (mContent->GetAttr(kNameSpaceID_None, nsGkAtoms::_class, _class))
+  if (mContent->AsElement()->GetAttr(kNameSpaceID_None, nsGkAtoms::_class, _class))
     nsAccUtils::SetAccAttr(attributes, nsGkAtoms::_class, _class);
 
   // Expose tag.
   nsAutoString tagName;
   mContent->NodeInfo()->GetName(tagName);
   nsAccUtils::SetAccAttr(attributes, nsGkAtoms::tag, tagName);
 
   // Expose draggable object attribute.
@@ -1174,19 +1173,20 @@ Accessible::State()
   // Apply ARIA states to be sure accessible states will be overridden.
   ApplyARIAState(&state);
 
   // If this is an ARIA item of the selectable widget and if it's focused and
   // not marked unselected explicitly (i.e. aria-selected="false") then expose
   // it as selected to make ARIA widget authors life easier.
   const nsRoleMapEntry* roleMapEntry = ARIARoleMap();
   if (roleMapEntry && !(state & states::SELECTED) &&
-      !mContent->AttrValueIs(kNameSpaceID_None,
-                             nsGkAtoms::aria_selected,
-                             nsGkAtoms::_false, eCaseMatters)) {
+      (!mContent->IsElement() ||
+       !mContent->AsElement()->AttrValueIs(kNameSpaceID_None,
+                                           nsGkAtoms::aria_selected,
+                                           nsGkAtoms::_false, eCaseMatters))) {
     // Special case for tabs: focused tab or focus inside related tab panel
     // implies selected state.
     if (roleMapEntry->role == roles::PAGETAB) {
       if (state & states::FOCUSED) {
         state |= states::SELECTED;
       } else {
         // If focus is in a child of the tab panel surely the tab is selected!
         Relation rel = RelationByType(RelationType::LABEL_FOR);
@@ -1334,20 +1334,24 @@ Accessible::Value(nsString& aValue)
   const nsRoleMapEntry* roleMapEntry = ARIARoleMap();
   if (!roleMapEntry)
     return;
 
   if (roleMapEntry->valueRule != eNoValue) {
     // aria-valuenow is a number, and aria-valuetext is the optional text
     // equivalent. For the string value, we will try the optional text
     // equivalent first.
-    if (!mContent->GetAttr(kNameSpaceID_None,
-                           nsGkAtoms::aria_valuetext, aValue)) {
-      mContent->GetAttr(kNameSpaceID_None, nsGkAtoms::aria_valuenow,
-                        aValue);
+    if (!mContent->IsElement()) {
+      return;
+    }
+
+    if (!mContent->AsElement()->GetAttr(kNameSpaceID_None,
+                                        nsGkAtoms::aria_valuetext, aValue)) {
+      mContent->AsElement()->GetAttr(kNameSpaceID_None, nsGkAtoms::aria_valuenow,
+                                     aValue);
     }
     return;
   }
 
   // Value of textbox is a textified subtree.
   if (roleMapEntry->Is(nsGkAtoms::textbox)) {
     nsTextEquivUtils::GetTextEquivFromSubtree(this, aValue);
     return;
@@ -1449,20 +1453,21 @@ Accessible::ARIATransformRole(role aRole
   // where the accessible role depends on both the role and ARIA state.
   if (aRole == roles::PUSHBUTTON) {
     if (nsAccUtils::HasDefinedARIAToken(mContent, nsGkAtoms::aria_pressed)) {
       // For simplicity, any existing pressed attribute except "" or "undefined"
       // indicates a toggle.
       return roles::TOGGLE_BUTTON;
     }
 
-    if (mContent->AttrValueIs(kNameSpaceID_None,
-                              nsGkAtoms::aria_haspopup,
-                              nsGkAtoms::_true,
-                              eCaseMatters)) {
+    if (mContent->IsElement() &&
+        mContent->AsElement()->AttrValueIs(kNameSpaceID_None,
+                                           nsGkAtoms::aria_haspopup,
+                                           nsGkAtoms::_true,
+                                           eCaseMatters)) {
       // For button with aria-haspopup="true".
       return roles::BUTTONMENU;
     }
 
   } else if (aRole == roles::LISTBOX) {
     // A listbox inside of a combobox needs a special role because of ATK
     // mapping to menu.
     if (mParent && mParent->IsCombobox()) {
@@ -1477,18 +1482,19 @@ Accessible::ARIATransformRole(role aRole
     }
 
   } else if (aRole == roles::OPTION) {
     if (mParent && mParent->Role() == roles::COMBOBOX_LIST)
       return roles::COMBOBOX_OPTION;
 
   } else if (aRole == roles::MENUITEM) {
     // Menuitem has a submenu.
-    if (mContent->AttrValueIs(kNameSpaceID_None, nsGkAtoms::aria_haspopup,
-                              nsGkAtoms::_true, eCaseMatters)) {
+    if (mContent->IsElement() &&
+        mContent->AsElement()->AttrValueIs(kNameSpaceID_None, nsGkAtoms::aria_haspopup,
+                                           nsGkAtoms::_true, eCaseMatters)) {
       return roles::PARENT_MENUITEM;
     }
   }
 
   return aRole;
 }
 
 nsAtom*
@@ -1592,17 +1598,20 @@ Accessible::DoAction(uint8_t aIndex)
   return false;
 }
 
 nsIContent*
 Accessible::GetAtomicRegion() const
 {
   nsIContent *loopContent = mContent;
   nsAutoString atomic;
-  while (loopContent && !loopContent->GetAttr(kNameSpaceID_None, nsGkAtoms::aria_atomic, atomic))
+  while (loopContent &&
+         (!loopContent->IsElement() ||
+          !loopContent->AsElement()->GetAttr(kNameSpaceID_None,
+                                             nsGkAtoms::aria_atomic, atomic)))
     loopContent = loopContent->GetParent();
 
   return atomic.EqualsLiteral("true") ? loopContent : nullptr;
 }
 
 Relation
 Accessible::RelationByType(RelationType aType)
 {
@@ -1982,17 +1991,19 @@ Accessible::ARIAName(nsString& aName)
   // aria-labelledby now takes precedence over aria-label
   nsresult rv = nsTextEquivUtils::
     GetTextEquivFromIDRefs(this, nsGkAtoms::aria_labelledby, aName);
   if (NS_SUCCEEDED(rv)) {
     aName.CompressWhitespace();
   }
 
   if (aName.IsEmpty() &&
-      mContent->GetAttr(kNameSpaceID_None, nsGkAtoms::aria_label, aName)) {
+      mContent->IsElement() &&
+      mContent->AsElement()->GetAttr(kNameSpaceID_None, nsGkAtoms::aria_label,
+                                     aName)) {
     aName.CompressWhitespace();
   }
 }
 
 // Accessible protected
 ENameValueFlag
 Accessible::NativeName(nsString& aName)
 {
@@ -2539,30 +2550,32 @@ Accessible::IsActiveWidget() const
 
   return false;
 }
 
 bool
 Accessible::AreItemsOperable() const
 {
   return HasOwnContent() &&
-    mContent->HasAttr(kNameSpaceID_None, nsGkAtoms::aria_activedescendant);
+    mContent->IsElement() &&
+    mContent->AsElement()->HasAttr(kNameSpaceID_None, nsGkAtoms::aria_activedescendant);
 }
 
 Accessible*
 Accessible::CurrentItem()
 {
   // Check for aria-activedescendant, which changes which element has focus.
   // For activedescendant, the ARIA spec does not require that the user agent
   // checks whether pointed node is actually a DOM descendant of the element
   // with the aria-activedescendant attribute.
   nsAutoString id;
   if (HasOwnContent() &&
-      mContent->GetAttr(kNameSpaceID_None,
-                        nsGkAtoms::aria_activedescendant, id)) {
+      mContent->IsElement() &&
+      mContent->AsElement()->GetAttr(kNameSpaceID_None,
+                                     nsGkAtoms::aria_activedescendant, id)) {
     nsIDocument* DOMDoc = mContent->OwnerDoc();
     dom::Element* activeDescendantElm = DOMDoc->GetElementById(id);
     if (activeDescendantElm) {
       DocAccessible* document = Document();
       if (document)
         return document->GetAccessible(activeDescendantElm);
     }
   }
@@ -2585,18 +2598,19 @@ Accessible::SetCurrentItem(Accessible* a
 
 Accessible*
 Accessible::ContainerWidget() const
 {
   if (HasARIARole() && mContent->HasID()) {
     for (Accessible* parent = Parent(); parent; parent = parent->Parent()) {
       nsIContent* parentContent = parent->GetContent();
       if (parentContent &&
-        parentContent->HasAttr(kNameSpaceID_None,
-                               nsGkAtoms::aria_activedescendant)) {
+          parentContent->IsElement() &&
+          parentContent->AsElement()->HasAttr(kNameSpaceID_None,
+                                              nsGkAtoms::aria_activedescendant)) {
         return parent;
       }
 
       // Don't cross DOM document boundaries.
       if (parent->IsDoc())
         break;
     }
   }
@@ -2659,33 +2673,34 @@ Accessible::GetSiblingAtOffset(int32_t a
 double
 Accessible::AttrNumericValue(nsAtom* aAttr) const
 {
   const nsRoleMapEntry* roleMapEntry = ARIARoleMap();
   if (!roleMapEntry || roleMapEntry->valueRule == eNoValue)
     return UnspecifiedNaN<double>();
 
   nsAutoString attrValue;
-  if (!mContent->GetAttr(kNameSpaceID_None, aAttr, attrValue))
+  if (!mContent->IsElement() ||
+      !mContent->AsElement()->GetAttr(kNameSpaceID_None, aAttr, attrValue))
     return UnspecifiedNaN<double>();
 
   nsresult error = NS_OK;
   double value = attrValue.ToDouble(&error);
   return NS_FAILED(error) ? UnspecifiedNaN<double>() : value;
 }
 
 uint32_t
 Accessible::GetActionRule() const
 {
   if (!HasOwnContent() || (InteractiveState() & states::UNAVAILABLE))
     return eNoAction;
 
   // Return "click" action on elements that have an attached popup menu.
   if (mContent->IsXULElement())
-    if (mContent->HasAttr(kNameSpaceID_None, nsGkAtoms::popup))
+    if (mContent->AsElement()->HasAttr(kNameSpaceID_None, nsGkAtoms::popup))
       return eClickAction;
 
   // Has registered 'click' event handler.
   bool isOnclick = nsCoreUtils::HasClickListener(mContent);
 
   if (isOnclick)
     return eClickAction;
 
--- a/accessible/generic/DocAccessible.cpp
+++ b/accessible/generic/DocAccessible.cpp
@@ -18,17 +18,16 @@
 #include "RootAccessible.h"
 #include "TreeWalker.h"
 #include "xpcAccessibleDocument.h"
 
 #include "nsIMutableArray.h"
 #include "nsICommandManager.h"
 #include "nsIDocShell.h"
 #include "nsIDocument.h"
-#include "nsIDOMAttr.h"
 #include "nsIDOMCharacterData.h"
 #include "nsIDOMDocument.h"
 #include "nsIDOMXULDocument.h"
 #include "nsIDOMMutationEvent.h"
 #include "nsPIDOMWindow.h"
 #include "nsIEditingSession.h"
 #include "nsIFrame.h"
 #include "nsIInterfaceRequestorUtils.h"
@@ -870,17 +869,17 @@ DocAccessible::AttributeChangedImpl(Acce
     return;
   }
 
   if (aAttribute == nsGkAtoms::aria_describedby) {
     FireDelayedEvent(nsIAccessibleEvent::EVENT_DESCRIPTION_CHANGE, aAccessible);
     return;
   }
 
-  nsIContent* elm = aAccessible->GetContent();
+  dom::Element* elm = aAccessible->GetContent()->AsElement();
   if (aAttribute == nsGkAtoms::aria_labelledby &&
       !elm->HasAttr(kNameSpaceID_None, nsGkAtoms::aria_label)) {
     FireDelayedEvent(nsIAccessibleEvent::EVENT_NAME_CHANGE, aAccessible);
     return;
   }
 
   if (aAttribute == nsGkAtoms::alt &&
       !elm->HasAttr(kNameSpaceID_None, nsGkAtoms::aria_label) &&
@@ -991,17 +990,17 @@ DocAccessible::ARIAAttributeChanged(Acce
   // change event; at least until native API comes up with a more meaningful event.
   uint8_t attrFlags = aria::AttrCharacteristicsFor(aAttribute);
   if (!(attrFlags & ATTR_BYPASSOBJ)) {
     RefPtr<AccEvent> event =
       new AccObjectAttrChangedEvent(aAccessible, aAttribute);
     FireDelayedEvent(event);
   }
 
-  nsIContent* elm = aAccessible->GetContent();
+  dom::Element* elm = aAccessible->GetContent()->AsElement();
 
   // Update aria-hidden flag for the whole subtree iff aria-hidden is changed
   // on the root, i.e. ignore any affiliated aria-hidden changes in the subtree
   // of top aria-hidden.
   if (aAttribute == nsGkAtoms::aria_hidden) {
     bool isDefined = aria::HasDefinedARIAHidden(elm);
     if (isDefined != aAccessible->IsARIAHidden() &&
         (!aAccessible->Parent() || !aAccessible->Parent()->IsARIAHidden())) {
@@ -1067,19 +1066,21 @@ DocAccessible::ARIAAttributeChanged(Acce
     mNotificationController->ScheduleRelocation(aAccessible);
   }
 }
 
 void
 DocAccessible::ARIAActiveDescendantChanged(Accessible* aAccessible)
 {
   nsIContent* elm = aAccessible->GetContent();
-  if (elm && aAccessible->IsActiveWidget()) {
+  if (elm && elm->IsElement() && aAccessible->IsActiveWidget()) {
     nsAutoString id;
-    if (elm->GetAttr(kNameSpaceID_None, nsGkAtoms::aria_activedescendant, id)) {
+    if (elm->AsElement()->GetAttr(kNameSpaceID_None,
+                                  nsGkAtoms::aria_activedescendant,
+                                  id)) {
       dom::Element* activeDescendantElm = elm->OwnerDoc()->GetElementById(id);
       if (activeDescendantElm) {
         Accessible* activeDescendant = GetAccessible(activeDescendantElm);
         if (activeDescendant) {
           FocusMgr()->ActiveItemChanged(activeDescendant, false);
 #ifdef A11Y_LOG
           if (logging::IsEnabled(logging::eFocus))
             logging::ActiveItemChangeCausedBy("ARIA activedescedant changed",
@@ -1244,36 +1245,24 @@ DocAccessible::GetAccessibleByUniqueIDIn
 }
 
 Accessible*
 DocAccessible::GetAccessibleOrContainer(nsINode* aNode) const
 {
   if (!aNode || !aNode->GetComposedDoc())
     return nullptr;
 
-  nsINode* currNode = aNode;
-  Accessible* accessible = nullptr;
-  while (!(accessible = GetAccessible(currNode))) {
-    nsINode* parent = nullptr;
-
-    // If this is a content node, try to get a flattened parent content node.
-    // This will smartly skip from the shadow root to the host element,
-    // over parentless document fragment
-    if (currNode->IsContent())
-      parent = currNode->AsContent()->GetFlattenedTreeParent();
-
-    // Fallback to just get parent node, in case there is no parent content
-    // node. Or current node is not a content node.
-    if (!parent)
-      parent = currNode->GetParentNode();
-
-    if (!(currNode = parent)) break;
+  for (nsINode* currNode = aNode; currNode;
+       currNode = currNode->GetFlattenedTreeParentNode()) {
+    if (Accessible* accessible = GetAccessible(currNode)) {
+      return accessible;
+    }
   }
 
-  return accessible;
+  return nullptr;
 }
 
 Accessible*
 DocAccessible::GetAccessibleOrDescendant(nsINode* aNode) const
 {
   Accessible* acc = GetAccessible(aNode);
   if (acc)
     return acc;
@@ -1306,18 +1295,19 @@ DocAccessible::BindToDocument(Accessible
   // Put into unique ID cache.
   mAccessibleCache.Put(aAccessible->UniqueID(), aAccessible);
 
   aAccessible->SetRoleMapEntry(aRoleMapEntry);
 
   if (aAccessible->HasOwnContent()) {
     AddDependentIDsFor(aAccessible);
 
-    nsIContent* el = aAccessible->GetContent();
-    if (el->HasAttr(kNameSpaceID_None, nsGkAtoms::aria_owns)) {
+    nsIContent* content = aAccessible->GetContent();
+    if (content->IsElement() &&
+        content->AsElement()->HasAttr(kNameSpaceID_None, nsGkAtoms::aria_owns)) {
       mNotificationController->ScheduleRelocation(aAccessible);
     }
   }
 }
 
 void
 DocAccessible::UnbindFromDocument(Accessible* aAccessible)
 {
@@ -1848,16 +1838,17 @@ InsertIterator::Next()
         return true;
       }
     }
     else {
       TreeWalker finder(container);
       if (finder.Seek(node)) {
         mChild = mWalker.Scope(node);
         if (mChild) {
+          MOZ_ASSERT(!mChild->IsRelocated(), "child cannot be aria owned");
           mChildBefore = finder.Prev();
           return true;
         }
       }
     }
   }
 
   return false;
@@ -2207,17 +2198,18 @@ DocAccessible::PutChildrenBack(nsTArray<
                       "old parent", owner, "child", child, nullptr);
 #endif
 
     // Unset relocated flag to find an insertion point for the child.
     child->SetRelocated(false);
 
     nsIContent* content = child->GetContent();
     int32_t idxInParent = -1;
-    Accessible* origContainer = AccessibleOrTrueContainer(content->GetParentNode());
+    Accessible* origContainer =
+      AccessibleOrTrueContainer(content->GetFlattenedTreeParentNode());
     if (origContainer) {
       TreeWalker walker(origContainer);
       if (walker.Seek(content)) {
         Accessible* prevChild = walker.Prev();
         if (prevChild) {
           idxInParent = prevChild->IndexInParent() + 1;
           MOZ_DIAGNOSTIC_ASSERT(origContainer == prevChild->Parent(), "Broken tree");
           origContainer = prevChild->Parent();
--- a/accessible/generic/FormControlAccessible.cpp
+++ b/accessible/generic/FormControlAccessible.cpp
@@ -35,17 +35,17 @@ ProgressMeterAccessible<Max>::NativeRole
 template<int Max>
 uint64_t
 ProgressMeterAccessible<Max>::NativeState()
 {
   uint64_t state = LeafAccessible::NativeState();
 
   // An undetermined progressbar (i.e. without a value) has a mixed state.
   nsAutoString attrValue;
-  mContent->GetAttr(kNameSpaceID_None, nsGkAtoms::value, attrValue);
+  mContent->AsElement()->GetAttr(kNameSpaceID_None, nsGkAtoms::value, attrValue);
 
   if (attrValue.IsEmpty())
     state |= states::MIXED;
 
   return state;
 }
 
 ////////////////////////////////////////////////////////////////////////////////
@@ -89,17 +89,17 @@ template<int Max>
 double
 ProgressMeterAccessible<Max>::MaxValue() const
 {
   double value = LeafAccessible::MaxValue();
   if (!IsNaN(value))
     return value;
 
   nsAutoString strValue;
-  if (mContent->GetAttr(kNameSpaceID_None, nsGkAtoms::max, strValue)) {
+  if (mContent->AsElement()->GetAttr(kNameSpaceID_None, nsGkAtoms::max, strValue)) {
     nsresult result = NS_OK;
     value = strValue.ToDouble(&result);
     if (NS_SUCCEEDED(result))
       return value;
   }
 
   return Max;
 }
@@ -124,17 +124,17 @@ template<int Max>
 double
 ProgressMeterAccessible<Max>::CurValue() const
 {
   double value = LeafAccessible::CurValue();
   if (!IsNaN(value))
     return value;
 
   nsAutoString attrValue;
-  if (!mContent->GetAttr(kNameSpaceID_None, nsGkAtoms::value, attrValue))
+  if (!mContent->AsElement()->GetAttr(kNameSpaceID_None, nsGkAtoms::value, attrValue))
     return UnspecifiedNaN<double>();
 
   nsresult error = NS_OK;
   value = attrValue.ToDouble(&error);
   return NS_FAILED(error) ? UnspecifiedNaN<double>() : value;
 }
 
 template<int Max>
--- a/accessible/generic/HyperTextAccessible.cpp
+++ b/accessible/generic/HyperTextAccessible.cpp
@@ -136,18 +136,18 @@ HyperTextAccessible::GetBoundsInFrame(ns
     rv = frame->GetPointFromOffset(startContentOffset, &frameTextStartPoint);
     NS_ENSURE_SUCCESS(rv, nsIntRect());
 
     // Use the point for the end offset to calculate the width
     nsPoint frameTextEndPoint;
     rv = frame->GetPointFromOffset(startContentOffset + frameSubStringLength, &frameTextEndPoint);
     NS_ENSURE_SUCCESS(rv, nsIntRect());
 
-    frameScreenRect.x += std::min(frameTextStartPoint.x, frameTextEndPoint.x);
-    frameScreenRect.width = mozilla::Abs(frameTextStartPoint.x - frameTextEndPoint.x);
+    frameScreenRect.SetRectX(frameScreenRect.X() + std::min(frameTextStartPoint.x, frameTextEndPoint.x),
+                             mozilla::Abs(frameTextStartPoint.x - frameTextEndPoint.x));
 
     screenRect.UnionRect(frameScreenRect, screenRect);
 
     // Get ready to loop back for next frame continuation
     startContentOffset += frameSubStringLength;
     startContentOffsetInFrame = 0;
     frame = frame->GetNextContinuation();
   }
@@ -237,17 +237,17 @@ HyperTextAccessible::DOMPointToOffset(ns
     // findNode could be null if aNodeOffset == # of child nodes, which means
     // one of two things:
     // 1) there are no children, and the passed-in node is not mContent -- use
     //    parentContent for the node to find
     // 2) there are no children and the passed-in node is mContent, which means
     //    we're an empty nsIAccessibleText
     // 3) there are children and we're at the end of the children
 
-    findNode = aNode->GetChildAt(aNodeOffset);
+    findNode = aNode->GetChildAt_Deprecated(aNodeOffset);
     if (!findNode) {
       if (aNodeOffset == 0) {
         if (aNode == GetNode()) {
           // Case #1: this accessible has no children and thus has empty text,
           // we can only be at hypertext offset 0.
           return 0;
         }
 
@@ -264,22 +264,21 @@ HyperTextAccessible::DOMPointToOffset(ns
     }
   }
 
   // Get accessible for this findNode, or if that node isn't accessible, use the
   // accessible for the next DOM node which has one (based on forward depth first search)
   Accessible* descendant = nullptr;
   if (findNode) {
     nsCOMPtr<nsIContent> findContent(do_QueryInterface(findNode));
-    if (findContent && findContent->IsHTMLElement() &&
-        findContent->NodeInfo()->Equals(nsGkAtoms::br) &&
-        findContent->AttrValueIs(kNameSpaceID_None,
-                                 nsGkAtoms::mozeditorbogusnode,
-                                 nsGkAtoms::_true,
-                                 eIgnoreCase)) {
+    if (findContent && findContent->IsHTMLElement(nsGkAtoms::br) &&
+        findContent->AsElement()->AttrValueIs(kNameSpaceID_None,
+                                              nsGkAtoms::mozeditorbogusnode,
+                                              nsGkAtoms::_true,
+                                              eIgnoreCase)) {
       // This <br> is the hacky "bogus node" used when there is no text in a control
       return 0;
     }
 
     descendant = mDoc->GetAccessible(findNode);
     if (!descendant && findNode->IsContent()) {
       Accessible* container = mDoc->GetContainerAccessible(findNode);
       if (container) {
@@ -424,17 +423,17 @@ HyperTextAccessible::OffsetToDOMPoint(in
     innerOffset = 1;
   }
 
   // Case of embedded object. The point is either before or after the element.
   NS_ASSERTION(innerOffset == 0 || innerOffset == 1, "A wrong inner offset!");
   nsINode* node = child->GetNode();
   nsINode* parentNode = node->GetParentNode();
   return parentNode ?
-    DOMPoint(parentNode, parentNode->IndexOf(node) + innerOffset) :
+    DOMPoint(parentNode, parentNode->ComputeIndexOf(node) + innerOffset) :
     DOMPoint();
 }
 
 DOMPoint
 HyperTextAccessible::ClosestNotGeneratedDOMPoint(const DOMPoint& aDOMPoint,
                                                  nsIContent* aElementContent)
 {
   MOZ_ASSERT(aDOMPoint.node, "The node must not be null");
@@ -1173,18 +1172,18 @@ HyperTextAccessible::OffsetAtPoint(int32
   nsPresContext* presContext = mDoc->PresContext();
   nsPoint coordsInAppUnits =
     ToAppUnits(coords, presContext->AppUnitsPerDevPixel());
 
   nsRect frameScreenRect = hyperFrame->GetScreenRectInAppUnits();
   if (!frameScreenRect.Contains(coordsInAppUnits.x, coordsInAppUnits.y))
     return -1; // Not found
 
-  nsPoint pointInHyperText(coordsInAppUnits.x - frameScreenRect.x,
-                           coordsInAppUnits.y - frameScreenRect.y);
+  nsPoint pointInHyperText(coordsInAppUnits.x - frameScreenRect.X(),
+                           coordsInAppUnits.y - frameScreenRect.Y());
 
   // Go through the frames to check if each one has the point.
   // When one does, add up the character offsets until we have a match
 
   // We have an point in an accessible child of this, now we need to add up the
   // offsets before it to what we already have
   int32_t offset = 0;
   uint32_t childCount = ChildCount();
@@ -1263,17 +1262,20 @@ HyperTextAccessible::TextBounds(int32_t 
 
     bounds.UnionRect(bounds, GetBoundsInFrame(frame, offset1,
                                               nextOffset - prevOffset));
 
     prevOffset = nextOffset;
     offset1 = 0;
   }
 
-  nsAccUtils::ConvertScreenCoordsTo(&bounds.x, &bounds.y, aCoordType, this);
+  auto boundsX = bounds.X();
+  auto boundsY = bounds.Y();
+  nsAccUtils::ConvertScreenCoordsTo(&boundsX, &boundsY, aCoordType, this);
+  bounds.MoveTo(boundsX, boundsY);
   return bounds;
 }
 
 already_AddRefed<TextEditor>
 HyperTextAccessible::GetEditor() const
 {
   if (!mContent->HasFlag(NODE_IS_EDITABLE)) {
     // If we're inside an editable container, then return that container's editor
@@ -1518,18 +1520,17 @@ HyperTextAccessible::GetCaretRect(nsIWid
 
   // Correct for character size, so that caret always matches the size of
   // the character. This is important for font size transitions, and is
   // necessary because the Gecko caret uses the previous character's size as
   // the user moves forward in the text by character.
   nsIntRect charRect = CharBounds(CaretOffset(),
                                   nsIAccessibleCoordinateType::COORDTYPE_SCREEN_RELATIVE);
   if (!charRect.IsEmpty()) {
-    caretRect.height -= charRect.y - caretRect.y;
-    caretRect.y = charRect.y;
+    caretRect.SetTopEdge(charRect.Y());
   }
   return caretRect;
 }
 
 void
 HyperTextAccessible::GetSelectionDOMRanges(SelectionType aSelectionType,
                                            nsTArray<nsRange*>* aRanges)
 {
@@ -1710,18 +1711,18 @@ HyperTextAccessible::ScrollSubstringToPo
   nsIFrame *parentFrame = frame;
   while ((parentFrame = parentFrame->GetParent())) {
     nsIScrollableFrame *scrollableFrame = do_QueryFrame(parentFrame);
     if (scrollableFrame) {
       if (!initialScrolled) {
         // Scroll substring to the given point. Turn the point into percents
         // relative scrollable area to use nsCoreUtils::ScrollSubstringTo.
         nsRect frameRect = parentFrame->GetScreenRectInAppUnits();
-        nscoord offsetPointX = coordsInAppUnits.x - frameRect.x;
-        nscoord offsetPointY = coordsInAppUnits.y - frameRect.y;
+        nscoord offsetPointX = coordsInAppUnits.x - frameRect.X();
+        nscoord offsetPointY = coordsInAppUnits.y - frameRect.Y();
 
         nsSize size(parentFrame->GetSize());
 
         // avoid divide by zero
         size.width = size.width ? size.width : 1;
         size.height = size.height ? size.height : 1;
 
         int16_t hPercent = offsetPointX * 100 / size.width;
@@ -1847,30 +1848,31 @@ HyperTextAccessible::RangeAtPoint(int32_
 
 // Accessible protected
 ENameValueFlag
 HyperTextAccessible::NativeName(nsString& aName)
 {
   // Check @alt attribute for invalid img elements.
   bool hasImgAlt = false;
   if (mContent->IsHTMLElement(nsGkAtoms::img)) {
-    hasImgAlt = mContent->GetAttr(kNameSpaceID_None, nsGkAtoms::alt, aName);
+    hasImgAlt =
+      mContent->AsElement()->GetAttr(kNameSpaceID_None, nsGkAtoms::alt, aName);
     if (!aName.IsEmpty())
       return eNameOK;
   }
 
   ENameValueFlag nameFlag = AccessibleWrap::NativeName(aName);
   if (!aName.IsEmpty())
     return nameFlag;
 
   // Get name from title attribute for HTML abbr and acronym elements making it
   // a valid name from markup. Otherwise their name isn't picked up by recursive
   // name computation algorithm. See NS_OK_NAME_FROM_TOOLTIP.
   if (IsAbbreviation() &&
-      mContent->GetAttr(kNameSpaceID_None, nsGkAtoms::title, aName))
+      mContent->AsElement()->GetAttr(kNameSpaceID_None, nsGkAtoms::title, aName))
     aName.CompressWhitespace();
 
   return hasImgAlt ? eNoNameOnPurpose : eNameOK;
 }
 
 void
 HyperTextAccessible::Shutdown()
 {
@@ -2074,17 +2076,17 @@ HyperTextAccessible::GetDOMPointByFrameO
     NS_ASSERTION(!aAccessible->IsDoc(),
                  "Shouldn't be called on document accessible!");
 
     nsIContent* content = aAccessible->GetContent();
     NS_ASSERTION(content, "Shouldn't operate on defunct accessible!");
 
     nsIContent* parent = content->GetParent();
 
-    aPoint->idx = parent->IndexOf(content) + 1;
+    aPoint->idx = parent->ComputeIndexOf(content) + 1;
     aPoint->node = parent;
 
   } else if (aFrame->IsTextFrame()) {
     nsIContent* content = aFrame->GetContent();
     NS_ENSURE_STATE(content);
 
     nsIFrame *primaryFrame = content->GetPrimaryFrame();
     nsresult rv = RenderedToContentOffset(primaryFrame, aOffset, &(aPoint->idx));
@@ -2094,17 +2096,17 @@ HyperTextAccessible::GetDOMPointByFrameO
 
   } else {
     nsIContent* content = aFrame->GetContent();
     NS_ENSURE_STATE(content);
 
     nsIContent* parent = content->GetParent();
     NS_ENSURE_STATE(parent);
 
-    aPoint->idx = parent->IndexOf(content);
+    aPoint->idx = parent->ComputeIndexOf(content);
     aPoint->node = parent;
   }
 
   return NS_OK;
 }
 
 // HyperTextAccessible
 void
--- a/accessible/generic/ImageAccessible.cpp
+++ b/accessible/generic/ImageAccessible.cpp
@@ -69,17 +69,17 @@ ImageAccessible::NativeState()
 
   return state;
 }
 
 ENameValueFlag
 ImageAccessible::NativeName(nsString& aName)
 {
   bool hasAltAttrib =
-    mContent->GetAttr(kNameSpaceID_None, nsGkAtoms::alt, aName);
+    mContent->AsElement()->GetAttr(kNameSpaceID_None, nsGkAtoms::alt, aName);
   if (!aName.IsEmpty())
     return eNameOK;
 
   ENameValueFlag nameFlag = Accessible::NativeName(aName);
   if (!aName.IsEmpty())
     return nameFlag;
 
   // No accessible name but empty 'alt' attribute is present. If further name
@@ -143,52 +143,52 @@ ImageAccessible::DoAction(uint8_t aIndex
 }
 
 ////////////////////////////////////////////////////////////////////////////////
 // ImageAccessible
 
 nsIntPoint
 ImageAccessible::Position(uint32_t aCoordType)
 {
-  nsIntRect rect = Bounds();
-  nsAccUtils::ConvertScreenCoordsTo(&rect.x, &rect.y, aCoordType, this);
-  return rect.TopLeft();
+  nsIntPoint point = Bounds().TopLeft();
+  nsAccUtils::ConvertScreenCoordsTo(&point.x, &point.y, aCoordType, this);
+  return point;
 }
 
 nsIntSize
 ImageAccessible::Size()
 {
   return Bounds().Size();
 }
 
 // Accessible
 already_AddRefed<nsIPersistentProperties>
 ImageAccessible::NativeAttributes()
 {
   nsCOMPtr<nsIPersistentProperties> attributes =
     LinkableAccessible::NativeAttributes();
 
   nsAutoString src;
-  mContent->GetAttr(kNameSpaceID_None, nsGkAtoms::src, src);
+  mContent->AsElement()->GetAttr(kNameSpaceID_None, nsGkAtoms::src, src);
   if (!src.IsEmpty())
     nsAccUtils::SetAccAttr(attributes, nsGkAtoms::src, src);
 
   return attributes.forget();
 }
 
 ////////////////////////////////////////////////////////////////////////////////
 // Private methods
 
 already_AddRefed<nsIURI>
 ImageAccessible::GetLongDescURI() const
 {
-  if (mContent->HasAttr(kNameSpaceID_None, nsGkAtoms::longdesc)) {
+  if (mContent->AsElement()->HasAttr(kNameSpaceID_None, nsGkAtoms::longdesc)) {
     // To check if longdesc contains an invalid url.
     nsAutoString longdesc;
-    mContent->GetAttr(kNameSpaceID_None, nsGkAtoms::longdesc, longdesc);
+    mContent->AsElement()->GetAttr(kNameSpaceID_None, nsGkAtoms::longdesc, longdesc);
     if (longdesc.FindChar(' ') != -1 || longdesc.FindChar('\t') != -1 ||
         longdesc.FindChar('\r') != -1 || longdesc.FindChar('\n') != -1) {
       return nullptr;
     }
     nsCOMPtr<nsIURI> baseURI = mContent->GetBaseURI();
     nsCOMPtr<nsIURI> uri;
     nsContentUtils::NewURIWithDocumentCharset(getter_AddRefs(uri), longdesc,
                                               mContent->OwnerDoc(), baseURI);
@@ -196,17 +196,17 @@ ImageAccessible::GetLongDescURI() const
   }
 
   DocAccessible* document = Document();
   if (document) {
     IDRefsIterator iter(document, mContent, nsGkAtoms::aria_describedby);
     while (nsIContent* target = iter.NextElem()) {
       if ((target->IsHTMLElement(nsGkAtoms::a) ||
            target->IsHTMLElement(nsGkAtoms::area)) &&
-          target->HasAttr(kNameSpaceID_None, nsGkAtoms::href)) {
+          target->AsElement()->HasAttr(kNameSpaceID_None, nsGkAtoms::href)) {
         nsGenericHTMLElement* element =
           nsGenericHTMLElement::FromContent(target);
 
         nsCOMPtr<nsIURI> uri;
         element->GetURIAttr(nsGkAtoms::href, nullptr, getter_AddRefs(uri));
         return uri.forget();
       }
     }
--- a/accessible/generic/OuterDocAccessible.cpp
+++ b/accessible/generic/OuterDocAccessible.cpp
@@ -65,18 +65,17 @@ OuterDocAccessible::NativeRole()
   return roles::INTERNAL_FRAME;
 }
 
 Accessible*
 OuterDocAccessible::ChildAtPoint(int32_t aX, int32_t aY,
                                  EWhichChildAtPoint aWhichChild)
 {
   nsIntRect docRect = Bounds();
-  if (aX < docRect.x || aX >= docRect.x + docRect.width ||
-      aY < docRect.y || aY >= docRect.y + docRect.height)
+  if (!docRect.Contains(aX, aY))
     return nullptr;
 
   // Always return the inner doc as direct child accessible unless bounds
   // outside of it.
   Accessible* child = GetChildAt(0);
   NS_ENSURE_TRUE(child, nullptr);
 
   if (aWhichChild == eDeepestChild)
--- a/accessible/html/HTMLFormControlAccessible.cpp
+++ b/accessible/html/HTMLFormControlAccessible.cpp
@@ -126,19 +126,19 @@ void
 HTMLRadioButtonAccessible::GetPositionAndSizeInternal(int32_t* aPosInSet,
                                                       int32_t* aSetSize)
 {
   int32_t namespaceId = mContent->NodeInfo()->NamespaceID();
   nsAutoString tagName;
   mContent->NodeInfo()->GetName(tagName);
 
   nsAutoString type;
-  mContent->GetAttr(kNameSpaceID_None, nsGkAtoms::type, type);
+  mContent->AsElement()->GetAttr(kNameSpaceID_None, nsGkAtoms::type, type);
   nsAutoString name;
-  mContent->GetAttr(kNameSpaceID_None, nsGkAtoms::name, name);
+  mContent->AsElement()->GetAttr(kNameSpaceID_None, nsGkAtoms::name, name);
 
   RefPtr<nsContentList> inputElms;
 
   nsCOMPtr<nsIFormControl> formControlNode(do_QueryInterface(mContent));
   dom::Element* formElm = formControlNode->GetFormElement();
   if (formElm)
     inputElms = NS_GetContentList(formElm, namespaceId, tagName);
   else
@@ -148,20 +148,21 @@ HTMLRadioButtonAccessible::GetPositionAn
   uint32_t inputCount = inputElms->Length(false);
 
   // Compute posinset and setsize.
   int32_t indexOf = 0;
   int32_t count = 0;
 
   for (uint32_t index = 0; index < inputCount; index++) {
     nsIContent* inputElm = inputElms->Item(index, false);
-    if (inputElm->AttrValueIs(kNameSpaceID_None, nsGkAtoms::type,
-                              type, eCaseMatters) &&
-        inputElm->AttrValueIs(kNameSpaceID_None, nsGkAtoms::name,
-                              name, eCaseMatters) && mDoc->HasAccessible(inputElm)) {
+    if (inputElm->AsElement()->AttrValueIs(kNameSpaceID_None, nsGkAtoms::type,
+                                           type, eCaseMatters) &&
+        inputElm->AsElement()->AttrValueIs(kNameSpaceID_None, nsGkAtoms::name,
+                                           name, eCaseMatters) &&
+        mDoc->HasAccessible(inputElm)) {
         count++;
       if (inputElm == mContent)
         indexOf = count;
     }
   }
 
   *aPosInSet = indexOf;
   *aSetSize = count;
@@ -247,22 +248,22 @@ HTMLButtonAccessible::NativeName(nsStrin
   // element that has no valid @src (note if input@type="image" has an image
   // then neither @alt nor @value attributes are used to generate a visual label
   // and thus we need to obtain the accessible name directly from attribute
   // value). Also the same algorithm works in case of default labels for
   // type="submit"/"reset"/"image" elements.
 
   ENameValueFlag nameFlag = Accessible::NativeName(aName);
   if (!aName.IsEmpty() || !mContent->IsHTMLElement(nsGkAtoms::input) ||
-      !mContent->AttrValueIs(kNameSpaceID_None, nsGkAtoms::type,
-                             nsGkAtoms::image, eCaseMatters))
+      !mContent->AsElement()->AttrValueIs(kNameSpaceID_None, nsGkAtoms::type,
+                                          nsGkAtoms::image, eCaseMatters))
     return nameFlag;
 
-  if (!mContent->GetAttr(kNameSpaceID_None, nsGkAtoms::alt, aName))
-    mContent->GetAttr(kNameSpaceID_None, nsGkAtoms::value, aName);
+  if (!mContent->AsElement()->GetAttr(kNameSpaceID_None, nsGkAtoms::alt, aName))
+    mContent->AsElement()->GetAttr(kNameSpaceID_None, nsGkAtoms::value, aName);
 
   aName.CompressWhitespace();
   return eNameOK;
 }
 
 ////////////////////////////////////////////////////////////////////////////////
 // HTMLButtonAccessible: Widgets
 
@@ -285,34 +286,34 @@ HTMLTextFieldAccessible::
 }
 
 NS_IMPL_ISUPPORTS_INHERITED0(HTMLTextFieldAccessible,
                              HyperTextAccessible)
 
 role
 HTMLTextFieldAccessible::NativeRole()
 {
-  if (mContent->AttrValueIs(kNameSpaceID_None, nsGkAtoms::type,
-                            nsGkAtoms::password, eIgnoreCase)) {
+  if (mContent->AsElement()->AttrValueIs(kNameSpaceID_None, nsGkAtoms::type,
+                                         nsGkAtoms::password, eIgnoreCase)) {
     return roles::PASSWORD_TEXT;
   }
 
   return roles::ENTRY;
 }
 
 already_AddRefed<nsIPersistentProperties>
 HTMLTextFieldAccessible::NativeAttributes()
 {
   nsCOMPtr<nsIPersistentProperties> attributes =
     HyperTextAccessibleWrap::NativeAttributes();
 
   // Expose type for text input elements as it gives some useful context,
   // especially for mobile.
   nsAutoString type;
-  if (mContent->GetAttr(kNameSpaceID_None, nsGkAtoms::type, type)) {
+  if (mContent->AsElement()->GetAttr(kNameSpaceID_None, nsGkAtoms::type, type)) {
     nsAccUtils::SetAccAttr(attributes, nsGkAtoms::textInputType, type);
     if (!ARIARoleMap() && type.EqualsLiteral("search")) {
       nsAccUtils::SetAccAttr(attributes, nsGkAtoms::xmlroles,
                              NS_LITERAL_STRING("searchbox"));
     }
   }
 
   return attributes.forget();
@@ -329,17 +330,17 @@ HTMLTextFieldAccessible::NativeName(nsSt
   nsIContent* widgetElm = XULWidgetElm();
   if (widgetElm)
     XULElmName(mDoc, widgetElm, aName);
 
   if (!aName.IsEmpty())
     return eNameOK;
 
   // text inputs and textareas might have useful placeholder text
-  mContent->GetAttr(kNameSpaceID_None, nsGkAtoms::placeholder, aName);
+  mContent->AsElement()->GetAttr(kNameSpaceID_None, nsGkAtoms::placeholder, aName);
   return eNameOK;
 }
 
 void
 HTMLTextFieldAccessible::Value(nsString& aValue)
 {
   aValue.Truncate();
   if (NativeState() & states::PROTECTED)    // Don't return password text!
@@ -377,22 +378,22 @@ HTMLTextFieldAccessible::NativeState()
 {
   uint64_t state = HyperTextAccessibleWrap::NativeState();
 
   // Text fields are always editable, even if they are also read only or
   // disabled.
   state |= states::EDITABLE;
 
   // can be focusable, focused, protected. readonly, unavailable, selected
-  if (mContent->AttrValueIs(kNameSpaceID_None, nsGkAtoms::type,
-                            nsGkAtoms::password, eIgnoreCase)) {
+  if (mContent->AsElement()->AttrValueIs(kNameSpaceID_None, nsGkAtoms::type,
+                                         nsGkAtoms::password, eIgnoreCase)) {
     state |= states::PROTECTED;
   }
 
-  if (mContent->HasAttr(kNameSpaceID_None, nsGkAtoms::readonly)) {
+  if (mContent->AsElement()->HasAttr(kNameSpaceID_None, nsGkAtoms::readonly)) {
     state |= states::READONLY;
   }
 
   // Is it an <input> or a <textarea> ?
   HTMLInputElement* input = HTMLInputElement::FromContent(mContent);
   state |= input && input->IsSingleLineTextControl() ?
     states::SINGLE_LINE : states::MULTI_LINE;
 
@@ -403,38 +404,38 @@ HTMLTextFieldAccessible::NativeState()
   // Expose autocomplete states if this input is part of autocomplete widget.
   Accessible* widget = ContainerWidget();
   if (widget && widget-IsAutoComplete()) {
     state |= states::HASPOPUP | states::SUPPORTS_AUTOCOMPLETION;
     return state;
   }
 
   // Expose autocomplete state if it has associated autocomplete list.
-  if (mContent->HasAttr(kNameSpaceID_None, nsGkAtoms::list))
+  if (mContent->AsElement()->HasAttr(kNameSpaceID_None, nsGkAtoms::list))
     return state | states::SUPPORTS_AUTOCOMPLETION | states::HASPOPUP;
 
   // Ordinal XUL textboxes don't support autocomplete.
   if (!XULWidgetElm() && Preferences::GetBool("browser.formfill.enable")) {
     // Check to see if autocompletion is allowed on this input. We don't expose
     // it for password fields even though the entire password can be remembered
     // for a page if the user asks it to be. However, the kind of autocomplete
     // we're talking here is based on what the user types, where a popup of
     // possible choices comes up.
     nsAutoString autocomplete;
-    mContent->GetAttr(kNameSpaceID_None, nsGkAtoms::autocomplete,
-                      autocomplete);
+    mContent->AsElement()->GetAttr(kNameSpaceID_None, nsGkAtoms::autocomplete,
+                                   autocomplete);
 
     if (!autocomplete.LowerCaseEqualsLiteral("off")) {
-      nsIContent* formContent = input->GetFormElement();
-      if (formContent) {
-        formContent->GetAttr(kNameSpaceID_None,
+      Element* formElement = input->GetFormElement();
+      if (formElement) {
+        formElement->GetAttr(kNameSpaceID_None,
                              nsGkAtoms::autocomplete, autocomplete);
       }
 
-      if (!formContent || !autocomplete.LowerCaseEqualsLiteral("off"))
+      if (!formElement || !autocomplete.LowerCaseEqualsLiteral("off"))
         state |= states::SUPPORTS_AUTOCOMPLETION;
     }
   }
 
   return state;
 }
 
 uint8_t
--- a/accessible/html/HTMLImageMapAccessible.cpp
+++ b/accessible/html/HTMLImageMapAccessible.cpp
@@ -150,29 +150,30 @@ HTMLAreaAccessible::
 
 ENameValueFlag
 HTMLAreaAccessible::NativeName(nsString& aName)
 {
   ENameValueFlag nameFlag = Accessible::NativeName(aName);
   if (!aName.IsEmpty())
     return nameFlag;
 
-  if (!mContent->GetAttr(kNameSpaceID_None, nsGkAtoms::alt, aName))
+  if (!mContent->AsElement()->GetAttr(kNameSpaceID_None, nsGkAtoms::alt, aName))
     Value(aName);
 
   return eNameOK;
 }
 
 void
 HTMLAreaAccessible::Description(nsString& aDescription)
 {
   aDescription.Truncate();
 
   // Still to do - follow IE's standard here
-  RefPtr<HTMLAreaElement> area = HTMLAreaElement::FromContentOrNull(mContent);
+  RefPtr<dom::HTMLAreaElement> area =
+    dom::HTMLAreaElement::FromContentOrNull(mContent);
   if (area)
     area->GetShape(aDescription);
 }
 
 ////////////////////////////////////////////////////////////////////////////////
 // HTMLAreaAccessible: Accessible public
 
 Accessible*
@@ -216,12 +217,11 @@ HTMLAreaAccessible::RelativeBounds(nsIFr
   nsRect bounds;
   nsresult rv = map->GetBoundsForAreaContent(mContent, bounds);
   if (NS_FAILED(rv))
     return nsRect();
 
   // XXX Areas are screwy; they return their rects as a pair of points, one pair
   // stored into the width and height.
   *aBoundingFrame = frame;
-  bounds.width -= bounds.x;
-  bounds.height -= bounds.y;
+  bounds.SizeTo(bounds.Width() - bounds.X(), bounds.Height() - bounds.Y());
   return bounds;
 }
--- a/accessible/html/HTMLLinkAccessible.cpp
+++ b/accessible/html/HTMLLinkAccessible.cpp
@@ -63,17 +63,17 @@ HTMLLinkAccessible::NativeLinkState() co
 uint64_t
 HTMLLinkAccessible::NativeInteractiveState() const
 {
   uint64_t state = HyperTextAccessibleWrap::NativeInteractiveState();
 
   // This is how we indicate it is a named anchor. In other words, this anchor
   // can be selected as a location :) There is no other better state to use to
   // indicate this.
-  if (mContent->HasAttr(kNameSpaceID_None, nsGkAtoms::name))
+  if (mContent->AsElement()->HasAttr(kNameSpaceID_None, nsGkAtoms::name))
     state |= states::SELECTABLE;
 
   return state;
 }
 
 void
 HTMLLinkAccessible::Value(nsString& aValue)
 {
--- a/accessible/html/HTMLListAccessible.cpp
+++ b/accessible/html/HTMLListAccessible.cpp
@@ -82,18 +82,18 @@ nsIntRect
 HTMLLIAccessible::Bounds() const
 {
   nsIntRect rect = AccessibleWrap::Bounds();
   if (rect.IsEmpty() || !mBullet || mBullet->IsInside())
     return rect;
 
   nsIntRect bulletRect = mBullet->Bounds();
 
-  rect.width += rect.x - bulletRect.x;
-  rect.x = bulletRect.x; // Move x coordinate of list item over to cover bullet as well
+  // Move x coordinate of list item over to cover bullet as well
+  rect.SetLeftEdge(bulletRect.X());
   return rect;
 }
 
 bool
 HTMLLIAccessible::InsertChildAt(uint32_t aIndex, Accessible* aChild)
 {
   // Adjust index if there's a bullet.
   if (mBullet && aIndex == 0 && aChild != mBullet) {
--- a/accessible/html/HTMLSelectAccessible.cpp
+++ b/accessible/html/HTMLSelectAccessible.cpp
@@ -37,17 +37,17 @@ HTMLSelectListAccessible::
 
 ////////////////////////////////////////////////////////////////////////////////
 // HTMLSelectListAccessible: Accessible public
 
 uint64_t
 HTMLSelectListAccessible::NativeState()
 {
   uint64_t state = AccessibleWrap::NativeState();
-  if (mContent->HasAttr(kNameSpaceID_None, nsGkAtoms::multiple))
+  if (mContent->AsElement()->HasAttr(kNameSpaceID_None, nsGkAtoms::multiple))
     state |= states::MULTISELECTABLE | states::EXTSELECTABLE;
 
   return state;
 }
 
 role
 HTMLSelectListAccessible::NativeRole()
 {
@@ -55,24 +55,24 @@ HTMLSelectListAccessible::NativeRole()
 }
 
 ////////////////////////////////////////////////////////////////////////////////
 // HTMLSelectListAccessible: SelectAccessible
 
 bool
 HTMLSelectListAccessible::SelectAll()
 {
-  return mContent->HasAttr(kNameSpaceID_None, nsGkAtoms::multiple) ?
+  return mContent->AsElement()->HasAttr(kNameSpaceID_None, nsGkAtoms::multiple) ?
     AccessibleWrap::SelectAll() : false;
 }
 
 bool
 HTMLSelectListAccessible::UnselectAll()
 {
-  return mContent->HasAttr(kNameSpaceID_None, nsGkAtoms::multiple) ?
+  return mContent->AsElement()->HasAttr(kNameSpaceID_None, nsGkAtoms::multiple) ?
     AccessibleWrap::UnselectAll() : false;
 }
 
 ////////////////////////////////////////////////////////////////////////////////
 // HTMLSelectListAccessible: Widgets
 
 bool
 HTMLSelectListAccessible::IsWidget() const
@@ -147,17 +147,17 @@ HTMLSelectOptionAccessible::NativeRole()
   return roles::OPTION;
 }
 
 ENameValueFlag
 HTMLSelectOptionAccessible::NativeName(nsString& aName)
 {
   // CASE #1 -- great majority of the cases
   // find the label attribute - this is what the W3C says we should use
-  mContent->GetAttr(kNameSpaceID_None, nsGkAtoms::label, aName);
+  mContent->AsElement()->GetAttr(kNameSpaceID_None, nsGkAtoms::label, aName);
   if (!aName.IsEmpty())
     return eNameOK;
 
   // CASE #2 -- no label parameter, get the first child,
   // use it if it is a text node
   nsIContent* text = mContent->GetFirstChild();
   if (text && text->IsNodeOfType(nsINode::eTEXT)) {
     nsTextEquivUtils::AppendTextEquivFromTextContent(text, &aName);
@@ -208,18 +208,18 @@ HTMLSelectOptionAccessible::NativeState(
     // XXX list frames are weird, don't rely on Accessible's general
     // visibility implementation unless they get reimplemented in layout
     state &= ~states::OFFSCREEN;
     // <select> is not collapsed: compare bounds to calculate OFFSCREEN
     Accessible* listAcc = Parent();
     if (listAcc) {
       nsIntRect optionRect = Bounds();
       nsIntRect listRect = listAcc->Bounds();
-      if (optionRect.y < listRect.y ||
-          optionRect.y + optionRect.height > listRect.y + listRect.height) {
+      if (optionRect.Y() < listRect.Y() ||
+          optionRect.YMost() > listRect.YMost()) {
         state |= states::OFFSCREEN;
       }
     }
   }
 
   return state;
 }
 
--- a/accessible/html/HTMLTableAccessible.cpp
+++ b/accessible/html/HTMLTableAccessible.cpp
@@ -117,24 +117,24 @@ HTMLTableCellAccessible::NativeAttribute
       nsIContent* firstChildNode = abbr->GetContent()->GetFirstChild();
       if (firstChildNode) {
         nsTextEquivUtils::
           AppendTextEquivFromTextContent(firstChildNode, &abbrText);
       }
     }
   }
   if (abbrText.IsEmpty())
-    mContent->GetAttr(kNameSpaceID_None, nsGkAtoms::abbr, abbrText);
+    mContent->AsElement()->GetAttr(kNameSpaceID_None, nsGkAtoms::abbr, abbrText);
 
   if (!abbrText.IsEmpty())
     nsAccUtils::SetAccAttr(attributes, nsGkAtoms::abbr, abbrText);
 
   // axis attribute
   nsAutoString axisText;
-  mContent->GetAttr(kNameSpaceID_None, nsGkAtoms::axis, axisText);
+  mContent->AsElement()->GetAttr(kNameSpaceID_None, nsGkAtoms::axis, axisText);
   if (!axisText.IsEmpty())
     nsAccUtils::SetAccAttr(attributes, nsGkAtoms::axis, axisText);
 
 #ifdef DEBUG
   nsAutoString unused;
   attributes->SetStringProperty(NS_LITERAL_CSTRING("cppclass"),
                                 NS_LITERAL_STRING("HTMLTableCellAccessible"),
                                 unused);
@@ -307,22 +307,22 @@ HTMLTableHeaderCellAccessible::
 
 ////////////////////////////////////////////////////////////////////////////////
 // HTMLTableHeaderCellAccessible: Accessible implementation
 
 role
 HTMLTableHeaderCellAccessible::NativeRole()
 {
   // Check value of @scope attribute.
-  static nsIContent::AttrValuesArray scopeValues[] =
+  static Element::AttrValuesArray scopeValues[] =
     { &nsGkAtoms::col, &nsGkAtoms::colgroup,
       &nsGkAtoms::row, &nsGkAtoms::rowgroup, nullptr };
   int32_t valueIdx =
-    mContent->FindAttrValueIn(kNameSpaceID_None, nsGkAtoms::scope,
-                              scopeValues, eCaseMatters);
+    mContent->AsElement()->FindAttrValueIn(kNameSpaceID_None, nsGkAtoms::scope,
+                                           scopeValues, eCaseMatters);
 
   switch (valueIdx) {
     case 0:
     case 1:
       return roles::COLUMNHEADER;
     case 2:
     case 3:
       return roles::ROWHEADER;
@@ -432,17 +432,17 @@ HTMLTableAccessible::NativeName(nsString
     if (captionContent) {
       nsTextEquivUtils::AppendTextEquivFromContent(this, captionContent, &aName);
       if (!aName.IsEmpty())
         return eNameOK;
     }
   }
 
   // If no caption then use summary as a name.
-  mContent->GetAttr(kNameSpaceID_None, nsGkAtoms::summary, aName);
+  mContent->AsElement()->GetAttr(kNameSpaceID_None, nsGkAtoms::summary, aName);
   return eNameOK;
 }
 
 already_AddRefed<nsIPersistentProperties>
 HTMLTableAccessible::NativeAttributes()
 {
   nsCOMPtr<nsIPersistentProperties> attributes =
     AccessibleWrap::NativeAttributes();
@@ -858,18 +858,18 @@ HTMLTableAccessible::Description(nsStrin
   if (caption) {
     nsIContent* captionContent = caption->GetContent();
     if (captionContent) {
       nsAutoString captionText;
       nsTextEquivUtils::AppendTextEquivFromContent(this, captionContent,
                                                    &captionText);
 
       if (!captionText.IsEmpty()) { // summary isn't used as a name.
-        mContent->GetAttr(kNameSpaceID_None, nsGkAtoms::summary,
-                          aDescription);
+        mContent->AsElement()->GetAttr(kNameSpaceID_None, nsGkAtoms::summary,
+                                       aDescription);
       }
     }
   }
 
 #ifdef SHOW_LAYOUT_HEURISTIC
   if (aDescription.IsEmpty()) {
     bool isProbablyForLayout = IsProbablyLayoutTable();
     aDescription = mLayoutHeuristic;
@@ -941,35 +941,35 @@ HTMLTableAccessible::IsProbablyLayoutTab
     }
   }
 
   // Check to see if an ARIA role overrides the role from native markup,
   // but for which we still expose table semantics (treegrid, for example).
   if (Role() != roles::TABLE)
     RETURN_LAYOUT_ANSWER(false, "Has role attribute");
 
-  if (mContent->HasAttr(kNameSpaceID_None, nsGkAtoms::role)) {
+  if (mContent->AsElement()->HasAttr(kNameSpaceID_None, nsGkAtoms::role)) {
     // Role attribute is present, but overridden roles have already been dealt with.
     // Only landmarks and other roles that don't override the role from native
     // markup are left to deal with here.
     RETURN_LAYOUT_ANSWER(false, "Has role attribute, weak role, and role is table");
   }
 
   NS_ASSERTION(mContent->IsHTMLElement(nsGkAtoms::table),
     "table should not be built by CSS display:table style");
 
   // Check if datatable attribute has "0" value.
-  if (mContent->AttrValueIs(kNameSpaceID_None, nsGkAtoms::datatable,
+  if (mContent->AsElement()->AttrValueIs(kNameSpaceID_None, nsGkAtoms::datatable,
                             NS_LITERAL_STRING("0"), eCaseMatters)) {
     RETURN_LAYOUT_ANSWER(true, "Has datatable = 0 attribute, it's for layout");
   }
 
   // Check for legitimate data table attributes.
   nsAutoString summary;
-  if (mContent->GetAttr(kNameSpaceID_None, nsGkAtoms::summary, summary) &&
+  if (mContent->AsElement()->GetAttr(kNameSpaceID_None, nsGkAtoms::summary, summary) &&
       !summary.IsEmpty())
     RETURN_LAYOUT_ANSWER(false, "Has summary -- legitimate table structures");
 
   // Check for legitimate data table elements.
   Accessible* caption = FirstChild();
   if (caption && caption->Role() == roles::CAPTION && caption->HasChildren())
     RETURN_LAYOUT_ANSWER(false, "Not empty caption -- legitimate table structures");
 
@@ -994,19 +994,19 @@ HTMLTableAccessible::IsProbablyLayoutTab
                cellElm = cellElm->GetNextSibling()) {
             if (cellElm->IsHTMLElement()) {
 
               if (cellElm->NodeInfo()->Equals(nsGkAtoms::th)) {
                 RETURN_LAYOUT_ANSWER(false,
                                      "Has th -- legitimate table structures");
               }
 
-              if (cellElm->HasAttr(kNameSpaceID_None, nsGkAtoms::headers) ||
-                  cellElm->HasAttr(kNameSpaceID_None, nsGkAtoms::scope) ||
-                  cellElm->HasAttr(kNameSpaceID_None, nsGkAtoms::abbr)) {
+              if (cellElm->AsElement()->HasAttr(kNameSpaceID_None, nsGkAtoms::headers) ||
+                  cellElm->AsElement()->HasAttr(kNameSpaceID_None, nsGkAtoms::scope) ||
+                  cellElm->AsElement()->HasAttr(kNameSpaceID_None, nsGkAtoms::abbr)) {
                 RETURN_LAYOUT_ANSWER(false,
                                      "Has headers, scope, or abbr attribute -- legitimate table structures");
               }
 
               Accessible* cell = mDoc->GetAccessible(cellElm);
               if (cell && cell->ChildCount() == 1 &&
                   cell->FirstChild()->IsAbbreviation()) {
                 RETURN_LAYOUT_ANSWER(false,
--- a/accessible/interfaces/nsIAccessible.idl
+++ b/accessible/interfaces/nsIAccessible.idl
@@ -2,17 +2,16 @@
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #include "nsISupports.idl"
 #include "nsIArray.idl"
 
 interface nsIPersistentProperties;
-interface nsIDOMCSSPrimitiveValue;
 interface nsIDOMNode;
 interface nsIAccessibleDocument;
 interface nsIAccessibleRelation;
 
 %{C++
 namespace mozilla {
 namespace a11y {
 class Accessible;
--- a/accessible/ipc/DocAccessibleParent.cpp
+++ b/accessible/ipc/DocAccessibleParent.cpp
@@ -618,18 +618,18 @@ DocAccessibleParent::MaybeInitWindowEmul
   RootAccessible* rootDocument = outerDoc->RootAccessible();
   MOZ_ASSERT(rootDocument);
 
   bool isActive = true;
   nsIntRect rect(CW_USEDEFAULT, CW_USEDEFAULT, 0, 0);
   if (Compatibility::IsDolphin()) {
     rect = Bounds();
     nsIntRect rootRect = rootDocument->Bounds();
-    rect.x = rootRect.x - rect.x;
-    rect.y -= rootRect.y;
+    rect.MoveToX(rootRect.X() - rect.X());
+    rect.MoveToY(rect.Y() - rootRect.Y());
 
     auto tab = static_cast<dom::TabParent*>(Manager());
     tab->GetDocShellIsActive(&isActive);
   }
 
   nsWinUtils::NativeWindowCreateProc onCreate([this](HWND aHwnd) -> void {
     IDispatchHolder hWndAccHolder;
 
@@ -647,18 +647,18 @@ DocAccessibleParent::MaybeInitWindowEmul
 
     Unused << SendEmulatedWindow(reinterpret_cast<uintptr_t>(mEmulatedWindowHandle),
                                  hWndAccHolder);
   });
 
   HWND parentWnd = reinterpret_cast<HWND>(rootDocument->GetNativeWindow());
   DebugOnly<HWND> hWnd = nsWinUtils::CreateNativeWindow(kClassNameTabContent,
                                                         parentWnd,
-                                                        rect.x, rect.y,
-                                                        rect.width, rect.height,
+                                                        rect.X(), rect.Y(),
+                                                        rect.Width(), rect.Height(),
                                                         isActive, &onCreate);
   MOZ_ASSERT(hWnd);
 }
 
 /**
  * @param aCOMProxy COM Proxy to the document in the content process.
  */
 void
--- a/accessible/ipc/win/ProxyAccessible.cpp
+++ b/accessible/ipc/win/ProxyAccessible.cpp
@@ -226,20 +226,17 @@ ProxyAccessible::Bounds()
   long left;
   long top;
   long width;
   long height;
   HRESULT hr = acc->accLocation(&left, &top, &width, &height, kChildIdSelf);
   if (FAILED(hr)) {
     return rect;
   }
-  rect.x = left;
-  rect.y = top;
-  rect.width = width;
-  rect.height = height;
+  rect.SetRect(left, top, width, height);
   return rect;
 }
 
 void
 ProxyAccessible::Language(nsString& aLocale)
 {
   aLocale.Truncate();
 
--- a/accessible/ipc/win/handler/AccessibleHandler.cpp
+++ b/accessible/ipc/win/handler/AccessibleHandler.cpp
@@ -1216,18 +1216,22 @@ static const GUID kUnsupportedServices[]
   // Unknown, queried by Windows
   {0x33f139ee, 0xe509, 0x47f7, {0xbf, 0x39, 0x83, 0x76, 0x44, 0xf7, 0x45, 0x76}},
   // Unknown, queried by Windows
   {0xFDA075CF, 0x7C8B, 0x498C, { 0xB5, 0x14, 0xA9, 0xCB, 0x52, 0x1B, 0xBF, 0xB4 }},
   // Unknown, queried by Windows
   {0x8EDAA462, 0x21F4, 0x4C87, { 0xA0, 0x12, 0xB3, 0xCD, 0xA3, 0xAB, 0x01, 0xFC }},
   // Unknown, queried by Windows
   {0xacd46652, 0x829d, 0x41cb, { 0xa5, 0xfc, 0x17, 0xac, 0xf4, 0x36, 0x61, 0xac }},
-  // Unknown, queried by Windows
-  {0xb96fdb85, 0x7204, 0x4724, { 0x84, 0x2b, 0xc7, 0x05, 0x9d, 0xed, 0xb9, 0xd0 }}
+  // SID_IsUIAutomationObject (undocumented), queried by Windows
+  {0xb96fdb85, 0x7204, 0x4724, { 0x84, 0x2b, 0xc7, 0x05, 0x9d, 0xed, 0xb9, 0xd0 }},
+  // IIS_IsOleaccProxy (undocumented), queried by Windows
+  {0x902697FA, 0x80E4, 0x4560, {0x80, 0x2A, 0xA1, 0x3F, 0x22, 0xA6, 0x47, 0x09}},
+  // IID_IHTMLElement, queried by JAWS
+  {0x3050F1FF, 0x98B5, 0x11CF, {0xBB, 0x82, 0x00, 0xAA, 0x00, 0xBD, 0xCE, 0x0B}}
 };
 
 /*** IServiceProvider ***/
 
 HRESULT
 AccessibleHandler::QueryService(REFGUID aServiceId, REFIID aIid,
                                 void** aOutInterface)
 {
@@ -1237,16 +1241,23 @@ AccessibleHandler::QueryService(REFGUID 
      of our own object to implement this just like a QI. */
   if (aIid == IID_IAccessible2_3 || aIid == IID_IAccessible2_2 ||
       aIid == IID_IAccessible2) {
     RefPtr<NEWEST_IA2_INTERFACE> ia2(this);
     ia2.forget(aOutInterface);
     return S_OK;
   }
 
+  // JAWS uses QueryService for these, but QI will work just fine and we can
+  // thus avoid a cross-process call. More importantly, if QS is used, the
+  // handler won't get used for that object, so our caching won't be used.
+  if (aIid == IID_IAccessibleAction || aIid == IID_IAccessibleText) {
+    return InternalQueryInterface(aIid, aOutInterface);
+  }
+
   for (uint32_t i = 0; i < ArrayLength(kUnsupportedServices); ++i) {
     if (aServiceId == kUnsupportedServices[i]) {
       return E_NOINTERFACE;
     }
   }
 
   if (!mServProvPassThru) {
     RefPtr<IUnknown> proxy(GetProxy());
--- a/accessible/tests/browser/tree/browser_aria_owns.js
+++ b/accessible/tests/browser/tree/browser_aria_owns.js
@@ -213,8 +213,41 @@ addAccessibleTask(`<div id="a"></div><di
       document.documentElement.getBoundingClientRect();
       document.body.setAttribute("aria-owns", "b a");
       document.documentElement.remove();
     });
 
     testChildrenIds(accDoc, []);
   }
 );
+
+// Don't allow ordinal child to be placed after aria-owned child (bug 1405796)
+addAccessibleTask(`<div id="container"><div id="a">Hello</div></div>
+                   <div><div id="c">There</div><div id="d">There</div></div>`,
+  async function(browser, accDoc) {
+    let containerAcc = findAccessibleChildByID(accDoc, "container");
+
+    testChildrenIds(containerAcc, ["a"]);
+
+    await contentSpawnMutation(browser, MOVE, function() {
+      document.getElementById("container").setAttribute("aria-owns", "c");
+    });
+
+    testChildrenIds(containerAcc, ["a", "c"]);
+
+    await contentSpawnMutation(browser, MOVE, function() {
+      let span = document.createElement("span");
+      document.getElementById("container").appendChild(span);
+
+      let b = document.createElement("div");
+      b.id = "b";
+      document.getElementById("container").appendChild(b);
+    });
+
+    testChildrenIds(containerAcc, ["a", "b", "c"]);
+
+    await contentSpawnMutation(browser, MOVE, function() {
+      document.getElementById("container").setAttribute("aria-owns", "c d");
+    });
+
+    testChildrenIds(containerAcc, ["a", "b", "c", "d"]);
+  }
+);
--- a/accessible/tests/mochitest/attributes/a11y.ini
+++ b/accessible/tests/mochitest/attributes/a11y.ini
@@ -1,13 +1,14 @@
 [DEFAULT]
 support-files =
   !/accessible/tests/mochitest/*.js
 
 [test_dpub_aria_xml-roles.html]
+[test_graphics_aria_xml-roles.html]
 [test_obj.html]
 [test_obj_css.html]
 [test_obj_css.xul]
 [test_obj_group.html]
 [test_obj_group.xul]
 [test_obj_group_tree.xul]
 [test_tag.html]
 [test_xml-roles.html]
new file mode 100644
--- /dev/null
+++ b/accessible/tests/mochitest/attributes/test_graphics_aria_xml-roles.html
@@ -0,0 +1,49 @@
+<!DOCTYPE html>
+<html>
+<head>
+  <title>XML roles tests</title>
+  <link rel="stylesheet" type="text/css"
+        href="chrome://mochikit/content/tests/SimpleTest/test.css" />
+
+  <script type="application/javascript"
+          src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"></script>
+
+  <script type="application/javascript"
+          src="../common.js"></script>
+  <script type="application/javascript"
+          src="../role.js"></script>
+  <script type="application/javascript"
+          src="../attributes.js"></script>
+
+  <script type="application/javascript">
+
+    function doTest() {
+      // Graphics ARIA roles should be exposed via the xml-roles object attribute.
+      let graphics_attrs = [
+        "graphics-document",
+        "graphics-object",
+        "graphics-symbol"
+      ];
+      for (let attr of graphics_attrs) {
+        testAttrs(attr, {"xml-roles": attr}, true);
+      }
+      SimpleTest.finish();
+    }
+    SimpleTest.waitForExplicitFinish();
+    addA11yLoadEvent(doTest);
+  </script>
+</head>
+<body>
+  <a target="_blank"
+     href="https://bugzilla.mozilla.org/show_bug.cgi?id=1432513"
+     title="implement ARIA Graphics roles">
+    Bug 1432513
+  </a>
+  <p id="display"></p>
+  <div id="content" style="display: none"></div>
+  <pre id="test"></pre>
+  <div id="graphics-document" role="graphics-document">document</div>
+  <div id="graphics-object" role="graphics-object">object</div>
+  <div id="graphics-symbol" role="graphics-symbol">symbol</div>
+</body>
+</html>
--- a/accessible/tests/mochitest/common.js
+++ b/accessible/tests/mochitest/common.js
@@ -705,29 +705,24 @@ function getLoadContext() {
                .getInterface(Ci.nsIWebNavigation)
                .QueryInterface(Ci.nsILoadContext);
 }
 
 /**
  * Return text from clipboard.
  */
 function getTextFromClipboard() {
-  var clip = Components.classes["@mozilla.org/widget/clipboard;1"].
-    getService(Components.interfaces.nsIClipboard);
-  if (!clip)
-    return "";
-
   var trans = Components.classes["@mozilla.org/widget/transferable;1"].
     createInstance(Components.interfaces.nsITransferable);
   trans.init(getLoadContext());
   if (!trans)
     return "";
 
   trans.addDataFlavor("text/unicode");
-  clip.getData(trans, clip.kGlobalClipboard);
+  Services.clipboard.getData(trans, Services.clipboard.kGlobalClipboard);
 
   var str = {};
   var strLength = {};
   trans.getTransferData("text/unicode", str, strLength);
 
   if (str)
     str = str.value.QueryInterface(Components.interfaces.nsISupportsString);
   if (str)
--- a/accessible/tests/mochitest/elm/a11y.ini
+++ b/accessible/tests/mochitest/elm/a11y.ini
@@ -10,8 +10,9 @@ skip-if = buildapp == 'mulet'
 [test_listbox.xul]
 [test_MathMLSpec.html]
 [test_nsApplicationAcc.html]
 [test_plugin.html]
 skip-if = buildapp == 'mulet'
 [test_canvas.html]
 [test_shadowroot.html]
 skip-if = stylo # bug 1293844
+support-files = test_shadowroot_subframe.html
--- a/accessible/tests/mochitest/elm/test_nsApplicationAcc.html
+++ b/accessible/tests/mochitest/elm/test_nsApplicationAcc.html
@@ -1,59 +1,54 @@
 <html>
 
 <head>
   <title>application accessible name</title>
-  <link rel="stylesheet" type="text/css" 
+  <link rel="stylesheet" type="text/css"
          href="chrome://mochikit/content/tests/SimpleTest/test.css" />
-  <script type="application/javascript" 
+  <script type="application/javascript"
           src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"></script>
 
-  <script type="application/javascript" 
+  <script type="application/javascript"
           src="../common.js"></script>
-  <script type="application/javascript" 
+  <script type="application/javascript"
           src="../role.js"></script>
 
   <script type="application/javascript">
+    /* import-globals-from ../common.js */
     function doTest() {
       var accessible = getApplicationAccessible();
       if (!accessible) {
         SimpleTest.finish();
         return;
       }
 
-      var bundleServ =
-        Components.classes["@mozilla.org/intl/stringbundle;1"].
-        getService(Components.interfaces.nsIStringBundleService);
       var brandBundle =
-        bundleServ.createBundle("chrome://branding/locale/brand.properties");
-
-      var appInfo = Components.classes["@mozilla.org/xre/app-info;1"].
-        getService(Components.interfaces.nsIXULAppInfo);
+        Services.strings.createBundle("chrome://branding/locale/brand.properties");
 
       // nsIAccessible::name
       var applicationName = "";
       if (LINUX || SOLARIS) {
-        applicationName = appInfo.name;
+        applicationName = Services.appinfo.name;
       } else {
         try {
           applicationName = brandBundle.GetStringFromName("brandShortName");
         } catch (e) {
         }
 
         if (applicationName == "")
           applicationName = "Gecko based application";
       }
       is(accessible.name, applicationName, "wrong application accessible name");
 
       // nsIAccessibleApplication
-      is(accessible.appName, appInfo.name, "Wrong application name");
-      is(accessible.appVersion, appInfo.version, "Wrong application version");
+      is(accessible.appName, Services.appinfo.name, "Wrong application name");
+      is(accessible.appVersion, Services.appinfo.version, "Wrong application version");
       is(accessible.platformName, "Gecko", "Wrong platform name");
-      is(accessible.platformVersion, appInfo.platformVersion,
+      is(accessible.platformVersion, Services.appinfo.platformVersion,
          "Wrong platform version");
 
       SimpleTest.finish();
     }
 
     SimpleTest.waitForExplicitFinish();
     addA11yLoadEvent(doTest);
   </script>
--- a/accessible/tests/mochitest/elm/test_shadowroot.html
+++ b/accessible/tests/mochitest/elm/test_shadowroot.html
@@ -3,57 +3,38 @@
 <head>
   <title>ShadowRoot tests</title>
   <link rel="stylesheet" type="text/css"
         href="chrome://mochikit/content/tests/SimpleTest/test.css" />
 
   <script type="application/javascript"
           src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"></script>
 
-  <script type="application/javascript"
-          src="../common.js"></script>
-  <script type="application/javascript"
-          src="../role.js"></script>
-
-  <script type="application/javascript">
-    function doTest() {
-      testElm("component", {
-        role: ROLE_GROUPING,
-        children: [
-        {
-          role: ROLE_PUSHBUTTON,
-        },
-        {
-          role: ROLE_LINK,
-        },
-        ]
-      });
-
-      SimpleTest.finish();
-    }
-
-    SimpleTest.waitForExplicitFinish();
-    addA11yLoadEvent(doTest);
-  </script>
 </head>
 <body>
 
   <a target="_blank"
     title="Ensure accessible objects are created for shadow root"
     href="https://bugzilla.mozilla.org/show_bug.cgi?id=1026125">
      Mozilla Bug 1026125
   </a><br/>
   <p id="display"></p>
   <div id="content" style="display: none"></div>
   <pre id="test">
   </pre>
 
-  <div role="group" id="component"></div>
   <script>
-    var component = document.getElementById("component");
-    var shadow = component.createShadowRoot();
-
-    shadow.innerHTML = "<button>Hello</button>" +
-      '<a href="#"> World</a>';
+    SimpleTest.waitForExplicitFinish();
+    SpecialPowers.pushPrefEnv({
+      set: [
+        ["dom.webcomponents.shadowdom.enabled", true]
+      ]
+    }, function() {
+      // This test loads in an iframe, to ensure that the element instance is
+      // loaded with the correct value of the preference.
+      var iframe = document.createElement("iframe");
+      iframe.src = "test_shadowroot_subframe.html";
+      document.body.appendChild(iframe);
+    });
   </script>
 
 </body>
 </html>
new file mode 100644
--- /dev/null
+++ b/accessible/tests/mochitest/elm/test_shadowroot_subframe.html
@@ -0,0 +1,43 @@
+<!DOCTYPE HTML>
+<html>
+<head>
+  <title>ShadowRoot tests</title>
+  <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
+  <script type="application/javascript" src="../common.js"></script>
+  <script type="application/javascript" src="../role.js"></script>
+
+  <script type="application/javascript">
+    let SimpleTest = window.parent.SimpleTest;
+    let ok = window.parent.ok;
+    let is = window.parent.is;
+
+    function doTest() {
+      testElm("component", {
+        role: ROLE_GROUPING,
+        children: [
+        {
+          role: ROLE_PUSHBUTTON,
+        },
+        {
+          role: ROLE_LINK,
+        },
+        ]
+      });
+
+      SimpleTest.finish();
+    }
+
+    addA11yLoadEvent(doTest);
+  </script>
+
+</head>
+<body>
+  <div role="group" id="component"></div>
+  <script>
+    var component = document.getElementById("component");
+    var shadow = component.attachShadow({mode: "open"});
+
+    shadow.innerHTML = "<button>Hello</button>" +
+      '<a href="#"> World</a>';
+  </script>
+</body>
--- a/accessible/tests/mochitest/hittest/a11y.ini
+++ b/accessible/tests/mochitest/hittest/a11y.ini
@@ -4,11 +4,12 @@ support-files = zoom_tree.xul
   !/accessible/tests/mochitest/letters.gif
 
 [test_browser.html]
 [test_canvas_hitregion.html]
 skip-if = (os == "android" || appname == "b2g")
 [test_general.html]
 [test_menu.xul]
 [test_shadowroot.html]
+support-files = test_shadowroot_subframe.html
 [test_zoom.html]
 [test_zoom_text.html]
 [test_zoom_tree.xul]
--- a/accessible/tests/mochitest/hittest/test_shadowroot.html
+++ b/accessible/tests/mochitest/hittest/test_shadowroot.html
@@ -3,70 +3,38 @@
 <head>
   <title>ShadowRoot hit tests</title>
   <link rel="stylesheet" type="text/css"
         href="chrome://mochikit/content/tests/SimpleTest/test.css" />
 
   <script type="application/javascript"
           src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"></script>
 
-  <script type="application/javascript"
-          src="../common.js"></script>
-  <script type="application/javascript"
-          src="../layout.js"></script>
-
-  <script type="application/javascript">
-    function doTest() {
-      var componentAcc = getAccessible("component1");
-      testChildAtPoint(componentAcc, 1, 1, componentAcc.firstChild,
-                       componentAcc.firstChild);
-
-      componentAcc = getAccessible("component2");
-      testChildAtPoint(componentAcc, 1, 1, componentAcc.firstChild,
-                       componentAcc.firstChild);
-      SimpleTest.finish();
-    }
-
-    SimpleTest.waitForExplicitFinish();
-    addA11yLoadEvent(doTest);
-  </script>
 </head>
 <body>
 
   <a target="_blank"
      title="Test getChildAtPoint works for shadow DOM content"
      href="https://bugzilla.mozilla.org/show_bug.cgi?id=1027315">
     Mozilla Bug 1027315
   </a><br/>
   <p id="display"></p>
   <div id="content" style="display: none"></div>
   <pre id="test">
   </pre>
 
-  <div role="group" class="components" id="component1" style="display: inline-block;">
-  <!--
-    <div role="button" id="component-child"
-         style="width: 100px; height: 100px; background-color: pink;">
-    </div>
-  -->
-  </div>
-  <div role="group" class="components"  id="component2" style="display: inline-block;">
-  <!--
-    <button>Hello world</button>
-  -->
-  </div>
   <script>
-    // This routine adds the comment children of each 'component' to its
-    // shadow root.
-    var components = document.querySelectorAll(".components");
-    for (var i = 0; i < components.length; i++) {
-      var component = components[i];
-      var shadow = component.createShadowRoot();
-      for (var child = component.firstChild; child; child = child.nextSibling) {
-        if (child.nodeType === 8)
-          // eslint-disable-next-line no-unsanitized/property
-          shadow.innerHTML = child.data;
-      }
-    }
+    SimpleTest.waitForExplicitFinish();
+    SpecialPowers.pushPrefEnv({
+      set: [
+        ["dom.webcomponents.shadowdom.enabled", true]
+      ]
+    }, function() {
+      // This test loads in an iframe, to ensure that the element instance is
+      // loaded with the correct value of the preference.
+      var iframe = document.createElement("iframe");
+      iframe.src = "test_shadowroot_subframe.html";
+      document.body.appendChild(iframe);
+    });
   </script>
 
 </body>
 </html>
new file mode 100644
--- /dev/null
+++ b/accessible/tests/mochitest/hittest/test_shadowroot_subframe.html
@@ -0,0 +1,58 @@
+<!DOCTYPE HTML>
+<html>
+<head>
+  <title>ShadowRoot hit tests</title>
+  <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
+  <script type="application/javascript" src="../common.js"></script>
+  <script type="application/javascript" src="../layout.js"></script>
+
+  <script type="application/javascript">
+    let SimpleTest = window.parent.SimpleTest;
+    let ok = window.parent.ok;
+    let is = window.parent.is;
+
+    function doTest() {
+      var componentAcc = getAccessible("component1");
+      testChildAtPoint(componentAcc, 1, 1, componentAcc.firstChild,
+                       componentAcc.firstChild);
+
+      componentAcc = getAccessible("component2");
+      testChildAtPoint(componentAcc, 1, 1, componentAcc.firstChild,
+                       componentAcc.firstChild);
+      SimpleTest.finish();
+    }
+
+    SimpleTest.waitForExplicitFinish();
+    addA11yLoadEvent(doTest);
+  </script>
+
+</head>
+<body>
+  <div role="group" class="components" id="component1" style="display: inline-block;">
+  <!--
+    <div role="button" id="component-child"
+         style="width: 100px; height: 100px; background-color: pink;">
+    </div>
+  -->
+  </div>
+  <div role="group" class="components"  id="component2" style="display: inline-block;">
+  <!--
+    <button>Hello world</button>
+  -->
+  </div>
+  <script>
+    // This routine adds the comment children of each 'component' to its
+    // shadow root.
+    var components = document.querySelectorAll(".components");
+    for (var i = 0; i < components.length; i++) {
+      var component = components[i];
+      var shadow = component.attachShadow({mode: "open"});
+      for (var child = component.firstChild; child; child = child.nextSibling) {
+        if (child.nodeType === 8)
+          // eslint-disable-next-line no-unsanitized/property
+          shadow.innerHTML = child.data;
+      }
+    }
+  </script>
+</body>
+</html>
--- a/accessible/tests/mochitest/role/a11y.ini
+++ b/accessible/tests/mochitest/role/a11y.ini
@@ -3,9 +3,10 @@ support-files =
   !/accessible/tests/mochitest/*.js
   !/accessible/tests/mochitest/moz.png
 
 [test_aria.html]
 [test_aria.xul]
 [test_dpub_aria.html]
 [test_general.html]
 [test_general.xul]
+[test_graphics_aria.html]
 [test_svg.html]
new file mode 100644
--- /dev/null
+++ b/accessible/tests/mochitest/role/test_graphics_aria.html
@@ -0,0 +1,43 @@
+<!DOCTYPE html>
+<html>
+<head>
+  <title>Test Graphics ARIA roles</title>
+
+  <link rel="stylesheet" type="text/css" href="chrome://mochikit/content/tests/SimpleTest/test.css" />
+
+  <script type="application/javascript"
+          src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"></script>
+
+  <script type="application/javascript"
+          src="../common.js"></script>
+  <script type="application/javascript"
+          src="../role.js"></script>
+
+  <script type="application/javascript">
+
+    function doTest() {
+      // Graphics ARIA role map.
+      testRole("graphics-document", ROLE_DOCUMENT);
+      testRole("graphics-object", ROLE_GROUPING);
+      testRole("graphics-symbol", ROLE_GRAPHIC);
+      SimpleTest.finish();
+    }
+
+    SimpleTest.waitForExplicitFinish();
+    addA11yLoadEvent(doTest);
+  </script>
+</head>
+<body>
+  <a target="_blank"
+     href="https://bugzilla.mozilla.org/show_bug.cgi?id=1432513"
+     title="implement ARIA Graphics roles">
+    Bug 1432513
+  </a>
+  <p id="display"></p>
+  <div id="content" style="display: none"></div>
+  <pre id="test"></pre>
+  <div id="graphics-document" role="graphics-document">document</div>
+  <div id="graphics-object" role="graphics-object">object</div>
+  <div id="graphics-symbol" role="graphics-symbol">symbol</div>
+</body>
+</html>
--- a/accessible/tests/mochitest/textcaret/test_general.html
+++ b/accessible/tests/mochitest/textcaret/test_general.html
@@ -10,23 +10,22 @@
           src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"></script>
 
   <script type="application/javascript"
           src="../common.js"></script>
   <script type="application/javascript"
           src="../events.js"></script>
 
   <script type="application/javascript">
+    /* import-globals-from ../common.js */
     /**
      * Turn on/off the caret browsing mode.
      */
     function turnCaretBrowsing(aIsOn) {
-      var prefs = Components.classes["@mozilla.org/preferences-service;1"].
-        getService(Components.interfaces.nsIPrefBranch);
-      prefs.setBoolPref("accessibility.browsewithcaret", aIsOn);
+      Services.prefs.setBoolPref("accessibility.browsewithcaret", aIsOn);
     }
 
     /**
      * Test caret offset for the given accessible.
      */
     function testCaretOffset(aID, aCaretOffset) {
       var acc = getAccessible(aID, [nsIAccessibleText]);
       is(acc.caretOffset, aCaretOffset,
--- a/accessible/tests/mochitest/tree/test_tabbrowser.xul
+++ b/accessible/tests/mochitest/tree/test_tabbrowser.xul
@@ -110,37 +110,27 @@
             {
               // xul:tab ("about:license")
               role: ROLE_PAGETAB,
               children: [
                 {
                   // xul:text, i.e. the tab label text
                   role: ROLE_TEXT_LEAF,
                   children: []
-                },
-                {
-                  // xul:toolbarbutton ("Close Tab")
-                  role: ROLE_PUSHBUTTON,
-                  children: []
                 }
               ]
             },
             {
               // tab ("about:mozilla")
               role: ROLE_PAGETAB,
               children: [
                 {
                   // xul:text, i.e. the tab label text
                   role: ROLE_TEXT_LEAF,
                   children: []
-                },
-                {
-                  // xul:toolbarbutton ("Close Tab")
-                  role: ROLE_PUSHBUTTON,
-                  children: []
                 }
               ]
             },
             {
               // xul:toolbarbutton ("Open a new tab")
               role: ROLE_PUSHBUTTON,
               children: newTabChildren
             }
--- a/accessible/tests/mochitest/treeupdate/a11y.ini
+++ b/accessible/tests/mochitest/treeupdate/a11y.ini
@@ -10,16 +10,17 @@ support-files =
 [test_bug883708.xhtml]
 [test_bug884251.xhtml]
 [test_bug895082.html]
 [test_bug1040735.html]
 [test_bug1100602.html]
 [test_bug1175913.html]
 [test_bug1189277.html]
 [test_bug1276857.html]
+support-files = test_bug1276857_subframe.html
 [test_canvas.html]
 [test_colorpicker.xul]
 [test_contextmenu.xul]
 [test_cssoverflow.html]
 [test_deck.xul]
 [test_doc.html]
 [test_gencontent.html]
 [test_general.html]
--- a/accessible/tests/mochitest/treeupdate/test_bug1276857.html
+++ b/accessible/tests/mochitest/treeupdate/test_bug1276857.html
@@ -13,80 +13,89 @@
           src="../common.js"></script>
   <script type="application/javascript"
           src="../role.js"></script>
   <script type="application/javascript"
           src="../events.js"></script>
 
   <script type="application/javascript">
     function runTest() {
+      let iframe = document.getElementById("iframe");
+
       // children change will recreate the table
       this.eventSeq = [
-        new invokerChecker(EVENT_REORDER, getNode("c1"))
+        new invokerChecker(EVENT_REORDER, () => {
+          let doc = getNode("iframe").contentDocument;
+          return doc && doc.getElementById("c1");
+        })
       ];
 
       this.invoke = function runTest_invoke() {
         var tree = {
           SECTION: [ // c1
             { TEXT_LEAF: [] }, // Some text
             { TEXT_CONTAINER: [
               { TEXT_LEAF: [] } // something with ..
             ] },
             { TEXT_LEAF: [] } // More text
           ]
         };
-        testAccessibleTree("c1", tree);
+        testAccessibleTree(iframe.contentDocument.getElementById("c1"), tree);
 
-        getNode("c1_t").querySelector("span").remove();
+        iframe.contentDocument.getElementById("c1_t").querySelector("span").remove();
       };
 
       this.finalCheck = function runTest_finalCheck() {
         var tree = {
           SECTION: [ // c1
             { TEXT_LEAF: [] }, // Some text
             { TEXT_LEAF: [] } // More text
           ]
         };
-        testAccessibleTree("c1", tree);
+        testAccessibleTree(iframe.contentDocument.getElementById("c1"), tree);
       };
 
       this.getID = function runTest_getID() {
         return "child DOM node is removed before the layout notifies the a11y about parent removal/show";
       };
     }
 
     function runShadowTest() {
       // children change will recreate the table
       this.eventSeq = [
-        new invokerChecker(EVENT_REORDER, "c2")
+        new invokerChecker(EVENT_REORDER, () => {
+          let doc = getNode("iframe").contentDocument;
+          return doc && doc.getElementById("c2");
+        })
       ];
 
       this.invoke = function runShadowTest_invoke() {
         var tree = {
           SECTION: [ // c2
             { TEXT_LEAF: [] }, // Some text
             { TEXT_CONTAINER: [
               { TEXT_LEAF: [] } // something with ..
             ] },
             { TEXT_LEAF: [] } // More text
           ]
         };
-        testAccessibleTree("c2", tree);
+        testAccessibleTree(iframe.contentDocument.getElementById("c2"), tree);
 
-        gShadowRoot.firstElementChild.querySelector("span").remove();
+        var shadowRoot = iframe.contentDocument.getElementById("c2_c").shadowRoot;
+        shadowRoot.firstElementChild.querySelector("span").remove();
       };
 
       this.finalCheck = function runShadowTest_finalCheck() {
         var tree = {
           SECTION: [ // c2
             { TEXT_LEAF: [] }, // Some text
             { TEXT_LEAF: [] } // More text
           ]
         };
-        testAccessibleTree("c2", tree);
+        testAccessibleTree(iframe.contentDocument.getElementById("c2"), tree);
       };
 
       this.getID = function runShadowTest_getID() {
         return "child DOM node is removed before the layout notifies the a11y about parent removal/show in shadow DOM";
       };
     }
 
     // enableLogging("tree");
@@ -96,44 +105,27 @@
     function doTest() {
       gQueue = new eventQueue();
       gQueue.push(new runTest());
       gQueue.push(new runShadowTest());
       gQueue.invoke(); // will call SimpleTest.finish();
     }
 
     SimpleTest.waitForExplicitFinish();
-    addA11yLoadEvent(doTest);
+    SpecialPowers.pushPrefEnv({
+      set: [
+        ["dom.webcomponents.shadowdom.enabled", true]
+      ]
+    }, function() {
+      // This test loads in an iframe, to ensure that the element instance is
+      // loaded with the correct value of the preference.
+      let iframe = document.createElement("iframe");
+      iframe.id = "iframe";
+      iframe.src = "test_bug1276857_subframe.html";
+      addA11yLoadEvent(doTest, iframe.contentWindow);
+      document.body.appendChild(iframe);
+    });
   </script>
 
 </head>
-
 <body>
-  <p id="display"></p>
-  <div id="content" style="display: none"></div>
-  <pre id="test">
-  </pre>
-
-  <div id="c1">
-    <div id="c1_t" style="display: table" role="presentation">
-    Some text
-    <span style="display: table-cell">something with accessibles goes here</span>
-    More text
-    </div>
-  </div>
-
-  <template id="tmpl">
-    <div style="display: table" role="presentation">
-    Some text
-    <span style="display: table-cell">something with accessibles goes here</span>
-    More text
-    </div>
-  </template>
-
-  <div id="c2"><div id="c2_c" role="presentation"></div></div>
-
-  <script>
-    var gShadowRoot = document.getElementById("c2_c").createShadowRoot();
-    var tmpl = document.getElementById("tmpl");
-    gShadowRoot.appendChild(document.importNode(tmpl.content, true));
-  </script>
 </body>
 </html>
new file mode 100644
--- /dev/null
+++ b/accessible/tests/mochitest/treeupdate/test_bug1276857_subframe.html
@@ -0,0 +1,33 @@
+<!DOCTYPE HTML>
+<html>
+<head>
+  <title>DOM mutations test</title>
+  <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
+  <script type="application/javascript" src="../role.js"></script>
+</head>
+<body>
+  <div id="c1">
+    <div id="c1_t" style="display: table" role="presentation">
+    Some text
+    <span style="display: table-cell">something with accessibles goes here</span>
+    More text
+    </div>
+  </div>
+
+  <template id="tmpl">
+    <div style="display: table" role="presentation">
+    Some text
+    <span style="display: table-cell">something with accessibles goes here</span>
+    More text
+    </div>
+  </template>
+
+  <div id="c2"><div id="c2_c" role="presentation"></div></div>
+
+  <script>
+    var gShadowRoot = document.getElementById("c2_c").attachShadow({mode: "open"});
+    var tmpl = document.getElementById("tmpl");
+    gShadowRoot.appendChild(document.importNode(tmpl.content, true));
+  </script>
+</body>
+</html>
--- a/accessible/tests/mochitest/treeview.js
+++ b/accessible/tests/mochitest/treeview.js
@@ -102,17 +102,16 @@ nsTreeView.prototype =
     return info.parentIndex;
   },
   hasNextSibling: function hasNextSibling(aRowIndex, aAfterIndex) { },
   getLevel: function getLevel(aIndex) {
     var info = this.getInfoByIndex(aIndex);
     return info.level;
   },
   getImageSrc: function getImageSrc(aRow, aCol) {},
-  getProgressMode: function getProgressMode(aRow, aCol) {},
   isContainer: function isContainer(aIndex) {
     var data = this.getDataForIndex(aIndex);
     return data.open != undefined;
   },
   isContainerOpen: function isContainerOpen(aIndex) {
     var data = this.getDataForIndex(aIndex);
     return data.open;
   },
--- a/accessible/windows/ia2/ia2AccessibleComponent.cpp
+++ b/accessible/windows/ia2/ia2AccessibleComponent.cpp
@@ -57,26 +57,26 @@ ia2AccessibleComponent::get_locationInPa
     return S_OK;
 
   nsIntRect rect = acc->Bounds();
 
   // The coordinates of the returned position are relative to this object's
   // parent or relative to the screen on which this object is rendered if it
   // has no parent.
   if (!acc->Parent()) {
-    *aX = rect.x;
-    *aY = rect.y;
+    *aX = rect.X();
+    *aY = rect.Y();
     return S_OK;
   }
 
   // The coordinates of the bounding box are given relative to the parent's
   // coordinate system.
   nsIntRect parentRect = acc->Parent()->Bounds();
-  *aX = rect.x - parentRect.x;
-  *aY = rect.y - parentRect.y;
+  *aX = rect.X() - parentRect.X();
+  *aY = rect.Y() - parentRect.Y();
   return S_OK;
 }
 
 STDMETHODIMP
 ia2AccessibleComponent::get_foreground(IA2Color* aForeground)
 {
   if (!aForeground)
     return E_INVALIDARG;
--- a/accessible/windows/ia2/ia2AccessibleText.cpp
+++ b/accessible/windows/ia2/ia2AccessibleText.cpp
@@ -105,20 +105,21 @@ ia2AccessibleText::get_characterExtents(
   nsIntRect rect;
   MOZ_ASSERT(!HyperTextProxyFor(this));
   HyperTextAccessible* textAcc = static_cast<HyperTextAccessibleWrap*>(this);
   if (textAcc->IsDefunct())
     return CO_E_OBJNOTCONNECTED;
 
   rect = textAcc->CharBounds(aOffset, geckoCoordType);
 
-  *aX = rect.x;
-  *aY = rect.y;
-  *aWidth = rect.width;
-  *aHeight = rect.height;
+  // Can't use GetRect() because of long vs. int32_t mismatch
+  *aX = rect.X();
+  *aY = rect.Y();
+  *aWidth = rect.Width();
+  *aHeight = rect.Height();
   return S_OK;
 }
 
 STDMETHODIMP
 ia2AccessibleText::get_nSelections(long* aNSelections)
 {
   if (!aNSelections)
     return E_INVALIDARG;
--- a/accessible/windows/msaa/AccessibleWrap.cpp
+++ b/accessible/windows/msaa/AccessibleWrap.cpp
@@ -491,17 +491,17 @@ AccessibleWrap::get_accRole(
   // Use BSTR role to expose role attribute or tag name + namespace
   nsIContent *content = GetContent();
   if (!content)
     return E_FAIL;
 
   if (content->IsElement()) {
     nsAutoString roleString;
     // Try the role attribute.
-    content->GetAttr(kNameSpaceID_None, nsGkAtoms::role, roleString);
+    content->AsElement()->GetAttr(kNameSpaceID_None, nsGkAtoms::role, roleString);
 
     if (roleString.IsEmpty()) {
       // No role attribute (or it is an empty string).
       // Use the tag name.
       nsIDocument * document = content->GetUncomposedDoc();
       if (!document)
         return E_FAIL;
 
@@ -897,20 +897,20 @@ AccessibleWrap::accLocation(
 
   if (accessible) {
     return accessible->accLocation(pxLeft, pyTop, pcxWidth, pcyHeight,
                                    kVarChildIdSelf);
   }
 
   nsIntRect rect = Bounds();
 
-  *pxLeft = rect.x;
-  *pyTop = rect.y;
-  *pcxWidth = rect.width;
-  *pcyHeight = rect.height;
+  *pxLeft = rect.X();
+  *pyTop = rect.Y();
+  *pcxWidth = rect.Width();
+  *pcyHeight = rect.Height();
   return S_OK;
 }
 
 STDMETHODIMP
 AccessibleWrap::accNavigate(
       /* [in] */ long navDir,
       /* [optional][in] */ VARIANT varStart,
       /* [retval][out] */ VARIANT __RPC_FAR *pvarEndUpAt)
@@ -1656,22 +1656,22 @@ AccessibleWrap::UpdateSystemCaretFor(HWN
                                      const LayoutDeviceIntRect& aCaretRect)
 {
   if (!aCaretWnd || aCaretRect.IsEmpty()) {
     return;
   }
 
   // Create invisible bitmap for caret, otherwise its appearance interferes
   // with Gecko caret
-  nsAutoBitmap caretBitMap(CreateBitmap(1, aCaretRect.height, 1, 1, nullptr));
-  if (::CreateCaret(aCaretWnd, caretBitMap, 1, aCaretRect.height)) {  // Also destroys the last caret
+  nsAutoBitmap caretBitMap(CreateBitmap(1, aCaretRect.Height(), 1, 1, nullptr));
+  if (::CreateCaret(aCaretWnd, caretBitMap, 1, aCaretRect.Height())) {  // Also destroys the last caret
     ::ShowCaret(aCaretWnd);
     RECT windowRect;
     ::GetWindowRect(aCaretWnd, &windowRect);
-    ::SetCaretPos(aCaretRect.x - windowRect.left, aCaretRect.y - windowRect.top);
+    ::SetCaretPos(aCaretRect.X() - windowRect.left, aCaretRect.Y() - windowRect.top);
   }
 }
 
 ITypeInfo*
 AccessibleWrap::GetTI(LCID lcid)
 {
   if (gTypeInfo)
     return gTypeInfo;
--- a/accessible/windows/msaa/CompatibilityUIA.cpp
+++ b/accessible/windows/msaa/CompatibilityUIA.cpp
@@ -2,20 +2,23 @@
 /* vim: set ts=8 sts=2 et sw=2 tw=80: */
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #include "Compatibility.h"
 
 #include "mozilla/Telemetry.h"
+#include "mozilla/WindowsVersion.h"
 
+#include "nsDataHashtable.h"
 #include "nsPrintfCString.h"
 #include "nsReadableUtils.h"
 #include "nsString.h"
+#include "nsTHashtable.h"
 #include "nsUnicharUtils.h"
 #include "nsWinUtils.h"
 
 #include "NtUndoc.h"
 
 #if defined(UIA_LOGGING)
 
 #define LOG_ERROR(FuncName) \
@@ -26,42 +29,112 @@
   }
 
 #else
 
 #define LOG_ERROR(FuncName)
 
 #endif // defined(UIA_LOGGING)
 
-static bool
-GetLocalObjectHandle(DWORD aSrcPid, HANDLE aSrcHandle, nsAutoHandle& aProcess,
-                     nsAutoHandle& aLocal)
+struct ByteArrayDeleter
 {
-  aLocal.reset();
+  void operator()(void* aBuf)
+  {
+    delete[] reinterpret_cast<char*>(aBuf);
+  }
+};
+
+typedef UniquePtr<OBJECT_DIRECTORY_INFORMATION, ByteArrayDeleter> ObjDirInfoPtr;
 
-  if (!aProcess) {
-    HANDLE rawProcess = ::OpenProcess(PROCESS_DUP_HANDLE, FALSE, aSrcPid);
-    if (!rawProcess) {
-      LOG_ERROR(OpenProcess);
-      return false;
-    }
-
-    aProcess.own(rawProcess);
+// ComparatorFnT returns true to continue searching, or else false to indicate
+// search completion.
+template <typename ComparatorFnT>
+static bool
+FindNamedObject(ComparatorFnT aComparator)
+{
+  // We want to enumerate every named kernel object in our session. We do this
+  // by opening a directory object using a path constructed using the session
+  // id under which our process resides.
+  DWORD sessionId;
+  if (!::ProcessIdToSessionId(::GetCurrentProcessId(), &sessionId)) {
+    return false;
   }
 
-  HANDLE rawDuped;
-  if (!::DuplicateHandle(aProcess.get(), aSrcHandle, ::GetCurrentProcess(),
-                         &rawDuped, GENERIC_READ, FALSE, 0)) {
-    LOG_ERROR(DuplicateHandle);
+  nsAutoString path;
+  path.AppendPrintf("\\Sessions\\%u\\BaseNamedObjects", sessionId);
+
+  UNICODE_STRING baseNamedObjectsName;
+  ::RtlInitUnicodeString(&baseNamedObjectsName, path.get());
+
+  OBJECT_ATTRIBUTES attributes;
+  InitializeObjectAttributes(&attributes, &baseNamedObjectsName, 0,
+                             nullptr, nullptr);
+
+  HANDLE rawBaseNamedObjects;
+  NTSTATUS ntStatus = ::NtOpenDirectoryObject(&rawBaseNamedObjects,
+                                              DIRECTORY_QUERY | DIRECTORY_TRAVERSE,
+                                              &attributes);
+  if (!NT_SUCCESS(ntStatus)) {
     return false;
   }
 
-  aLocal.own(rawDuped);
+  nsAutoHandle baseNamedObjects(rawBaseNamedObjects);
+
+  ULONG context = 0, returnedLen;
+
+  ULONG objDirInfoBufLen = 1024 * sizeof(OBJECT_DIRECTORY_INFORMATION);
+  ObjDirInfoPtr objDirInfo(
+    reinterpret_cast<OBJECT_DIRECTORY_INFORMATION*>(new char[objDirInfoBufLen]));
+
+  // Now query that directory object for every named object that it contains.
+
+  BOOL firstCall = TRUE;
 
-  return true;
+  do {
+    ntStatus = ::NtQueryDirectoryObject(baseNamedObjects, objDirInfo.get(),
+                                        objDirInfoBufLen, FALSE, firstCall,
+                                        &context, &returnedLen);
+#if defined(HAVE_64BIT_BUILD)
+    if (!NT_SUCCESS(ntStatus)) {
+      return false;
+    }
+#else
+    if (ntStatus == STATUS_BUFFER_TOO_SMALL) {
+      // This case only occurs on 32-bit builds running atop WOW64.
+      // (See https://bugzilla.mozilla.org/show_bug.cgi?id=1423999#c3)
+      objDirInfo.reset(reinterpret_cast<OBJECT_DIRECTORY_INFORMATION*>(new char[returnedLen]));
+      objDirInfoBufLen = returnedLen;
+      continue;
+    } else if (!NT_SUCCESS(ntStatus)) {
+      return false;
+    }
+#endif
+
+    // NtQueryDirectoryObject gave us an array of OBJECT_DIRECTORY_INFORMATION
+    // structures whose final entry is zeroed out.
+    OBJECT_DIRECTORY_INFORMATION* curDir = objDirInfo.get();
+    while (curDir->mName.Length && curDir->mTypeName.Length) {
+      // We use nsDependentSubstring here because UNICODE_STRINGs are not
+      // guaranteed to be null-terminated.
+      nsDependentSubstring objName(curDir->mName.Buffer,
+                                   curDir->mName.Length / sizeof(wchar_t));
+      nsDependentSubstring typeName(curDir->mTypeName.Buffer,
+                                    curDir->mTypeName.Length / sizeof(wchar_t));
+
+      if (!aComparator(objName, typeName)) {
+        return true;
+      }
+
+      ++curDir;
+    }
+
+    firstCall = FALSE;
+  } while (ntStatus == STATUS_MORE_ENTRIES);
+
+  return false;
 }
 
 namespace mozilla {
 namespace a11y {
 
 Maybe<DWORD> Compatibility::sUiaRemotePid;
 
 Maybe<bool>
@@ -69,215 +142,164 @@ Compatibility::OnUIAMessage(WPARAM aWPar
 {
   Maybe<DWORD>& remotePid = sUiaRemotePid;
   auto clearUiaRemotePid = MakeScopeExit([&remotePid]() {
     remotePid = Nothing();
   });
 
   Telemetry::AutoTimer<Telemetry::A11Y_UIA_DETECTION_TIMING_MS> timer;
 
-  static auto pNtQuerySystemInformation =
-    reinterpret_cast<decltype(&::NtQuerySystemInformation)>(
-      ::GetProcAddress(::GetModuleHandleW(L"ntdll.dll"),
-                       "NtQuerySystemInformation"));
-
-  static auto pNtQueryObject =
-    reinterpret_cast<decltype(&::NtQueryObject)>(
-      ::GetProcAddress(::GetModuleHandleW(L"ntdll.dll"), "NtQueryObject"));
-
   // UIA creates a section containing the substring "HOOK_SHMEM_"
   NS_NAMED_LITERAL_STRING(kStrHookShmem, "HOOK_SHMEM_");
 
   // The section name always ends with this suffix, which is derived from the
   // current thread id and the UIA message's WPARAM and LPARAM.
   nsAutoString partialSectionSuffix;
   partialSectionSuffix.AppendPrintf("_%08x_%08x_%08x", ::GetCurrentThreadId(),
-                                    aLParam, aWParam);
+                                    static_cast<DWORD>(aLParam), aWParam);
+
+  // Find any named Section that matches the naming convention of the UIA shared
+  // memory.
+  nsAutoHandle section;
+  auto comparator = [&](const nsDependentSubstring& aName,
+                        const nsDependentSubstring& aType) -> bool {
+    if (aType.Equals(NS_LITERAL_STRING("Section")) &&
+        FindInReadable(kStrHookShmem, aName) &&
+        StringEndsWith(aName, partialSectionSuffix)) {
+      section.own(::OpenFileMapping(GENERIC_READ, FALSE,
+                                    PromiseFlatString(aName).get()));
+      return false;
+    }
+
+    return true;
+  };
+
+  if (!FindNamedObject(comparator) || !section) {
+    return Nothing();
+  }
 
   NTSTATUS ntStatus;
 
   // First we must query for a list of all the open handles in the system.
   UniquePtr<char[]> handleInfoBuf;
   ULONG handleInfoBufLen = sizeof(SYSTEM_HANDLE_INFORMATION_EX) +
                            1024 * sizeof(SYSTEM_HANDLE_TABLE_ENTRY_INFO_EX);
 
   // We must query for handle information in a loop, since we are effectively
   // asking the kernel to take a snapshot of all the handles on the system;
   // the size of the required buffer may fluctuate between successive calls.
   while (true) {
     handleInfoBuf = MakeUnique<char[]>(handleInfoBufLen);
 
-    ntStatus = pNtQuerySystemInformation(
+    ntStatus = ::NtQuerySystemInformation(
                  (SYSTEM_INFORMATION_CLASS) SystemExtendedHandleInformation,
                  handleInfoBuf.get(), handleInfoBufLen, &handleInfoBufLen);
     if (ntStatus == STATUS_INFO_LENGTH_MISMATCH) {
       continue;
     }
 
     if (!NT_SUCCESS(ntStatus)) {
       return Nothing();
     }
 
     break;
   }
 
-  // Now we iterate through the system handle list, searching for a section
-  // handle whose name matches the section name used by UIA.
-
-  static Maybe<USHORT> sSectionObjTypeIndex;
-
   const DWORD ourPid = ::GetCurrentProcessId();
-
   Maybe<PVOID> kernelObject;
-
-  ULONG lastPid = 0;
-  nsAutoHandle process;
+  static Maybe<USHORT> sectionObjTypeIndex;
+  nsTHashtable<nsUint32HashKey> nonSectionObjTypes;
+  nsDataHashtable<nsVoidPtrHashKey, DWORD> objMap;
 
   auto handleInfo = reinterpret_cast<SYSTEM_HANDLE_INFORMATION_EX*>(handleInfoBuf.get());
 
   for (ULONG index = 0; index < handleInfo->mHandleCount; ++index) {
     SYSTEM_HANDLE_TABLE_ENTRY_INFO_EX& curHandle = handleInfo->mHandles[index];
 
-    if (lastPid && lastPid == curHandle.mPid && !process) {
-      // During the previous iteration, we could not obtain a handle for this
-      // pid. Skip any remaining handles belonging to that pid.
-      continue;
-    }
-
-    // As a perf optimization, we reuse the same process handle as long as we're
-    // still looking at the same pid. Once the pid changes, we need to reset
-    // process so that we open a new handle to the newly-seen process.
-    if (lastPid != curHandle.mPid) {
-      process.reset();
-    }
+    HANDLE handle = reinterpret_cast<HANDLE>(curHandle.mHandle);
 
-    nsAutoHandle handle;
-
-    if (kernelObject.isSome() && kernelObject.value() == curHandle.mObject) {
-      // If we know the value of the underlying kernel object, we can immediately
-      // check for equality by comparing against curHandle.mObject
-      remotePid = Some(static_cast<DWORD>(curHandle.mPid));
-      break;
-    } else if (sSectionObjTypeIndex.isSome()) {
-      // Otherwise, if we know which object type value corresponds to a Section
-      // object, we can use that to eliminate any handles that are not sections.
-      if (curHandle.mObjectTypeIndex != sSectionObjTypeIndex.value()) {
-        // Not a section handle
+    // The mapping of the curHandle.mObjectTypeIndex field depends on the
+    // underlying OS kernel. As we scan through the handle list, we record the
+    // type indices such that we may use those values to skip over handles that
+    // refer to non-section objects.
+    if (sectionObjTypeIndex) {
+      // If we know the type index for Sections, that's the fastest check...
+      if (sectionObjTypeIndex.value() != curHandle.mObjectTypeIndex) {
+        // Not a section
         continue;
       }
-    } else {
-      // Otherwise we need to query the handle to determine its type. Note that
-      // each handle in the system list is relative to its owning process, so
-      // we cannot do anything with it until we duplicate the handle into our
-      // own process.
-
-      lastPid = curHandle.mPid;
-
-      if (!GetLocalObjectHandle((DWORD) curHandle.mPid,
-                                (HANDLE) curHandle.mHandle,
-                                process, handle)) {
-        // We don't have access to do this, assume this handle isn't relevant
-        continue;
-      }
-
-      // Now we have our own handle to the object, lets find out what type of
-      // object this handle represents. Any handle whose type is not "Section"
-      // is of no interest to us.
+    } else if (nonSectionObjTypes.Contains(static_cast<uint32_t>(
+                                             curHandle.mObjectTypeIndex))) {
+      // Otherwise we check whether or not the object type is definitely _not_
+      // a Section...
+      continue;
+    } else if (ourPid == curHandle.mPid) {
+      // Otherwise we need to issue some system calls to find out the object
+      // type corresponding to the current handle's type index.
       ULONG objTypeBufLen;
-      ntStatus = pNtQueryObject(handle, ObjectTypeInformation, nullptr,
-                                0, &objTypeBufLen);
+      ntStatus = ::NtQueryObject(handle, ObjectTypeInformation,
+                                 nullptr, 0, &objTypeBufLen);
       if (ntStatus != STATUS_INFO_LENGTH_MISMATCH) {
         continue;
       }
 
       auto objTypeBuf = MakeUnique<char[]>(objTypeBufLen);
-      ntStatus = pNtQueryObject(handle, ObjectTypeInformation, objTypeBuf.get(),
-                                objTypeBufLen, &objTypeBufLen);
+      ntStatus = ::NtQueryObject(handle, ObjectTypeInformation, objTypeBuf.get(),
+                                 objTypeBufLen, &objTypeBufLen);
       if (!NT_SUCCESS(ntStatus)) {
-        // We don't have access to do this, assume this handle isn't relevant
         continue;
       }
 
       auto objType =
         reinterpret_cast<PUBLIC_OBJECT_TYPE_INFORMATION*>(objTypeBuf.get());
 
-      nsDependentString objTypeName(objType->TypeName.Buffer,
-                                    objType->TypeName.Length / sizeof(wchar_t));
+      // Now we check whether the object's type name matches "Section"
+      nsDependentSubstring objTypeName(objType->TypeName.Buffer,
+                                       objType->TypeName.Length / sizeof(wchar_t));
       if (!objTypeName.Equals(NS_LITERAL_STRING("Section"))) {
-        // Not a section, so we don't care about this handle anymore.
+        nonSectionObjTypes.PutEntry(static_cast<uint32_t>(curHandle.mObjectTypeIndex));
         continue;
       }
 
-      // We have a section, save this handle's type code so that we can go
-      // faster in future iterations.
-      sSectionObjTypeIndex = Some(curHandle.mObjectTypeIndex);
-    }
-
-    // If we reached this point without needing to query the handle, then we
-    // need to open it here so that we can query its name.
-    lastPid = curHandle.mPid;
-
-    if ((!process || !handle) &&
-        !GetLocalObjectHandle((DWORD) curHandle.mPid, (HANDLE) curHandle.mHandle,
-                              process, handle)) {
-      // We don't have access to do this, assume this handle isn't relevant
-      continue;
-    }
-
-    // At this point, |handle| is a valid section handle. Let's try to find
-    // out the name of its underlying object.
-    ULONG objNameBufLen;
-    ntStatus = pNtQueryObject(handle,
-                              (OBJECT_INFORMATION_CLASS)ObjectNameInformation,
-                              nullptr, 0, &objNameBufLen);
-    if (ntStatus != STATUS_INFO_LENGTH_MISMATCH) {
-      continue;
-    }
-
-    auto objNameBuf = MakeUnique<char[]>(objNameBufLen);
-    ntStatus = pNtQueryObject(handle,
-                              (OBJECT_INFORMATION_CLASS)ObjectNameInformation,
-                              objNameBuf.get(), objNameBufLen, &objNameBufLen);
-    if (!NT_SUCCESS(ntStatus)) {
-      continue;
+      sectionObjTypeIndex = Some(curHandle.mObjectTypeIndex);
     }
 
-    auto objNameInfo = reinterpret_cast<OBJECT_NAME_INFORMATION*>(objNameBuf.get());
-    if (!objNameInfo->mName.Length) {
-      // This section is unnamed. We don't care about those.
-      continue;
-    }
+    // At this point we know that curHandle references a Section object.
+    // Now we can do some actual tests on it.
 
-    nsDependentString objName(objNameInfo->mName.Buffer,
-                              objNameInfo->mName.Length / sizeof(wchar_t));
-
-    // Check to see if the section's name matches our expected name.
-    if (!FindInReadable(kStrHookShmem, objName) ||
-        !StringEndsWith(objName, partialSectionSuffix)) {
-      // The names don't match, continue searching.
-      continue;
-    }
+    if (ourPid != curHandle.mPid) {
+      if (kernelObject && kernelObject.value() == curHandle.mObject) {
+        // The kernel objects match -- we have found the remote pid!
+        remotePid = Some(curHandle.mPid);
+        break;
+      }
 
-    // At this point we have a section handle whose name matches the one that
-    // we're looking for.
-
-    if (curHandle.mPid == ourPid) {
-      // Our own process also has a handle to the section of interest. While we
-      // don't want our own pid, this *does* give us an opportunity to speed up
-      // future iterations by examining each handle for its kernel object (which
-      // is the same for all processes) instead of searching by name.
+      // An object that is not ours. Since we do not yet know which kernel
+      // object we're interested in, we'll save the current object for later.
+      objMap.Put(curHandle.mObject, curHandle.mPid);
+    } else if (handle == section.get()) {
+      // This is the file mapping that we opened above. We save this mObject
+      // in order to compare to Section objects opened by other processes.
       kernelObject = Some(curHandle.mObject);
-      continue;
     }
+  }
+
+  if (!kernelObject) {
+    return Nothing();
+  }
 
-    // Bingo! We want this pid!
-    remotePid = Some(static_cast<DWORD>(curHandle.mPid));
+  if (!remotePid) {
+    // We found kernelObject *after* we saw the remote process's copy. Now we
+    // must look it up in objMap.
+    DWORD pid;
+    if (objMap.Get(kernelObject.value(), &pid)) {
+      remotePid = Some(pid);
+    }
+  }
 
-    break;
-  }
 
   if (!remotePid) {
     return Nothing();
   }
 
   a11y::SetInstantiator(remotePid.value());
 
   /* This is where we could block UIA stuff
--- a/accessible/windows/msaa/DocAccessibleWrap.cpp
+++ b/accessible/windows/msaa/DocAccessibleWrap.cpp
@@ -149,33 +149,33 @@ DocAccessibleWrap::DoInitialUpdate()
     // Create window for tab document.
     if (mDocFlags & eTabDocument) {
       a11y::RootAccessible* rootDocument = RootAccessible();
       bool isActive = true;
       nsIntRect rect(CW_USEDEFAULT, CW_USEDEFAULT, 0, 0);
       if (Compatibility::IsDolphin()) {
         rect = Bounds();
         nsIntRect rootRect = rootDocument->Bounds();
-        rect.x = rootRect.x - rect.x;
-        rect.y -= rootRect.y;
+        rect.MoveToX(rootRect.X() - rect.X());
+        rect.MoveByY(-rootRect.Y());
 
         nsCOMPtr<nsISupports> container = mDocumentNode->GetContainer();
         nsCOMPtr<nsIDocShell> docShell = do_QueryInterface(container);
         docShell->GetIsActive(&isActive);
       }
 
       RefPtr<DocAccessibleWrap> self(this);
       nsWinUtils::NativeWindowCreateProc onCreate([self](HWND aHwnd) -> void {
         ::SetPropW(aHwnd, kPropNameDocAcc, reinterpret_cast<HANDLE>(self.get()));
       });
 
       HWND parentWnd = reinterpret_cast<HWND>(rootDocument->GetNativeWindow());
       mHWND = nsWinUtils::CreateNativeWindow(kClassNameTabContent, parentWnd,
-                                             rect.x, rect.y,
-                                             rect.width, rect.height, isActive,
+                                             rect.X(), rect.Y(),
+                                             rect.Width(), rect.Height(), isActive,
                                              &onCreate);
     } else {
       DocAccessible* parentDocument = ParentDocument();
       if (parentDocument)
         mHWND = parentDocument->GetNativeWindow();
     }
   }
 }
--- a/accessible/windows/msaa/NtUndoc.h
+++ b/accessible/windows/msaa/NtUndoc.h
@@ -4,20 +4,32 @@
  * 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_NtUndoc_h
 #define mozilla_NtUndoc_h
 
 #include <winternl.h>
 
+#if defined(__cplusplus)
+extern "C" {
+#endif
+
 #ifndef STATUS_INFO_LENGTH_MISMATCH
 #define STATUS_INFO_LENGTH_MISMATCH ((NTSTATUS)0xC0000004L)
 #endif
 
+#ifndef STATUS_BUFFER_TOO_SMALL
+#define STATUS_BUFFER_TOO_SMALL ((NTSTATUS)0xC0000023L)
+#endif
+
+#ifndef STATUS_MORE_ENTRIES
+#define STATUS_MORE_ENTRIES ((NTSTATUS)0x00000105L)
+#endif
+
 enum UndocSystemInformationClass
 {
   SystemExtendedHandleInformation = 64
 };
 
 struct SYSTEM_HANDLE_TABLE_ENTRY_INFO_EX
 {
   PVOID       mObject;
@@ -42,9 +54,41 @@ enum UndocObjectInformationClass
   ObjectNameInformation = 1
 };
 
 struct OBJECT_NAME_INFORMATION
 {
   UNICODE_STRING  mName;
 };
 
+// The following declarations are documented on MSDN but are not included in
+// public user-mode headers.
+
+enum DirectoryObjectAccessFlags
+{
+  DIRECTORY_QUERY = 0x0001,
+  DIRECTORY_TRAVERSE = 0x0002,
+  DIRECTORY_CREATE_OBJECT = 0x0004,
+  DIRECTORY_CREATE_SUBDIRECTORY = 0x0008,
+  DIRECTORY_ALL_ACCESS = STANDARD_RIGHTS_REQUIRED | 0x000F
+};
+
+NTSTATUS WINAPI
+NtOpenDirectoryObject(PHANDLE aDirectoryHandle, ACCESS_MASK aDesiredAccess,
+                      POBJECT_ATTRIBUTES aObjectAttributes);
+
+struct OBJECT_DIRECTORY_INFORMATION
+{
+  UNICODE_STRING  mName;
+  UNICODE_STRING  mTypeName;
+};
+
+NTSTATUS WINAPI
+NtQueryDirectoryObject(HANDLE aDirectoryHandle, PVOID aOutBuffer,
+                       ULONG aBufferLength, BOOLEAN aReturnSingleEntry,
+                       BOOLEAN aRestartScan, PULONG aContext,
+                       PULONG aOutReturnLength);
+
+#if defined(__cplusplus)
+} // extern "C"
+#endif
+
 #endif // mozilla_NtUndoc_h
--- a/accessible/windows/msaa/XULMenuAccessibleWrap.cpp
+++ b/accessible/windows/msaa/XULMenuAccessibleWrap.cpp
@@ -23,14 +23,16 @@ XULMenuitemAccessibleWrap::Name(nsString
 {
   // XXX This should be done in MSAA's get_accName() so that Accessible::Name()]
   // provides the same results on all platforms
   XULMenuitemAccessible::Name(aName);
   if (aName.IsEmpty())
     return eNameOK;
 
   nsAutoString accel;
-  mContent->GetAttr(kNameSpaceID_None, nsGkAtoms::acceltext, accel);
+  if (mContent->IsElement()) {
+    mContent->AsElement()->GetAttr(kNameSpaceID_None, nsGkAtoms::acceltext, accel);
+  }
   if (!accel.IsEmpty())
     aName += NS_LITERAL_STRING("\t") + accel;
 
   return eNameOK;
 }
--- a/accessible/windows/msaa/moz.build
+++ b/accessible/windows/msaa/moz.build
@@ -41,16 +41,20 @@ UNIFIED_SOURCES += [
 
 SOURCES += [
     # This file cannot be built in unified mode because it redefines _WIN32_WINNT
     'LazyInstantiator.cpp',
     # This file cannot be built in unified mode because it includes ISimpleDOMNode_i.c.
     'ServiceProvider.cpp',
 ]
 
+OS_LIBS += [
+    'ntdll',
+]
+
 if CONFIG['MOZ_XUL']:
     UNIFIED_SOURCES += [
         'XULListboxAccessibleWrap.cpp',
         'XULMenuAccessibleWrap.cpp',
         'XULTreeGridAccessibleWrap.cpp',
     ]
 
 LOCAL_INCLUDES += [
--- a/accessible/windows/msaa/nsWinUtils.cpp
+++ b/accessible/windows/msaa/nsWinUtils.cpp
@@ -34,35 +34,34 @@ const wchar_t* kPropNameTabContent = L"A
 /**
  * WindowProc to process WM_GETOBJECT messages, used in windows emulation mode.
  */
 static LRESULT CALLBACK WindowProc(HWND hWnd, UINT msg,
                                    WPARAM wParam, LPARAM lParam);
 
 bool nsWinUtils::sWindowEmulationStarted = false;
 
-already_AddRefed<nsIDOMCSSStyleDeclaration>
+already_AddRefed<nsICSSDeclaration>
 nsWinUtils::GetComputedStyleDeclaration(nsIContent* aContent)
 {
   nsIContent* elm = nsCoreUtils::GetDOMElementFor(aContent);
   if (!elm)
     return nullptr;
 
   // Returns number of items in style declaration
   nsCOMPtr<nsPIDOMWindowInner> window = elm->OwnerDoc()->GetInnerWindow();
   if (!window)
     return nullptr;
 
   ErrorResult dummy;
-  nsCOMPtr<nsICSSDeclaration> cssDecl;
   nsCOMPtr<Element> domElement(do_QueryInterface(elm));
-  cssDecl = window->GetComputedStyle(*domElement, EmptyString(), dummy);
-  nsCOMPtr<nsIDOMCSSStyleDeclaration> domDecl = do_QueryInterface(cssDecl);
+  nsCOMPtr<nsICSSDeclaration> cssDecl =
+     window->GetComputedStyle(*domElement, EmptyString(), dummy);
   dummy.SuppressException();
-  return domDecl.forget();
+  return cssDecl.forget();
 }
 
 bool
 nsWinUtils::MaybeStartWindowEmulation()
 {
   // Register window class that'll be used for document accessibles associated
   // with tabs.
   if (IPCAccessibilityActive())
--- a/accessible/windows/msaa/nsWinUtils.h
+++ b/accessible/windows/msaa/nsWinUtils.h
@@ -6,17 +6,17 @@
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #ifndef nsWinUtils_h_
 #define nsWinUtils_h_
 
 #include <functional>
 #include <windows.h>
 
-#include "nsIDOMCSSStyleDeclaration.h"
+#include "nsICSSDeclaration.h"
 #include "nsCOMPtr.h"
 
 class nsIContent;
 
 namespace mozilla {
 namespace a11y {
 
 class DocAccessible;
@@ -30,17 +30,17 @@ class nsWinUtils
 {
 public:
   /**
    * Return computed styles declaration for the given node.
    *
    * @note Please use it carefully since it can shutdown the accessible tree
    *       you operate on.
    */
-  static already_AddRefed<nsIDOMCSSStyleDeclaration>
+  static already_AddRefed<nsICSSDeclaration>
     GetComputedStyleDeclaration(nsIContent* aContent);
 
   /**
    * Start window emulation if presence of specific AT is detected.
    */
   static bool MaybeStartWindowEmulation();
 
   /**
--- a/accessible/windows/sdn/sdnAccessible.cpp
+++ b/accessible/windows/sdn/sdnAccessible.cpp
@@ -8,17 +8,17 @@
 #include "ISimpleDOM_i.c"
 
 #include "DocAccessibleWrap.h"
 
 #include "nsAttrName.h"
 #include "nsCoreUtils.h"
 #include "nsIAccessibleTypes.h"
 #include "nsIDOMHTMLElement.h"
-#include "nsIDOMCSSStyleDeclaration.h"
+#include "nsICSSDeclaration.h"
 #include "nsNameSpaceManager.h"
 #include "nsServiceManagerUtils.h"
 #include "nsWinUtils.h"
 #include "nsRange.h"
 
 #include "mozilla/dom/BorrowedAttrInfo.h"
 #include "mozilla/dom/Element.h"
 
@@ -226,30 +226,31 @@ sdnAccessible::get_computedStyle(unsigne
   if (IsDefunct())
     return CO_E_OBJNOTCONNECTED;
 
   *aNumStyleProperties = 0;
 
   if (mNode->IsNodeOfType(nsINode::eDOCUMENT))
     return S_FALSE;
 
-  nsCOMPtr<nsIDOMCSSStyleDeclaration> cssDecl =
+  nsCOMPtr<nsICSSDeclaration> cssDecl =
     nsWinUtils::GetComputedStyleDeclaration(mNode->AsContent());
   NS_ENSURE_TRUE(cssDecl, E_FAIL);
 
   uint32_t length = 0;
   cssDecl->GetLength(&length);
 
   uint32_t index = 0, realIndex = 0;
   for (index = realIndex = 0; index < length && realIndex < aMaxStyleProperties;
        index ++) {
     nsAutoString property, value;
 
     // Ignore -moz-* properties.
-    if (NS_SUCCEEDED(cssDecl->Item(index, property)) && property.CharAt(0) != '-')
+    cssDecl->Item(index, property);
+    if (property.CharAt(0) != '-')
       cssDecl->GetPropertyValue(property, value);  // Get property value
 
     if (!value.IsEmpty()) {
       aStyleProperties[realIndex] = ::SysAllocString(property.get());
       aStyleValues[realIndex] = ::SysAllocString(value.get());
       ++realIndex;
     }
   }
@@ -269,17 +270,17 @@ sdnAccessible::get_computedStyleForPrope
     return E_INVALIDARG;
 
   if (IsDefunct())
     return CO_E_OBJNOTCONNECTED;
 
   if (mNode->IsNodeOfType(nsINode::eDOCUMENT))
     return S_FALSE;
 
-  nsCOMPtr<nsIDOMCSSStyleDeclaration> cssDecl =
+  nsCOMPtr<nsICSSDeclaration> cssDecl =
     nsWinUtils::GetComputedStyleDeclaration(mNode->AsContent());
   NS_ENSURE_TRUE(cssDecl, E_FAIL);
 
   uint32_t index = 0;
   for (index = 0; index < aNumStyleProperties; index++) {
     nsAutoString value;
     if (aStyleProperties[index])
       cssDecl->GetPropertyValue(nsDependentString(aStyleProperties[index]), value);  // Get property value
@@ -408,17 +409,17 @@ sdnAccessible::get_childAt(unsigned aChi
 {
   if (!aNode)
     return E_INVALIDARG;
   *aNode = nullptr;
 
   if (IsDefunct())
     return CO_E_OBJNOTCONNECTED;
 
-  nsINode* resultNode = mNode->GetChildAt(aChildIndex);
+  nsINode* resultNode = mNode->GetChildAt_Deprecated(aChildIndex);
   if (resultNode) {
     *aNode = static_cast<ISimpleDOMNode*>(new sdnAccessible(resultNode));
     (*aNode)->AddRef();
   }
 
 
   return S_OK;
 }
--- a/accessible/windows/sdn/sdnTextAccessible.cpp
+++ b/accessible/windows/sdn/sdnTextAccessible.cpp
@@ -70,20 +70,20 @@ sdnTextAccessible::get_clippedSubstringB
                "There must always be a doc accessible, but there isn't. Crash!");
 
   nsIntRect docRect = document->Bounds();
   nsIntRect unclippedRect(x, y, width, height);
 
   nsIntRect clippedRect;
   clippedRect.IntersectRect(unclippedRect, docRect);
 
-  *aX = clippedRect.x;
-  *aY = clippedRect.y;
-  *aWidth = clippedRect.width;
-  *aHeight = clippedRect.height;
+  *aX = clippedRect.X();
+  *aY = clippedRect.Y();
+  *aWidth = clippedRect.Width();
+  *aHeight = clippedRect.Height();
   return S_OK;
 }
 
 STDMETHODIMP
 sdnTextAccessible::get_unclippedSubstringBounds(unsigned int aStartIndex,
                                                 unsigned int aEndIndex,
                                                 int __RPC_FAR* aX,
                                                 int __RPC_FAR* aY,
@@ -107,27 +107,27 @@ sdnTextAccessible::get_unclippedSubstrin
     return E_FAIL;
 
   nsRect sum;
   nsIFrame* iter = startFrame;
   nsIFrame* stopLoopFrame = endFrame->GetNextContinuation();
   for (; iter != stopLoopFrame; iter = iter->GetNextContinuation()) {
     nsRect rect = iter->GetScreenRectInAppUnits();
     nscoord start = (iter == startFrame) ? startPoint.x : 0;
-    nscoord end = (iter == endFrame) ? endPoint.x : rect.width;
-    rect.x += start;
-    rect.width = end - start;
+    nscoord end = (iter == endFrame) ? endPoint.x : rect.Width();
+    rect.MoveByX(start);
+    rect.SetWidth(end - start);
     sum.UnionRect(sum, rect);
   }
 
   nsPresContext* presContext = mAccessible->Document()->PresContext();
-  *aX = presContext->AppUnitsToDevPixels(sum.x);
-  *aY = presContext->AppUnitsToDevPixels(sum.y);
-  *aWidth = presContext->AppUnitsToDevPixels(sum.width);
-  *aHeight = presContext->AppUnitsToDevPixels(sum.height);
+  *aX = presContext->AppUnitsToDevPixels(sum.X());
+  *aY = presContext->AppUnitsToDevPixels(sum.Y());
+  *aWidth = presContext->AppUnitsToDevPixels(sum.Width());
+  *aHeight = presContext->AppUnitsToDevPixels(sum.Height());
 
   return S_OK;
 }
 
 STDMETHODIMP
 sdnTextAccessible::scrollToSubstring(unsigned int aStartIndex,
                                      unsigned int aEndIndex)
 {
--- a/accessible/xpcom/xpcAccessible.cpp
+++ b/accessible/xpcom/xpcAccessible.cpp
@@ -447,21 +447,17 @@ xpcAccessible::GetBounds(int32_t* aX, in
 
   nsIntRect rect;
   if (Accessible* acc = IntlGeneric().AsAccessible()) {
     rect = acc->Bounds();
   } else {
     rect = IntlGeneric().AsProxy()->Bounds();
   }
 
-  *aX = rect.x;
-  *aY = rect.y;
-  *aWidth = rect.width;
-  *aHeight = rect.height;
-
+  rect.GetRect(aX, aY, aWidth, aHeight);
   return NS_OK;
 }
 
 NS_IMETHODIMP
 xpcAccessible::GroupPosition(int32_t* aGroupLevel,
                              int32_t* aSimilarItemsInGroup,
                              int32_t* aPositionInGroup)
 {
--- a/accessible/xpcom/xpcAccessibleHyperText.cpp
+++ b/accessible/xpcom/xpcAccessibleHyperText.cpp
@@ -265,18 +265,17 @@ xpcAccessibleHyperText::GetCharacterExte
     rect = Intl()->CharBounds(aOffset, aCoordType);
   } else {
 #if defined(XP_WIN)
     return NS_ERROR_NOT_IMPLEMENTED;
 #else
     rect = mIntl.AsProxy()->CharBounds(aOffset, aCoordType);
 #endif
   }
-  *aX = rect.x; *aY = rect.y;
-  *aWidth = rect.width; *aHeight = rect.height;
+  rect.GetRect(aX, aY, aWidth, aHeight);
   return NS_OK;
 }
 
 NS_IMETHODIMP
 xpcAccessibleHyperText::GetRangeExtents(int32_t aStartOffset, int32_t aEndOffset,
                                         int32_t* aX, int32_t* aY,
                                         int32_t* aWidth, int32_t* aHeight,
                                         uint32_t aCoordType)
@@ -295,18 +294,17 @@ xpcAccessibleHyperText::GetRangeExtents(
     rect = Intl()->TextBounds(aStartOffset, aEndOffset, aCoordType);
   } else {
 #if defined(XP_WIN)
     return NS_ERROR_NOT_IMPLEMENTED;
 #else
     rect = mIntl.AsProxy()->TextBounds(aStartOffset, aEndOffset, aCoordType);
 #endif
   }
-  *aX = rect.x; *aY = rect.y;
-  *aWidth = rect.width; *aHeight = rect.height;
+  rect.GetRect(aX, aY, aWidth, aHeight);
   return NS_OK;
 }
 
 NS_IMETHODIMP
 xpcAccessibleHyperText::GetOffsetAtPoint(int32_t aX, int32_t aY,
                                          uint32_t aCoordType, int32_t* aOffset)
 {
   NS_ENSURE_ARG_POINTER(aOffset);
--- a/accessible/xul/XULColorPickerAccessible.cpp
+++ b/accessible/xul/XULColorPickerAccessible.cpp
@@ -30,30 +30,30 @@ XULColorPickerTileAccessible::
 ////////////////////////////////////////////////////////////////////////////////
 // XULColorPickerTileAccessible: Accessible
 
 void
 XULColorPickerTileAccessible::Value(nsString& aValue)
 {
   aValue.Truncate();
 
-  mContent->GetAttr(kNameSpaceID_None, nsGkAtoms::color, aValue);
+  mContent->AsElement()->GetAttr(kNameSpaceID_None, nsGkAtoms::color, aValue);
 }
 
 role
 XULColorPickerTileAccessible::NativeRole()
 {
   return roles::PUSHBUTTON;
 }
 
 uint64_t
 XULColorPickerTileAccessible::NativeState()
 {
   uint64_t state = AccessibleWrap::NativeState();
-  if (mContent->HasAttr(kNameSpaceID_None, nsGkAtoms::selected))
+  if (mContent->AsElement()->HasAttr(kNameSpaceID_None, nsGkAtoms::selected))
     state |= states::SELECTED;
 
   return state;
 }
 
 uint64_t
 XULColorPickerTileAccessible::NativeInteractiveState() const
 {
@@ -133,11 +133,12 @@ XULColorPickerAccessible::AreItemsOperab
 // XULColorPickerAccessible: Accessible
 
 bool
 XULColorPickerAccessible::IsAcceptableChild(nsIContent* aEl) const
 {
   nsAutoString role;
   nsCoreUtils::XBLBindingRole(aEl, role);
   return role.EqualsLiteral("xul:panel") &&
-    aEl->AttrValueIs(kNameSpaceID_None, nsGkAtoms::noautofocus,
-                     nsGkAtoms::_true, eCaseMatters);
+    aEl->IsElement() &&
+    aEl->AsElement()->AttrValueIs(kNameSpaceID_None, nsGkAtoms::noautofocus,
+                                  nsGkAtoms::_true, eCaseMatters);
 }
--- a/accessible/xul/XULComboboxAccessible.cpp
+++ b/accessible/xul/XULComboboxAccessible.cpp
@@ -21,28 +21,29 @@ using namespace mozilla::a11y;
 ////////////////////////////////////////////////////////////////////////////////
 // XULComboboxAccessible
 ////////////////////////////////////////////////////////////////////////////////
 
 XULComboboxAccessible::
   XULComboboxAccessible(nsIContent* aContent, DocAccessible* aDoc) :
   AccessibleWrap(aContent, aDoc)
 {
-  if (mContent->AttrValueIs(kNameSpaceID_None, nsGkAtoms::type,
-                            nsGkAtoms::autocomplete, eIgnoreCase))
+  if (mContent->AsElement()->AttrValueIs(kNameSpaceID_None, nsGkAtoms::type,
+                                         nsGkAtoms::autocomplete, eIgnoreCase))
     mGenericTypes |= eAutoComplete;
   else
     mGenericTypes |= eCombobox;
 
   // Both the XUL <textbox type="autocomplete"> and <menulist editable="true">
   // widgets use XULComboboxAccessible. We need to walk the anonymous children
   // for these so that the entry field is a child. Otherwise no XBL children.
   if (!mContent->NodeInfo()->Equals(nsGkAtoms::textbox, kNameSpaceID_XUL) &&
-      !mContent->AttrValueIs(kNameSpaceID_None, nsGkAtoms::editable,
-                             nsGkAtoms::_true, eIgnoreCase)) {
+      !mContent->AsElement()->AttrValueIs(kNameSpaceID_None,
+                                          nsGkAtoms::editable, nsGkAtoms::_true,
+                                          eIgnoreCase)) {
     mStateFlags |= eNoXBLKids;
   }
 }
 
 role
 XULComboboxAccessible::NativeRole()
 {
   return IsAutoComplete() ? roles::AUTOCOMPLETE : roles::COMBOBOX;
@@ -150,18 +151,18 @@ XULComboboxAccessible::ActionNameAt(uint
 
 ////////////////////////////////////////////////////////////////////////////////
 // Widgets
 
 bool
 XULComboboxAccessible::IsActiveWidget() const
 {
   if (IsAutoComplete() ||
-     mContent->AttrValueIs(kNameSpaceID_None, nsGkAtoms::editable,
-                           nsGkAtoms::_true, eIgnoreCase)) {
+     mContent->AsElement()->AttrValueIs(kNameSpaceID_None, nsGkAtoms::editable,
+                                        nsGkAtoms::_true, eIgnoreCase)) {
     int32_t childCount = mChildren.Length();
     for (int32_t idx = 0; idx < childCount; idx++) {
       Accessible* child = mChildren[idx];
       if (child->Role() == roles::ENTRY)
         return FocusMgr()->HasDOMFocus(child->GetContent());
     }
     return false;
   }
--- a/accessible/xul/XULElementAccessibles.cpp
+++ b/accessible/xul/XULElementAccessibles.cpp
@@ -179,23 +179,23 @@ XULLinkAccessible::~XULLinkAccessible()
 ////////////////////////////////////////////////////////////////////////////////
 // XULLinkAccessible: Accessible
 
 void
 XULLinkAccessible::Value(nsString& aValue)
 {
   aValue.Truncate();
 
-  mContent->GetAttr(kNameSpaceID_None, nsGkAtoms::href, aValue);
+  mContent->AsElement()->GetAttr(kNameSpaceID_None, nsGkAtoms::href, aValue);
 }
 
 ENameValueFlag
 XULLinkAccessible::NativeName(nsString& aName)
 {
-  mContent->GetAttr(kNameSpaceID_None, nsGkAtoms::value, aName);
+  mContent->AsElement()->GetAttr(kNameSpaceID_None, nsGkAtoms::value, aName);
   if (!aName.IsEmpty())
     return eNameOK;
 
   nsTextEquivUtils::GetNameFromSubtree(this, aName);
   return aName.IsEmpty() ? eNameOK : eNameFromSubtree;
 }
 
 role
@@ -269,17 +269,17 @@ XULLinkAccessible::EndOffset()
 
 already_AddRefed<nsIURI>
 XULLinkAccessible::AnchorURIAt(uint32_t aAnchorIndex)
 {
   if (aAnchorIndex != 0)
     return nullptr;
 
   nsAutoString href;
-  mContent->GetAttr(kNameSpaceID_None, nsGkAtoms::href, href);
+  mContent->AsElement()->GetAttr(kNameSpaceID_None, nsGkAtoms::href, href);
 
   nsCOMPtr<nsIURI> baseURI = mContent->GetBaseURI();
   nsIDocument* document = mContent->OwnerDoc();
 
   nsCOMPtr<nsIURI> anchorURI;
   NS_NewURI(getter_AddRefs(anchorURI), href,
             document->GetDocumentCharacterSet(),
             baseURI);
--- a/accessible/xul/XULFormControlAccessible.cpp
+++ b/accessible/xul/XULFormControlAccessible.cpp
@@ -117,17 +117,17 @@ XULButtonAccessible::NativeState()
         }
       }
     }
   }
 
   if (ContainsMenu())
     state |= states::HASPOPUP;
 
-  if (mContent->HasAttr(kNameSpaceID_None, nsGkAtoms::_default))
+  if (mContent->AsElement()->HasAttr(kNameSpaceID_None, nsGkAtoms::_default))
     state |= states::DEFAULT;
 
   return state;
 }
 
 ////////////////////////////////////////////////////////////////////////////////
 // XULButtonAccessible: Widgets
 
@@ -184,32 +184,32 @@ XULButtonAccessible::IsAcceptableChild(n
   // Button type="menu-button" contains a real button. Get an accessible
   // for it. Ignore dropmarker button which is placed as a last child.
   if ((!role.EqualsLiteral("xul:button") &&
        !role.EqualsLiteral("xul:toolbarbutton")) ||
       aEl->IsXULElement(nsGkAtoms::dropMarker)) {
     return false;
   }
 
-  return mContent->AttrValueIs(kNameSpaceID_None, nsGkAtoms::type,
-                               nsGkAtoms::menuButton, eCaseMatters);
+  return mContent->AsElement()->AttrValueIs(kNameSpaceID_None, nsGkAtoms::type,
+                                            nsGkAtoms::menuButton, eCaseMatters);
 }
 
 ////////////////////////////////////////////////////////////////////////////////
 // XULButtonAccessible protected
 
 bool
 XULButtonAccessible::ContainsMenu() const
 {
-  static nsIContent::AttrValuesArray strings[] =
+  static Element::AttrValuesArray strings[] =
     {&nsGkAtoms::menu, &nsGkAtoms::menuButton, nullptr};
 
-  return mContent->FindAttrValueIn(kNameSpaceID_None,
-                                   nsGkAtoms::type,
-                                   strings, eCaseMatters) >= 0;
+  return mContent->AsElement()->FindAttrValueIn(kNameSpaceID_None,
+                                                nsGkAtoms::type,
+                                                strings, eCaseMatters) >= 0;
 }
 
 ////////////////////////////////////////////////////////////////////////////////
 // XULDropmarkerAccessible
 ////////////////////////////////////////////////////////////////////////////////
 
 XULDropmarkerAccessible::
   XULDropmarkerAccessible(nsIContent* aContent, DocAccessible* aDoc) :
@@ -598,17 +598,17 @@ role
 XULToolbarAccessible::NativeRole()
 {
   return roles::TOOLBAR;
 }
 
 ENameValueFlag
 XULToolbarAccessible::NativeName(nsString& aName)
 {
-  if (mContent->GetAttr(kNameSpaceID_None, nsGkAtoms::toolbarname, aName))
+  if (mContent->AsElement()->GetAttr(kNameSpaceID_None, nsGkAtoms::toolbarname, aName))
     aName.CompressWhitespace();
 
   return eNameOK;
 }
 
 
 ////////////////////////////////////////////////////////////////////////////////
 // XULToolbarAccessible
--- a/accessible/xul/XULListboxAccessible.cpp
+++ b/accessible/xul/XULListboxAccessible.cpp
@@ -121,18 +121,18 @@ XULListboxAccessible::NativeState()
   // As a XULListboxAccessible we can have the following states:
   //   FOCUSED, READONLY, FOCUSABLE
 
   // Get focus status from base class
   uint64_t states = Accessible::NativeState();
 
   // see if we are multiple select if so set ourselves as such
 
-  if (mContent->AttrValueIs(kNameSpaceID_None, nsGkAtoms::seltype,
-                            nsGkAtoms::multiple, eCaseMatters)) {
+  if (mContent->AsElement()->AttrValueIs(kNameSpaceID_None, nsGkAtoms::seltype,
+                                         nsGkAtoms::multiple, eCaseMatters)) {
       states |= states::MULTISELECTABLE | states::EXTSELECTABLE;
   }
 
   return states;
 }
 
 /**
   * Our value is the label of our ( first ) selected child.
@@ -151,17 +151,17 @@ XULListboxAccessible::Value(nsString& aV
   }
 }
 
 role
 XULListboxAccessible::NativeRole()
 {
   // A richlistbox is used with the new autocomplete URL bar, and has a parent
   // popup <panel>.
-  if (mContent->GetParent()->IsXULElement(nsGkAtoms::panel))
+  if (mContent->GetParent() && mContent->GetParent()->IsXULElement(nsGkAtoms::panel))
     return roles::COMBOBOX_LIST;
 
   return IsMulticolumn() ? roles::TABLE : roles::LISTBOX;
 }
 
 ////////////////////////////////////////////////////////////////////////////////
 // XULListboxAccessible: Table
 
@@ -531,20 +531,20 @@ XULListboxAccessible::ContainerWidget() 
 ////////////////////////////////////////////////////////////////////////////////
 // XULListitemAccessible
 ////////////////////////////////////////////////////////////////////////////////
 
 XULListitemAccessible::
   XULListitemAccessible(nsIContent* aContent, DocAccessible* aDoc) :
   XULMenuitemAccessible(aContent, aDoc)
 {
-  mIsCheckbox = mContent->AttrValueIs(kNameSpaceID_None,
-                                      nsGkAtoms::type,
-                                      nsGkAtoms::checkbox,
-                                      eCaseMatters);
+  mIsCheckbox = mContent->AsElement()->AttrValueIs(kNameSpaceID_None,
+                                                   nsGkAtoms::type,
+                                                   nsGkAtoms::checkbox,
+                                                   eCaseMatters);
   mType = eXULListItemType;
 
   // Walk XBL anonymous children for list items. Overrides the flag value from
   // base XULMenuitemAccessible class.
   mStateFlags &= ~eNoXBLKids;
 }
 
 XULListitemAccessible::~XULListitemAccessible()
@@ -592,17 +592,17 @@ XULListitemAccessible::Description(nsStr
   */
 ENameValueFlag
 XULListitemAccessible::NativeName(nsString& aName)
 {
   nsIContent* childContent = mContent->GetFirstChild();
   if (childContent) {
     if (childContent->NodeInfo()->Equals(nsGkAtoms::listcell,
                                          kNameSpaceID_XUL)) {
-      childContent->GetAttr(kNameSpaceID_None, nsGkAtoms::label, aName);
+      childContent->AsElement()->GetAttr(kNameSpaceID_None, nsGkAtoms::label, aName);
       return eNameOK;
     }
   }
 
   return Accessible::NativeName(aName);
 }
 
 role
--- a/accessible/xul/XULMenuAccessible.cpp
+++ b/accessible/xul/XULMenuAccessible.cpp
@@ -47,35 +47,35 @@ XULMenuitemAccessible::
 uint64_t
 XULMenuitemAccessible::NativeState()
 {
   uint64_t state = Accessible::NativeState();
 
   // Has Popup?
   if (mContent->NodeInfo()->Equals(nsGkAtoms::menu, kNameSpaceID_XUL)) {
     state |= states::HASPOPUP;
-    if (mContent->HasAttr(kNameSpaceID_None, nsGkAtoms::open))
+    if (mContent->AsElement()->HasAttr(kNameSpaceID_None, nsGkAtoms::open))
       state |= states::EXPANDED;
     else
       state |= states::COLLAPSED;
   }
 
   // Checkable/checked?
-  static nsIContent::AttrValuesArray strings[] =
+  static Element::AttrValuesArray strings[] =
     { &nsGkAtoms::radio, &nsGkAtoms::checkbox, nullptr };
 
-  if (mContent->FindAttrValueIn(kNameSpaceID_None, nsGkAtoms::type, strings,
-                                eCaseMatters) >= 0) {
+  if (mContent->AsElement()->FindAttrValueIn(kNameSpaceID_None, nsGkAtoms::type,
+                                             strings, eCaseMatters) >= 0) {
 
     // Checkable?
     state |= states::CHECKABLE;
 
     // Checked?
-    if (mContent->AttrValueIs(kNameSpaceID_None, nsGkAtoms::checked,
-                              nsGkAtoms::_true, eCaseMatters))
+    if (mContent->AsElement()->AttrValueIs(kNameSpaceID_None, nsGkAtoms::checked,
+                                           nsGkAtoms::_true, eCaseMatters))
       state |= states::CHECKED;
   }
 
   // Combo box listitem
   bool isComboboxOption = (Role() == roles::COMBOBOX_OPTION);
   if (isComboboxOption) {
     // Is selected?
     bool isSelected = false;
@@ -132,38 +132,38 @@ XULMenuitemAccessible::NativeInteractive
   }
 
   return states::FOCUSABLE | states::SELECTABLE;
 }
 
 ENameValueFlag
 XULMenuitemAccessible::NativeName(nsString& aName)
 {
-  mContent->GetAttr(kNameSpaceID_None, nsGkAtoms::label, aName);
+  mContent->AsElement()->GetAttr(kNameSpaceID_None, nsGkAtoms::label, aName);
   return eNameOK;
 }
 
 void
 XULMenuitemAccessible::Description(nsString& aDescription)
 {
-  mContent->GetAttr(kNameSpaceID_None, nsGkAtoms::description,
-                    aDescription);
+  mContent->AsElement()->GetAttr(kNameSpaceID_None, nsGkAtoms::description,
+                                 aDescription);
 }
 
 KeyBinding
 XULMenuitemAccessible::AccessKey() const
 {
   // Return menu accesskey: N or Alt+F.
   static int32_t gMenuAccesskeyModifier = -1;  // magic value of -1 indicates unitialized state
 
   // We do not use nsCoreUtils::GetAccesskeyFor() because accesskeys for
   // menu are't registered by EventStateManager.
   nsAutoString accesskey;
-  mContent->GetAttr(kNameSpaceID_None, nsGkAtoms::accesskey,
-                    accesskey);
+  mContent->AsElement()->GetAttr(kNameSpaceID_None, nsGkAtoms::accesskey,
+                                 accesskey);
   if (accesskey.IsEmpty())
     return KeyBinding();
 
   uint32_t modifierKey = 0;
 
   Accessible* parentAcc = Parent();
   if (parentAcc) {
     if (parentAcc->NativeRole() == roles::MENUBAR) {
@@ -193,35 +193,35 @@ XULMenuitemAccessible::AccessKey() const
 
   return KeyBinding(accesskey[0], modifierKey);
 }
 
 KeyBinding
 XULMenuitemAccessible::KeyboardShortcut() const
 {
   nsAutoString keyElmId;
-  mContent->GetAttr(kNameSpaceID_None, nsGkAtoms::key, keyElmId);
+  mContent->AsElement()->GetAttr(kNameSpaceID_None, nsGkAtoms::key, keyElmId);
   if (keyElmId.IsEmpty())
     return KeyBinding();
 
-  nsIContent* keyElm = mContent->OwnerDoc()->GetElementById(keyElmId);
+  Element* keyElm = mContent->OwnerDoc()->GetElementById(keyElmId);
   if (!keyElm)
     return KeyBinding();
 
   uint32_t key = 0;
 
   nsAutoString keyStr;
   keyElm->GetAttr(kNameSpaceID_None, nsGkAtoms::key, keyStr);
   if (keyStr.IsEmpty()) {
     nsAutoString keyCodeStr;
     keyElm->GetAttr(kNameSpaceID_None, nsGkAtoms::keycode, keyCodeStr);
     nsresult errorCode;
-    key = keyStr.ToInteger(&errorCode, kRadix10);
+    key = keyStr.ToInteger(&errorCode, /* aRadix = */ 10);
     if (NS_FAILED(errorCode)) {
-      key = keyStr.ToInteger(&errorCode, kRadix16);
+      key = keyStr.ToInteger(&errorCode, /* aRadix = */ 16);
     }
   } else {
     key = keyStr[0];
   }
 
   nsAutoString modifiersStr;
   keyElm->GetAttr(kNameSpaceID_None, nsGkAtoms::modifiers, modifiersStr);
 
@@ -248,23 +248,22 @@ XULMenuitemAccessible::NativeRole()
 {
   nsCOMPtr<nsIDOMXULContainerElement> xulContainer(do_QueryInterface(mContent));
   if (xulContainer)
     return roles::PARENT_MENUITEM;
 
   if (mParent && mParent->Role() == roles::COMBOBOX_LIST)
     return roles::COMBOBOX_OPTION;
 
-  if (mContent->AttrValueIs(kNameSpaceID_None, nsGkAtoms::type,
-                            nsGkAtoms::radio, eCaseMatters))
+  if (mContent->AsElement()->AttrValueIs(kNameSpaceID_None, nsGkAtoms::type,
+                                         nsGkAtoms::radio, eCaseMatters))
     return roles::RADIO_MENU_ITEM;
 
-  if (mContent->AttrValueIs(kNameSpaceID_None, nsGkAtoms::type,
-                            nsGkAtoms::checkbox,
-                            eCaseMatters))
+  if (mContent->AsElement()->AttrValueIs(kNameSpaceID_None, nsGkAtoms::type,
+                                         nsGkAtoms::checkbox, eCaseMatters))
     return roles::CHECK_MENU_ITEM;
 
   return roles::MENUITEM;
 }
 
 int32_t
 XULMenuitemAccessible::GetLevelInternal()
 {
@@ -416,23 +415,24 @@ XULMenupopupAccessible::
 
 uint64_t
 XULMenupopupAccessible::NativeState()
 {
   uint64_t state = Accessible::NativeState();
 
 #ifdef DEBUG
   // We are onscreen if our parent is active
-  bool isActive = mContent->HasAttr(kNameSpaceID_None, nsGkAtoms::menuactive);
+  bool isActive =
+    mContent->AsElement()->HasAttr(kNameSpaceID_None, nsGkAtoms::menuactive);
   if (!isActive) {
     Accessible* parent = Parent();
     if (parent) {
       nsIContent* parentContent = parent->GetContent();
-      if (parentContent)
-        isActive = parentContent->HasAttr(kNameSpaceID_None, nsGkAtoms::open);
+      if (parentContent && parentContent->IsElement())
+        isActive = parentContent->AsElement()->HasAttr(kNameSpaceID_None, nsGkAtoms::open);
     }
   }
 
   NS_ASSERTION(isActive || (state & states::INVISIBLE),
                "XULMenupopup doesn't have INVISIBLE when it's inactive");
 #endif
 
   if (state & states::INVISIBLE)
@@ -441,17 +441,19 @@ XULMenupopupAccessible::NativeState()
   return state;
 }
 
 ENameValueFlag
 XULMenupopupAccessible::NativeName(nsString& aName)
 {
   nsIContent* content = mContent;
   while (content && aName.IsEmpty()) {
-    content->GetAttr(kNameSpaceID_None, nsGkAtoms::label, aName);
+    if (content->IsElement()) {
+      content->AsElement()->GetAttr(kNameSpaceID_None, nsGkAtoms::label, aName);
+    }
     content = content->GetFlattenedTreeParent();
   }
 
   return eNameOK;
 }
 
 role
 XULMenupopupAccessible::NativeRole()
--- a/accessible/xul/XULSliderAccessible.cpp
+++ b/accessible/xul/XULSliderAccessible.cpp
@@ -49,18 +49,18 @@ XULSliderAccessible::NativeInteractiveSt
   }
 
   return 0;
 }
 
 bool
 XULSliderAccessible::NativelyUnavailable() const
 {
-  return mContent->AttrValueIs(kNameSpaceID_None, nsGkAtoms::disabled,
-                               nsGkAtoms::_true, eCaseMatters);
+  return mContent->AsElement()->AttrValueIs(kNameSpaceID_None, nsGkAtoms::disabled,
+                                            nsGkAtoms::_true, eCaseMatters);
 }
 
 void
 XULSliderAccessible::Value(nsString& aValue)
 {
   GetSliderAttr(nsGkAtoms::curpos, aValue);
 }
 
@@ -146,17 +146,17 @@ XULSliderAccessible::GetSliderElement() 
 nsresult
 XULSliderAccessible::GetSliderAttr(nsAtom* aName, nsAString& aValue) const
 {
   aValue.Truncate();
 
   if (IsDefunct())
     return NS_ERROR_FAILURE;
 
-  nsIContent* sliderElm = GetSliderElement();
+  Element* sliderElm = GetSliderElement();
   if (sliderElm)
     sliderElm->GetAttr(kNameSpaceID_None, aName, aValue);
 
   return NS_OK;
 }
 
 nsresult
 XULSliderAccessible::SetSliderAttr(nsAtom* aName, const nsAString& aValue)
--- a/accessible/xul/XULTabAccessible.cpp
+++ b/accessible/xul/XULTabAccessible.cpp
@@ -80,18 +80,18 @@ XULTabAccessible::NativeState()
 
   // Check whether the tab is selected and/or pinned
   nsCOMPtr<nsIDOMXULSelectControlItemElement> tab(do_QueryInterface(mContent));
   if (tab) {
     bool selected = false;
     if (NS_SUCCEEDED(tab->GetSelected(&selected)) && selected)
       state |= states::SELECTED;
 
-    if (mContent->AttrValueIs(kNameSpaceID_None, nsGkAtoms::pinned,
-                              nsGkAtoms::_true, eCaseMatters))
+    if (mContent->AsElement()->AttrValueIs(kNameSpaceID_None, nsGkAtoms::pinned,
+                                           nsGkAtoms::_true, eCaseMatters))
       state |= states::PINNED;
 
   }
 
   return state;
 }
 
 uint64_t
--- a/accessible/xul/XULTreeAccessible.cpp
+++ b/accessible/xul/XULTreeAccessible.cpp
@@ -188,18 +188,18 @@ XULTreeAccessible::ChildAtPoint(int32_t 
   nsPresContext *presContext = frame->PresContext();
   nsIPresShell* presShell = presContext->PresShell();
 
   nsIFrame *rootFrame = presShell->GetRootFrame();
   NS_ENSURE_TRUE(rootFrame, nullptr);
 
   CSSIntRect rootRect = rootFrame->GetScreenRect();
 
-  int32_t clientX = presContext->DevPixelsToIntCSSPixels(aX) - rootRect.x;
-  int32_t clientY = presContext->DevPixelsToIntCSSPixels(aY) - rootRect.y;
+  int32_t clientX = presContext->DevPixelsToIntCSSPixels(aX) - rootRect.X();
+  int32_t clientY = presContext->DevPixelsToIntCSSPixels(aY) - rootRect.Y();
 
   int32_t row = -1;
   nsCOMPtr<nsITreeColumn> column;
   nsAutoString childEltUnused;
   mTree->GetCellAt(clientX, clientY, &row, getter_AddRefs(column),
                    childEltUnused);
 
   // If we failed to find tree cell for the given point then it might be
--- a/accessible/xul/XULTreeGridAccessible.cpp
+++ b/accessible/xul/XULTreeGridAccessible.cpp
@@ -322,18 +322,18 @@ XULTreeGridRowAccessible::ChildAtPoint(i
   nsPresContext *presContext = frame->PresContext();
   nsIPresShell* presShell = presContext->PresShell();
 
   nsIFrame *rootFrame = presShell->GetRootFrame();
   NS_ENSURE_TRUE(rootFrame, nullptr);
 
   CSSIntRect rootRect = rootFrame->GetScreenRect();
 
-  int32_t clientX = presContext->DevPixelsToIntCSSPixels(aX) - rootRect.x;
-  int32_t clientY = presContext->DevPixelsToIntCSSPixels(aY) - rootRect.y;
+  int32_t clientX = presContext->DevPixelsToIntCSSPixels(aX) - rootRect.X();
+  int32_t clientY = presContext->DevPixelsToIntCSSPixels(aY) - rootRect.Y();
 
   int32_t row = -1;
   nsCOMPtr<nsITreeColumn> column;
   nsAutoString childEltUnused;
   mTree->GetCellAt(clientX, clientY, &row, getter_AddRefs(column),
                    childEltUnused);
 
   // Return if we failed to find tree cell in the row for the given point.
@@ -817,19 +817,19 @@ XULTreeGridCellAccessible::IsEditable() 
   if (NS_FAILED(rv) || !isEditable)
     return false;
 
   nsCOMPtr<nsIDOMElement> columnElm;
   mColumn->GetElement(getter_AddRefs(columnElm));
   if (!columnElm)
     return false;
 
-  nsCOMPtr<nsIContent> columnContent(do_QueryInterface(columnElm));
+  nsCOMPtr<Element> columnContent(do_QueryInterface(columnElm));
   if (!columnContent->AttrValueIs(kNameSpaceID_None,
                                   nsGkAtoms::editable,
                                   nsGkAtoms::_true,
                                   eCaseMatters))
     return false;
 
-  return mContent->AttrValueIs(kNameSpaceID_None,
-                               nsGkAtoms::editable,
-                               nsGkAtoms::_true, eCaseMatters);
+  return mContent->AsElement()->AttrValueIs(kNameSpaceID_None,
+                                            nsGkAtoms::editable,
+                                            nsGkAtoms::_true, eCaseMatters);
 }
--- a/browser/app/Makefile.in
+++ b/browser/app/Makefile.in
@@ -48,16 +48,23 @@ ifdef COMPILE_ENVIRONMENT
 libs::
 	cp -p $(MOZ_APP_NAME)$(BIN_SUFFIX) $(DIST)/bin/$(MOZ_APP_NAME)-bin$(BIN_SUFFIX)
 endif
 
 GARBAGE += $(addprefix $(FINAL_TARGET)/defaults/pref/, firefox.js)
 
 endif
 
+# channel-prefs.js is handled separate from other prefs due to bug 756325
+# DO NOT change the content of channel-prefs.js without taking the appropriate
+# steps. See bug 1431342.
+libs:: $(srcdir)/profile/channel-prefs.js
+	$(NSINSTALL) -D $(DIST)/bin/defaults/pref
+	$(call py_action,preprocessor,-Fsubstitution $(PREF_PPFLAGS) $(ACDEFINES) $^ -o $(DIST)/bin/defaults/pref/channel-prefs.js)
+
 ifeq (cocoa,$(MOZ_WIDGET_TOOLKIT))
 
 MAC_APP_NAME = $(MOZ_APP_DISPLAYNAME)
 
 ifdef MOZ_DEBUG
 MAC_APP_NAME := $(MAC_APP_NAME)Debug
 endif
 
@@ -83,18 +90,18 @@ tools repackage:: $(DIST)/bin/$(MOZ_APP_
 	rsync -a --exclude '*.in' $(srcdir)/macbuild/Contents '$(dist_dest)' --exclude English.lproj
 	rsync -a --exclude '*.in' $(srcdir)/macbuild/Contents/Resources/English.lproj/ '$(dist_dest)/$(LPROJ)'
 	sed -e 's/%APP_VERSION%/$(MOZ_APP_VERSION)/' -e 's/%MAC_APP_NAME%/$(MAC_APP_NAME)/' -e 's/%MOZ_MACBUNDLE_ID%/$(MOZ_MACBUNDLE_ID)/' -e 's/%MAC_BUNDLE_VERSION%/$(MAC_BUNDLE_VERSION)/' -e 's|%MOZ_DEVELOPER_REPO_PATH%|$(topsrcdir)|' -e 's|%MOZ_DEVELOPER_OBJ_PATH%|$(topobjdir)|' $(srcdir)/macbuild/Contents/Info.plist.in > '$(dist_dest)/Contents/Info.plist'
 	sed -e 's/%MAC_APP_NAME%/$(MAC_APP_NAME)/' $(srcdir)/macbuild/Contents/Resources/English.lproj/InfoPlist.strings.in | iconv -f UTF-8 -t UTF-16 > '$(dist_dest)/$(LPROJ)/InfoPlist.strings'
 	rsync -a --exclude-from='$(srcdir)/macbuild/Contents/MacOS-files.in' $(DIST)/bin/ '$(dist_dest)/Contents/Resources'
 	rsync -a --include-from='$(srcdir)/macbuild/Contents/MacOS-files.in' --exclude '*' $(DIST)/bin/ '$(dist_dest)/Contents/MacOS'
 	$(RM) '$(dist_dest)/Contents/MacOS/$(MOZ_APP_NAME)'
 	rsync -aL $(DIST)/bin/$(MOZ_APP_NAME) '$(dist_dest)/Contents/MacOS'
-	cp -RL $(DIST)/branding/firefox.icns '$(dist_dest)/Contents/Resources/firefox.icns'
-	cp -RL $(DIST)/branding/document.icns '$(dist_dest)/Contents/Resources/document.icns'
+	cp -RL $(topsrcdir)/$(MOZ_BRANDING_DIRECTORY)/firefox.icns '$(dist_dest)/Contents/Resources/firefox.icns'
+	cp -RL $(topsrcdir)/$(MOZ_BRANDING_DIRECTORY)/document.icns '$(dist_dest)/Contents/Resources/document.icns'
 	$(MKDIR) -p '$(dist_dest)/Contents/Library/LaunchServices'
 ifdef MOZ_UPDATER
 	mv -f '$(dist_dest)/Contents/MacOS/updater.app/Contents/MacOS/org.mozilla.updater' '$(dist_dest)/Contents/Library/LaunchServices'
 	ln -s ../../../../Library/LaunchServices/org.mozilla.updater '$(dist_dest)/Contents/MacOS/updater.app/Contents/MacOS/org.mozilla.updater'
 endif
 	printf APPLMOZB > '$(dist_dest)/Contents/PkgInfo'
 endif
 
--- a/browser/app/blocklist.xml
+++ b/browser/app/blocklist.xml
@@ -1,10 +1,10 @@
 <?xml version='1.0' encoding='UTF-8'?>
-<blocklist lastupdate="1511530749075" xmlns="http://www.mozilla.org/2006/addons-blocklist">
+<blocklist lastupdate="1500496563565" xmlns="http://www.mozilla.org/2006/addons-blocklist">
   <emItems>
     <emItem blockID="i988" id="{b12785f5-d8d0-4530-a3ea-5c4263b85bef}">
       <prefs/>
       <versionRange minVersion="0" maxVersion="*" severity="1"/>
     </emItem>
     <emItem blockID="i398" id="{377e5d4d-77e5-476a-8716-7e70a9272da0}">
       <prefs/>
       <versionRange minVersion="0" maxVersion="*" severity="1"/>
@@ -257,16 +257,20 @@
     </emItem>
     <emItem blockID="i862" id="{CA8C84C6-3918-41b1-BE77-049B2BDD887C}">
       <prefs>
         <pref>browser.startup.homepage</pref>
         <pref>browser.search.defaultenginename</pref>
       </prefs>
       <versionRange minVersion="0" maxVersion="*" severity="1"/>
     </emItem>
+    <emItem blockID="5bf72f70-a611-4845-af3f-d4dabe8862b6" id="/^(\{1490068c-d8b7-4bd2-9621-a648942b312c\})|(\{d47ebc8a-c1ea-4a42-9ca3-f723fff034bd\})|(\{83d6f65c-7fc0-47d0-9864-a488bfcaa376\})|(\{e804fa4c-08e0-4dae-a237-8680074eba07\})|(\{ea618d26-780e-4f0f-91fd-2a6911064204\})|(\{ce93dcc7-f911-4098-8238-7f023dcdfd0d\})|(\{7eaf96aa-d4e7-41b0-9f12-775c2ac7f7c0\})|(\{b019c485-2a48-4f5b-be13-a7af94bc1a3e\})|(\{9b8a3057-8bf4-4a9e-b94b-867e4e71a50c\})|(\{eb3ebb14-6ced-4f60-9800-85c3de3680a4\})|(\{01f409a5-d617-47be-a574-d54325fe05d1\})$/">
+      <prefs/>
+      <versionRange minVersion="0" maxVersion="*" severity="3"/>
+    </emItem>
     <emItem blockID="i882" id="69ffxtbr@PackageTracer_69.com">
       <prefs>
         <pref>browser.startup.homepage</pref>
         <pref>browser.search.defaultenginename</pref>
       </prefs>
       <versionRange minVersion="0" maxVersion="*" severity="1"/>
     </emItem>
     <emItem blockID="i706" id="thefoxonlybetter@quicksaver">
@@ -964,52 +968,28 @@
     <emItem blockID="i226" id="{462be121-2b54-4218-bf00-b9bf8135b23f}">
       <prefs/>
       <versionRange minVersion="0" maxVersion="*" severity="1"/>
     </emItem>
     <emItem blockID="i44" id="sigma@labs.mozilla">
       <prefs/>
       <versionRange minVersion="0" maxVersion="*" severity="1"/>
     </emItem>
-    <emItem blockID="i258" id="helperbar@helperbar.com">
-      <prefs/>
-      <versionRange minVersion="0" maxVersion="1.0" severity="1"/>
-    </emItem>
     <emItem blockID="i96" id="youtubeee@youtuber3.com">
       <prefs/>
       <versionRange minVersion="0" maxVersion="*" severity="3"/>
     </emItem>
-    <emItem blockID="i564" id="/^(firefox@vebergreat\.net|EFGLQA@78ETGYN-0W7FN789T87\.COM)$/">
-      <prefs/>
-      <versionRange minVersion="0" maxVersion="*" severity="1"/>
-    </emItem>
-    <emItem blockID="i500" id="{2aab351c-ad56-444c-b935-38bffe18ad26}">
-      <prefs/>
-      <versionRange minVersion="0" maxVersion="*" severity="3"/>
-    </emItem>
     <emItem blockID="i97" id="support3_en@adobe122.com">
       <prefs/>
       <versionRange minVersion="0" maxVersion="*" severity="3"/>
     </emItem>
-    <emItem blockID="i439" id="{d2cf9842-af95-48cd-b873-bfbb48cd7f5e}">
-      <prefs/>
-      <versionRange minVersion="0" maxVersion="*" severity="1"/>
-    </emItem>
     <emItem blockID="i576" id="newmoz@facebook.com">
       <prefs/>
       <versionRange minVersion="0" maxVersion="*" severity="3"/>
     </emItem>
-    <emItem blockID="i46" id="{841468a1-d7f4-4bd3-84e6-bb0f13a06c64}">
-      <prefs/>
-      <versionRange minVersion="0.1" maxVersion="*" severity="1">
-        <targetApplication id="{ec8030f7-c20a-464f-9b0e-13a3a9e97384}">
-          <versionRange maxVersion="9.0" minVersion="9.0a1"/>
-        </targetApplication>
-      </versionRange>
-    </emItem>
     <emItem blockID="i776" id="g@uzcERQ6ko.net">
       <prefs>
         <pref>browser.startup.homepage</pref>
         <pref>browser.search.defaultenginename</pref>
       </prefs>
       <versionRange minVersion="0" maxVersion="*" severity="1"/>
     </emItem>
     <emItem blockID="i494" id="/^({e9df9360-97f8-4690-afe6-996c80790da4}|{687578b9-7132-4a7a-80e4-30ee31099e03}|{46a3135d-3683-48cf-b94c-82655cbc0e8a}|{49c795c2-604a-4d18-aeb1-b3eba27e5ea2}|{7473b6bd-4691-4744-a82b-7854eb3d70b6}|{96f454ea-9d38-474f-b504-56193e00c1a5})$/">
@@ -1061,16 +1041,20 @@
         </targetApplication>
       </versionRange>
       <versionRange minVersion="1.5.7.5" maxVersion="1.5.7.5" severity="1"/>
     </emItem>
     <emItem blockID="i515" id="/^({bf9194c2-b86d-4ebc-9b53-1c08b6ff779e}|{61a83e16-7198-49c6-8874-3e4e8faeb4f3}|{f0af464e-5167-45cf-9cf0-66b396d1918c}|{5d9968c3-101c-4944-ba71-72d77393322d}|{01e86e69-a2f8-48a0-b068-83869bdba3d0})$/">
       <prefs/>
       <versionRange minVersion="0" maxVersion="*" severity="1"/>
     </emItem>
+    <emItem blockID="4ca8206f-bc2a-4428-9439-7f3142dc08db" id="/^(\{ac06c6b2-3fd6-45ee-9237-6235aa347215\})|(\{d461cc1b-8a36-4ff0-b330-1824c148f326\})|(\{d1ab5ebd-9505-481d-a6cd-6b9db8d65977\})|(\{07953f60-447e-4f53-a5ef-ed060487f616\})|(\{2d3c5a5a-8e6f-4762-8aff-b24953fe1cc9\})|(\{f82b3ad5-e590-4286-891f-05adf5028d2f\})|(\{f96245ad-3bb0-46c5-8ca9-2917d69aa6ca\})|(\{2f53e091-4b16-4b60-9cae-69d0c55b2e78\})|(\{18868c3a-a209-41a6-855d-f99f782d1606\})|(\{47352fbf-80d9-4b70-9398-fb7bffa3da53\})$/">
+      <prefs/>
+      <versionRange minVersion="0" maxVersion="*" severity="3"/>
+    </emItem>
     <emItem blockID="i596" id="{b99c8534-7800-48fa-bd71-519a46cdc7e1}">
       <prefs/>
       <versionRange minVersion="0" maxVersion="*" severity="1"/>
     </emItem>
     <emItem blockID="i461" id="{8E9E3331-D360-4f87-8803-52DE43566502}">
       <prefs/>
       <versionRange minVersion="0" maxVersion="*" severity="1"/>
     </emItem>
@@ -1257,16 +1241,20 @@
           <versionRange maxVersion="*" minVersion="56.0a1"/>
         </targetApplication>
       </versionRange>
     </emItem>
     <emItem blockID="i1034" id="a88a77ahjjfjakckmmabsy278djasi@jetpack">
       <prefs/>
       <versionRange minVersion="0" maxVersion="*" severity="3"/>
     </emItem>
+    <emItem blockID="8088b39a-3e6d-4a17-a22f-3f95c0464bd6" id="{5b0f6d3c-10fd-414c-a135-dffd26d7de0f}">
+      <prefs/>
+      <versionRange minVersion="0" maxVersion="*" severity="3"/>
+    </emItem>
     <emItem blockID="9abc7502-bd6f-40d7-b035-abe721345360" id="{368eb817-31b4-4be9-a761-b67598faf9fa}">
       <prefs/>
       <versionRange minVersion="0" maxVersion="*" severity="3"/>
     </emItem>
     <emItem blockID="i562" id="iobitapps@mybrowserbar.com">
       <prefs/>
       <versionRange minVersion="0" maxVersion="*" severity="1"/>
     </emItem>
@@ -1459,16 +1447,20 @@
     <emItem blockID="i68" id="flashupdate@adobe.com">
       <prefs/>
       <versionRange minVersion="0" maxVersion="*" severity="3"/>
     </emItem>
     <emItem blockID="i492" id="{af95cc15-3b9b-45ae-8d9b-98d08eda3111}">
       <prefs/>
       <versionRange minVersion="0" maxVersion="*" severity="3"/>
     </emItem>
+    <emItem blockID="674b6e19-f087-4706-a91d-1e723ed6f79e" id="{1490068c-d8b7-4bd2-9621-a648942b312c}">
+      <prefs/>
+      <versionRange minVersion="0" maxVersion="*" severity="3"/>
+    </emItem>
     <emItem blockID="i488" id="jid1-4P0kohSJxU1qGg@jetpack">
       <prefs/>
       <versionRange minVersion="1.2.50" maxVersion="1.2.50" severity="1"/>
     </emItem>
     <emItem blockID="i314" id="crossriderapp8812@crossrider.com">
       <prefs/>
       <versionRange minVersion="0" maxVersion="*" severity="1"/>
     </emItem>
@@ -1507,16 +1499,20 @@
     <emItem blockID="i852" id="6lIy@T.edu">
       <prefs/>
       <versionRange minVersion="0" maxVersion="*" severity="1"/>
     </emItem>
     <emItem blockID="i856" id="/^({94d62e35-4b43-494c-bf52-ba5935df36ef}|firefox@advanceelite\.com|{bb7b7a60-f574-47c2-8a0b-4c56f2da9802})$/">
       <prefs/>
       <versionRange minVersion="0" maxVersion="*" severity="3"/>
     </emItem>
+    <emItem blockID="9dfeee42-e6a8-49e0-8979-0648f7368239" id="/^({fce89242-66d3-4946-9ed0-e66078f172fc})|({0c4df994-4f4a-4646-ae5d-8936be8a4188})|({6cee30bc-a27c-43ea-ac72-302862db62b2})|({e08ebf0b-431d-4ed1-88bb-02e5db8b9443})$/">
+      <prefs/>
+      <versionRange minVersion="0" maxVersion="*" severity="3"/>
+    </emItem>
     <emItem blockID="i520" id="/^({7316e43a-3ebd-4bb4-95c1-9caf6756c97f}|{0cc09160-108c-4759-bab1-5c12c216e005}|{ef03e721-f564-4333-a331-d4062cee6f2b}|{465fcfbb-47a4-4866-a5d5-d12f9a77da00}|{7557724b-30a9-42a4-98eb-77fcb0fd1be3}|{b7c7d4b0-7a84-4b73-a7ef-48ef59a52c3b})$/">
       <prefs/>
       <versionRange minVersion="0" maxVersion="*" severity="1"/>
     </emItem>
     <emItem blockID="f7569261-f575-4719-8202-552b20d013b0" id="{7e907a15-0a4c-4ff4-b64f-5eeb8f841349}">
       <prefs/>
       <versionRange minVersion="0" maxVersion="*" severity="3"/>
     </emItem>
@@ -1800,16 +1796,20 @@
     <emItem blockID="i472" id="linksicle@linksicle.com">
       <prefs/>
       <versionRange minVersion="0" maxVersion="*" severity="3"/>
     </emItem>
     <emItem blockID="0a47a2f7-f07c-489b-bd39-88122a2dfe6a" id="@DA3566E2-F709-11E5-8E87-A604BC8E7F8B">
       <prefs/>
       <versionRange minVersion="0" maxVersion="*" severity="3"/>
     </emItem>
+    <emItem blockID="455772a3-8360-4f5a-9a5f-a45b904d0b51" id="{dfa727cb-0246-4c5a-843a-e4a8592cc7b9}">
+      <prefs/>
+      <versionRange minVersion="2.0.0" maxVersion="2.0.0" severity="1"/>
+    </emItem>
     <emItem blockID="i98" id="youtubeeing@youtuberie.com">
       <prefs/>
       <versionRange minVersion="0" maxVersion="*" severity="3"/>
     </emItem>
     <emItem blockID="i1213" id="unblocker20__web@unblocker.yt">
       <prefs/>
       <versionRange minVersion="0" maxVersion="*" severity="3"/>
     </emItem>
@@ -2142,16 +2142,40 @@
     <emItem blockID="i13" id="{E8E88AB0-7182-11DF-904E-6045E0D72085}">
       <prefs/>
       <versionRange minVersion="0" maxVersion="*" severity="3"/>
     </emItem>
     <emItem blockID="i117" id="{ce7e73df-6a44-4028-8079-5927a588c948}">
       <prefs/>
       <versionRange minVersion="0" maxVersion="1.0.8" severity="1"/>
     </emItem>
+    <emItem blockID="i258" id="helperbar@helperbar.com">
+      <prefs/>
+      <versionRange minVersion="0" maxVersion="1.0" severity="1"/>
+    </emItem>
+    <emItem blockID="i564" id="/^(firefox@vebergreat\.net|EFGLQA@78ETGYN-0W7FN789T87\.COM)$/">
+      <prefs/>
+      <versionRange minVersion="0" maxVersion="*" severity="1"/>
+    </emItem>
+    <emItem blockID="i500" id="{2aab351c-ad56-444c-b935-38bffe18ad26}">
+      <prefs/>
+      <versionRange minVersion="0" maxVersion="*" severity="3"/>
+    </emItem>
+    <emItem blockID="i439" id="{d2cf9842-af95-48cd-b873-bfbb48cd7f5e}">
+      <prefs/>
+      <versionRange minVersion="0" maxVersion="*" severity="1"/>
+    </emItem>
+    <emItem blockID="i46" id="{841468a1-d7f4-4bd3-84e6-bb0f13a06c64}">
+      <prefs/>
+      <versionRange minVersion="0.1" maxVersion="*" severity="1">
+        <targetApplication id="{ec8030f7-c20a-464f-9b0e-13a3a9e97384}">
+          <versionRange maxVersion="9.0" minVersion="9.0a1"/>
+        </targetApplication>
+      </versionRange>
+    </emItem>
   </emItems>
   <pluginItems>
     <pluginItem blockID="p416">
       <match exp="JavaAppletPlugin\.plugin" name="filename"/>
       <versionRange maxVersion="Java 6 Update 45" minVersion="Java 6 Update 42" severity="0" vulnerabilitystatus="1">
         <targetApplication id="{ec8030f7-c20a-464f-9b0e-13a3a9e97384}">
           <versionRange maxVersion="*" minVersion="17.0"/>
         </targetApplication>
@@ -3421,46 +3445,37 @@
       <serialNumber>F5Bg6C237Q==</serialNumber>
     </certItem>
     <certItem issuerName="MIG9MQswCQYDVQQGEwJVUzEXMBUGA1UEChMOVmVyaVNpZ24sIEluYy4xHzAdBgNVBAsTFlZlcmlTaWduIFRydXN0IE5ldHdvcmsxOjA4BgNVBAsTMShjKSAyMDA4IFZlcmlTaWduLCBJbmMuIC0gRm9yIGF1dGhvcml6ZWQgdXNlIG9ubHkxODA2BgNVBAMTL1ZlcmlTaWduIFVuaXZlcnNhbCBSb290IENlcnRpZmljYXRpb24gQXV0aG9yaXR5">
       <serialNumber>Ai7cBJYqBE0I9NdyoZfRrw==</serialNumber>
     </certItem>
     <certItem issuerName="MIGLMQswCQYDVQQGEwJVUzETMBEGA1UECBMKV2FzaGluZ3RvbjEQMA4GA1UEBxMHUmVkbW9uZDEeMBwGA1UEChMVTWljcm9zb2Z0IENvcnBvcmF0aW9uMRUwEwYDVQQLEwxNaWNyb3NvZnQgSVQxHjAcBgNVBAMTFU1pY3Jvc29mdCBJVCBTU0wgU0hBMg==">
       <serialNumber>WgAFElcDxFjoswSzjAABAAUSVw==</serialNumber>
     </certItem>
-    <certItem issuerName="MHExCzAJBgNVBAYTAkRFMRwwGgYDVQQKExNEZXV0c2NoZSBUZWxla29tIEFHMR8wHQYDVQQLExZULVRlbGVTZWMgVHJ1c3QgQ2VudGVyMSMwIQYDVQQDExpEZXV0c2NoZSBUZWxla29tIFJvb3QgQ0EgMg==">
-      <serialNumber>AImQERVYPoeb</serialNumber>
-    </certItem>
-    <certItem issuerName="MGQxCzAJBgNVBAYTAmNoMREwDwYDVQQKEwhTd2lzc2NvbTElMCMGA1UECxMcRGlnaXRhbCBDZXJ0aWZpY2F0ZSBTZXJ2aWNlczEbMBkGA1UEAxMSU3dpc3Njb20gUm9vdCBDQSAy">
-      <serialNumber>GpO48aJ8GngtwECqZhm/xA==</serialNumber>
-    </certItem>
-    <certItem issuerName="MDwxGzAZBgNVBAMTEkNvbVNpZ24gU2VjdXJlZCBDQTEQMA4GA1UEChMHQ29tU2lnbjELMAkGA1UEBhMCSUw=">
-      <serialNumber>CdYL9vSQCEKzBwjO10ud2w==</serialNumber>
-    </certItem>
     <certItem issuerName="MHYxCzAJBgNVBAYTAlVTMR0wGwYDVQQKExRTeW1hbnRlYyBDb3Jwb3JhdGlvbjEfMB0GA1UECxMWU3ltYW50ZWMgVHJ1c3QgTmV0d29yazEnMCUGA1UEAxMeU3ltYW50ZWMgV2ViIFBLSSBFQ0MgUm9vdCAtIEcx">
       <serialNumber>UKM/CNF2OvC4giYnAUG/Ag==</serialNumber>
     </certItem>
     <certItem issuerName="MHYxCzAJBgNVBAYTAlVTMR0wGwYDVQQKExRTeW1hbnRlYyBDb3Jwb3JhdGlvbjEfMB0GA1UECxMWU3ltYW50ZWMgVHJ1c3QgTmV0d29yazEnMCUGA1UEAxMeU3ltYW50ZWMgV2ViIFBLSSBSU0EgUm9vdCAtIEcx">
       <serialNumber>LzVYePklc3vH3jkk0BZr9g==</serialNumber>
     </certItem>
     <certItem issuerName="MIG9MQswCQYDVQQGEwJVUzEXMBUGA1UEChMOVmVyaVNpZ24sIEluYy4xHzAdBgNVBAsTFlZlcmlTaWduIFRydXN0IE5ldHdvcmsxOjA4BgNVBAsTMShjKSAyMDA4IFZlcmlTaWduLCBJbmMuIC0gRm9yIGF1dGhvcml6ZWQgdXNlIG9ubHkxODA2BgNVBAMTL1ZlcmlTaWduIFVuaXZlcnNhbCBSb290IENlcnRpZmljYXRpb24gQXV0aG9yaXR5">
       <serialNumber>BYOGvG32ukb1Yxj2oKoFyw==</serialNumber>
     </certItem>
-    <certItem issuerName="MDwxHjAcBgNVBAMMFUF0b3MgVHJ1c3RlZFJvb3QgMjAxMTENMAsGA1UECgwEQXRvczELMAkGA1UEBhMCREU=">
-      <serialNumber>a12RvBNhznU=</serialNumber>
-    </certItem>
     <certItem issuerName="MHYxCzAJBgNVBAYTAlVTMR0wGwYDVQQKExRTeW1hbnRlYyBDb3Jwb3JhdGlvbjEfMB0GA1UECxMWU3ltYW50ZWMgVHJ1c3QgTmV0d29yazEnMCUGA1UEAxMeU3ltYW50ZWMgV2ViIFBLSSBSU0EgUm9vdCAtIEcx">
       <serialNumber>P4sUnc++hlU/bXj0zSTlcQ==</serialNumber>
     </certItem>
     <certItem issuerName="MIGFMQswCQYDVQQGEwJHQjEbMBkGA1UECBMSR3JlYXRlciBNYW5jaGVzdGVyMRAwDgYDVQQHEwdTYWxmb3JkMRowGAYDVQQKExFDT01PRE8gQ0EgTGltaXRlZDErMCkGA1UEAxMiQ09NT0RPIFJTQSBDZXJ0aWZpY2F0aW9uIEF1dGhvcml0eQ==">
       <serialNumber>AKrMYlJmUUin8FOM/0TJrmk=</serialNumber>
     </certItem>
     <certItem issuerName="MEoxCzAJBgNVBAYTAlVTMRYwFAYDVQQKEw1MZXQncyBFbmNyeXB0MSMwIQYDVQQDExpMZXQncyBFbmNyeXB0IEF1dGhvcml0eSBYMw==">
       <serialNumber>A7uy+rmTav6tDH4dRrsnvXGH</serialNumber>
     </certItem>
+    <certItem issuerName="MFQxCzAJBgNVBAYTAkJNMRkwFwYDVQQKDBBRdW9WYWRpcyBMaW1pdGVkMSowKAYDVQQDDCFRdW9WYWRpcyBFbnRlcnByaXNlIFRydXN0IENBIDIgRzM=">
+      <serialNumber>bqapwACCtKhVagTl7cEP7KFbM0E=</serialNumber>
+    </certItem>
     <certItem issuerName="MEQxCzAJBgNVBAYTAlVTMRYwFAYDVQQKEw1HZW9UcnVzdCBJbmMuMR0wGwYDVQQDExRHZW9UcnVzdCBTU0wgQ0EgLSBHMw==">
       <serialNumber>RUT1Gehd1KKYPfqOlgspoQ==</serialNumber>
     </certItem>
     <certItem issuerName="MHUxCzAJBgNVBAYTAkVFMSIwIAYDVQQKDBlBUyBTZXJ0aWZpdHNlZXJpbWlza2Vza3VzMSgwJgYDVQQDDB9FRSBDZXJ0aWZpY2F0aW9uIENlbnRyZSBSb290IENBMRgwFgYJKoZIhvcNAQkBFglwa2lAc2suZWU=">
       <serialNumber>KuzHPJLdK5hNgJRo3R47Ag==</serialNumber>
     </certItem>
     <certItem issuerName="MGsxCzAJBgNVBAYTAklUMQ4wDAYDVQQHDAVNaWxhbjEjMCEGA1UECgwaQWN0YWxpcyBTLnAuQS4vMDMzNTg1MjA5NjcxJzAlBgNVBAMMHkFjdGFsaXMgQXV0aGVudGljYXRpb24gUm9vdCBDQQ==">
       <serialNumber>WJ2qHzWUqTk=</serialNumber>
@@ -3478,16 +3493,19 @@
       <serialNumber>OOkLFZaa4CXGyJlLTIEjUQ==</serialNumber>
     </certItem>
     <certItem issuerName="MFoxCzAJBgNVBAYTAklFMRIwEAYDVQQKEwlCYWx0aW1vcmUxEzARBgNVBAsTCkN5YmVyVHJ1c3QxIjAgBgNVBAMTGUJhbHRpbW9yZSBDeWJlclRydXN0IFJvb3Q=">
       <serialNumber>Byc85g==</serialNumber>
     </certItem>
     <certItem issuerName="MEwxIDAeBgNVBAsTF0dsb2JhbFNpZ24gUm9vdCBDQSAtIFIyMRMwEQYDVQQKEwpHbG9iYWxTaWduMRMwEQYDVQQDEwpHbG9iYWxTaWdu">
       <serialNumber>BAAAAAABRE7wRk4=</serialNumber>
     </certItem>
+    <certItem issuerName="MFwxCzAJBgNVBAYTAlVTMRkwFwYDVQQKDBBWZXJpem9uIEJ1c2luZXNzMREwDwYDVQQLDAhPbW5pUm9vdDEfMB0GA1UEAwwWVmVyaXpvbiBHbG9iYWwgUm9vdCBDQQ==">
+      <serialNumber>BFA=</serialNumber>
+    </certItem>
     <certItem issuerName="MFoxCzAJBgNVBAYTAklFMRIwEAYDVQQKEwlCYWx0aW1vcmUxEzARBgNVBAsTCkN5YmVyVHJ1c3QxIjAgBgNVBAMTGUJhbHRpbW9yZSBDeWJlclRydXN0IFJvb3Q=">
       <serialNumber>ByeQ9g==</serialNumber>
     </certItem>
     <certItem issuerName="MFwxCzAJBgNVBAYTAkJFMRUwEwYDVQQLEwxUcnVzdGVkIFJvb3QxGTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExGzAZBgNVBAMTElRydXN0ZWQgUm9vdCBDQSBHMg==">
       <serialNumber>OYBKgxEHpW/8XGAGAlvJyMA=</serialNumber>
     </certItem>
     <certItem issuerName="MIG8MQswCQYDVQQGEwJVUzEXMBUGA1UEChMOVmVyaVNpZ24sIEluYy4xHzAdBgNVBAsTFlZlcmlTaWduIFRydXN0IE5ldHdvcmsxOzA5BgNVBAsTMlRlcm1zIG9mIHVzZSBhdCBodHRwczovL3d3dy52ZXJpc2lnbi5jb20vcnBhIChjKTEwMTYwNAYDVQQDEy1WZXJpU2lnbiBDbGFzcyAzIEludGVybmF0aW9uYWwgU2VydmVyIENBIC0gRzM=">
       <serialNumber>bzTw0uq05TUYEGS98bh0Ww==</serialNumber>
@@ -3817,16 +3835,19 @@
       <serialNumber>GN2Hrh9LtnE=</serialNumber>
     </certItem>
     <certItem issuerName="MHYxCzAJBgNVBAYTAlVTMR0wGwYDVQQKExRTeW1hbnRlYyBDb3Jwb3JhdGlvbjEfMB0GA1UECxMWU3ltYW50ZWMgVHJ1c3QgTmV0d29yazEnMCUGA1UEAxMeU3ltYW50ZWMgV2ViIFBLSSBFQ0MgUm9vdCAtIEcx">
       <serialNumber>UT6GtTGbEC6SXJteWAKy2g==</serialNumber>
     </certItem>
     <certItem issuerName="MGYxCzAJBgNVBAYTAlVTMRYwFAYDVQQKEw1HZW9UcnVzdCBJbmMuMR0wGwYDVQQLExREb21haW4gVmFsaWRhdGVkIFNTTDEgMB4GA1UEAxMXR2VvVHJ1c3QgRFYgU1NMIENBIC0gRzI=">
       <serialNumber>P6G7IYSL2RZxtzTh8I6qPA==</serialNumber>
     </certItem>
+    <certItem issuerName="MIGSMQswCQYDVQQGEwJHQjEbMBkGA1UECBMSR3JlYXRlciBNYW5jaGVzdGVyMRAwDgYDVQQHEwdTYWxmb3JkMRowGAYDVQQKExFDT01PRE8gQ0EgTGltaXRlZDE4MDYGA1UEAxMvQ09NT0RPIFJTQSBFeHRlbmRlZCBWYWxpZGF0aW9uIFNlY3VyZSBTZXJ2ZXIgQ0E=">
+      <serialNumber>TasC8Zd8BT8kXEE67cFQmA==</serialNumber>
+    </certItem>
     <certItem issuerName="MGcxCzAJBgNVBAYTAkRFMRMwEQYDVQQKEwpGcmF1bmhvZmVyMSEwHwYDVQQLExhGcmF1bmhvZmVyIENvcnBvcmF0ZSBQS0kxIDAeBgNVBAMTF0ZyYXVuaG9mZXIgUm9vdCBDQSAyMDA3">
       <serialNumber>YR3YYQAAAAAABA==</serialNumber>
     </certItem>
     <certItem issuerName="MIGVMQswCQYDVQQGEwJHUjFEMEIGA1UEChM7SGVsbGVuaWMgQWNhZGVtaWMgYW5kIFJlc2VhcmNoIEluc3RpdHV0aW9ucyBDZXJ0LiBBdXRob3JpdHkxQDA+BgNVBAMTN0hlbGxlbmljIEFjYWRlbWljIGFuZCBSZXNlYXJjaCBJbnN0aXR1dGlvbnMgUm9vdENBIDIwMTE=">
       <serialNumber>GN2Hrh9LtnQ=</serialNumber>
     </certItem>
     <certItem issuerName="MFoxCzAJBgNVBAYTAklFMRIwEAYDVQQKEwlCYWx0aW1vcmUxEzARBgNVBAsTCkN5YmVyVHJ1c3QxIjAgBgNVBAMTGUJhbHRpbW9yZSBDeWJlclRydXN0IFJvb3Q=">
       <serialNumber>ByfNeA==</serialNumber>
@@ -3892,16 +3913,19 @@
       <serialNumber>CuUEKEJM4xhxlFXraPcSpQ==</serialNumber>
     </certItem>
     <certItem issuerName="MD8xJDAiBgNVBAoTG0RpZ2l0YWwgU2lnbmF0dXJlIFRydXN0IENvLjEXMBUGA1UEAxMORFNUIFJvb3QgQ0EgWDM=">
       <serialNumber>CgFBQQAAATjkOB1sAAAAAg==</serialNumber>
     </certItem>
     <certItem issuerName="MIG9MQswCQYDVQQGEwJVUzEXMBUGA1UEChMOVmVyaVNpZ24sIEluYy4xHzAdBgNVBAsTFlZlcmlTaWduIFRydXN0IE5ldHdvcmsxOjA4BgNVBAsTMShjKSAyMDA4IFZlcmlTaWduLCBJbmMuIC0gRm9yIGF1dGhvcml6ZWQgdXNlIG9ubHkxODA2BgNVBAMTL1ZlcmlTaWduIFVuaXZlcnNhbCBSb290IENlcnRpZmljYXRpb24gQXV0aG9yaXR5">
       <serialNumber>QOu0a5Z9rCkw6Nk7Rg1/AQ==</serialNumber>
     </certItem>
+    <certItem issuerName="MFoxCzAJBgNVBAYTAklFMRIwEAYDVQQKEwlCYWx0aW1vcmUxEzARBgNVBAsTCkN5YmVyVHJ1c3QxIjAgBgNVBAMTGUJhbHRpbW9yZSBDeWJlclRydXN0IFJvb3Q=">
+      <serialNumber>ByfNbw==</serialNumber>
+    </certItem>
     <certItem issuerName="MHYxCzAJBgNVBAYTAlVTMR0wGwYDVQQKExRTeW1hbnRlYyBDb3Jwb3JhdGlvbjEfMB0GA1UECxMWU3ltYW50ZWMgVHJ1c3QgTmV0d29yazEnMCUGA1UEAxMeU3ltYW50ZWMgV2ViIFBLSSBSU0EgUm9vdCAtIEcx">
       <serialNumber>ElBUYv/f+6+gnbAJ23qnAA==</serialNumber>
     </certItem>
     <certItem issuerName="MIGVMQswCQYDVQQGEwJVUzELMAkGA1UECBMCVVQxFzAVBgNVBAcTDlNhbHQgTGFrZSBDaXR5MR4wHAYDVQQKExVUaGUgVVNFUlRSVVNUIE5ldHdvcmsxITAfBgNVBAsTGGh0dHA6Ly93d3cudXNlcnRydXN0LmNvbTEdMBsGA1UEAxMUVVROLVVTRVJGaXJzdC1PYmplY3Q=">
       <serialNumber>a9rf7/BmG9JkKvRuy7J5QA==</serialNumber>
     </certItem>
     <certItem issuerName="MFwxCzAJBgNVBAYTAkJFMRUwEwYDVQQLEwxUcnVzdGVkIFJvb3QxGTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExGzAZBgNVBAMTElRydXN0ZWQgUm9vdCBDQSBHMg==">
       <serialNumber>QM1zZ4GZ4gfwpQtUYye3Ne0=</serialNumber>
@@ -4417,16 +4441,19 @@
       <serialNumber>JD1wxDd8IgmiqX7MyPPg1g==</serialNumber>
     </certItem>
     <certItem issuerName="MDsxGDAWBgNVBAoTD0N5YmVydHJ1c3QsIEluYzEfMB0GA1UEAxMWQ3liZXJ0cnVzdCBHbG9iYWwgUm9vdA==">
       <serialNumber>BAAAAAABQaHhNLo=</serialNumber>
     </certItem>
     <certItem issuerName="MEoxCzAJBgNVBAYTAlVTMRYwFAYDVQQKEw1MZXQncyBFbmNyeXB0MSMwIQYDVQQDExpMZXQncyBFbmNyeXB0IEF1dGhvcml0eSBYMw==">
       <serialNumber>AwBGo0Zmp6KRryAguuMvXATI</serialNumber>
     </certItem>
+    <certItem issuerName="MHIxCzAJBgNVBAYTAlVTMQswCQYDVQQIEwJUWDEQMA4GA1UEBxMHSG91c3RvbjEVMBMGA1UEChMMY1BhbmVsLCBJbmMuMS0wKwYDVQQDEyRjUGFuZWwsIEluYy4gQ2VydGlmaWNhdGlvbiBBdXRob3JpdHk=">
+      <serialNumber>AJk3QFH13eHUHHVnsvwS0Vo=</serialNumber>
+    </certItem>
     <certItem issuerName="MG8xCzAJBgNVBAYTAlNFMRQwEgYDVQQKEwtBZGRUcnVzdCBBQjEmMCQGA1UECxMdQWRkVHJ1c3QgRXh0ZXJuYWwgVFRQIE5ldHdvcmsxIjAgBgNVBAMTGUFkZFRydXN0IEV4dGVybmFsIENBIFJvb3Q=">
       <serialNumber>U3t2Vk8pfxTcaUPpIq0seQ==</serialNumber>
     </certItem>
     <certItem issuerName="MEQxCzAJBgNVBAYTAlVTMRYwFAYDVQQKEw1HZW9UcnVzdCBJbmMuMR0wGwYDVQQDExRHZW9UcnVzdCBTU0wgQ0EgLSBHMw==">
       <serialNumber>bx/XHJqcwxDOptxJ2lh5vw==</serialNumber>
     </certItem>
     <certItem issuerName="MHUxCzAJBgNVBAYTAkVFMSIwIAYDVQQKDBlBUyBTZXJ0aWZpdHNlZXJpbWlza2Vza3VzMSgwJgYDVQQDDB9FRSBDZXJ0aWZpY2F0aW9uIENlbnRyZSBSb290IENBMRgwFgYJKoZIhvcNAQkBFglwa2lAc2suZWU=">
       <serialNumber>LU4d0t7PAsZNgJGZcb+o/w==</serialNumber>
@@ -4588,16 +4615,19 @@
       <serialNumber>Fw==</serialNumber>
     </certItem>
     <certItem issuerName="MHYxCzAJBgNVBAYTAlVTMR0wGwYDVQQKExRTeW1hbnRlYyBDb3Jwb3JhdGlvbjEfMB0GA1UECxMWU3ltYW50ZWMgVHJ1c3QgTmV0d29yazEnMCUGA1UEAxMeU3ltYW50ZWMgV2ViIFBLSSBFQ0MgUm9vdCAtIEcx">
       <serialNumber>Gz4uHrL2usrTZrPCHeuF5g==</serialNumber>
     </certItem>
     <certItem issuerName="MIHKMQswCQYDVQQGEwJVUzEXMBUGA1UEChMOVmVyaVNpZ24sIEluYy4xHzAdBgNVBAsTFlZlcmlTaWduIFRydXN0IE5ldHdvcmsxOjA4BgNVBAsTMShjKSAyMDA2IFZlcmlTaWduLCBJbmMuIC0gRm9yIGF1dGhvcml6ZWQgdXNlIG9ubHkxRTBDBgNVBAMTPFZlcmlTaWduIENsYXNzIDMgUHVibGljIFByaW1hcnkgQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkgLSBHNQ==">
       <serialNumber>UWMOvf4tj/x5cQN2PXVSww==</serialNumber>
     </certItem>
+    <certItem issuerName="MHIxCzAJBgNVBAYTAlVTMQswCQYDVQQIEwJUWDEQMA4GA1UEBxMHSG91c3RvbjEVMBMGA1UEChMMY1BhbmVsLCBJbmMuMS0wKwYDVQQDEyRjUGFuZWwsIEluYy4gQ2VydGlmaWNhdGlvbiBBdXRob3JpdHk=">
+      <serialNumber>NlLRZJFLco/An3cLAGjGgQ==</serialNumber>
+    </certItem>
     <certItem issuerName="MFwxCzAJBgNVBAYTAkJFMRUwEwYDVQQLEwxUcnVzdGVkIFJvb3QxGTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExGzAZBgNVBAMTElRydXN0ZWQgUm9vdCBDQSBHMg==">
       <serialNumber>e/fIfg2Dj2tkYIWVu2r82Cc=</serialNumber>
     </certItem>
     <certItem issuerName="MH4xCzAJBgNVBAYTAlVTMR0wGwYDVQQKExRTeW1hbnRlYyBDb3Jwb3JhdGlvbjEfMB0GA1UECxMWU3ltYW50ZWMgVHJ1c3QgTmV0d29yazEvMC0GA1UEAxMmU3ltYW50ZWMgQ2xhc3MgMyBTZWN1cmUgU2VydmVyIENBIC0gRzQ=">
       <serialNumber>UMUwXwT1Z4juyQ/CNTf4mw==</serialNumber>
     </certItem>
     <certItem issuerName="MH4xCzAJBgNVBAYTAlVTMR0wGwYDVQQKExRTeW1hbnRlYyBDb3Jwb3JhdGlvbjEfMB0GA1UECxMWU3ltYW50ZWMgVHJ1c3QgTmV0d29yazEvMC0GA1UEAxMmU3ltYW50ZWMgQ2xhc3MgMyBTZWN1cmUgU2VydmVyIENBIC0gRzQ=">
       <serialNumber>d8AtKymQwkOPDBj+hjPzFg==</serialNumber>
@@ -4744,16 +4774,19 @@
       <serialNumber>ESDu2nhlLPzfx+LYgjlYFP/k</serialNumber>
     </certItem>
     <certItem issuerName="MIHKMQswCQYDVQQGEwJVUzEXMBUGA1UEChMOVmVyaVNpZ24sIEluYy4xHzAdBgNVBAsTFlZlcmlTaWduIFRydXN0IE5ldHdvcmsxOjA4BgNVBAsTMShjKSAyMDA2IFZlcmlTaWduLCBJbmMuIC0gRm9yIGF1dGhvcml6ZWQgdXNlIG9ubHkxRTBDBgNVBAMTPFZlcmlTaWduIENsYXNzIDMgUHVibGljIFByaW1hcnkgQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkgLSBHNQ==">
       <serialNumber>buROL/l2GuXISv+/JVLkdA==</serialNumber>
     </certItem>
     <certItem issuerName="MGMxCzAJBgNVBAYTAlVTMRUwEwYDVQQKEwx0aGF3dGUsIEluYy4xHTAbBgNVBAsTFERvbWFpbiBWYWxpZGF0ZWQgU1NMMR4wHAYDVQQDExV0aGF3dGUgRFYgU1NMIENBIC0gRzI=">
       <serialNumber>CqZgEvHAsnzkT//QV9KjXw==</serialNumber>
     </certItem>
+    <certItem issuerName="MHMxCzAJBgNVBAYTAlVTMQswCQYDVQQIEwJDQTEUMBIGA1UEBxMLU2FudGEgQ2xhcmExGjAYBgNVBAoTEUludGVsIENvcnBvcmF0aW9uMSUwIwYDVQQDExxJbnRlbCBFeHRlcm5hbCBJc3N1aW5nIENBIDZC">
+      <serialNumber>HwAABsvzDP+DIzUG6QAAAAAGyw==</serialNumber>
+    </certItem>
     <certItem issuerName="MH4xCzAJBgNVBAYTAlVTMR0wGwYDVQQKExRTeW1hbnRlYyBDb3Jwb3JhdGlvbjEfMB0GA1UECxMWU3ltYW50ZWMgVHJ1c3QgTmV0d29yazEvMC0GA1UEAxMmU3ltYW50ZWMgQ2xhc3MgMyBTZWN1cmUgU2VydmVyIENBIC0gRzQ=">
       <serialNumber>HZyLf+K70FKc+jomm8DiDw==</serialNumber>
     </certItem>
     <certItem issuerName="MDQxCzAJBgNVBAYTAkZSMRIwEAYDVQQKDAlEaGlteW90aXMxETAPBgNVBAMMCENlcnRpZ25h">
       <serialNumber>Ew==</serialNumber>
     </certItem>
     <certItem issuerName="MHYxCzAJBgNVBAYTAlVTMR0wGwYDVQQKExRTeW1hbnRlYyBDb3Jwb3JhdGlvbjEfMB0GA1UECxMWU3ltYW50ZWMgVHJ1c3QgTmV0d29yazEnMCUGA1UEAxMeU3ltYW50ZWMgV2ViIFBLSSBFQ0MgUm9vdCAtIEcx">
       <serialNumber>IARKrBjlKQLyVGA4X52L7w==</serialNumber>
@@ -4841,16 +4874,19 @@
     </certItem>
     <certItem issuerName="MHYxCzAJBgNVBAYTAlVTMR0wGwYDVQQKExRTeW1hbnRlYyBDb3Jwb3JhdGlvbjEfMB0GA1UECxMWU3ltYW50ZWMgVHJ1c3QgTmV0d29yazEnMCUGA1UEAxMeU3ltYW50ZWMgV2ViIFBLSSBFQ0MgUm9vdCAtIEcx">
       <serialNumber>CGo/+42e75JBJ2JcOEaMFw==</serialNumber>
     </certItem>
     <certItem issuerName="MGMxCzAJBgNVBAYTAkZSMRMwEQYDVQQKEwpDZXJ0aW5vbWlzMRcwFQYDVQQLEw4wMDAyIDQzMzk5ODkwMzEmMCQGA1UEAwwdQ2VydGlub21pcyAtIEF1dG9yaXTDqSBSYWNpbmU=">
       <serialNumber>Eg==</serialNumber>
     </certItem>
     <certItem issuerName="MH4xCzAJBgNVBAYTAlVTMR0wGwYDVQQKExRTeW1hbnRlYyBDb3Jwb3JhdGlvbjEfMB0GA1UECxMWU3ltYW50ZWMgVHJ1c3QgTmV0d29yazEvMC0GA1UEAxMmU3ltYW50ZWMgQ2xhc3MgMyBTZWN1cmUgU2VydmVyIENBIC0gRzQ=">
+      <serialNumber>UDE/uwr4z5V8eZI4+1gkAw==</serialNumber>
+    </certItem>
+    <certItem issuerName="MH4xCzAJBgNVBAYTAlVTMR0wGwYDVQQKExRTeW1hbnRlYyBDb3Jwb3JhdGlvbjEfMB0GA1UECxMWU3ltYW50ZWMgVHJ1c3QgTmV0d29yazEvMC0GA1UEAxMmU3ltYW50ZWMgQ2xhc3MgMyBTZWN1cmUgU2VydmVyIENBIC0gRzQ=">
       <serialNumber>ezdAeCxKH7BFs7vn3byYaw==</serialNumber>
     </certItem>
     <certItem issuerName="MIGFMQswCQYDVQQGEwJVUzEgMB4GA1UECgwXV2VsbHMgRmFyZ28gV2VsbHNTZWN1cmUxHDAaBgNVBAsME1dlbGxzIEZhcmdvIEJhbmsgTkExNjA0BgNVBAMMLVdlbGxzU2VjdXJlIFB1YmxpYyBSb290IENlcnRpZmljYXRlIEF1dGhvcml0eQ==">
       <serialNumber>AZ0=</serialNumber>
     </certItem>
     <certItem issuerName="MFoxCzAJBgNVBAYTAkRFMRMwEQYDVQQKEwpERk4tVmVyZWluMRAwDgYDVQQLEwdERk4tUEtJMSQwIgYDVQQDExtERk4tVmVyZWluIFBDQSBHbG9iYWwgLSBHMDE=">
       <serialNumber>CcHC1w==</serialNumber>
     </certItem>
@@ -4984,16 +5020,19 @@
       <serialNumber>TA6BjA==</serialNumber>
     </certItem>
     <certItem issuerName="MEwxIDAeBgNVBAsTF0dsb2JhbFNpZ24gUm9vdCBDQSAtIFIzMRMwEQYDVQQKEwpHbG9iYWxTaWduMRMwEQYDVQQDEwpHbG9iYWxTaWdu">
       <serialNumber>BAAAAAABMYnGRuw=</serialNumber>
     </certItem>
     <certItem issuerName="MHYxCzAJBgNVBAYTAlVTMR0wGwYDVQQKExRTeW1hbnRlYyBDb3Jwb3JhdGlvbjEfMB0GA1UECxMWU3ltYW50ZWMgVHJ1c3QgTmV0d29yazEnMCUGA1UEAxMeU3ltYW50ZWMgV2ViIFBLSSBFQ0MgUm9vdCAtIEcx">
       <serialNumber>a2GKnRbYMZ0oZkRzJE8NIw==</serialNumber>
     </certItem>
+    <certItem issuerName="MH8xCzAJBgNVBAYTAkVVMScwJQYDVQQKEx5BQyBDYW1lcmZpcm1hIFNBIENJRiBBODI3NDMyODcxIzAhBgNVBAsTGmh0dHA6Ly93d3cuY2hhbWJlcnNpZ24ub3JnMSIwIAYDVQQDExlDaGFtYmVycyBvZiBDb21tZXJjZSBSb290">
+      <serialNumber>Eg==</serialNumber>
+    </certItem>
     <certItem issuerName="MHYxCzAJBgNVBAYTAlVTMRcwFQYDVQQKEw5WZXJpU2lnbiwgSW5jLjEfMB0GA1UECxMWVmVyaVNpZ24gVHJ1c3QgTmV0d29yazEtMCsGA1UEAxMkVmVyaVNpZ24gQ2xhc3MgMyBTU1AgSW50ZXJtZWRpYXRlIENB">
       <serialNumber>G8sz+bm+vQjTpQNBh5CfMg==</serialNumber>
     </certItem>
     <certItem issuerName="MEUxCzAJBgNVBAYTAkJNMRkwFwYDVQQKExBRdW9WYWRpcyBMaW1pdGVkMRswGQYDVQQDExJRdW9WYWRpcyBSb290IENBIDI=">
       <serialNumber>EM8bDLBnnoYe4LnWpLIhS4esr3I=</serialNumber>
     </certItem>
     <certItem issuerName="MFoxCzAJBgNVBAYTAkRFMRMwEQYDVQQKEwpERk4tVmVyZWluMRAwDgYDVQQLEwdERk4tUEtJMSQwIgYDVQQDExtERk4tVmVyZWluIFBDQSBHbG9iYWwgLSBHMDE=">
       <serialNumber>Cfk9oA==</serialNumber>
@@ -5041,10 +5080,22 @@
       <serialNumber>ESByYNtAIfizf2L3NMzCH8zZ</serialNumber>
     </certItem>
     <certItem issuerName="MHYxCzAJBgNVBAYTAlVTMR0wGwYDVQQKExRTeW1hbnRlYyBDb3Jwb3JhdGlvbjEfMB0GA1UECxMWU3ltYW50ZWMgVHJ1c3QgTmV0d29yazEnMCUGA1UEAxMeU3ltYW50ZWMgV2ViIFBLSSBFQ0MgUm9vdCAtIEcx">
       <serialNumber>QspbHxzWb41SX9TUhF1N1A==</serialNumber>
     </certItem>
     <certItem issuerName="MHYxCzAJBgNVBAYTAlVTMR0wGwYDVQQKExRTeW1hbnRlYyBDb3Jwb3JhdGlvbjEfMB0GA1UECxMWU3ltYW50ZWMgVHJ1c3QgTmV0d29yazEnMCUGA1UEAxMeU3ltYW50ZWMgV2ViIFBLSSBFQ0MgUm9vdCAtIEcx">
       <serialNumber>KNhgX8XuJduYciIyatpOQg==</serialNumber>
     </certItem>
+    <certItem issuerName="MHExCzAJBgNVBAYTAkRFMRwwGgYDVQQKExNEZXV0c2NoZSBUZWxla29tIEFHMR8wHQYDVQQLExZULVRlbGVTZWMgVHJ1c3QgQ2VudGVyMSMwIQYDVQQDExpEZXV0c2NoZSBUZWxla29tIFJvb3QgQ0EgMg==">
+      <serialNumber>AImQERVYPoeb</serialNumber>
+    </certItem>
+    <certItem issuerName="MGQxCzAJBgNVBAYTAmNoMREwDwYDVQQKEwhTd2lzc2NvbTElMCMGA1UECxMcRGlnaXRhbCBDZXJ0aWZpY2F0ZSBTZXJ2aWNlczEbMBkGA1UEAxMSU3dpc3Njb20gUm9vdCBDQSAy">
+      <serialNumber>GpO48aJ8GngtwECqZhm/xA==</serialNumber>
+    </certItem>
+    <certItem issuerName="MDwxGzAZBgNVBAMTEkNvbVNpZ24gU2VjdXJlZCBDQTEQMA4GA1UEChMHQ29tU2lnbjELMAkGA1UEBhMCSUw=">
+      <serialNumber>CdYL9vSQCEKzBwjO10ud2w==</serialNumber>
+    </certItem>
+    <certItem issuerName="MDwxHjAcBgNVBAMMFUF0b3MgVHJ1c3RlZFJvb3QgMjAxMTENMAsGA1UECgwEQXRvczELMAkGA1UEBhMCREU=">
+      <serialNumber>a12RvBNhznU=</serialNumber>
+    </certItem>
   </certItems>
 </blocklist>
--- a/browser/app/moz.build
+++ b/browser/app/moz.build
@@ -38,19 +38,16 @@ GeckoProgram(CONFIG['MOZ_APP_NAME'])
 
 SOURCES += [
     'nsBrowserApp.cpp',
 ]
 
 # Neither channel-prefs.js nor firefox.exe want to end up in dist/bin/browser.
 DIST_SUBDIR = ""
 
-# channel-prefs.js is handled separate from other prefs due to bug 756325
-JS_PREFERENCE_PP_FILES += ['profile/channel-prefs.js']
-
 LOCAL_INCLUDES += [
     '!/build',
     '/toolkit/xre',
     '/xpcom/base',
     '/xpcom/build',
 ]
 
 if CONFIG['LIBFUZZER']:
--- a/browser/app/profile/channel-prefs.js
+++ b/browser/app/profile/channel-prefs.js
@@ -1,6 +1,5 @@
 /* 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/. */
 
-#filter substitution
 pref("app.update.channel", "@MOZ_UPDATE_CHANNEL@");
--- a/browser/app/profile/firefox.js
+++ b/browser/app/profile/firefox.js
@@ -126,17 +126,21 @@ pref("app.update.altwindowtype", "Browse
 pref("app.update.log", false);
 
 // The number of general background check failures to allow before notifying the
 // user of the failure. User initiated update checks always notify the user of
 // the failure.
 pref("app.update.backgroundMaxErrors", 10);
 
 // Whether or not app updates are enabled
+#ifdef MOZ_UPDATER
 pref("app.update.enabled", true);
+#else
+pref("app.update.enabled", false);
+#endif
 
 // Whether or not to use the doorhanger application update UI.
 pref("app.update.doorhanger", true);
 
 // Ids of the links to the "What's new" update documentation
 pref("app.update.link.updateAvailableWhatsNew", "update-available-whats-new");
 pref("app.update.link.updateManualWhatsNew", "update-manual-whats-new");
 
@@ -518,18 +522,16 @@ pref("general.warnOnAboutConfig",       
 #endif
 
 // This is the pref to control the location bar, change this to true to
 // force this - this makes the origin of popup windows more obvious to avoid
 // spoofing. We would rather not do it by default because it affects UE for web
 // applications, but without it there isn't a really good way to prevent chrome
 // spoofing, see bug 337344
 pref("dom.disable_window_open_feature.location",  true);
-// prevent JS from setting status messages
-pref("dom.disable_window_status_change",          true);
 // allow JS to move and resize existing windows
 pref("dom.disable_window_move_resize",            false);
 // prevent JS from monkeying with window focus, etc
 pref("dom.disable_window_flip",                   true);
 
 // popups.policy 1=allow,2=reject
 pref("privacy.popups.policy",               1);
 pref("privacy.popups.usecustom",            true);
@@ -908,19 +910,16 @@ pref("browser.sessionstore.cleanup.forge
 // Maximum number of bytes of DOMSessionStorage data we collect per origin.
 pref("browser.sessionstore.dom_storage_limit", 2048);
 // Amount of failed SessionFile writes until we restart the worker.
 pref("browser.sessionstore.max_write_failures", 5);
 
 // allow META refresh by default
 pref("accessibility.blockautorefresh", false);
 
-// Whether useAsyncTransactions is enabled or not.
-pref("browser.places.useAsyncTransactions", true);
-
 // Whether history is enabled or not.
 pref("places.history.enabled", true);
 
 // the (maximum) number of the recent visits to sample
 // when calculating frecency
 pref("places.frecency.numVisits", 10);
 
 // buckets (in days) for frecency calculation
@@ -1089,28 +1088,29 @@ pref("security.sandbox.content.level", 3
 
 #if defined(XP_LINUX) && defined(MOZ_SANDBOX) && defined(MOZ_CONTENT_SANDBOX)
 // This pref is introduced as part of bug 742434, the naming is inspired from
 // its Windows/Mac counterpart, but on Linux it's an integer which means:
 // 0 -> "no sandbox"
 // 1 -> "content sandbox using seccomp-bpf when available"
 // 2 -> "seccomp-bpf + write file broker"
 // 3 -> "seccomp-bpf + read/write file brokering"
+// 4 -> all of the above + network/socket restrictions
 // Content sandboxing on Linux is currently in the stage of
 // 'just getting it enabled', which includes a very permissive whitelist. We
 // enable seccomp-bpf on nightly to see if everything is running, or if we need
 // to whitelist more system calls.
 //
 // So the purpose of this setting is to allow nightly users to disable the
 // sandbox while we fix their problems. This way, they won't have to wait for
 // another nightly release which disables seccomp-bpf again.
 //
 // This setting may not be required anymore once we decide to permanently
 // enable the content sandbox.
-pref("security.sandbox.content.level", 3);
+pref("security.sandbox.content.level", 4);
 pref("security.sandbox.content.write_path_whitelist", "");
 pref("security.sandbox.content.read_path_whitelist", "");
 pref("security.sandbox.content.syscall_whitelist", "");
 #endif
 
 #if defined(XP_MACOSX) || defined(XP_WIN)
 #if defined(MOZ_SANDBOX) && defined(MOZ_CONTENT_SANDBOX)
 // ID (a UUID when set by gecko) that is used to form the name of a
@@ -1179,16 +1179,17 @@ pref("services.sync.prefs.sync.browser.s
 pref("services.sync.prefs.sync.browser.search.update", true);
 pref("services.sync.prefs.sync.browser.sessionstore.restore_on_demand", true);
 pref("services.sync.prefs.sync.browser.startup.homepage", true);
 pref("services.sync.prefs.sync.browser.startup.page", true);
 pref("services.sync.prefs.sync.browser.tabs.loadInBackground", true);
 pref("services.sync.prefs.sync.browser.tabs.warnOnClose", true);
 pref("services.sync.prefs.sync.browser.tabs.warnOnOpen", true);
 pref("services.sync.prefs.sync.browser.urlbar.autocomplete.enabled", true);
+pref("services.sync.prefs.sync.browser.urlbar.matchBuckets", true);
 pref("services.sync.prefs.sync.browser.urlbar.maxRichResults", true);
 pref("services.sync.prefs.sync.browser.urlbar.suggest.bookmark", true);
 pref("services.sync.prefs.sync.browser.urlbar.suggest.history", true);
 pref("services.sync.prefs.sync.browser.urlbar.suggest.history.onlyTyped", true);
 pref("services.sync.prefs.sync.browser.urlbar.suggest.openpage", true);
 pref("services.sync.prefs.sync.browser.urlbar.suggest.searches", true);
 pref("services.sync.prefs.sync.dom.disable_open_during_load", true);
 pref("services.sync.prefs.sync.dom.disable_window_flip", true);
@@ -1217,16 +1218,18 @@ pref("services.sync.prefs.sync.privacy.c
 pref("services.sync.prefs.sync.privacy.clearOnShutdown.offlineApps", true);
 pref("services.sync.prefs.sync.privacy.clearOnShutdown.sessions", true);
 pref("services.sync.prefs.sync.privacy.clearOnShutdown.siteSettings", true);
 pref("services.sync.prefs.sync.privacy.donottrackheader.enabled", true);
 pref("services.sync.prefs.sync.privacy.sanitize.sanitizeOnShutdown", true);
 pref("services.sync.prefs.sync.privacy.trackingprotection.enabled", true);
 pref("services.sync.prefs.sync.privacy.trackingprotection.pbmode.enabled", true);
 pref("services.sync.prefs.sync.privacy.resistFingerprinting", true);
+pref("services.sync.prefs.sync.privacy.reduceTimerPrecision", true);
+pref("services.sync.prefs.sync.privacy.resistFingerprinting.reduceTimerPrecision.microseconds", true);
 pref("services.sync.prefs.sync.security.OCSP.enabled", true);
 pref("services.sync.prefs.sync.security.OCSP.require", true);
 pref("services.sync.prefs.sync.security.default_personal_cert", true);
 pref("services.sync.prefs.sync.security.tls.version.min", true);
 pref("services.sync.prefs.sync.security.tls.version.max", true);
 pref("services.sync.prefs.sync.services.sync.syncedTabs.showRemoteIcons", true);
 pref("services.sync.prefs.sync.signon.rememberSignons", true);
 pref("services.sync.prefs.sync.spellchecker.dictionary", true);
@@ -1332,16 +1335,20 @@ pref("security.insecure_password.ui.enab
 
 // Show in-content login form warning UI for insecure login fields
 pref("security.insecure_field_warning.contextual.enabled", true);
 
 // Show degraded UI for http pages; disabled for now
 pref("security.insecure_connection_icon.enabled", false);
 pref("security.insecure_connection_icon.pbmode.enabled", false);
 
+// Show "Not Secure" text for http pages; disabled for now
+pref("security.insecure_connection_text.enabled", false);
+pref("security.insecure_connection_text.pbmode.enabled", false);
+
 // 1 = allow MITM for certificate pinning checks.
 pref("security.cert_pinning.enforcement_level", 1);
 
 
 // Override the Gecko-default value of false for Firefox.
 pref("plain_text.wrap_long_lines", true);
 
 // If this turns true, Moz*Gesture events are not called stopPropagation()
@@ -1518,16 +1525,18 @@ pref("toolkit.telemetry.shutdownPingSend
 // Enables sending a duplicate of the first shutdown ping from the first session.
 pref("toolkit.telemetry.firstShutdownPing.enabled", true);
 // Enables sending the 'new-profile' ping on new profiles.
 pref("toolkit.telemetry.newProfilePing.enabled", true);
 // Enables sending 'update' pings on Firefox updates.
 pref("toolkit.telemetry.updatePing.enabled", true);
 // Enables sending 'bhr' pings when the browser hangs.
 pref("toolkit.telemetry.bhrPing.enabled", true);
+// Enables using Hybrid Content Telemetry from Mozilla privileged pages.
+pref("toolkit.telemetry.hybridContent.enabled", true);
 
 // Telemetry experiments settings.
 pref("experiments.enabled", true);
 pref("experiments.manifest.fetchIntervalSeconds", 86400);
 pref("experiments.manifest.uri", "https://telemetry-experiment.cdn.mozilla.net/manifest/v1/firefox/%VERSION%/%CHANNEL%");
 // Whether experiments are supported by the current application profile.
 pref("experiments.supported", true);
 
@@ -1688,27 +1697,27 @@ pref("browser.crashReports.unsubmittedCh
 pref("browser.crashReports.unsubmittedCheck.enabled", false);
 #endif
 
 // chancesUntilSuppress is how many times we'll show the unsubmitted
 // crash report notification across different days and shutdown
 // without a user choice before we suppress the notification for
 // some number of days.
 pref("browser.crashReports.unsubmittedCheck.chancesUntilSuppress", 4);
-pref("browser.crashReports.unsubmittedCheck.autoSubmit", false);
+pref("browser.crashReports.unsubmittedCheck.autoSubmit2", false);
 
 // Preferences for the form autofill system extension
 // The truthy values of "extensions.formautofill.available" are "on" and "detect",
 // any other value means autofill isn't available.
 // "detect" means it's enabled if conditions defined in the extension are met.
 #ifdef NIGHTLY_BUILD
 pref("extensions.formautofill.available", "on");
 pref("extensions.formautofill.creditCards.available", true);
 #elif MOZ_UPDATE_CHANNEL == release
-pref("extensions.formautofill.available", "staged-rollout");
+pref("extensions.formautofill.available", "detect");
 pref("extensions.formautofill.creditCards.available", false);
 #else
 pref("extensions.formautofill.available", "detect");
 pref("extensions.formautofill.creditCards.available", true);
 #endif
 pref("extensions.formautofill.addresses.enabled", true);
 pref("extensions.formautofill.creditCards.enabled", true);
 // Pref for shield/heartbeat to recognize users who have used Credit Card
@@ -1719,17 +1728,23 @@ pref("extensions.formautofill.creditCard
 // 2: saw the doorhanger
 // 3: submitted an autofill'ed credit card form
 pref("extensions.formautofill.creditCards.used", 0);
 pref("extensions.formautofill.firstTimeUse", true);
 pref("extensions.formautofill.heuristics.enabled", true);
 pref("extensions.formautofill.section.enabled", true);
 pref("extensions.formautofill.loglevel", "Warn");
 // Comma separated list of countries Form Autofill supports
+#ifdef MOZ_UPDATE_CHANNEL == release
+pref("extensions.formautofill.supportedCountries", "US");
+pref("extensions.formautofill.supportRTL", false);
+#else
 pref("extensions.formautofill.supportedCountries", "US,CA,DE");
+pref("extensions.formautofill.supportRTL", true);
+#endif
 
 // Whether or not to restore a session with lazy-browser tabs.
 pref("browser.sessionstore.restore_tabs_lazily", true);
 
 pref("browser.suppress_first_window_animation", true);
 
 // Preferences for Photon onboarding system extension
 pref("browser.onboarding.enabled", true);
deleted file mode 100644
--- a/browser/app/profile/pagethemes.rdf
+++ /dev/null
@@ -1,7 +0,0 @@
-<?xml version="1.0"?> <!-- -*- Mode: SGML -*- -->
-<!-- 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/. -->
-
-<RDF:RDF xmlns:RDF="http://www.w3.org/1999/02/22-rdf-syntax-ns#"/>
-
--- a/browser/base/content/aboutTabCrashed.js
+++ b/browser/base/content/aboutTabCrashed.js
@@ -298,13 +298,14 @@ var AboutTabCrashed = {
     sendAsyncMessage(messageName, {
       sendReport,
       comments,
       email,
       emailMe,
       includeURL,
       URL,
       autoSubmit,
+      hasReport: this.hasReport,
     });
   },
 };
 
 AboutTabCrashed.init();
--- a/browser/base/content/browser-addons.js
+++ b/browser/base/content/browser-addons.js
@@ -239,26 +239,26 @@ var gXPInstallObserver = {
       timeout: Date.now() + 30000,
     };
 
     switch (aTopic) {
     case "addon-install-disabled": {
       notificationID = "xpinstall-disabled";
       let secondaryActions = null;
 
-      if (gPrefService.prefIsLocked("xpinstall.enabled")) {
+      if (Services.prefs.prefIsLocked("xpinstall.enabled")) {
         messageString = gNavigatorBundle.getString("xpinstallDisabledMessageLocked");
       } else {
         messageString = gNavigatorBundle.getString("xpinstallDisabledMessage");
 
         action = {
           label: gNavigatorBundle.getString("xpinstallDisabledButton"),
           accessKey: gNavigatorBundle.getString("xpinstallDisabledButton.accesskey"),
           callback: function editPrefs() {
-            gPrefService.setBoolPref("xpinstall.enabled", true);
+            Services.prefs.setBoolPref("xpinstall.enabled", true);
           }
         };
 
         secondaryActions = [{
           label: gNavigatorBundle.getString("addonInstall.cancelButton.label"),
           accessKey: gNavigatorBundle.getString("addonInstall.cancelButton.accesskey"),
           callback: () => {},
         }];
--- a/browser/base/content/browser-ctrlTab.js
+++ b/browser/base/content/browser-ctrlTab.js
@@ -11,22 +11,23 @@
 var tabPreviews = {
   init: function tabPreviews_init() {
     if (this._selectedTab)
       return;
     this._selectedTab = gBrowser.selectedTab;
 
     gBrowser.tabContainer.addEventListener("TabSelect", this);
     gBrowser.tabContainer.addEventListener("SSTabRestored", this);
+  },
 
-    let screenManager = Cc["@mozilla.org/gfx/screenmanager;1"]
-                          .getService(Ci.nsIScreenManager);
-    let left = {}, top = {}, width = {}, height = {};
-    screenManager.primaryScreen.GetRectDisplayPix(left, top, width, height);
-    this.aspectRatio = height.value / width.value;
+  get aspectRatio() {
+    let { PageThumbUtils } = Cu.import("resource://gre/modules/PageThumbUtils.jsm", {});
+    let [ width, height ] = PageThumbUtils.getThumbnailSize(window);
+    delete this.aspectRatio;
+    return this.aspectRatio = height / width;
   },
 
   get: function tabPreviews_get(aTab) {
     let uri = aTab.linkedBrowser.currentURI.spec;
 
     if (aTab.__thumbnail_lastURI &&
         aTab.__thumbnail_lastURI != uri) {
       aTab.__thumbnail = null;
@@ -210,18 +211,18 @@ var ctrlTab = {
       this._recentlyUsedTabs = null;
       this._init(false);
     }
   },
 
   prefName: "browser.ctrlTab.previews",
   readPref: function ctrlTab_readPref() {
     var enable =
-      gPrefService.getBoolPref(this.prefName) &&
-      !gPrefService.getBoolPref("browser.ctrlTab.disallowForScreenReaders", false);
+      Services.prefs.getBoolPref(this.prefName) &&
+      !Services.prefs.getBoolPref("browser.ctrlTab.disallowForScreenReaders", false);
 
     if (enable)
       this.init();
     else
       this.uninit();
   },
   observe(aSubject, aTopic, aPrefName) {
     this.readPref();
@@ -282,16 +283,20 @@ var ctrlTab = {
 
     if (this._selectedIndex == -1) {
       // Focus is already in the panel.
       this.previews[selectedIndex].focus();
     } else {
       this._selectedIndex = selectedIndex;
     }
 
+    if (this.previews[selectedIndex]._tab) {
+      gBrowser.warmupTab(this.previews[selectedIndex]._tab);
+    }
+
     if (this._timer) {
       clearTimeout(this._timer);
       this._timer = null;
       this._openPanel();
     }
   },
 
   _mouseOverFocus: function ctrlTab_mouseOverFocus(aPreview) {
@@ -342,16 +347,17 @@ var ctrlTab = {
   open: function ctrlTab_open() {
     if (this.isOpen)
       return;
 
     document.addEventListener("keyup", this, true);
 
     this.updatePreviews();
     this._selectedIndex = 1;
+    gBrowser.warmupTab(this.selected._tab);
 
     // Add a slight delay before showing the UI, so that a quick
     // "ctrl-tab" keypress just flips back to the MRU tab.
     this._timer = setTimeout(function(self) {
       self._timer = null;
       self._openPanel();
     }, 200, this);
   },
--- a/browser/base/content/browser-doctype.inc
+++ b/browser/base/content/browser-doctype.inc
@@ -4,18 +4,16 @@
 <!ENTITY % browserDTD SYSTEM "chrome://browser/locale/browser.dtd" >
 %browserDTD;
 <!ENTITY % baseMenuDTD SYSTEM "chrome://browser/locale/baseMenuOverlay.dtd" >
 %baseMenuDTD;
 <!ENTITY % charsetDTD SYSTEM "chrome://global/locale/charsetMenu.dtd" >
 %charsetDTD;
 <!ENTITY % textcontextDTD SYSTEM "chrome://global/locale/textcontext.dtd" >
 %textcontextDTD;
-<!ENTITY % customizeToolbarDTD SYSTEM "chrome://global/locale/customizeToolbar.dtd">
-  %customizeToolbarDTD;
 <!ENTITY % placesDTD SYSTEM "chrome://browser/locale/places/places.dtd">
 %placesDTD;
 <!ENTITY % safebrowsingDTD SYSTEM "chrome://browser/locale/safebrowsing/phishing-afterload-warning-message.dtd">
 %safebrowsingDTD;
 <!ENTITY % aboutHomeDTD SYSTEM "chrome://browser/locale/aboutHome.dtd">
 %aboutHomeDTD;
 <!ENTITY % syncBrandDTD SYSTEM "chrome://browser/locale/syncBrand.dtd">
 %syncBrandDTD;
--- a/browser/base/content/browser-feeds.js
+++ b/browser/base/content/browser-feeds.js
@@ -203,21 +203,16 @@ var FeedHandler = {
    */
   subscribeToFeed(href, event) {
     // Just load the feed in the content area to either subscribe or show the
     // preview UI
     if (!href)
       href = event.target.getAttribute("feed");
     urlSecurityCheck(href, gBrowser.contentPrincipal,
                      Ci.nsIScriptSecurityManager.DISALLOW_INHERIT_PRINCIPAL);
-    let feedURI = makeURI(href, document.characterSet);
-    // Use the feed scheme so X-Moz-Is-Feed will be set
-    // The value doesn't matter
-    if (/^https?$/.test(feedURI.scheme))
-      href = "feed:" + href;
     this.loadFeed(href, event);
   },
 
   loadFeed(href, event) {
     let feeds = gBrowser.selectedBrowser.feeds;
     try {
       openUILink(href, event, { ignoreAlt: true });
     } finally {
@@ -274,16 +269,23 @@ var FeedHandler = {
       this._feedMenupopup.setAttribute("hidden", "true");
     }
   },
 
   addFeed(link, browserForLink) {
     if (!browserForLink.feeds)
       browserForLink.feeds = [];
 
+    urlSecurityCheck(link.href, gBrowser.contentPrincipal,
+                     Ci.nsIScriptSecurityManager.DISALLOW_INHERIT_PRINCIPAL);
+
+    let feedURI = makeURI(link.href, document.characterSet);
+    if (!/^https?$/.test(feedURI.scheme))
+      return;
+
     browserForLink.feeds.push({ href: link.href, title: link.title });
 
     // If this addition was for the current browser, update the UI. For
     // background browsers, we'll update on tab switch.
     if (browserForLink == gBrowser.selectedBrowser) {
       // Batch updates to avoid updating the UI for multiple onLinkAdded events
       // fired within 100ms of each other.
       if (this._updateFeedTimeout)
--- a/browser/base/content/browser-fullScreenAndPointerLock.js
+++ b/browser/base/content/browser-fullScreenAndPointerLock.js
@@ -38,24 +38,24 @@ var PointerlockFsWarning = {
     }
     get delay() {
       return this._delay;
     }
   },
 
   showPointerLock(aOrigin) {
     if (!document.fullscreen) {
-      let timeout = gPrefService.getIntPref("pointer-lock-api.warning.timeout");
+      let timeout = Services.prefs.getIntPref("pointer-lock-api.warning.timeout");
       this.show(aOrigin, "pointerlock-warning", timeout, 0);
     }
   },
 
   showFullScreen(aOrigin) {
-    let timeout = gPrefService.getIntPref("full-screen-api.warning.timeout");
-    let delay = gPrefService.getIntPref("full-screen-api.warning.delay");
+    let timeout = Services.prefs.getIntPref("full-screen-api.warning.timeout");
+    let delay = Services.prefs.getIntPref("full-screen-api.warning.delay");
     this.show(aOrigin, "fullscreen-warning", timeout, delay);
   },
 
   // Shows a warning that the site has entered fullscreen or
   // pointer lock for a short duration.
   show(aOrigin, elementId, timeout, delay) {
 
     if (!this._element) {
@@ -524,17 +524,17 @@ var FullScreen = {
       FullScreen.showNavToolbox();
     }
   },
 
   // Checks whether we are allowed to collapse the chrome
   _isPopupOpen: false,
   _isChromeCollapsed: false,
   _safeToCollapse() {
-    if (!gPrefService.getBoolPref("browser.fullscreen.autohide"))
+    if (!Services.prefs.getBoolPref("browser.fullscreen.autohide"))
       return false;
 
     // a popup menu is open in chrome: don't collapse chrome
     if (this._isPopupOpen)
       return false;
 
     // On OS X Lion we don't want to hide toolbars.
     if (this.useLionFullScreen)
@@ -568,20 +568,20 @@ var FullScreen = {
   },
 
   get navToolboxHidden() {
     return this._isChromeCollapsed;
   },
 
   // Autohide helpers for the context menu item
   getAutohide(aItem) {
-    aItem.setAttribute("checked", gPrefService.getBoolPref("browser.fullscreen.autohide"));
+    aItem.setAttribute("checked", Services.prefs.getBoolPref("browser.fullscreen.autohide"));
   },
   setAutohide() {
-    gPrefService.setBoolPref("browser.fullscreen.autohide", !gPrefService.getBoolPref("browser.fullscreen.autohide"));
+    Services.prefs.setBoolPref("browser.fullscreen.autohide", !Services.prefs.getBoolPref("browser.fullscreen.autohide"));
     // Try again to hide toolbar when we change the pref.
     FullScreen.hideNavToolbox(true);
   },
 
   showNavToolbox(trackMouse = true) {
     this._fullScrToggler.hidden = true;
     gNavToolbox.removeAttribute("fullscreenShouldAnimate");
     gNavToolbox.style.marginTop = "";
@@ -607,17 +607,17 @@ var FullScreen = {
   },
 
   hideNavToolbox(aAnimate = false) {
     if (this._isChromeCollapsed || !this._safeToCollapse())
       return;
 
     this._fullScrToggler.hidden = false;
 
-    if (aAnimate && gPrefService.getBoolPref("toolkit.cosmeticAnimations.enabled")) {
+    if (aAnimate && Services.prefs.getBoolPref("toolkit.cosmeticAnimations.enabled")) {
       gNavToolbox.setAttribute("fullscreenShouldAnimate", true);
       // Hide the fullscreen toggler until the transition ends.
       let listener = () => {
         gNavToolbox.removeEventListener("transitionend", listener, true);
         if (this._isChromeCollapsed)
           this._fullScrToggler.hidden = false;
       };
       gNavToolbox.addEventListener("transitionend", listener, true);
--- a/browser/base/content/browser-fullZoom.js
+++ b/browser/base/content/browser-fullZoom.js
@@ -26,18 +26,18 @@ var FullZoom = {
 
   // Stores initial locations if we receive onLocationChange
   // events before we're initialized.
   _initialLocations: new WeakMap(),
 
   get siteSpecific() {
     if (this._siteSpecificPref === undefined) {
       this._siteSpecificPref =
-        !gPrefService.getBoolPref("privacy.resistFingerprinting") &&
-        gPrefService.getBoolPref("browser.zoom.siteSpecific");
+        !Services.prefs.getBoolPref("privacy.resistFingerprinting") &&
+        Services.prefs.getBoolPref("browser.zoom.siteSpecific");
     }
     return this._siteSpecificPref;
   },
 
   // nsISupports
 
   QueryInterface: XPCOMUtils.generateQI([Ci.nsIDOMEventListener,
                                          Ci.nsIObserver,
@@ -51,40 +51,40 @@ var FullZoom = {
     gBrowser.addEventListener("ZoomChangeUsingMouseWheel", this);
 
     // Register ourselves with the service so we know when our pref changes.
     this._cps2 = Cc["@mozilla.org/content-pref/service;1"].
                  getService(Ci.nsIContentPrefService2);
     this._cps2.addObserverForName(this.name, this);
 
     this.updateBackgroundTabs =
-      gPrefService.getBoolPref("browser.zoom.updateBackgroundTabs");
+      Services.prefs.getBoolPref("browser.zoom.updateBackgroundTabs");
 
     // Listen for changes to the browser.zoom branch so we can enable/disable
     // updating background tabs and per-site saving and restoring of zoom levels.
-    gPrefService.addObserver("browser.zoom.", this, true);
+    Services.prefs.addObserver("browser.zoom.", this, true);
 
     // Also need to listen to privacy.resistFingerprinting in order to update
     // this._siteSpecificPref.
-    gPrefService.addObserver("privacy.resistFingerprinting", this, true);
+    Services.prefs.addObserver("privacy.resistFingerprinting", this, true);
 
     // If we received onLocationChange events for any of the current browsers
     // before we were initialized we want to replay those upon initialization.
     for (let browser of gBrowser.browsers) {
       if (this._initialLocations.has(browser)) {
         this.onLocationChange(...this._initialLocations.get(browser), browser);
       }
     }
 
     // This should be nulled after initialization.
     this._initialLocations = null;
   },
 
   destroy: function FullZoom_destroy() {
-    gPrefService.removeObserver("browser.zoom.", this);
+    Services.prefs.removeObserver("browser.zoom.", this);
     this._cps2.removeObserverForName(this.name, this);
     gBrowser.removeEventListener("ZoomChangeUsingMouseWheel", this);
   },
 
 
   // Event Handlers
 
   // nsIDOMEventListener
@@ -108,17 +108,17 @@ var FullZoom = {
           case "privacy.resistFingerprinting":
             // fall through
           case "browser.zoom.siteSpecific":
             // Invalidate pref cache.
             this._siteSpecificPref = undefined;
             break;
           case "browser.zoom.updateBackgroundTabs":
             this.updateBackgroundTabs =
-              gPrefService.getBoolPref("browser.zoom.updateBackgroundTabs");
+              Services.prefs.getBoolPref("browser.zoom.updateBackgroundTabs");
             break;
         }
         break;
     }
   },
 
   // nsIContentPrefObserver
 
--- a/browser/base/content/browser-gestureSupport.js
+++ b/browser/base/content/browser-gestureSupport.js
@@ -428,17 +428,17 @@ var gGestureSupport = {
     try {
       // Determine what type of data to load based on default value's type
       let type = typeof aDef;
       let getFunc = "Char";
       if (type == "boolean")
         getFunc = "Bool";
       else if (type == "number")
         getFunc = "Int";
-      return gPrefService["get" + getFunc + "Pref"](branch + aPref);
+      return Services.prefs["get" + getFunc + "Pref"](branch + aPref);
     } catch (e) {
       return aDef;
     }
   },
 
   /**
    * Perform rotation for ImageDocuments
    *
@@ -1009,17 +1009,17 @@ var gHistorySwipeAnimation = {
     }
   },
 
   /**
    * Retrieves the maximum number of snapshots that should be kept in memory.
    * This limit is a global limit and is valid across all open tabs.
    */
   _getMaxSnapshots: function HSA__getMaxSnapshots() {
-    return gPrefService.getIntPref("browser.snapshots.limit");
+    return Services.prefs.getIntPref("browser.snapshots.limit");
   },
 
   /**
    * Adds a snapshot to the list and initiates the compression of said snapshot.
    * Once the compression is completed, it will replace the uncompressed
    * snapshot in the list.
    *
    * @param aCanvas
--- a/browser/base/content/browser-media.js
+++ b/browser/base/content/browser-media.js
@@ -29,21 +29,29 @@ var gEMEHandler = {
       return false;
     }
     if (keySystem == "com.widevine.alpha" &&
         Services.prefs.getPrefType("media.gmp-widevinecdm.visible")) {
       return Services.prefs.getBoolPref("media.gmp-widevinecdm.visible");
     }
     return true;
   },
-  getLearnMoreLink(msgId) {
-    let text = gNavigatorBundle.getString("emeNotifications." + msgId + ".learnMoreLabel");
+  getEMEDisabledFragment(msgId) {
+    let mainMessage = gNavigatorBundle.getString("emeNotifications.drmContentDisabled.message");
+    let text = gNavigatorBundle.getString("emeNotifications.drmContentDisabled.learnMoreLabel");
     let baseURL = Services.urlFormatter.formatURLPref("app.support.baseURL");
-    return "<label class='text-link' href='" + baseURL + "drm-content'>" +
-           text + "</label>";
+    let link = document.createElement("label");
+    link.className = "text-link";
+    link.setAttribute("href", baseURL + "drm-content");
+    link.textContent = text;
+    return BrowserUtils.getLocalizedFragment(document, mainMessage, link);
+  },
+  getMessageWithBrandName(notificationId) {
+    let msgId = "emeNotifications." + notificationId + ".message";
+    return gNavigatorBundle.getFormattedString(msgId, [this._brandShortName]);
   },
   receiveMessage({target: browser, data: data}) {
     let parsedData;
     try {
       parsedData = JSON.parse(data);
     } catch (ex) {
       Cu.reportError("Malformed EME video message with data: " + data);
       return;
@@ -51,91 +59,75 @@ var gEMEHandler = {
     let {status: status, keySystem: keySystem} = parsedData;
     // Don't need to show if disabled or keysystem not visible.
     if (!this.uiEnabled || !this.isKeySystemVisible(keySystem)) {
       return;
     }
 
     let notificationId;
     let buttonCallback;
-    let params = [];
+    // Notification message can be either a string or a DOM fragment.
+    let notificationMessage;
     switch (status) {
       case "available":
       case "cdm-created":
         // Only show the chain icon for proprietary CDMs. Clearkey is not one.
         if (keySystem != "org.w3.clearkey") {
           this.showPopupNotificationForSuccess(browser, keySystem);
         }
         // ... and bail!
         return;
 
       case "api-disabled":
       case "cdm-disabled":
         notificationId = "drmContentDisabled";
         buttonCallback = gEMEHandler.ensureEMEEnabled.bind(gEMEHandler, browser, keySystem);
-        params = [this.getLearnMoreLink(notificationId)];
+        notificationMessage = this.getEMEDisabledFragment();
         break;
 
       case "cdm-insufficient-version":
         notificationId = "drmContentCDMInsufficientVersion";
-        params = [this._brandShortName];
+        notificationMessage = this.getMessageWithBrandName(notificationId);
         break;
 
       case "cdm-not-installed":
         notificationId = "drmContentCDMInstalling";
-        params = [this._brandShortName];
+        notificationMessage = this.getMessageWithBrandName(notificationId);
         break;
 
       case "cdm-not-supported":
         // Not to pop up user-level notification because they cannot do anything
         // about it.
         return;
       default:
         Cu.reportError(new Error("Unknown message ('" + status + "') dealing with EME key request: " + data));
         return;
     }
 
-    this.showNotificationBar(browser, notificationId, keySystem, params, buttonCallback);
-  },
-  showNotificationBar(browser, notificationId, keySystem, labelParams, callback) {
+    // Now actually create the notification
+
     let box = gBrowser.getNotificationBox(browser);
     if (box.getNotificationWithValue(notificationId)) {
       return;
     }
 
-    let msgPrefix = "emeNotifications." + notificationId + ".";
-    let msgId = msgPrefix + "message";
-
-    let message = labelParams.length ?
-                  gNavigatorBundle.getFormattedString(msgId, labelParams) :
-                  gNavigatorBundle.getString(msgId);
-
     let buttons = [];
-    if (callback) {
+    if (buttonCallback) {
+      let msgPrefix = "emeNotifications." + notificationId + ".";
       let btnLabelId = msgPrefix + "button.label";
       let btnAccessKeyId = msgPrefix + "button.accesskey";
       buttons.push({
         label: gNavigatorBundle.getString(btnLabelId),
         accessKey: gNavigatorBundle.getString(btnAccessKeyId),
-        callback
+        callback: buttonCallback,
       });
     }
 
     let iconURL = "chrome://browser/skin/drm-icon.svg";
-
-    // Do a little dance to get rich content into the notification:
-    let fragment = document.createDocumentFragment();
-    let descriptionContainer = document.createElement("description");
-    // eslint-disable-next-line no-unsanitized/property
-    descriptionContainer.innerHTML = message;
-    while (descriptionContainer.childNodes.length) {
-      fragment.appendChild(descriptionContainer.childNodes[0]);
-    }
-
-    box.appendNotification(fragment, notificationId, iconURL, box.PRIORITY_WARNING_MEDIUM,
+    box.appendNotification(notificationMessage, notificationId, iconURL, box.PRIORITY_WARNING_MEDIUM,
                            buttons);
   },
   showPopupNotificationForSuccess(browser, keySystem) {
     // We're playing EME content! Remove any "we can't play because..." messages.
     var box = gBrowser.getNotificationBox(browser);
     ["drmContentDisabled",
      "drmContentCDMInstalling"
      ].forEach(function(value) {
--- a/browser/base/content/browser-places.js
+++ b/browser/base/content/browser-places.js
@@ -6,18 +6,16 @@
 /* eslint-env mozilla/browser-window */
 
 XPCOMUtils.defineLazyScriptGetter(this, ["PlacesToolbar", "PlacesMenu",
                                          "PlacesPanelview", "PlacesPanelMenuView"],
                                   "chrome://browser/content/places/browserPlacesViews.js");
 
 var StarUI = {
   _itemGuids: null,
-  // TODO (bug 1131491): _itemIdsMap is only used for the old transactions manager.
-  _itemIdsMap: null,
   _batching: false,
   _isNewBookmark: false,
   _isComposing: false,
   _autoCloseTimer: 0,
   // The autoclose timer is diasbled if the user interacts with the
   // popup, such as making a change through typing or clicking on
   // the popup.
   _autoCloseTimerEnabled: true,
@@ -91,46 +89,30 @@ var StarUI = {
 
           if (this._anchorToolbarButton) {
             this._anchorToolbarButton.removeAttribute("open");
             this._anchorToolbarButton = null;
           }
           this._restoreCommandsState();
           let removeBookmarksOnPopupHidden = this._removeBookmarksOnPopupHidden;
           this._removeBookmarksOnPopupHidden = false;
-          let idsForRemoval = this._itemIdsMap;
           let guidsForRemoval = this._itemGuids;
           this._itemGuids = null;
-          this._itemIdsMap = null;
 
           if (this._batching) {
             this.endBatch();
           }
 
           if (removeBookmarksOnPopupHidden && guidsForRemoval) {
             if (this._isNewBookmark) {
-              if (!PlacesUIUtils.useAsyncTransactions) {
-                PlacesUtils.transactionManager.undoTransaction();
-                break;
-              }
               PlacesTransactions.undo().catch(Cu.reportError);
               break;
             }
             // Remove all bookmarks for the bookmark's url, this also removes
             // the tags for the url.
-            if (!PlacesUIUtils.useAsyncTransactions) {
-              if (idsForRemoval) {
-                for (let itemId of idsForRemoval.values()) {
-                  let txn = new PlacesRemoveItemTransaction(itemId);
-                  PlacesUtils.transactionManager.doTransaction(txn);
-                }
-              }
-              break;
-            }
-
             PlacesTransactions.Remove(guidsForRemoval)
                               .transact().catch(Cu.reportError);
           } else if (this._isNewBookmark) {
             LibraryUI.triggerLibraryAnimation("bookmark");
           }
         }
         break;
       }
@@ -225,17 +207,16 @@ var StarUI = {
     // Slow double-clicks (not true double-clicks) shouldn't
     // cause the panel to flicker.
     if (this.panel.state == "showing" ||
         this.panel.state == "open") {
       return;
     }
 
     this._isNewBookmark = aIsNewBookmark;
-    this._itemIdsMap = null;
     this._itemGuids = null;
     // TODO (bug 1131491): Deprecate this once async transactions are enabled
     // and the legacy transactions code is gone.
     if (typeof(aNode) == "number") {
       let itemId = aNode;
       let guid = await PlacesUtils.promiseItemGuid(itemId);
       aNode = await PlacesUIUtils.fetchNodeLike(guid);
     }
@@ -286,19 +267,16 @@ var StarUI = {
 
     // The label of the remove button differs if the URI is bookmarked
     // multiple times.
     this._itemGuids = [];
 
     await PlacesUtils.bookmarks.fetch({url: aUrl},
       bookmark => this._itemGuids.push(bookmark.guid));
 
-    if (!PlacesUIUtils.useAsyncTransactions) {
-      this._itemIdsMap = await PlacesUtils.promiseManyItemIds(this._itemGuids);
-    }
     let forms = gNavigatorBundle.getString("editBookmark.removeBookmarks.label");
     let bookmarksCount = this._itemGuids.length;
     let label = PluralForm.get(bookmarksCount, forms)
                           .replace("#1", bookmarksCount);
     this._element("editBookmarkPanelRemoveButton").label = label;
 
     this.beginBatch();
 
@@ -360,37 +338,29 @@ var StarUI = {
   // editBookmarkOverlay so that all of the actions done in the panel
   // are treated by PlacesTransactions as a single batch.  To do so,
   // we start a PlacesTransactions batch when the star UI panel is shown, and
   // we keep the batch ongoing until the panel is hidden.
   _batchBlockingDeferred: null,
   beginBatch() {
     if (this._batching)
       return;
-    if (PlacesUIUtils.useAsyncTransactions) {
-      this._batchBlockingDeferred = PromiseUtils.defer();
-      PlacesTransactions.batch(async () => {
-        await this._batchBlockingDeferred.promise;
-      });
-    } else {
-      PlacesUtils.transactionManager.beginBatch(null);
-    }
+    this._batchBlockingDeferred = PromiseUtils.defer();
+    PlacesTransactions.batch(async () => {
+      await this._batchBlockingDeferred.promise;
+    });
     this._batching = true;
   },
 
   endBatch() {
     if (!this._batching)
       return;
 
-    if (PlacesUIUtils.useAsyncTransactions) {
-      this._batchBlockingDeferred.resolve();
-      this._batchBlockingDeferred = null;
-    } else {
-      PlacesUtils.transactionManager.endBatch(false);
-    }
+    this._batchBlockingDeferred.resolve();
+    this._batchBlockingDeferred = null;
     this._batching = false;
   }
 };
 
 // Checks if an element is visible without flushing layout changes.
 function isVisible(element) {
   let windowUtils = window.QueryInterface(Ci.nsIInterfaceRequestor)
                           .getInterface(Ci.nsIDOMWindowUtils);
@@ -408,85 +378,16 @@ var PlacesCommandHook = {
    *        whether or not to show the edit-bookmark UI for the bookmark item
    * @param [optional] aUrl
    *        Option to provide a URL to bookmark rather than the current page
    * @param [optional] aTitle
    *        Option to provide a title for a bookmark to use rather than the
    *        getting the current page's title
    */
   async bookmarkPage(aBrowser, aShowEditUI, aUrl = null, aTitle = null) {
-    if (PlacesUIUtils.useAsyncTransactions) {
-      await this._bookmarkPagePT(aBrowser, aShowEditUI, aUrl, aTitle);
-      return;
-    }
-
-    // If aUrl is provided, we want to bookmark that url rather than the
-    // the current page
-    var uri = aUrl ? Services.io.newURI(aUrl) : aBrowser.currentURI;
-    var itemId = PlacesUtils.getMostRecentBookmarkForURI(uri);
-    let isNewBookmark = itemId == -1;
-    if (isNewBookmark) {
-      // Bug 1148838 - Make this code work for full page plugins.
-      var title;
-      var description;
-      var charset;
-
-      let docInfo = aUrl ? {} : await this._getPageDetails(aBrowser);
-
-      try {
-        title = aTitle ||
-                (docInfo.isErrorPage ? PlacesUtils.history.getPageTitle(uri)
-                                     : aBrowser.contentTitle) ||
-                uri.displaySpec;
-        description = docInfo.description;
-        charset = aUrl ? null : aBrowser.characterSet;
-      } catch (e) { }
-
-      if (aShowEditUI) {
-        // If we bookmark the page here but open right into a cancelable
-        // state (i.e. new bookmark in Library), start batching here so
-        // all of the actions can be undone in a single undo step.
-        StarUI.beginBatch();
-      }
-
-      var descAnno = { name: PlacesUIUtils.DESCRIPTION_ANNO, value: description };
-      var txn = new PlacesCreateBookmarkTransaction(uri,
-                                                    PlacesUtils.unfiledBookmarksFolderId,
-                                                    PlacesUtils.bookmarks.DEFAULT_INDEX,
-                                                    title, null, [descAnno]);
-      PlacesUtils.transactionManager.doTransaction(txn);
-      itemId = txn.item.id;
-      // Set the character-set.
-      if (charset && !PrivateBrowsingUtils.isBrowserPrivate(aBrowser))
-        PlacesUtils.setCharsetForURI(uri, charset);
-    }
-
-    // Revert the contents of the location bar
-    gURLBar.handleRevert();
-
-    // If it was not requested to open directly in "edit" mode, we are done.
-    if (!aShowEditUI)
-      return;
-
-    let anchor = BookmarkingUI.anchor;
-    if (anchor) {
-      await StarUI.showEditBookmarkPopup(itemId, anchor,
-                                         "bottomcenter topright", isNewBookmark,
-                                         uri);
-      return;
-    }
-
-    // Fall back to showing the panel over the content area.
-    await StarUI.showEditBookmarkPopup(itemId, aBrowser, "overlap",
-                                       isNewBookmark, uri);
-  },
-
-  // TODO: Replace bookmarkPage code with this function once legacy
-  // transactions are removed.
-  async _bookmarkPagePT(aBrowser, aShowEditUI, aUrl, aTitle) {
     // If aUrl is provided, we want to bookmark that url rather than the
     // the current page
     let url = aUrl ? new URL(aUrl) : new URL(aBrowser.currentURI.spec);
     let info = await PlacesUtils.bookmarks.fetch({ url });
     let isNewBookmark = !info;
     if (!info) {
       let parentGuid = PlacesUtils.bookmarks.unfiledGuid;
       info = { url, parentGuid };
--- a/browser/base/content/browser-sets.inc
+++ b/browser/base/content/browser-sets.inc
@@ -160,17 +160,17 @@
 
     <!-- Sync broadcasters -->
     <!-- A broadcaster of a number of attributes suitable for "sync now" UI -
         A 'syncstatus' attribute is set while actively syncing, and the label
         attribute which changes from "sync now" to "syncing" etc. -->
     <broadcaster id="sync-status"/>
     <!-- broadcasters of the "hidden" attribute to reflect setup state for
          menus -->
-    <broadcaster id="sync-setup-state"/>
+    <broadcaster id="sync-setup-state" hidden="true"/>
     <broadcaster id="sync-unverified-state" hidden="true"/>
     <broadcaster id="sync-syncnow-state" hidden="true"/>
     <broadcaster id="sync-reauth-state" hidden="true"/>
     <broadcaster id="viewTabsSidebar" autoCheck="false" sidebartitle="&syncedTabs.sidebar.label;"
                  type="checkbox" group="sidebar"
                  sidebarurl="chrome://browser/content/syncedtabs/sidebar.xhtml"
                  oncommand="SidebarUI.toggle('viewTabsSidebar');"/>
     <broadcaster id="workOfflineMenuitemState"/>
--- a/browser/base/content/browser-sync.js
+++ b/browser/base/content/browser-sync.js
@@ -76,16 +76,32 @@ var gSync = {
       delete this[prop];
       this.__defineGetter__(prop, function() {
         delete this[prop];
         return this[prop] = document.getElementById("appMenu-fxa-" + suffix);
       });
     }
   },
 
+  _definePrefGetters() {
+    XPCOMUtils.defineLazyPreferenceGetter(this, "UNSENDABLE_URL_REGEXP",
+        "services.sync.engine.tabs.filteredUrls", null, null, rx => {
+          try {
+            return new RegExp(rx, "i");
+          } catch (e) {
+            Cu.reportError(`Failed to build url filter regexp for send tab: ${e}`);
+            return null;
+          }
+        });
+    XPCOMUtils.defineLazyPreferenceGetter(this, "FXA_CONNECT_DEVICE_URI",
+        "identity.fxaccounts.remote.connectdevice.uri");
+    XPCOMUtils.defineLazyPreferenceGetter(this, "PRODUCT_INFO_BASE_URL",
+        "app.productInfo.baseURL");
+  },
+
   _maybeUpdateUIState() {
     // Update the UI.
     if (UIState.isReady()) {
       const state = UIState.get();
       // If we are not configured, the UI is already in the right state when
       // we open the window. We can avoid a repaint.
       if (state.status != UIState.STATUS_NOT_CONFIGURED) {
         this.updateAllUI(state);
@@ -98,20 +114,25 @@ var gSync = {
       return;
     }
 
     for (let topic of this._obs) {
       Services.obs.addObserver(this, topic, true);
     }
 
     this._generateNodeGetters();
+    this._definePrefGetters();
 
     // initial label for the sync buttons.
-    let broadcaster = document.getElementById("sync-status");
-    broadcaster.setAttribute("label", this.syncStrings.GetStringFromName("syncnow.label"));
+    let statusBroadcaster = document.getElementById("sync-status");
+    statusBroadcaster.setAttribute("label", this.syncStrings.GetStringFromName("syncnow.label"));
+    // We start with every broadcasters hidden, so that we don't need to init
+    // the sync UI on windows like pageInfo.xul (see bug 1384856).
+    let setupBroadcaster = document.getElementById("sync-setup-state");
+    setupBroadcaster.hidden = false;
 
     this._maybeUpdateUIState();
 
     EnsureFxAccountsWebChannel();
 
     this._initialized = true;
   },
 
@@ -154,16 +175,21 @@ var gSync = {
   updateAllUI(state) {
     this.updatePanelPopup(state);
     this.updateStateBroadcasters(state);
     this.updateSyncButtonsTooltip(state);
     this.updateSyncStatus(state);
   },
 
   updatePanelPopup(state) {
+    // Some windows (e.g. places.xul) won't contain the panel UI, so we can
+    // abort immediately for those (bug 1384856).
+    if (!this.appMenuContainer) {
+      return;
+    }
     let defaultLabel = this.appMenuStatus.getAttribute("defaultlabel");
     // The localization string is for the signed in text, but it's the default text as well
     let defaultTooltiptext = this.appMenuStatus.getAttribute("signedinTooltiptext");
 
     const status = state.status;
     // Reset the status bar to its original state.
     this.appMenuLabel.setAttribute("label", defaultLabel);
     this.appMenuStatus.setAttribute("tooltiptext", defaultTooltiptext);
@@ -272,23 +298,23 @@ var gSync = {
     let url = await fxAccounts.promiseAccountsManageDevicesURI(entryPoint);
     switchToTabHavingURI(url, true, {
       replaceQueryString: true,
       triggeringPrincipal: Services.scriptSecurityManager.getSystemPrincipal(),
     });
   },
 
   openConnectAnotherDevice(entryPoint) {
-    let url = new URL(Services.prefs.getCharPref("identity.fxaccounts.remote.connectdevice.uri"));
+    let url = new URL(this.FXA_CONNECT_DEVICE_URI);
     url.searchParams.append("entrypoint", entryPoint);
     openUILinkIn(url.href, "tab");
   },
 
   openSendToDevicePromo() {
-    let url = Services.prefs.getCharPref("app.productInfo.baseURL");
+    let url = this.PRODUCT_INFO_BASE_URL;
     url += "send-tabs/?utm_source=" + Services.appinfo.name.toLowerCase();
     switchToTabHavingURI(url, true, { replaceQueryString: true });
   },
 
   sendTabToDevice(url, clientId, title) {
     Weave.Service.clientsEngine.sendURIToClientForDisplay(url, clientId, title).catch(e => {
       console.error("Could not send tab to device", e);
     });
@@ -428,28 +454,24 @@ var gSync = {
   isSendableURI(aURISpec) {
     if (!aURISpec) {
       return false;
     }
     // Disallow sending tabs with more than 65535 characters.
     if (aURISpec.length > 65535) {
       return false;
     }
-    try {
-      // Filter out un-sendable URIs -- things like local files, object urls, etc.
-      const unsendableRegexp = new RegExp(
-        Services.prefs.getCharPref("services.sync.engine.tabs.filteredUrls"), "i");
-      return !unsendableRegexp.test(aURISpec);
-    } catch (e) {
-      // The preference has been removed, or is an invalid regexp, so we log an
-      // error and treat it as a valid URI -- and the more problematic case is
-      // the length, which we've already addressed.
-      Cu.reportError(`Failed to build url filter regexp for send tab: ${e}`);
-      return true;
+    if (this.UNSENDABLE_URL_REGEXP) {
+      return !this.UNSENDABLE_URL_REGEXP.test(aURISpec);
     }
+    // The preference has been removed, or is an invalid regexp, so we treat it
+    // as a valid URI. We've already logged an error when trying to construct
+    // the regexp, and the more problematic case is the length, which we've
+    // already addressed.
+    return true;
   },
 
   // "Send Tab to Device" menu item
   updateTabContextMenu(aPopupMenu, aTargetTab) {
     const enabled = !this.syncConfiguredAndLoading &&
                     this.isSendableURI(aTargetTab.linkedBrowser.currentURI.spec);
 
     document.getElementById("context_sendTabToDevice").disabled = !enabled;
--- a/browser/base/content/browser-tabPreviews.xml
+++ b/browser/base/content/browser-tabPreviews.xml
@@ -6,29 +6,27 @@
 # file, You can obtain one at http://mozilla.org/MPL/2.0/.
 
 <bindings id="tabPreviews"
           xmlns="http://www.mozilla.org/xbl"
           xmlns:xul="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"
           xmlns:xbl="http://www.mozilla.org/xbl">
   <binding id="ctrlTab-preview" extends="chrome://global/content/bindings/button.xml#button-base">
     <content pack="center">
-      <xul:stack>
-        <xul:vbox class="ctrlTab-preview-inner" align="center" pack="center"
-                  xbl:inherits="width=canvaswidth">
-          <xul:hbox class="tabPreview-canvas" xbl:inherits="style=canvasstyle">
-            <children/>
-          </xul:hbox>
-          <xul:label xbl:inherits="value=label" crop="end" class="plain"/>
-        </xul:vbox>
+      <xul:vbox class="ctrlTab-preview-inner">
+        <xul:hbox class="ctrlTab-canvas" xbl:inherits="style=canvasstyle,width=canvaswidth">
+          <children/>
+        </xul:hbox>
         <xul:hbox class="ctrlTab-favicon-container" xbl:inherits="hidden=noicon">
           <xul:image class="ctrlTab-favicon" xbl:inherits="src=image"/>
         </xul:hbox>
-      </xul:stack>
+        <xul:label class="ctrlTab-label plain" xbl:inherits="value=label" crop="end"/>
+      </xul:vbox>
     </content>
+
     <handlers>
       <handler event="mouseover" action="ctrlTab._mouseOverFocus(this);"/>
       <handler event="command" action="ctrlTab.pick(this);"/>
       <handler event="click" button="1" action="ctrlTab.remove(this);"/>
 #ifdef XP_MACOSX
 # Control+click is a right click on OS X
       <handler event="click" button="2" action="ctrlTab.pick(this);"/>
 #endif
--- a/browser/base/content/browser-tabsintitlebar.js
+++ b/browser/base/content/browser-tabsintitlebar.js
@@ -263,20 +263,16 @@ var TabsInTitlebar = {
       // Reset the margins and padding that might have been modified:
       titlebarContent.style.marginTop = "";
       titlebarContent.style.marginBottom = "";
       titlebar.style.marginBottom = "";
       menubar.style.paddingBottom = "";
     }
 
     ToolbarIconColor.inferFromText("tabsintitlebar", TabsInTitlebar.enabled);
-
-    if (document.documentElement.hasAttribute("customizing")) {
-      gCustomizeMode.updateLWTStyling();
-    }
   },
 
   _sizePlaceholder(type, width) {
     Array.forEach(document.querySelectorAll(".titlebar-placeholder[type='" + type + "']"),
                   function(node) { node.width = width; });
   },
 
   uninit() {
--- a/browser/base/content/browser-trackingprotection.js
+++ b/browser/base/content/browser-trackingprotection.js
@@ -103,20 +103,20 @@ var TrackingProtection = {
 
     if (isBlocking) {
       this.icon.setAttribute("tooltiptext", this.activeTooltipText);
       this.icon.setAttribute("state", "blocked-tracking-content");
       this.content.setAttribute("state", "blocked-tracking-content");
 
       // Open the tracking protection introduction panel, if applicable.
       if (this.enabledGlobally) {
-        let introCount = gPrefService.getIntPref("privacy.trackingprotection.introCount");
+        let introCount = Services.prefs.getIntPref("privacy.trackingprotection.introCount");
         if (introCount < TrackingProtection.MAX_INTROS) {
-          gPrefService.setIntPref("privacy.trackingprotection.introCount", ++introCount);
-          gPrefService.savePrefFile(null);
+          Services.prefs.setIntPref("privacy.trackingprotection.introCount", ++introCount);
+          Services.prefs.savePrefFile(null);
           this.showIntroPanel();
         }
       }
 
       this.shieldHistogramAdd(2);
     } else if (isAllowing) {
       this.icon.setAttribute("tooltiptext", this.disabledTooltipText);
       this.icon.setAttribute("state", "loaded-tracking-content");
@@ -183,19 +183,19 @@ var TrackingProtection = {
 
     BrowserReload();
   },
 
   dontShowIntroPanelAgain() {
     // This function may be called in private windows, but it does not change
     // any preference unless Tracking Protection is enabled globally.
     if (this.enabledGlobally) {
-      gPrefService.setIntPref("privacy.trackingprotection.introCount",
-                              this.MAX_INTROS);
-      gPrefService.savePrefFile(null);
+      Services.prefs.setIntPref("privacy.trackingprotection.introCount",
+                                this.MAX_INTROS);
+      Services.prefs.savePrefFile(null);
     }
   },
 
   async showIntroPanel() {
     let brandBundle = document.getElementById("bundle_brand");
     let brandShortName = brandBundle.getString("brandShortName");
 
     let openStep2 = () => {
--- a/browser/base/content/browser.css
+++ b/browser/base/content/browser.css
@@ -357,17 +357,17 @@ toolbarpaletteitem {
   }
 
   .webextension-browser-action[cui-areatype="menu-panel"]:-moz-lwtheme-darktext,
   toolbarpaletteitem[place="palette"] > .webextension-browser-action:-moz-lwtheme-darktext {
     list-style-image: var(--webextension-menupanel-image-dark, inherit);
   }
 
   .webextension-menuitem {
-    list-style-image: var(--webextension-menuitem-image, inherit);
+    list-style-image: var(--webextension-menuitem-image, inherit) !important;
   }
 }
 
 @media (min-resolution: 1.1dppx) {
   .webextension-browser-action {
     list-style-image: var(--webextension-toolbar-image-2x, inherit);
   }
 
@@ -389,32 +389,32 @@ toolbarpaletteitem {
   }
 
   .webextension-browser-action[cui-areatype="menu-panel"]:-moz-lwtheme-darktext,
   toolbarpaletteitem[place="palette"] > .webextension-browser-action:-moz-lwtheme-darktext {
     list-style-image: var(--webextension-menupanel-image-2x-dark, inherit);
   }
 
   .webextension-menuitem {
-    list-style-image: var(--webextension-menuitem-image-2x, inherit);
+    list-style-image: var(--webextension-menuitem-image-2x, inherit) !important;
   }
 }
 
 toolbarbutton.webextension-menuitem > .toolbarbutton-icon {
   width: 16px;
   height: 16px;
 }
 
 toolbarpaletteitem[removable="false"] {
   opacity: 0.5;
 }
 
 %ifndef XP_MACOSX
 toolbarpaletteitem[place="palette"],
-toolbarpaletteitem[place="panel"],
+toolbarpaletteitem[place="menu-panel"],
 toolbarpaletteitem[place="toolbar"] {
   -moz-user-focus: normal;
 }
 %endif
 
 #bookmarks-toolbar-placeholder,
 #bookmarks-toolbar-button,
 toolbarpaletteitem > #personal-bookmarks > #PlacesToolbar,
@@ -634,24 +634,16 @@ html|input.urlbar-input[textoverflow]:no
 #PopupAutoComplete > richlistbox > richlistitem[originaltype="insecureWarning"] > .ac-title > label {
   margin-inline-start: 0;
 }
 
 #PopupSearchAutoComplete {
   -moz-binding: url("chrome://browser/content/search/search.xml#browser-search-autocomplete-result-popup");
 }
 
-/* Overlay a badge on top of the icon of additional open search providers
-   in the search panel. */
-.addengine-item > .button-box > .button-icon,
-.addengine-item[type="menu"] > .button-box > .box-inherit > .button-icon {
-  -moz-binding: url("chrome://browser/content/search/search.xml#addengine-icon");
-  display: -moz-stack;
-}
-
 #PopupAutoCompleteRichResult {
   -moz-binding: url("chrome://browser/content/urlbarBindings.xml#urlbar-rich-result-popup");
 }
 
 #PopupAutoCompleteRichResult.showSearchSuggestionsNotification {
   transition: height 100ms;
 }
 
@@ -907,45 +899,16 @@ html|*.pointerlockfswarning-domain-text:
 }
 
 html|*#fullscreen-exit-button {
   pointer-events: auto;
 }
 
 /* ::::: Ctrl-Tab Panel ::::: */
 
-.ctrlTab-preview > html|img,
-.ctrlTab-preview > html|canvas {
-  min-width: inherit;
-  max-width: inherit;
-  min-height: inherit;
-  max-height: inherit;
-}
-
-.ctrlTab-favicon-container {
-  -moz-box-align: start;
-%ifdef XP_MACOSX
-  -moz-box-pack: end;
-%else
-  -moz-box-pack: start;
-%endif
-}
-
-.ctrlTab-favicon {
-  width: 16px;
-  height: 16px;
-}
-
-/* Apply crisp rendering for favicons at exactly 2dppx resolution */
-@media (resolution: 2dppx) {
-  .ctrlTab-favicon {
-    image-rendering: -moz-crisp-edges;
-  }
-}
-
 .ctrlTab-preview {
   -moz-binding: url("chrome://browser/content/browser-tabPreviews.xml#ctrlTab-preview");
 }
 
 
 /* notification anchors should only be visible when their associated
    notifications are */
 .notification-anchor-icon {
--- a/browser/base/content/browser.js
+++ b/browser/base/content/browser.js
@@ -144,20 +144,16 @@ XPCOMUtils.defineLazyGetter(this, "gTabB
 });
 
 XPCOMUtils.defineLazyGetter(this, "gCustomizeMode", function() {
   let scope = {};
   Cu.import("resource:///modules/CustomizeMode.jsm", scope);
   return new scope.CustomizeMode(window);
 });
 
-XPCOMUtils.defineLazyGetter(this, "gPrefService", function() {
-  return Services.prefs;
-});
-
 XPCOMUtils.defineLazyGetter(this, "InlineSpellCheckerUI", function() {
   let tmp = {};
   Cu.import("resource://gre/modules/InlineSpellChecker.jsm", tmp);
   return new tmp.InlineSpellChecker();
 });
 
 XPCOMUtils.defineLazyGetter(this, "PageMenuParent", function() {
   let tmp = {};
@@ -601,17 +597,17 @@ var gPopupBlockerObserver = {
       }
       return;
     }
 
     // Only show the notification again if we've not already shown it. Since
     // notifications are per-browser, we don't need to worry about re-adding
     // it.
     if (!gBrowser.selectedBrowser.blockedPopups.reported) {
-      if (gPrefService.getBoolPref("privacy.popups.showBrowserMessage")) {
+      if (Services.prefs.getBoolPref("privacy.popups.showBrowserMessage")) {
         var brandBundle = document.getElementById("bundle_brand");
         var brandShortName = brandBundle.getString("brandShortName");
         var popupCount = gBrowser.selectedBrowser.blockedPopups.length;
 
         var stringKey = AppConstants.platform == "win"
                         ? "popupWarningButton"
                         : "popupWarningButtonUnix";
 
@@ -694,17 +690,17 @@ var gPopupBlockerObserver = {
     }
 
     if (PrivateBrowsingUtils.isWindowPrivate(window))
       blockedPopupAllowSite.setAttribute("disabled", "true");
     else
       blockedPopupAllowSite.removeAttribute("disabled");
 
     let blockedPopupDontShowMessage = document.getElementById("blockedPopupDontShowMessage");
-    let showMessage = gPrefService.getBoolPref("privacy.popups.showBrowserMessage");
+    let showMessage = Services.prefs.getBoolPref("privacy.popups.showBrowserMessage");
     blockedPopupDontShowMessage.setAttribute("checked", !showMessage);
     blockedPopupDontShowMessage.setAttribute("label", gNavigatorBundle.getString("popupWarningDontShowFromMessage"));
 
     let blockedPopupsSeparator =
         document.getElementById("blockedPopupsSeparator");
     blockedPopupsSeparator.setAttribute("hidden", true);
 
     gBrowser.selectedBrowser.retrieveListOfBlockedPopups().then(blockedPopups => {
@@ -812,18 +808,18 @@ var gPopupBlockerObserver = {
       existingWindow.initWithParams(params);
       existingWindow.focus();
     } else
       window.openDialog("chrome://browser/content/preferences/permissions.xul",
                         "_blank", "resizable,dialog=no,centerscreen", params);
   },
 
   dontShowMessage() {
-    var showMessage = gPrefService.getBoolPref("privacy.popups.showBrowserMessage");
-    gPrefService.setBoolPref("privacy.popups.showBrowserMessage", !showMessage);
+    var showMessage = Services.prefs.getBoolPref("privacy.popups.showBrowserMessage");
+    Services.prefs.setBoolPref("privacy.popups.showBrowserMessage", !showMessage);
     gBrowser.getNotificationBox().removeCurrentNotification();
   }
 };
 
 function gKeywordURIFixup({ target: browser, data: fixupInfo }) {
   let deserializeURI = (spec) => spec ? makeURI(spec) : null;
 
   // We get called irrespective of whether we did a keyword search, or
@@ -1037,22 +1033,22 @@ function _loadURIWithFlags(browser, uri,
     // createFixupURI throws if it can't create a URI. If that's the case then
     // we still need to pass down the uri because docshell handles this case.
     requiredRemoteType = gMultiProcessBrowser ? E10SUtils.DEFAULT_REMOTE_TYPE
                                               : E10SUtils.NOT_REMOTE;
   }
 
   let mustChangeProcess = requiredRemoteType != currentRemoteType;
   let newFrameloader = false;
-  if (browser.getAttribute("isPreloadBrowser") == "true" && uri != "about:newtab") {
+  if (browser.getAttribute("preloadedState") === "consumed" && uri != "about:newtab") {
     // Leaving about:newtab from a used to be preloaded browser should run the process
     // selecting algorithm again.
     mustChangeProcess = true;
     newFrameloader = true;
-    browser.removeAttribute("isPreloadBrowser");
+    browser.removeAttribute("preloadedState");
   }
 
   // !requiredRemoteType means we're loading in the parent/this process.
   if (!requiredRemoteType) {
     browser.inLoadURI = true;
   }
   try {
     if (!mustChangeProcess) {
@@ -1124,18 +1120,18 @@ function _loadURIWithFlags(browser, uri,
 function LoadInOtherProcess(browser, loadOptions, historyIndex = -1) {
   let tab = gBrowser.getTabForBrowser(browser);
   SessionStore.navigateAndRestore(tab, loadOptions, historyIndex);
 }
 
 // Called when a docshell has attempted to load a page in an incorrect process.
 // This function is responsible for loading the page in the correct process.
 function RedirectLoad({ target: browser, data }) {
-  if (browser.getAttribute("isPreloadBrowser") == "true") {
-    browser.removeAttribute("isPreloadBrowser");
+  if (browser.getAttribute("preloadedState") === "consumed") {
+    browser.removeAttribute("preloadedState");
     data.loadOptions.newFrameloader = true;
   }
 
   if (data.loadOptions.reloadInFreshProcess) {
     // Convert the fresh process load option into a large allocation remote type
     // to use common processing from this point.
     data.loadOptions.remoteType = E10SUtils.LARGE_ALLOCATION_REMOTE_TYPE;
     data.loadOptions.newFrameloader = true;
@@ -1212,16 +1208,35 @@ var gBrowserInit = {
       if (linkedBrowser) {
         remoteType = linkedBrowser.remoteType;
         isRemote = remoteType != E10SUtils.NOT_REMOTE;
         sameProcessAsFrameLoader = linkedBrowser.frameLoader;
       }
       initBrowser.removeAttribute("blank");
     }
 
+    // Set a sane starting width/height for all resolutions on new profiles.
+    if (Services.prefs.getBoolPref("privacy.resistFingerprinting")) {
+      // When the fingerprinting resistance is enabled, making sure that we don't
+      // have a maximum window to interfere with generating rounded window dimensions.
+      document.documentElement.setAttribute("sizemode", "normal");
+    } else if (!document.documentElement.hasAttribute("width")) {
+      const TARGET_WIDTH = 1280;
+      const TARGET_HEIGHT = 1040;
+      let width = Math.min(screen.availWidth * .9, TARGET_WIDTH);
+      let height = Math.min(screen.availHeight * .9, TARGET_HEIGHT);
+
+      document.documentElement.setAttribute("width", width);
+      document.documentElement.setAttribute("height", height);
+
+      if (width < TARGET_WIDTH && height < TARGET_HEIGHT) {
+        document.documentElement.setAttribute("sizemode", "maximized");
+      }
+    }
+
     gBrowser.updateBrowserRemoteness(initBrowser, isRemote, {
       remoteType, sameProcessAsFrameLoader
     });
   },
 
   onLoad() {
     gBrowser.addEventListener("DOMUpdatePageReport", gPopupBlockerObserver);
 
@@ -1243,16 +1258,17 @@ var gBrowserInit = {
     TrackingProtection.init();
     CaptivePortalWatcher.init();
     ZoomUI.init(window);
 
     let mm = window.getGroupMessageManager("browsers");
     mm.loadFrameScript("chrome://browser/content/tab-content.js", true);
     mm.loadFrameScript("chrome://browser/content/content.js", true);
     mm.loadFrameScript("chrome://browser/content/content-UITour.js", true);
+    mm.loadFrameScript("chrome://global/content/content-HybridContentTelemetry.js", true);
     mm.loadFrameScript("chrome://global/content/manifestMessages.js", true);
 
     window.messageManager.addMessageListener("Browser:LoadURI", RedirectLoad);
 
     if (!gMultiProcessBrowser) {
       // There is a Content:Click message manually sent from content.
       Services.els.addSystemEventListener(gBrowser, "click", contentAreaClick, true);
     }
@@ -1274,37 +1290,16 @@ var gBrowserInit = {
     Services.obs.notifyObservers(window, "browser-window-before-show");
 
     gUIDensity.init();
 
     if (AppConstants.CAN_DRAW_IN_TITLEBAR) {
       gDragSpaceObserver.init();
     }
 
-    let isResistFingerprintingEnabled = gPrefService.getBoolPref("privacy.resistFingerprinting");
-
-    // Set a sane starting width/height for all resolutions on new profiles.
-    if (isResistFingerprintingEnabled) {
-      // When the fingerprinting resistance is enabled, making sure that we don't
-      // have a maximum window to interfere with generating rounded window dimensions.
-      document.documentElement.setAttribute("sizemode", "normal");
-    } else if (!document.documentElement.hasAttribute("width")) {
-      const TARGET_WIDTH = 1280;
-      const TARGET_HEIGHT = 1040;
-      let width = Math.min(screen.availWidth * .9, TARGET_WIDTH);
-      let height = Math.min(screen.availHeight * .9, TARGET_HEIGHT);
-
-      document.documentElement.setAttribute("width", width);
-      document.documentElement.setAttribute("height", height);
-
-      if (width < TARGET_WIDTH && height < TARGET_HEIGHT) {
-        document.documentElement.setAttribute("sizemode", "maximized");
-      }
-    }
-
     if (!window.toolbar.visible) {
       // adjust browser UI for popups
       gURLBar.setAttribute("readonly", "true");
     }
 
     // Misc. inits.
     TabletModeUpdater.init();
     CombinedStopReload.ensureInitialized();
@@ -1347,16 +1342,18 @@ var gBrowserInit = {
 
     this._setInitialFocus();
 
     // Hack to ensure that the about:home favicon is loaded
     // instantaneously, to avoid flickering and improve perceived performance.
     this._uriToLoadPromise.then(uriToLoad => {
       if (uriToLoad == "about:home") {
         gBrowser.setIcon(gBrowser.selectedTab, "chrome://branding/content/icon32.png");
+      } else if (uriToLoad == "about:privatebrowsing") {
+        gBrowser.setIcon(gBrowser.selectedTab, "chrome://browser/skin/privatebrowsing/favicon.svg");
       }
     });
 
     // Wait until chrome is painted before executing code not critical to making the window visible
     this._boundDelayedStartup = this._delayedStartup.bind(this);
     window.addEventListener("MozAfterPaint", this._boundDelayedStartup);
 
     this._loadHandled = true;
@@ -1440,17 +1437,17 @@ var gBrowserInit = {
     UpdateUrlbarSearchSplitterState();
 
     // Enable/Disable auto-hide tabbar
     gBrowser.tabContainer.updateVisibility();
 
     BookmarkingUI.init();
     AutoShowBookmarksToolbar.init();
 
-    gPrefService.addObserver(gHomeButton.prefDomain, gHomeButton);
+    Services.prefs.addObserver(gHomeButton.prefDomain, gHomeButton);
 
     var homeButton = document.getElementById("home-button");
     gHomeButton.updateTooltip(homeButton);
 
     let safeMode = document.getElementById("helpSafeMode");
     if (Services.appinfo.inSafeMode) {
       safeMode.label = safeMode.getAttribute("stoplabel");
       safeMode.accesskey = safeMode.getAttribute("stopaccesskey");
@@ -1471,17 +1468,17 @@ var gBrowserInit = {
       SetClickAndHoldHandlers();
 
     Cu.import("resource:///modules/UpdateTopLevelContentWindowIDHelper.jsm", {})
       .trackBrowserWindow(window);
 
     PlacesToolbarHelper.init();
 
     ctrlTab.readPref();
-    gPrefService.addObserver(ctrlTab.prefName, ctrlTab);
+    Services.prefs.addObserver(ctrlTab.prefName, ctrlTab);
 
     // The object handling the downloads indicator is initialized here in the
     // delayed startup function, but the actual indicator element is not loaded
     // unless there are downloads to be displayed.
     DownloadsButton.initializeIndicator();
 
     if (AppConstants.platform != "macosx") {
       updateEditUIVisibility();
@@ -1827,17 +1824,17 @@ var gBrowserInit = {
     // Now either cancel delayedStartup, or clean up the services initialized from
     // it.
     if (this._boundDelayedStartup) {
       this._cancelDelayedStartup();
     } else {
       if (Win7Features)
         Win7Features.onCloseWindow();
 
-      gPrefService.removeObserver(ctrlTab.prefName, ctrlTab);
+      Services.prefs.removeObserver(ctrlTab.prefName, ctrlTab);
       ctrlTab.uninit();
       gBrowserThumbnails.uninit();
       FullZoom.destroy();
 
       Services.obs.removeObserver(gIdentityHandler, "perm-changed");
       Services.obs.removeObserver(gRemoteControl, "remote-active");
       Services.obs.removeObserver(gSessionHistoryObserver, "browser:purge-session-history");
       Services.obs.removeObserver(gStoragePressureObserver, "QuotaManager::StoragePressure");
@@ -1847,17 +1844,17 @@ var gBrowserInit = {
       Services.obs.removeObserver(gXPInstallObserver, "addon-install-origin-blocked");
       Services.obs.removeObserver(gXPInstallObserver, "addon-install-failed");
       Services.obs.removeObserver(gXPInstallObserver, "addon-install-confirmation");
       Services.obs.removeObserver(gXPInstallObserver, "addon-install-complete");
       window.messageManager.removeMessageListener("Browser:URIFixup", gKeywordURIFixup);
       window.messageManager.removeMessageListener("Browser:LoadURI", RedirectLoad);
 
       try {
-        gPrefService.removeObserver(gHomeButton.prefDomain, gHomeButton);
+        Services.prefs.removeObserver(gHomeButton.prefDomain, gHomeButton);
       } catch (ex) {
         Cu.reportError(ex);
       }
 
       if (AppConstants.isPlatformAndVersionAtLeast("win", "10")) {
         MenuTouchModeObserver.uninit();
       }
       BrowserOffline.uninit();
@@ -2080,28 +2077,28 @@ function BrowserBack(aEvent) {
     } catch (ex) {
     }
   } else {
     duplicateTabIn(gBrowser.selectedTab, where, -1);
   }
 }
 
 function BrowserHandleBackspace() {
-  switch (gPrefService.getIntPref("browser.backspace_action")) {
+  switch (Services.prefs.getIntPref("browser.backspace_action")) {
   case 0:
     BrowserBack();
     break;
   case 1:
     goDoCommand("cmd_scrollPageUp");
     break;
   }
 }
 
 function BrowserHandleShiftBackspace() {
-  switch (gPrefService.getIntPref("browser.backspace_action")) {
+  switch (Services.prefs.getIntPref("browser.backspace_action")) {
   case 0:
     BrowserForward();
     break;
   case 1:
     goDoCommand("cmd_scrollPageDown");
     break;
   }
 }
@@ -2287,18 +2284,18 @@ function BrowserOpenTab(event) {
   openUILinkIn(BROWSER_NEW_TAB_URL, where, { relatedToCurrent });
 }
 
 var gLastOpenDirectory = {
   _lastDir: null,
   get path() {
     if (!this._lastDir || !this._lastDir.exists()) {
       try {
-        this._lastDir = gPrefService.getComplexValue("browser.open.lastDir",
-                                                     Ci.nsIFile);
+        this._lastDir = Services.prefs.getComplexValue("browser.open.lastDir",
+                                                       Ci.nsIFile);
         if (!this._lastDir.exists())
           this._lastDir = null;
       } catch (e) {}
     }
     return this._lastDir;
   },
   set path(val) {
     try {
@@ -2306,18 +2303,18 @@ var gLastOpenDirectory = {
         return;
     } catch (e) {
       return;
     }
     this._lastDir = val.clone();
 
     // Don't save the last open directory pref inside the Private Browsing mode
     if (!PrivateBrowsingUtils.isWindowPrivate(window))
-      gPrefService.setComplexValue("browser.open.lastDir", Ci.nsIFile,
-                                   this._lastDir);
+      Services.prefs.setComplexValue("browser.open.lastDir", Ci.nsIFile,
+                                     this._lastDir);
   },
   reset() {
     this._lastDir = null;
   }
 };
 
 function BrowserOpenFileWindow() {
   // Get filepicker component.
@@ -2873,25 +2870,23 @@ function UpdatePopupNotificationsVisibil
 
   // Notify PopupNotifications that the visible anchors may have changed. This
   // also checks the suppression state according to the "shouldSuppress"
   // function defined earlier in this file.
   PopupNotifications.anchorVisibilityChange();
 }
 
 function PageProxyClickHandler(aEvent) {
-  if (aEvent.button == 1 && gPrefService.getBoolPref("middlemouse.paste"))
+  if (aEvent.button == 1 && Services.prefs.getBoolPref("middlemouse.paste"))
     middleMousePaste(aEvent);
 }
 
 // Values for telemtery bins: see TLS_ERROR_REPORT_UI in Histograms.json
 const TLS_ERROR_REPORT_TELEMETRY_AUTO_CHECKED   = 2;
 const TLS_ERROR_REPORT_TELEMETRY_AUTO_UNCHECKED = 3;
-const TLS_ERROR_REPORT_TELEMETRY_MANUAL_SEND    = 4;
-const TLS_ERROR_REPORT_TELEMETRY_AUTO_SEND      = 5;
 
 const PREF_SSL_IMPACT_ROOTS = ["security.tls.version.", "security.ssl3."];
 
 /**
  * Handle command events bubbling up from error page content
  * or from about:newtab or from remote error pages that invoke
  * us via async messaging.
  */
@@ -3080,17 +3075,17 @@ var BrowserOnClick = {
     switch (elementId) {
       case "goBackButton":
         if (sendTelemetry) {
           secHistogram.add(nsISecTel[bucketName + "GET_ME_OUT_OF_HERE"]);
         }
         getMeOutOfHere();
         break;
       case "ignore_warning_link":
-        if (gPrefService.getBoolPref("browser.safebrowsing.allowOverride")) {
+        if (Services.prefs.getBoolPref("browser.safebrowsing.allowOverride")) {
           if (sendTelemetry) {
             secHistogram.add(nsISecTel[bucketName + "IGNORE_WARNING"]);
           }
           this.ignoreWarningLink(reason, blockedInfo);
         }
         break;
     }
   },
@@ -3147,34 +3142,17 @@ var BrowserOnClick = {
       // There is no button for reporting errors since Google doesn't currently
       // provide a URL endpoint for these reports.
     } else if (reason === "harmful") {
       title = gNavigatorBundle.getString("safebrowsing.reportedHarmfulSite");
       // There is no button for reporting errors since Google doesn't currently
       // provide a URL endpoint for these reports.
     }
 
-    let notificationBox = gBrowser.getNotificationBox();
-    let value = "blocked-badware-page";
-
-    let previousNotification = notificationBox.getNotificationWithValue(value);
-    if (previousNotification) {
-      notificationBox.removeNotification(previousNotification);
-    }
-
-    let notification = notificationBox.appendNotification(
-      title,
-      value,
-      "chrome://global/skin/icons/blacklist_favicon.png",
-      notificationBox.PRIORITY_CRITICAL_HIGH,
-      buttons
-    );
-    // Persist the notification until the user removes so it
-    // doesn't get removed on redirects.
-    notification.persistence = -1;
+    SafeBrowsingNotificationBox.show(title, buttons);
   },
 };
 
 /**
  * Re-direct the browser to a known-safe page.  This function is
  * used when, for example, the user browses to a known malware page
  * and is presented with about:blocked.  The "Get me out of here!"
  * button should take the user to the default start page so that even
@@ -3512,17 +3490,17 @@ var homeButtonObserver = {
       // disallow setting home pages that inherit the principal
       let links = browserDragAndDrop.dropLinks(aEvent, true);
       if (links.length) {
         setTimeout(openHomeDialog, 0, links.map(link => link.url).join("|"));
       }
     },
 
   onDragOver(aEvent) {
-      if (gPrefService.prefIsLocked("browser.startup.homepage")) {
+      if (Services.prefs.prefIsLocked("browser.startup.homepage")) {
         return;
       }
       browserDragAndDrop.dragOver(aEvent);
       aEvent.dropEffect = "link";
     },
   onDragExit(aEvent) {
     }
 };
@@ -3537,17 +3515,17 @@ function openHomeDialog(aURL) {
   }
 
   var pressedVal  = Services.prompt.confirmEx(window, promptTitle, promptMsg,
                           Services.prompt.STD_YES_NO_BUTTONS,
                           null, null, null, null, {value: 0});
 
   if (pressedVal == 0) {
     try {
-      gPrefService.setStringPref("browser.startup.homepage", aURL);
+      Services.prefs.setStringPref("browser.startup.homepage", aURL);
     } catch (ex) {
       dump("Failed to set the home page.\n" + ex + "\n");
     }
   }
 }
 
 var newTabButtonObserver = {
   onDragOver(aEvent) {
@@ -3841,17 +3819,17 @@ const BrowserSearch = {
     return document.getElementById("searchbar");
   },
 
   get searchEnginesURL() {
     return formatURL("browser.search.searchEnginesURL", true);
   },
 
   loadAddEngines: function BrowserSearch_loadAddEngines() {
-    var newWindowPref = gPrefService.getIntPref("browser.link.open_newwindow");
+    var newWindowPref = Services.prefs.getIntPref("browser.link.open_newwindow");
     var where = newWindowPref == 3 ? "tab" : "window";
     openUILinkIn(this.searchEnginesURL, where);
   },
 
   _getSearchEngineId(engine) {
     if (engine && engine.identifier) {
       return engine.identifier;
     }
@@ -4586,16 +4564,18 @@ var XULBrowserWindow = {
       URLBarSetURI(aLocationURI);
 
       BookmarkingUI.onLocationChange();
 
       gIdentityHandler.onLocationChange();
 
       BrowserPageActions.onLocationChange();
 
+      SafeBrowsingNotificationBox.onLocationChange(aLocationURI);
+
       gTabletModePageCounter.inc();
 
       // Utility functions for disabling find
       var shouldDisableFind = function(aDocument) {
         let docElt = aDocument.documentElement;
         return docElt && docElt.getAttribute("disablefastfind") == "true";
       };
 
@@ -5141,17 +5121,17 @@ nsBrowserAccess.prototype = {
     }
 
     if (aIsExternal && (!aURI || aURI.spec == "about:blank")) {
       win.BrowserOpenTab(); // this also focuses the location bar
       win.focus();
       return win.gBrowser.selectedBrowser;
     }
 
-    let loadInBackground = gPrefService.getBoolPref("browser.tabs.loadDivertedInBackground");
+    let loadInBackground = Services.prefs.getBoolPref("browser.tabs.loadDivertedInBackground");
 
     let tab = win.gBrowser.loadOneTab(aURI ? aURI.spec : "about:blank", {
                                       triggeringPrincipal: aTriggeringPrincipal,
                                       referrerURI: aReferrer,
                                       referrerPolicy: aReferrerPolicy,
                                       userContextId: aUserContextId,
                                       fromExternal: aIsExternal,
                                       inBackground: loadInBackground,
@@ -5203,20 +5183,20 @@ nsBrowserAccess.prototype = {
 
     if (isExternal && aURI && aURI.schemeIs("chrome")) {
       dump("use --chrome command-line option to load external chrome urls\n");
       return null;
     }
 
     if (aWhere == Ci.nsIBrowserDOMWindow.OPEN_DEFAULTWINDOW) {
       if (isExternal &&
-          gPrefService.prefHasUserValue("browser.link.open_newwindow.override.external"))
-        aWhere = gPrefService.getIntPref("browser.link.open_newwindow.override.external");
+          Services.prefs.prefHasUserValue("browser.link.open_newwindow.override.external"))
+        aWhere = Services.prefs.getIntPref("browser.link.open_newwindow.override.external");
       else
-        aWhere = gPrefService.getIntPref("browser.link.open_newwindow");
+        aWhere = Services.prefs.getIntPref("browser.link.open_newwindow");
     }
 
     let referrer = aOpener ? makeURI(aOpener.location.href) : null;
     let referrerPolicy = Ci.nsIHttpChannel.REFERRER_POLICY_UNSET;
     if (aOpener && aOpener.document) {
       referrerPolicy = aOpener.document.referrerPolicy;
     }
     let isPrivate = aOpener
@@ -5263,17 +5243,17 @@ nsBrowserAccess.prototype = {
                             Ci.nsIWebNavigation.LOAD_FLAGS_NONE;
           gBrowser.loadURIWithFlags(aURI.spec, {
                                     aTriggeringPrincipal,
                                     flags: loadflags,
                                     referrerURI: referrer,
                                     referrerPolicy,
                                     });
         }
-        if (!gPrefService.getBoolPref("browser.tabs.loadDivertedInBackground"))
+        if (!Services.prefs.getBoolPref("browser.tabs.loadDivertedInBackground"))
           window.focus();
     }
     return newWindow;
   },
 
   createContentWindowInFrame: function browser_createContentWindowInFrame(
                               aURI, aParams, aWhere, aFlags, aNextTabParentId,
                               aName) {
@@ -5317,40 +5297,37 @@ nsBrowserAccess.prototype = {
     return gBrowser.browsers.some(browser => browser.contentWindow == aWindow);
   },
 
   canClose() {
     return CanCloseWindow();
   },
 };
 
-function getTogglableToolbars() {
-  let toolbarNodes = Array.slice(gNavToolbox.childNodes);
-  toolbarNodes = toolbarNodes.concat(gNavToolbox.externalToolbars);
-  toolbarNodes = toolbarNodes.filter(node => node.getAttribute("toolbarname"));
-  return toolbarNodes;
-}
-
 function onViewToolbarsPopupShowing(aEvent, aInsertPoint) {
   var popup = aEvent.target;
   if (popup != aEvent.currentTarget)
     return;
 
   // Empty the menu
   for (var i = popup.childNodes.length - 1; i >= 0; --i) {
     var deadItem = popup.childNodes[i];
     if (deadItem.hasAttribute("toolbarId"))
       popup.removeChild(deadItem);
   }
 
   var firstMenuItem = aInsertPoint || popup.firstChild;
 
-  let toolbarNodes = getTogglableToolbars();
+  let toolbarNodes = gNavToolbox.childNodes;
 
   for (let toolbar of toolbarNodes) {
+    if (!toolbar.hasAttribute("toolbarname")) {
+      continue;
+    }
+
     let menuItem = document.createElement("menuitem");
     let hidingAttribute = toolbar.getAttribute("type") == "menubar" ?
                           "autohide" : "collapsed";
     menuItem.setAttribute("id", "toggle_" + toolbar.id);
     menuItem.setAttribute("toolbarId", toolbar.id);
     menuItem.setAttribute("type", "checkbox");
     menuItem.setAttribute("label", toolbar.getAttribute("toolbarname"));
     menuItem.setAttribute("checked", toolbar.getAttribute(hidingAttribute) != "true");
@@ -5547,33 +5524,33 @@ function displaySecurityInfo() {
 
 // Adds additional drag space to the window by listening to
 // the corresponding preference.
 var gDragSpaceObserver = {
   pref: "browser.tabs.extraDragSpace",
 
   init() {
     this.update();
-    gPrefService.addObserver(this.pref, this);
+    Services.prefs.addObserver(this.pref, this);
   },
 
   uninit() {
-    gPrefService.removeObserver(this.pref, this);
+    Services.prefs.removeObserver(this.pref, this);
   },
 
   observe(aSubject, aTopic, aPrefName) {
     if (aTopic != "nsPref:changed" || aPrefName != this.pref) {
       return;
     }
 
     this.update();
   },
 
   update() {
-    if (gPrefService.getBoolPref(this.pref)) {
+    if (Services.prefs.getBoolPref(this.pref)) {
       document.documentElement.setAttribute("extradragspace", "true");
     } else {
       document.documentElement.removeAttribute("extradragspace");
     }
     TabsInTitlebar.updateAppearance(true);
   },
 };
 
@@ -5582,47 +5559,47 @@ var gUIDensity = {
   MODE_NORMAL: 0,
   MODE_COMPACT: 1,
   MODE_TOUCH: 2,
   uiDensityPref: "browser.uidensity",
   autoTouchModePref: "browser.touchmode.auto",
 
   init() {
     this.update();
-    gPrefService.addObserver(this.uiDensityPref, this);
-    gPrefService.addObserver(this.autoTouchModePref, this);
+    Services.prefs.addObserver(this.uiDensityPref, this);
+    Services.prefs.addObserver(this.autoTouchModePref, this);
   },
 
   uninit() {
-    gPrefService.removeObserver(this.uiDensityPref, this);
-    gPrefService.removeObserver(this.autoTouchModePref, this);
+    Services.prefs.removeObserver(this.uiDensityPref, this);
+    Services.prefs.removeObserver(this.autoTouchModePref, this);
   },
 
   observe(aSubject, aTopic, aPrefName) {
     if (aTopic != "nsPref:changed" ||
         (aPrefName != this.uiDensityPref &&
          aPrefName != this.autoTouchModePref)) {
       return;
     }
 
     this.update();
   },
 
   getCurrentDensity() {
     // Automatically override the uidensity to touch in Windows tablet mode.
     if (AppConstants.isPlatformAndVersionAtLeast("win", "10") &&
         WindowsUIUtils.inTabletMode &&
-        gPrefService.getBoolPref(this.autoTouchModePref)) {
+        Services.prefs.getBoolPref(this.autoTouchModePref)) {
       return { mode: this.MODE_TOUCH, overridden: true };
     }
-    return { mode: gPrefService.getIntPref(this.uiDensityPref), overridden: false };
+    return { mode: Services.prefs.getIntPref(this.uiDensityPref), overridden: false };
   },
 
   setCurrentMode(mode) {
-    gPrefService.setIntPref(this.uiDensityPref, mode);
+    Services.prefs.setIntPref(this.uiDensityPref, mode);
   },
 
   update(mode) {
     if (mode == null) {
       mode = this.getCurrentDensity().mode;
     }
 
     let docs = [
@@ -5675,18 +5652,18 @@ var gHomeButton = {
       else
         homeButton.setAttribute("tooltiptext", homePage);
     }
   },
 
   getHomePage() {
     var url;
     try {
-      url = gPrefService.getComplexValue(this.prefDomain,
-                                Components.interfaces.nsIPrefLocalizedString).data;
+      url = Services.prefs.getComplexValue(this.prefDomain,
+                                  Components.interfaces.nsIPrefLocalizedString).data;
     } catch (e) {
     }
 
     // use this if we can't find the pref
     if (!url) {
       var configBundle = Services.strings
                                  .createBundle("chrome://branding/locale/browserconfig.properties");
       url = configBundle.GetStringFromName(this.prefDomain);
@@ -5862,18 +5839,18 @@ function hrefAndLinkNodeForClickEvent(ev
 function contentAreaClick(event, isPanelClick) {
   if (!event.isTrusted || event.defaultPrevented || event.button == 2)
     return;
 
   let [href, linkNode] = hrefAndLinkNodeForClickEvent(event);
   if (!href) {
     // Not a link, handle middle mouse navigation.
     if (event.button == 1 &&
-        gPrefService.getBoolPref("middlemouse.contentLoadURL") &&
-        !gPrefService.getBoolPref("general.autoScroll")) {
+        Services.prefs.getBoolPref("middlemouse.contentLoadURL") &&
+        !Services.prefs.getBoolPref("general.autoScroll")) {
       middleMousePaste(event);
       event.preventDefault();
     }
     return;
   }
 
   // This code only applies if we have a linkNode (i.e. clicks on real anchor
   // elements, as opposed to XLink).
@@ -6051,24 +6028,28 @@ function middleMousePaste(event) {
   });
 
   event.stopPropagation();
 }
 
 function stripUnsafeProtocolOnPaste(pasteData) {
   // Don't allow pasting javascript URIs since we don't support
   // LOAD_FLAGS_DISALLOW_INHERIT_PRINCIPAL for those.
-  let changed = false;
-  let pasteDataNoJS = pasteData.replace(/\r?\n/g, "")
-                               .replace(/^(?:\W*javascript:)+/i,
-                                        () => {
-                                                changed = true;
-                                                return "";
-                                              });
-  return changed ? pasteDataNoJS : pasteData;
+  while (true) {
+    let scheme = "";
+    try {
+      scheme = Services.io.extractScheme(pasteData);
+    } catch (ex) { }
+    if (scheme != "javascript") {
+      break;
+    }
+
+    pasteData = pasteData.substring(pasteData.indexOf(":") + 1);
+  }
+  return pasteData;
 }
 
 // handleDroppedLink has the following 2 overloads:
 //   handleDroppedLink(event, url, name, triggeringPrincipal)
 //   handleDroppedLink(event, links, triggeringPrincipal)
 function handleDroppedLink(event, urlOrLinks, nameOrTriggeringPrincipal, triggeringPrincipal) {
   let links;
   if (Array.isArray(urlOrLinks)) {
@@ -6336,17 +6317,17 @@ var BrowserOffline = {
     } catch (ex) {
     }
 
     return true;
   },
 
   _uiElement: null,
   _updateOfflineUI(aOffline) {
-    var offlineLocked = gPrefService.prefIsLocked("network.online");
+    var offlineLocked = Services.prefs.prefIsLocked("network.online");
     if (offlineLocked)
       this._uiElement.setAttribute("disabled", "true");
 
     this._uiElement.setAttribute("checked", aOffline);
   }
 };
 
 var OfflineApps = {
@@ -6605,20 +6586,26 @@ var CanvasPermissionPromptHelper = {
     }
 
     let uri = Services.io.newURI(aData);
     if (gBrowser.selectedBrowser !== browser) {
       // Must belong to some other window.
       return;
     }
 
-    let message = gNavigatorBundle.getFormattedString("canvas.siteprompt", [ uri.asciiHost ]);
+    let message = {};
+    let header = gNavigatorBundle.getFormattedString("canvas.siteprompt", ["<>"], 1);
+
+    header = header.split("<>");
+    message.start = header[0];
+    message.host = uri.asciiHost;
+    message.end = header[1];
 
     function setCanvasPermission(aURI, aPerm, aPersistent) {
-      Services.perms.add(aURI, "canvas/extractData", aPerm,
+      Services.perms.add(aURI, "canvas", aPerm,
                           aPersistent ? Ci.nsIPermissionManager.EXPIRE_NEVER
                                       : Ci.nsIPermissionManager.EXPIRE_SESSION);
     }
 
     let mainAction = {
       label: gNavigatorBundle.getString("canvas.allow"),
       accessKey: gNavigatorBundle.getString("canvas.allow.accesskey"),
       callback(state) {
@@ -7478,21 +7465,21 @@ var gIdentityHandler = {
         tooltip = gNavigatorBundle.getFormattedString("identity.identified.verifier",
                                                       [iData.caOrg]);
         icon_label = iData.subjectOrg;
         if (iData.country)
           icon_country_label = "(" + iData.country + ")";
 
         // If the organization name starts with an RTL character, then
         // swap the positions of the organization and country code labels.
-        // The Unicode ranges reflect the definition of the UCS2_CHAR_IS_BIDI
+        // The Unicode ranges reflect the definition of the UTF16_CODE_UNIT_IS_BIDI
         // macro in intl/unicharutil/util/nsBidiUtils.h. When bug 218823 gets
         // fixed, this test should be replaced by one adhering to the
         // Unicode Bidirectional Algorithm proper (at the paragraph level).
-        icon_labels_dir = /^[\u0590-\u08ff\ufb1d-\ufdff\ufe70-\ufefc]/.test(icon_label) ?
+        icon_labels_dir = /^[\u0590-\u08ff\ufb1d-\ufdff\ufe70-\ufefc\ud802\ud803\ud83a\ud83b]/.test(icon_label) ?
                           "rtl" : "ltr";
       }
     } else if (this._pageExtensionPolicy) {
       this._identityBox.className = "extensionPage";
       let extensionName = this._pageExtensionPolicy.name;
       icon_label = gNavigatorBundle.getFormattedString(
         "identity.extension.label", [extensionName]);
     } else if (this._uriHasHost && this._isSecure) {
@@ -7525,18 +7512,25 @@ var gIdentityHandler = {
         } else {
           this._identityBox.classList.add("weakCipher");
         }
       } else {
         let warnOnInsecure = Services.prefs.getBoolPref("security.insecure_connection_icon.enabled") ||
                              (Services.prefs.getBoolPref("security.insecure_connection_icon.pbmode.enabled") &&
                              PrivateBrowsingUtils.isWindowPrivate(window));
         let className = warnOnInsecure ? "notSecure" : "unknownIdentity";
-
         this._identityBox.className = className;
+
+        let warnTextOnInsecure = Services.prefs.getBoolPref("security.insecure_connection_text.enabled") ||
+                                 (Services.prefs.getBoolPref("security.insecure_connection_text.pbmode.enabled") &&
+                                 PrivateBrowsingUtils.isWindowPrivate(window));
+        if (warnTextOnInsecure) {
+          icon_label = gNavigatorBundle.getString("identity.notSecure.label");
+          this._identityBox.classList.add("notSecureText");
+        }
       }
       if (this._hasInsecureLoginForms) {
         // Insecure login forms can only be present on "unknown identity"
         // pages, either already insecure or with mixed active content loaded.
         this._identityBox.classList.add("insecureLoginForms");
       }
     }
 
@@ -8162,17 +8156,17 @@ function getTabModalPromptBox(aWindow) {
 /* DEPRECATED */
 function getBrowser() {
   return gBrowser;
 }
 
 const gAccessibilityServiceIndicator = {
   init() {
     // Pref to enable accessibility service indicator.
-    gPrefService.addObserver("accessibility.indicator.enabled", this);
+    Services.prefs.addObserver("accessibility.indicator.enabled", this);
     // Accessibility service init/shutdown event.
     Services.obs.addObserver(this, "a11y-init-or-shutdown");
     this.update(Services.appinfo.accessibilityEnabled);
   },
 
   update(accessibilityEnabled = false) {
     if (this.enabled && accessibilityEnabled) {
       this._active = true;
@@ -8197,31 +8191,31 @@ const gAccessibilityServiceIndicator = {
     } else if (topic === "a11y-init-or-shutdown") {
       // When "a11y-init-or-shutdown" event is fired, "1" indicates that
       // accessibility service is started and "0" that it is shut down.
       this.update(data === "1");
     }
   },
 
   get enabled() {
-    return gPrefService.getBoolPref("accessibility.indicator.enabled");
+    return Services.prefs.getBoolPref("accessibility.indicator.enabled");
   },
 
   handleEvent({ key, type }) {
     if ((type === "keypress" && [" ", "Enter"].includes(key)) ||
          type === "click") {
       let a11yServicesSupportURL =
         Services.urlFormatter.formatURLPref("accessibility.support.url");
       gBrowser.selectedTab = gBrowser.addTab(a11yServicesSupportURL);
       Services.telemetry.scalarSet("a11y.indicator_acted_on", true);
     }
   },
 
   uninit() {
-    gPrefService.removeObserver("accessibility.indicator.enabled", this);
+    Services.prefs.removeObserver("accessibility.indicator.enabled", this);
     Services.obs.removeObserver(this, "a11y-init-or-shutdown");
     this.update();
   }
 };
 
 var gPrivateBrowsingUI = {
   init: function PBUI_init() {
     // Do nothing for normal windows
@@ -8543,27 +8537,26 @@ var TabContextMenu = {
     document.getElementById("context_undoCloseTab").disabled =
       SessionStore.getClosedTabCount(window) == 0;
 
     // Only one of pin/unpin should be visible
     document.getElementById("context_pinTab").hidden = this.contextTab.pinned;
     document.getElementById("context_unpinTab").hidden = !this.contextTab.pinned;
 
     // Disable "Close Tabs to the Right" if there are no tabs
-    // following it and hide it when the user rightclicked on a pinned
-    // tab.
+    // following it.
     document.getElementById("context_closeTabsToTheEnd").disabled =
       gBrowser.getTabsToTheEndFrom(this.contextTab).length == 0;
-    document.getElementById("context_closeTabsToTheEnd").hidden = this.contextTab.pinned;
-
-    // Disable "Close other Tabs" if there is only one unpinned tab and
-    // hide it when the user rightclicked on a pinned tab.
-    let unpinnedTabs = gBrowser.visibleTabs.length - gBrowser._numPinnedTabs;
-    document.getElementById("context_closeOtherTabs").disabled = unpinnedTabs <= 1;
-    document.getElementById("context_closeOtherTabs").hidden = this.contextTab.pinned;
+
+    // Disable "Close other Tabs" if there are no unpinned tabs.
+    let unpinnedTabsToClose = gBrowser.visibleTabs.length - gBrowser._numPinnedTabs;
+    if (!this.contextTab.pinned) {
+      unpinnedTabsToClose--;
+    }
+    document.getElementById("context_closeOtherTabs").disabled = unpinnedTabsToClose < 1;
 
     // Hide "Bookmark All Tabs" for a pinned tab.  Update its state if visible.
     let bookmarkAllTabs = document.getElementById("context_bookmarkAllTabs");
     bookmarkAllTabs.hidden = this.contextTab.pinned;
     if (!bookmarkAllTabs.hidden)
       PlacesCommandHook.updateBookmarkAllTabsCommand();
 
     // Adjust the state of the toggle mute menu item.
@@ -8906,16 +8899,63 @@ var AboutPrivateBrowsingListener = {
     window.messageManager.addMessageListener(
       "AboutPrivateBrowsing:DontShowIntroPanelAgain",
       msg => {
         TrackingProtection.dontShowIntroPanelAgain();
     });
   }
 };
 
+const SafeBrowsingNotificationBox = {
+  _currentURIBaseDomain: null,
+  show(title, buttons) {
+    let uri = gBrowser.currentURI;
+
+    // start tracking host so that we know when we leave the domain
+    this._currentURIBaseDomain = Services.eTLD.getBaseDomain(uri);
+
+    let notificationBox = gBrowser.getNotificationBox();
+    let value = "blocked-badware-page";
+
+    let previousNotification = notificationBox.getNotificationWithValue(value);
+    if (previousNotification) {
+      notificationBox.removeNotification(previousNotification);
+    }
+
+    let notification = notificationBox.appendNotification(
+      title,
+      value,
+      "chrome://global/skin/icons/blacklist_favicon.png",
+      notificationBox.PRIORITY_CRITICAL_HIGH,
+      buttons
+    );
+    // Persist the notification until the user removes so it
+    // doesn't get removed on redirects.
+    notification.persistence = -1;
+  },
+  onLocationChange(aLocationURI) {
+    // take this to represent that you haven't visited a bad place
+    if (!this._currentURIBaseDomain) {
+      return;
+    }
+
+    let newURIBaseDomain = Services.eTLD.getBaseDomain(aLocationURI);
+
+    if (newURIBaseDomain !== this._currentURIBaseDomain) {
+      let notificationBox = gBrowser.getNotificationBox();
+      let notification = notificationBox.getNotificationWithValue("blocked-badware-page");
+      if (notification) {
+        notificationBox.removeNotification(notification, false);
+      }
+
+      this._currentURIBaseDomain = null;
+    }
+  }
+};
+
 function TabModalPromptBox(browser) {
   this._weakBrowserRef = Cu.getWeakReference(browser);
 }
 
 TabModalPromptBox.prototype = {
   _promptCloseCallback(onCloseCallback, principalToAllowFocusFor, allowFocusCheckbox, ...args) {
     if (principalToAllowFocusFor && allowFocusCheckbox &&
         allowFocusCheckbox.checked) {
--- a/browser/base/content/browser.xul
+++ b/browser/base/content/browser.xul
@@ -291,18 +291,18 @@
       <toolbarbutton id="sidebar-switcher-tabs"
                      label="&syncedTabs.sidebar.label;"
                      class="subviewbutton subviewbutton-iconic"
                      observes="viewTabsSidebar"
                      oncommand="SidebarUI.show('viewTabsSidebar');">
         <observes element="viewTabsSidebar" attribute="checked"/>
       </toolbarbutton>
       <toolbarseparator/>
-      <vbox id="sidebar-extensions"></vbox>
-      <toolbarseparator/>
+      <!-- Extension toolbarbuttons go here. -->
+      <toolbarseparator id="sidebar-extensions-separator"/>
       <toolbarbutton id="sidebar-reverse-position"
                      class="subviewbutton"
                      oncommand="SidebarUI.reversePosition()"/>
       <toolbarseparator/>
       <toolbarbutton label="&sidebarMenuClose.label;"
                      class="subviewbutton"
                      oncommand="SidebarUI.hide()"/>
     </panel>
@@ -591,23 +591,20 @@
       <hbox class="private-browsing-indicator"/>
       <hbox id="titlebar-fullscreen-button"/>
     </hbox>
 #endif
   </hbox>
 </vbox>
 #endif
 
-<deck flex="1" id="tab-view-deck">
-<vbox flex="1" id="browser-panel">
-
-  <toolbox id="navigator-toolbox" mode="icons">
+  <toolbox id="navigator-toolbox">
     <!-- Menu -->
     <toolbar type="menubar" id="toolbar-menubar" class="chromeclass-menubar" customizable="true"
-             mode="icons" iconsize="small"
+             mode="icons"
 #ifdef MENUBAR_CAN_AUTOHIDE
              toolbarname="&menubarCmd.label;"
              accesskey="&menubarCmd.accesskey;"
              autohide="true"
 #endif
              context="toolbar-context-menu">
       <toolbaritem id="menubar-items" align="center">
 # The entire main menubar is placed into browser-menubar.inc, so that it can be shared by
@@ -623,17 +620,16 @@
 #endif
 #endif
     </toolbar>
 
     <toolbar id="TabsToolbar"
              fullscreentoolbar="true"
              customizable="true"
              mode="icons"
-             iconsize="small"
              aria-label="&tabsToolbar.label;"
              context="toolbar-context-menu"
              collapsed="true">
 
 #ifdef CAN_DRAW_IN_TITLEBAR
       <hbox class="titlebar-placeholder" type="pre-tabs"
             skipintoolbarset="true"/>
 #endif
@@ -706,17 +702,16 @@
             skipintoolbarset="true"/>
 #endif
 #endif
     </toolbar>
 
     <toolbar id="nav-bar"
              aria-label="&navbarCmd.label;"
              fullscreentoolbar="true" mode="icons" customizable="true"
-             iconsize="small"
              customizationtarget="nav-bar-customization-target"
              overflowable="true"
              overflowbutton="nav-bar-overflow-button"
              overflowtarget="widget-overflow-list"
              overflowpanel="widget-overflow"
              context="toolbar-context-menu">
 
       <hbox id="nav-bar-customization-target" flex="1">
@@ -810,16 +805,18 @@
                   <image data-permission-id="microphone" class="blocked-permission-icon microphone-icon" role="button"
                          tooltiptext="&urlbar.microphoneBlocked.tooltip;"/>
                   <image data-permission-id="screen" class="blocked-permission-icon screen-icon" role="button"
                          tooltiptext="&urlbar.screenBlocked.tooltip;"/>
                   <image data-permission-id="persistent-storage" class="blocked-permission-icon persistent-storage-icon" role="button"
                          tooltiptext="&urlbar.persistentStorageBlocked.tooltip;"/>
                   <image data-permission-id="popup" class="blocked-permission-icon popup-icon" role="button"
                          tooltiptext="&urlbar.popupBlocked.tooltip;"/>
+                  <image data-permission-id="canvas" class="blocked-permission-icon canvas-icon" role="button"
+                         tooltiptext="&urlbar.canvasBlocked.tooltip;"/>
                 </box>
                 <box id="notification-popup-box"
                      hidden="true"
                      onmouseover="document.getElementById('identity-box').classList.add('no-hover');"
                      onmouseout="document.getElementById('identity-box').classList.remove('no-hover');"
                      align="center">
                   <image id="default-notification-icon" class="notification-anchor-icon" role="button"
                          tooltiptext="&urlbar.defaultNotificationAnchor.tooltip;"/>
@@ -971,20 +968,18 @@
                        oncommand="BrowserFullScreen();"/>
 
         <toolbarbutton id="close-button"
                        tooltiptext="&fullScreenClose.tooltip;"
                        oncommand="BrowserTryToCloseWindow();"/>
       </hbox>
     </toolbar>
 
-    <toolbarset id="customToolbars" context="toolbar-context-menu"/>
-
     <toolbar id="PersonalToolbar"
-             mode="icons" iconsize="small"
+             mode="icons"
              class="chromeclass-directories"
              context="toolbar-context-menu"
              toolbarname="&personalbarCmd.label;" accesskey="&personalbarCmd.accesskey;"
              collapsed="true"
              customizable="true">
       <toolbaritem id="personal-bookmarks"
                    title="&bookmarksToolbarItem.label;"
                    cui-areatype="toolbar"
@@ -1235,15 +1230,9 @@
       &pointerlockWarning.generic.label;
     </html:div>
   </html:div>
 
   <vbox id="browser-bottombox" layer="true">
     <notificationbox id="global-notificationbox" notificationside="bottom"/>
   </vbox>
 
-</vbox>
-# <iframe id="tab-view"> is dynamically appended as the 2nd child of #tab-view-deck.
-#     Introducing the iframe dynamically, as needed, was found to be better than
-#     starting with an empty iframe here in browser.xul from a Ts standpoint.
-</deck>
-
 </window>
--- a/browser/base/content/content.js
+++ b/browser/base/content/content.js
@@ -62,22 +62,16 @@ addEventListener("pageshow", function(ev
 });
 addEventListener("DOMAutoComplete", function(event) {
   LoginManagerContent.onUsernameInput(event);
 });
 addEventListener("blur", function(event) {
   LoginManagerContent.onUsernameInput(event);
 });
 
-// Values for telemtery bins: see TLS_ERROR_REPORT_UI in Histograms.json
-const TLS_ERROR_REPORT_TELEMETRY_UI_SHOWN = 0;
-const TLS_ERROR_REPORT_TELEMETRY_EXPANDED = 1;
-const TLS_ERROR_REPORT_TELEMETRY_SUCCESS  = 6;
-const TLS_ERROR_REPORT_TELEMETRY_FAILURE  = 7;
-
 const SEC_ERROR_BASE          = Ci.nsINSSErrorsService.NSS_SEC_ERROR_BASE;
 const MOZILLA_PKIX_ERROR_BASE = Ci.nsINSSErrorsService.MOZILLA_PKIX_ERROR_BASE;
 
 const SEC_ERROR_EXPIRED_CERTIFICATE                = SEC_ERROR_BASE + 11;
 const SEC_ERROR_UNKNOWN_ISSUER                     = SEC_ERROR_BASE + 13;
 const SEC_ERROR_EXPIRED_ISSUER_CERTIFICATE         = SEC_ERROR_BASE + 30;
 const SEC_ERROR_OCSP_FUTURE_RESPONSE               = SEC_ERROR_BASE + 131;
 const SEC_ERROR_OCSP_OLD_RESPONSE                  = SEC_ERROR_BASE + 132;
@@ -309,17 +303,17 @@ var AboutNetAndCertErrorListener = {
         let now = Date.now();
         let certRange = this._getCertValidityRange();
 
         let approximateDate = now - difference * 1000;
         // If the difference is more than a day, we last fetched the date in the last 5 days,
         // and adjusting the date per the interval would make the cert valid, warn the user:
         if (Math.abs(difference) > 60 * 60 * 24 && (now - lastFetched) <= 60 * 60 * 24 * 5 &&
             certRange.notBefore < approximateDate && certRange.notAfter > approximateDate) {
-          let formatter = Services.intl.createDateTimeFormat(undefined, {
+          let formatter = new Services.intl.DateTimeFormat(undefined, {
             dateStyle: "short"
           });
           let systemDate = formatter.format(new Date());
           // negative difference means local time is behind server time
           approximateDate = formatter.format(new Date(approximateDate));
 
           content.document.getElementById("wrongSystemTime_URL")
             .textContent = content.document.location.hostname;
@@ -345,17 +339,17 @@ var AboutNetAndCertErrorListener = {
           let buildDate = new Date(year, month, day);
           let systemDate = new Date();
 
           // We don't check the notBefore of the cert with the build date,
           // as it is of course almost certain that it is now later than the build date,
           // so we shouldn't exclude the possibility that the cert has become valid
           // since the build date.
           if (buildDate > systemDate && new Date(certRange.notAfter) > buildDate) {
-            let formatter = Services.intl.createDateTimeFormat(undefined, {
+            let formatter = new Services.intl.DateTimeFormat(undefined, {
               dateStyle: "short"
             });
 
             content.document.getElementById("wrongSystemTimeWithoutReference_URL")
               .textContent = content.document.location.hostname;
             content.document.getElementById("wrongSystemTimeWithoutReference_systemDate")
               .textContent = formatter.format(systemDate);
 
@@ -404,16 +398,19 @@ var AboutNetAndCertErrorListener = {
         return true;
       }
     }
 
     return false;
   },
 
   onPageLoad(evt) {
+    // Values for telemtery bins: see TLS_ERROR_REPORT_UI in Histograms.json
+    const TLS_ERROR_REPORT_TELEMETRY_UI_SHOWN = 0;
+
     if (this.isAboutCertError) {
       let originalTarget = evt.originalTarget;
       let ownerDoc = originalTarget.ownerDocument;
       ClickEventHandler.onCertError(originalTarget, ownerDoc);
     }
 
     let automatic = Services.prefs.getBoolPref("security.ssl.errorReporting.automatic");
     content.dispatchEvent(new content.CustomEvent("AboutNetErrorOptions", {
--- a/browser/base/content/newtab/page.js
+++ b/browser/base/content/newtab/page.js
@@ -175,21 +175,16 @@ var gPage = {
     }
   },
 
   /**
    * Handles unload event
    */
   _handleUnloadEvent: function Page_handleUnloadEvent() {
     gAllPages.unregister(this);
-    // compute page life-span and send telemetry probe: using milli-seconds will leave
-    // many low buckets empty. Instead we use half-second precision to make low end
-    // of histogram linear and not lose the change in user attention
-    let delta = Math.round((Date.now() - this._firstVisibleTime) / 500);
-    Services.telemetry.getHistogramById("NEWTAB_PAGE_LIFE_SPAN").add(delta);
   },
 
   /**
    * Handles all page events.
    */
   handleEvent: function Page_handleEvent(aEvent) {
     switch (aEvent.type) {
       case "load":
@@ -228,28 +223,22 @@ var gPage = {
 
         setTimeout(() => this.onPageFirstVisible());
         removeEventListener("visibilitychange", this);
         break;
     }
   },
 
   onPageFirstVisible: function () {
-    // Record another page impression.
-    Services.telemetry.getHistogramById("NEWTAB_PAGE_SHOWN").add(true);
-
     for (let site of gGrid.sites) {
       if (site) {
         site.captureIfMissing();
       }
     }
 
-    // save timestamp to compute page life-span delta
-    this._firstVisibleTime = Date.now();
-
     if (document.readyState == "complete") {
       this.onPageVisibleAndLoaded();
     } else {
       addEventListener("load", this);
     }
   },
 
   onPageVisibleAndLoaded() {
--- a/browser/base/content/newtab/sites.js
+++ b/browser/base/content/newtab/sites.js
@@ -238,48 +238,26 @@ Site.prototype = {
       let originAttributes = document.docShell.getOriginAttributes();
       let principal = Services.scriptSecurityManager
                               .createCodebasePrincipal(uri, originAttributes);
       sc.speculativeConnect2(uri, principal, null);
     } catch (e) {}
   },
 
   /**
-   * Record interaction with site using telemetry.
-   */
-  _recordSiteClicked: function Site_recordSiteClicked(aIndex) {
-    if (Services.prefs.prefHasUserValue("browser.newtabpage.rows") ||
-        Services.prefs.prefHasUserValue("browser.newtabpage.columns") ||
-        aIndex > 8) {
-      // We only want to get indices for the default configuration, everything
-      // else goes in the same bucket.
-      aIndex = 9;
-    }
-    Services.telemetry.getHistogramById("NEWTAB_PAGE_SITE_CLICKED")
-                      .add(aIndex);
-  },
-
-  /**
    * Handles site click events.
    */
   onClick: function Site_onClick(aEvent) {
     let pinned = this.isPinned();
-    let tileIndex = this.cell.index;
     let {button, target} = aEvent;
+    const isLinkClick = target.classList.contains("newtab-link") ||
+      target.parentElement.classList.contains("newtab-link");
 
-    // Handle tile/thumbnail link click
-    if (target.classList.contains("newtab-link") ||
-        target.parentElement.classList.contains("newtab-link")) {
-      // Record for primary and middle clicks
-      if (button == 0 || button == 1) {
-        this._recordSiteClicked(tileIndex);
-      }
-    }
-    // Only handle primary clicks for the remaining targets
-    else if (button == 0) {
+    // Handle primary click for pin and block
+    if (button == 0 && !isLinkClick) {
       aEvent.preventDefault();
       if (target.classList.contains("newtab-control-block")) {
         this.block();
       }
       else if (pinned && target.classList.contains("newtab-control-pin")) {
         this.unpin();
       }
       else if (!pinned && target.classList.contains("newtab-control-pin")) {
--- a/browser/base/content/nsContextMenu.js
+++ b/browser/base/content/nsContextMenu.js
@@ -128,18 +128,18 @@ nsContextMenu.prototype = {
       };
       subject.wrappedJSObject = subject;
       Services.obs.notifyObservers(subject, "on-build-contextmenu");
     }
 
     this.isFrameImage = document.getElementById("isFrameImage");
     this.ellipsis = "\u2026";
     try {
-      this.ellipsis = gPrefService.getComplexValue("intl.ellipsis",
-                                                   Ci.nsIPrefLocalizedString).data;
+      this.ellipsis = Services.prefs.getComplexValue("intl.ellipsis",
+                                                     Ci.nsIPrefLocalizedString).data;
     } catch (e) { }
 
     // Reset after "on-build-contextmenu" notification in case selection was
     // changed during the notification.
     this.isContentSelected = !this.selectionInfo.docSelectionIsCollapsed;
     this.onPlainTextLink = false;
 
     let bookmarkPage = document.getElementById("context-bookmarkpage");
@@ -428,17 +428,17 @@ nsContextMenu.prototype = {
                   this.onMathML && !this.isContentSelected);
 
     var shouldShow = !(this.isContentSelected ||
                        this.onImage || this.onCanvas ||
                        this.onVideo || this.onAudio ||
                        this.onLink || this.onTextInput);
 
     var showInspect = this.inTabBrowser &&
-                      gPrefService.getBoolPref("devtools.inspector.enabled", true);
+                      Services.prefs.getBoolPref("devtools.inspector.enabled", true);
 
     this.showItem("context-viewsource", shouldShow);
     this.showItem("context-viewinfo", shouldShow);
     // The page info is broken for WebExtension popups, as the browser is
     // destroyed when the popup is closed.
     this.setItemAttr("context-viewinfo", "disabled", this.webExtBrowserType === "popup");
     this.showItem("inspect-separator", showInspect);
     this.showItem("context-inspect", showInspect);
@@ -859,34 +859,39 @@ nsContextMenu.prototype = {
 
   reload(event) {
     BrowserReloadOrDuplicate(event);
   },
 
   // View Partial Source
   viewPartialSource(aContext) {
     let inWindow = !Services.prefs.getBoolPref("view_source.tab");
+    let {browser} = this;
     let openSelectionFn = inWindow ? null : function() {
       let tabBrowser = gBrowser;
       // In the case of popups, we need to find a non-popup browser window.
-      if (!tabBrowser || !window.toolbar.visible) {
+      // We might also not have a tabBrowser reference (if this isn't in a
+      // a tabbrowser scope) or might have a fake/stub tabbrowser reference
+      // (in the sidebar). Deal with those cases:
+      if (!tabBrowser || !tabBrowser.loadOneTab || !window.toolbar.visible) {
         // This returns only non-popup browser windows by default.
         let browserWindow = RecentWindow.getMostRecentBrowserWindow();
         tabBrowser = browserWindow.gBrowser;
       }
+      let relatedToCurrent = gBrowser && gBrowser.selectedBrowser == browser;
       let tab = tabBrowser.loadOneTab("about:blank", {
-        relatedToCurrent: true,
+        relatedToCurrent,
         inBackground: false,
         triggeringPrincipal: Services.scriptSecurityManager.getSystemPrincipal(),
       });
       return tabBrowser.getBrowserForTab(tab);
     };
 
     let target = aContext == "mathml" ? this.target : null;
-    top.gViewSourceUtils.viewPartialSourceInBrowser(gBrowser.selectedBrowser, target, openSelectionFn);
+    top.gViewSourceUtils.viewPartialSourceInBrowser(browser, target, openSelectionFn);
   },
 
   // Open new "view source" window with the frame's URL.
   viewFrameSource() {
     BrowserViewSourceOfDocument({
       browser: this.browser,
       URL: gContextMenuContentData.docLocation,
       outerWindowID: this.frameOuterWindowID,
@@ -1151,17 +1156,17 @@ nsContextMenu.prototype = {
                     loadingPrincipal: this.principal,
                     contentPolicyType: Ci.nsIContentPolicy.TYPE_SAVEAS_DOWNLOAD,
                     securityFlags: Ci.nsILoadInfo.SEC_ALLOW_CROSS_ORIGIN_DATA_INHERITS,
                   });
 
     if (linkDownload)
       channel.contentDispositionFilename = linkDownload;
     if (channel instanceof Ci.nsIPrivateBrowsingChannel) {
-      let docIsPrivate = PrivateBrowsingUtils.isBrowserPrivate(gBrowser.selectedBrowser);
+      let docIsPrivate = PrivateBrowsingUtils.isBrowserPrivate(this.browser);
       channel.setPrivate(docIsPrivate);
     }
     channel.notificationCallbacks = new callbacks();
 
     let flags = Ci.nsIChannel.LOAD_CALL_CONTENT_SNIFFERS;
 
     if (bypassCache)
       flags |= Ci.nsIRequest.LOAD_BYPASS_CACHE;
@@ -1174,17 +1179,17 @@ nsContextMenu.prototype = {
     if (channel instanceof Ci.nsIHttpChannel) {
       channel.referrer = docURI;
       if (channel instanceof Ci.nsIHttpChannelInternal)
         channel.forceAllowThirdPartyCookie = true;
     }
 
     // fallback to the old way if we don't see the headers quickly
     var timeToWait =
-      gPrefService.getIntPref("browser.download.saveLinkAsFilenameTimeout");
+      Services.prefs.getIntPref("browser.download.saveLinkAsFilenameTimeout");
     var timer = Cc["@mozilla.org/timer;1"].createInstance(Ci.nsITimer);
     timer.initWithCallback(new timerCallback(), timeToWait,
                            timer.TYPE_ONE_SHOT);
 
     // kick off the channel with our proxy object as the listener
     channel.asyncOpen2(new saveAsListener());
   },
 
@@ -1378,28 +1383,28 @@ nsContextMenu.prototype = {
     return false;
   },
 
   addDictionaries() {
     var uri = formatURL("browser.dictionaries.download.url", true);
 
     var locale = "-";
     try {
-      locale = gPrefService.getComplexValue("intl.accept_languages",
-                                            Ci.nsIPrefLocalizedString).data;
+      locale = Services.prefs.getComplexValue("intl.accept_languages",
+                                              Ci.nsIPrefLocalizedString).data;
     } catch (e) { }
 
     var version = "-";
     try {
       version = Services.appinfo.version;
     } catch (e) { }
 
     uri = uri.replace(/%LOCALE%/, escape(locale)).replace(/%VERSION%/, version);
 
-    var newWindowPref = gPrefService.getIntPref("browser.link.open_newwindow");
+    var newWindowPref = Services.prefs.getIntPref("browser.link.open_newwindow");
     var where = newWindowPref == 3 ? "tab" : "window";
 
     openUILinkIn(uri, where);
   },
 
   bookmarkThisPage: function CM_bookmarkThisPage() {
     window.top.PlacesCommandHook
               .bookmarkPage(this.browser, true)
--- a/browser/base/content/pageinfo/pageInfo.js
+++ b/browser/base/content/pageinfo/pageInfo.js
@@ -123,17 +123,16 @@ pageInfoTreeView.prototype = {
   isSeparator(index) { return false; },
   isSorted() { return this.sortcol > -1; },
   canDrop(index, orientation) { return false; },
   drop(row, orientation) { return false; },
   getParentIndex(index) { return 0; },
   hasNextSibling(index, after) { return false; },
   getLevel(index) { return 0; },
   getImageSrc(row, column) { },
-  getProgressMode(row, column) { },
   getCellValue(row, column) { },
   toggleOpenState(index) { },
   cycleHeader(col) { },
   selectionChanged() { },
   cycleCell(row, column) { },
   isEditable(row, column) { return false; },
   isSelectable(row, column) { return false; },
   performAction(action) { },
@@ -257,19 +256,16 @@ function getClipboardHelper() {
         return Components.classes["@mozilla.org/widget/clipboardhelper;1"].getService(Components.interfaces.nsIClipboardHelper);
     } catch (e) {
         // do nothing, later code will handle the error
         return null;
     }
 }
 const gClipboardHelper = getClipboardHelper();
 
-// Interface for image loading content
-const nsIImageLoadingContent = Components.interfaces.nsIImageLoadingContent;
-
 // namespaces, don't need all of these yet...
 const XLinkNS  = "http://www.w3.org/1999/xlink";
 const XULNS    = "http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul";
 const XMLNS    = "http://www.w3.org/XML/1998/namespace";
 const XHTMLNS  = "http://www.w3.org/1999/xhtml";
 const XHTML2NS = "http://www.w3.org/2002/06/xhtml2";
 
 const XHTMLNSre  = "^http\:\/\/www\.w3\.org\/1999\/xhtml$";
@@ -1011,17 +1007,17 @@ function formatNumber(number) {
   return (+number).toLocaleString(); // coerce number to a numeric value before calling toLocaleString()
 }
 
 function formatDate(datestr, unknown) {
   var date = new Date(datestr);
   if (!date.valueOf())
     return unknown;
 
-  const dateTimeFormatter = Services.intl.createDateTimeFormat(undefined, {
+  const dateTimeFormatter = new Services.intl.DateTimeFormat(undefined, {
     dateStyle: "long", timeStyle: "long"
   });
   return dateTimeFormatter.format(date);
 }
 
 function doCopy() {
   if (!gClipboardHelper)
     return;
--- a/browser/base/content/pageinfo/pageInfo.xul
+++ b/browser/base/content/pageinfo/pageInfo.xul
@@ -163,33 +163,33 @@
       </hbox>
     </vbox>
 
     <!-- Media information -->
     <vbox id="mediaPanel">
       <tree id="imagetree" onselect="onImageSelect();" contextmenu="picontext"
             ondragstart="onBeginLinkDrag(event,'image-address','image-alt')">
         <treecols>
-          <treecol sortSeparators="true" primary="true" persist="width" flex="10"
+          <treecol primary="true" persist="width" flex="10"
                         width="10" id="image-address" label="&mediaAddress;"
                         onclick="gImageView.onPageMediaSort('image-address');"/>
           <splitter class="tree-splitter"/>
-          <treecol sortSeparators="true" persist="hidden width" flex="2"
+          <treecol persist="hidden width" flex="2"
                         width="2"  id="image-type"    label="&mediaType;"
                         onclick="gImageView.onPageMediaSort('image-type');"/>
           <splitter class="tree-splitter"/>
-          <treecol sortSeparators="true" hidden="true" persist="hidden width" flex="2"
+          <treecol hidden="true" persist="hidden width" flex="2"
                         width="2"  id="image-size"  label="&mediaSize;" value="size"
                         onclick="gImageView.onPageMediaSort('image-size');"/>
           <splitter class="tree-splitter"/>
-          <treecol sortSeparators="true" hidden="true" persist="hidden width" flex="4"
+          <treecol hidden="true" persist="hidden width" flex="4"
                         width="4"  id="image-alt"    label="&mediaAltHeader;"
                         onclick="gImageView.onPageMediaSort('image-alt');"/>
           <splitter class="tree-splitter"/>
-          <treecol sortSeparators="true" hidden="true" persist="hidden width" flex="1"
+          <treecol hidden="true" persist="hidden width" flex="1"
                         width="1"  id="image-count"    label="&mediaCount;"
                         onclick="gImageView.onPageMediaSort('image-count');"/>
         </treecols>
         <treechildren id="imagetreechildren" flex="1"/>
       </tree>
       <splitter orient="vertical" id="mediaSplitter"/>
       <vbox flex="1" id="mediaPreviewBox" collapsed="true">
         <grid id="mediaGrid">
@@ -240,17 +240,17 @@
           <spacer id="imageSaveBoxSpacer" flex="1"/>
           <button label="&selectall.label;" accesskey="&selectall.accesskey;"
                   id="selectallbutton"
                   oncommand="doSelectAllMedia();"/>
           <button label="&mediaSaveAs;" accesskey="&mediaSaveAs.accesskey;"
                   icon="save" id="imagesaveasbutton"
                   oncommand="saveMedia();"/>
         </hbox>
-        <vbox id="imagecontainerbox" class="inset iframe" flex="1" pack="center">
+        <vbox id="imagecontainerbox" flex="1" pack="center">
           <hbox id="theimagecontainer" pack="center">
             <image id="thepreviewimage"/>
           </hbox>
           <hbox id="brokenimagecontainer" pack="center" collapsed="true">
             <image id="brokenimage" src="resource://gre-resources/broken-image.png"/>
           </hbox>
         </vbox>
       </vbox>
--- a/browser/base/content/pageinfo/security.js
+++ b/browser/base/content/pageinfo/security.js
@@ -4,16 +4,18 @@
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 Components.utils.import("resource://gre/modules/BrowserUtils.jsm");
 
 /* import-globals-from pageInfo.js */
 
 XPCOMUtils.defineLazyModuleGetter(this, "LoginHelper",
                                   "resource://gre/modules/LoginHelper.jsm");
+XPCOMUtils.defineLazyModuleGetter(this, "PluralForm",
+                                  "resource://gre/modules/PluralForm.jsm");
 
 var security = {
   init(uri, windowInfo) {
     this.uri = uri;
     this.windowInfo = windowInfo;
   },
 
   // Display the server certificate (static)
@@ -224,25 +226,22 @@ function securityOnLoad(uri, windowInfo)
   var noStr = pageInfoBundle.getString("no");
 
   setText("security-privacy-cookies-value",
           hostHasCookies(uri) ? yesStr : noStr);
   setText("security-privacy-passwords-value",
           realmHasPasswords(uri) ? yesStr : noStr);
 
   var visitCount = previousVisitCount(info.hostName);
-  if (visitCount > 1) {
-    setText("security-privacy-history-value",
-            pageInfoBundle.getFormattedString("securityNVisits", [visitCount.toLocaleString()]));
-  } else if (visitCount == 1) {
-    setText("security-privacy-history-value",
-            pageInfoBundle.getString("securityOneVisit"));
-  } else {
-    setText("security-privacy-history-value", noStr);
-  }
+
+  let visitCountStr = visitCount > 0
+    ? PluralForm.get(visitCount, pageInfoBundle.getString("securityVisitsNumber"))
+        .replace("#1", visitCount.toLocaleString())
+    : pageInfoBundle.getString("securityNoVisits");
+  setText("security-privacy-history-value", visitCountStr);
 
   /* Set the Technical Detail section messages */
   const pkiBundle = document.getElementById("pkiBundle");
   var hdr;
   var msg1;
   var msg2;
 
   if (info.isBroken) {
--- a/browser/base/content/sanitize.xul
+++ b/browser/base/content/sanitize.xul
@@ -1,64 +1,58 @@
 <?xml version="1.0"?>
 
 <!-- -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- -->
 <!-- This Source Code Form is subject to the terms of the Mozilla Public
    - License, v. 2.0. If a copy of the MPL was not distributed with this
    - file, You can obtain one at http://mozilla.org/MPL/2.0/. -->
 
 <?xml-stylesheet href="chrome://global/skin/"?>
+<?xml-stylesheet href="chrome://browser/skin/preferences/preferences.css"?>
 <?xml-stylesheet href="chrome://browser/skin/sanitizeDialog.css"?>
 
 
 <?xml-stylesheet href="chrome://browser/content/sanitizeDialog.css"?>
 
-<!DOCTYPE prefwindow [
+<!DOCTYPE dialog [
+  <!ENTITY % preferencesDTD SYSTEM "chrome://global/locale/preferences.dtd">
+  <!ENTITY % globalKeysDTD SYSTEM "chrome://global/locale/globalKeys.dtd">
   <!ENTITY % brandDTD SYSTEM "chrome://branding/locale/brand.dtd">
   <!ENTITY % sanitizeDTD SYSTEM "chrome://browser/locale/sanitize.dtd">
+  %preferencesDTD;
+  %globalKeysDTD;
   %brandDTD;
   %sanitizeDTD;
 ]>
 
-<prefwindow id="SanitizeDialog" type="child"
-            xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"
-            dlgbuttons="accept,cancel"
-            title="&sanitizeDialog2.title;"
-            noneverythingtitle="&sanitizeDialog2.title;"
-            style="width: &sanitizeDialog2.width;;"
-            ondialogaccept="return gSanitizePromptDialog.sanitize();">
+<dialog id="SanitizeDialog" class="prefwindow" type="child"
+        xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"
+        buttons="accept,cancel"
+        persist="lastSelected screenX screenY"
+        closebuttonlabel="&preferencesCloseButton.label;"
+        closebuttonaccesskey="&preferencesCloseButton.accesskey;"
+        role="dialog"
+        title="&sanitizeDialog2.title;"
+        noneverythingtitle="&sanitizeDialog2.title;"
+        style="width: &sanitizeDialog2.width;;"
+        onload="gSanitizePromptDialog.init();"
+        ondialogaccept="return gSanitizePromptDialog.sanitize();">
 
-  <prefpane id="SanitizeDialogPane" onpaneload="gSanitizePromptDialog.init();">
+  <vbox id="SanitizeDialogPane" class="prefpane">
     <stringbundle id="bundleBrowser"
                   src="chrome://browser/locale/browser.properties"/>
 
     <script type="application/javascript"
             src="chrome://browser/content/sanitize.js"/>
 
-
+    <script type="application/javascript"
+            src="chrome://global/content/preferencesBindings.js"/>
     <script type="application/javascript"
             src="chrome://browser/content/sanitizeDialog.js"/>
 
-    <preferences id="sanitizePreferences">
-      <preference id="privacy.cpd.history"               name="privacy.cpd.history"               type="bool"/>
-      <preference id="privacy.cpd.formdata"              name="privacy.cpd.formdata"              type="bool"/>
-      <preference id="privacy.cpd.downloads"             name="privacy.cpd.downloads"             type="bool" disabled="true"/>
-      <preference id="privacy.cpd.cookies"               name="privacy.cpd.cookies"               type="bool"/>
-      <preference id="privacy.cpd.cache"                 name="privacy.cpd.cache"                 type="bool"/>
-      <preference id="privacy.cpd.sessions"              name="privacy.cpd.sessions"              type="bool"/>
-      <preference id="privacy.cpd.offlineApps"           name="privacy.cpd.offlineApps"           type="bool"/>
-      <preference id="privacy.cpd.siteSettings"          name="privacy.cpd.siteSettings"          type="bool"/>
-    </preferences>
-    
-    <preferences id="nonItemPreferences">
-      <preference id="privacy.sanitize.timeSpan"
-                  name="privacy.sanitize.timeSpan"
-                  type="int"/>
-    </preferences>
-
     <hbox id="SanitizeDurationBox" align="center">
       <label value="&clearTimeDuration.label;"
              accesskey="&clearTimeDuration.accesskey;"
              control="sanitizeDurationChoice"
              id="sanitizeDurationLabel"/>
       <menulist id="sanitizeDurationChoice"
                 preference="privacy.sanitize.timeSpan"
                 onselect="gSanitizePromptDialog.selectByTimespan();"
@@ -139,10 +133,10 @@
       <listitem label="&itemSitePreferences.label;"
                 type="checkbox"
                 accesskey="&itemSitePreferences.accesskey;"
                 preference="privacy.cpd.siteSettings"
                 noduration="true"
                 onsyncfrompreference="return gSanitizePromptDialog.onReadGeneric();"/>
     </listbox>
 
-  </prefpane>
-</prefwindow>
+  </vbox>
+</dialog>
--- a/browser/base/content/sanitizeDialog.js
+++ b/browser/base/content/sanitizeDialog.js
@@ -1,40 +1,46 @@
 /* -*- 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/. */
 
+/* import-globals-from ../../../toolkit/content/preferencesBindings.js */
+
 var Cc = Components.classes;
 var Ci = Components.interfaces;
 var Cu = Components.utils;
 
 var {Sanitizer} = Cu.import("resource:///modules/Sanitizer.jsm", {});
 
+Preferences.addAll([
+  { id: "privacy.cpd.history", type: "bool" },
+  { id: "privacy.cpd.formdata", type: "bool" },
+  { id: "privacy.cpd.downloads", type: "bool", disabled: true },
+  { id: "privacy.cpd.cookies", type: "bool" },
+  { id: "privacy.cpd.cache", type: "bool" },
+  { id: "privacy.cpd.sessions", type: "bool" },
+  { id: "privacy.cpd.offlineApps", type: "bool" },
+  { id: "privacy.cpd.siteSettings", type: "bool" },
+  { id: "privacy.sanitize.timeSpan", type: "int" },
+]);
+
 var gSanitizePromptDialog = {
 
   get bundleBrowser() {
     if (!this._bundleBrowser)
       this._bundleBrowser = document.getElementById("bundleBrowser");
     return this._bundleBrowser;
   },
 
   get selectedTimespan() {
     var durList = document.getElementById("sanitizeDurationChoice");
     return parseInt(durList.value);
   },
 
-  get sanitizePreferences() {
-    if (!this._sanitizePreferences) {
-      this._sanitizePreferences =
-        document.getElementById("sanitizePreferences");
-    }
-    return this._sanitizePreferences;
-  },
-
   get warningBox() {
     return document.getElementById("sanitizeEverythingWarningBox");
   },
 
   init() {
     // This is used by selectByTimespan() to determine if the window has loaded.
     this._inited = true;
 
@@ -136,73 +142,72 @@ var gSanitizePromptDialog = {
     }
 
     var warningDesc = document.getElementById("sanitizeEverythingWarning");
     warningDesc.textContent =
       this.bundleBrowser.getString(warningStringID);
   },
 
   /**
+   * Return the boolean prefs that enable/disable clearing of various kinds
+   * of history.  The only pref this excludes is privacy.sanitize.timeSpan.
+   */
+  _getItemPrefs() {
+    return Preferences.getAll().filter(p => p.id !== "privacy.sanitize.timeSpan");
+  },
+
+  /**
    * Called when the value of a preference element is synced from the actual
    * pref.  Enables or disables the OK button appropriately.
    */
   onReadGeneric() {
-    var found = false;
-
-    // Find any other pref that's checked and enabled.
-    var i = 0;
-    while (!found && i < this.sanitizePreferences.childNodes.length) {
-      var preference = this.sanitizePreferences.childNodes[i];
-
-      found = !!preference.value &&
-              !preference.disabled;
-      i++;
-    }
+    // Find any other pref that's checked and enabled (except for
+    // privacy.sanitize.timeSpan, which doesn't affect the button's status).
+    var found = this._getItemPrefs().some(pref => !!pref.value && !pref.disabled);
 
     try {
       document.documentElement.getButton("accept").disabled = !found;
     } catch (e) { }
 
     // Update the warning prompt if needed
     this.prepareWarning(true);
 
     return undefined;
   },
 
   /**
    * Sanitizer.prototype.sanitize() requires the prefs to be up-to-date.
    * Because the type of this prefwindow is "child" -- and that's needed because
    * without it the dialog has no OK and Cancel buttons -- the prefs are not
-   * updated on dialogaccept on platforms that don't support instant-apply
-   * (i.e., Windows).  We must therefore manually set the prefs from their
-   * corresponding preference elements.
+   * updated on dialogaccept.  We must therefore manually set the prefs
+   * from their corresponding preference elements.
    */
   updatePrefs() {
     Sanitizer.prefs.setIntPref("timeSpan", this.selectedTimespan);
 
     // Keep the pref for the download history in sync with the history pref.
-    document.getElementById("privacy.cpd.downloads").value =
-      document.getElementById("privacy.cpd.history").value;
+    Preferences.get("privacy.cpd.downloads").value =
+      Preferences.get("privacy.cpd.history").value;
 
     // Now manually set the prefs from their corresponding preference
     // elements.
-    var prefs = this.sanitizePreferences.rootBranch;
-    for (let i = 0; i < this.sanitizePreferences.childNodes.length; ++i) {
-      var p = this.sanitizePreferences.childNodes[i];
-      prefs.setBoolPref(p.name, p.value);
+    var prefs = this._getItemPrefs();
+    for (let i = 0; i < prefs.length; ++i) {
+      var p = prefs[i];
+      Services.prefs.setBoolPref(p.name, p.value);
     }
   },
 
   /**
    * Check if all of the history items have been selected like the default status.
    */
   hasNonSelectedItems() {
     let checkboxes = document.querySelectorAll("#itemList > [preference]");
     for (let i = 0; i < checkboxes.length; ++i) {
-      let pref = document.getElementById(checkboxes[i].getAttribute("preference"));
+      let pref = Preferences.get(checkboxes[i].getAttribute("preference"));
       if (!pref.value)
         return true;
     }
     return false;
   },
 
   /**
    * Show the history items list.
--- a/browser/base/content/tab-content.js
+++ b/browser/base/content/tab-content.js
@@ -597,108 +597,16 @@ addEventListener("unload", () => {
 }, false);
 
 addMessageListener("Browser:AppTab", function(message) {
   if (docShell) {
     docShell.isAppTab = message.data.isAppTab;
   }
 });
 
-let PrerenderContentHandler = {
-  init() {
-    this._pending = [];
-    this._idMonotonic = 0;
-    this._initialized = true;
-    addMessageListener("Prerender:Canceled", this);
-    addMessageListener("Prerender:Swapped", this);
-  },
-
-  get initialized() {
-    return !!this._initialized;
-  },
-
-  receiveMessage(aMessage) {
-    switch (aMessage.name) {
-      case "Prerender:Canceled": {
-        for (let i = 0; i < this._pending.length; ++i) {
-          if (this._pending[i].id === aMessage.data.id) {
-            if (this._pending[i].failure) {
-              this._pending[i].failure.run();
-            }
-            // Remove the item from the array
-            this._pending.splice(i, 1);
-            break;
-          }
-        }
-        break;
-      }
-      case "Prerender:Swapped": {
-        for (let i = 0; i < this._pending.length; ++i) {
-          if (this._pending[i].id === aMessage.data.id) {
-            if (this._pending[i].success) {
-              this._pending[i].success.run();
-            }
-            // Remove the item from the array
-            this._pending.splice(i, 1);
-            break;
-          }
-        }
-        break;
-      }
-    }
-  },
-
-  startPrerenderingDocument(aHref, aReferrer, aTriggeringPrincipal) {
-    // XXX: Make this constant a pref
-    if (this._pending.length >= 2) {
-      return;
-    }
-
-    let id = ++this._idMonotonic;
-    sendAsyncMessage("Prerender:Request", {
-      href: aHref.spec,
-      referrer: aReferrer ? aReferrer.spec : null,
-      id,
-      triggeringPrincipal: Utils.serializePrincipal(aTriggeringPrincipal),
-    });
-
-    this._pending.push({
-      href: aHref,
-      referrer: aReferrer,
-      id,
-      success: null,
-      failure: null,
-    });
-  },
-
-  shouldSwitchToPrerenderedDocument(aHref, aReferrer, aSuccess, aFailure) {
-    // Check if we think there is a prerendering document pending for the given
-    // href and referrer. If we think there is one, we will send a message to
-    // the parent process asking it to do a swap, and hook up the success and
-    // failure listeners.
-    for (let i = 0; i < this._pending.length; ++i) {
-      let p = this._pending[i];
-      if (p.href.equals(aHref) && p.referrer.equals(aReferrer)) {
-        p.success = aSuccess;
-        p.failure = aFailure;
-        sendAsyncMessage("Prerender:Swap", {id: p.id});
-        return true;
-      }
-    }
-
-    return false;
-  }
-};
-
-if (Services.appinfo.processType == Services.appinfo.PROCESS_TYPE_CONTENT) {
-  // We only want to initialize the PrerenderContentHandler in the content
-  // process. Outside of the content process, this should be unused.
-  PrerenderContentHandler.init();
-}
-
 var WebBrowserChrome = {
   onBeforeLinkTraversal(originalTarget, linkURI, linkNode, isAppTab) {
     return BrowserUtils.onBeforeLinkTraversal(originalTarget, linkURI, linkNode, isAppTab);
   },
 
   // Check whether this URI should load in the current process
   shouldLoadURI(aDocShell, aURI, aReferrer, aHasPostData, aTriggeringPrincipal) {
     if (!E10SUtils.shouldLoadURI(aDocShell, aURI, aReferrer, aHasPostData)) {
@@ -712,30 +620,16 @@ var WebBrowserChrome = {
   shouldLoadURIInThisProcess(aURI) {
     return E10SUtils.shouldLoadURIInThisProcess(aURI);
   },
 
   // Try to reload the currently active or currently loading page in a new process.
   reloadInFreshProcess(aDocShell, aURI, aReferrer, aTriggeringPrincipal, aLoadFlags) {
     E10SUtils.redirectLoad(aDocShell, aURI, aReferrer, aTriggeringPrincipal, true, aLoadFlags);
     return true;
-  },
-
-  startPrerenderingDocument(aHref, aReferrer, aTriggeringPrincipal) {
-    if (PrerenderContentHandler.initialized) {
-      PrerenderContentHandler.startPrerenderingDocument(aHref, aReferrer, aTriggeringPrincipal);
-    }
-  },
-
-  shouldSwitchToPrerenderedDocument(aHref, aReferrer, aSuccess, aFailure) {
-    if (PrerenderContentHandler.initialized) {
-      return PrerenderContentHandler.shouldSwitchToPrerenderedDocument(
-        aHref, aReferrer, aSuccess, aFailure);
-    }
-    return false;
   }
 };
 
 if (Services.appinfo.processType == Services.appinfo.PROCESS_TYPE_CONTENT) {
   let tabchild = docShell.QueryInterface(Ci.nsIInterfaceRequestor)
                          .getInterface(Ci.nsITabChild);
   tabchild.webBrowserChrome = WebBrowserChrome;
 }
--- a/browser/base/content/tabbrowser.css
+++ b/browser/base/content/tabbrowser.css
@@ -5,20 +5,16 @@
 .tabbrowser-tabpanels {
   -moz-binding: url("chrome://browser/content/tabbrowser.xml#tabbrowser-tabpanels");
 }
 
 .tabbrowser-arrowscrollbox {
   -moz-binding: url("chrome://browser/content/tabbrowser.xml#tabbrowser-arrowscrollbox");
 }
 
-.tab-close-button {
-  -moz-binding: url("chrome://browser/content/tabbrowser.xml#tabbrowser-close-tab-button");
-}
-
 .tab-close-button[pinned],
 #tabbrowser-tabs[closebuttons="activetab"] > .tabbrowser-tab > .tab-stack > .tab-content > .tab-close-button:not([selected="true"]),
 .tab-icon-image:not([src]):not([pinned]):not([crashed])[selected],
 .tab-icon-image:not([src]):not([pinned]):not([crashed]):not([sharing]),
 .tab-icon-image[busy],
 .tab-throbber:not([busy]),
 .tab-throbber-fallback:not([busy]),
 .tab-icon-sound:not([soundplaying]):not([muted]):not([activemedia-blocked]),
--- a/browser/base/content/tabbrowser.xml
+++ b/browser/base/content/tabbrowser.xml
@@ -796,17 +796,26 @@
                       URLBarSetURI();
                     }
                   } else if (isSuccessful) {
                     this.mBrowser.urlbarChangeTracker.finishedLoad();
                   }
 
                   // Ignore initial about:blank to prevent flickering.
                   if (!this.mBrowser.mIconURL && !ignoreBlank) {
-                    this.mTabBrowser.useDefaultIcon(this.mTab);
+                    // Don't switch to the default icon on about:home or about:newtab,
+                    // since these pages get their favicon set in browser code to
+                    // improve perceived performance.
+                    let isNewTab = originalLocation &&
+                      (originalLocation.spec == "about:newtab" ||
+                       originalLocation.spec == "about:privatebrowsing" ||
+                       originalLocation.spec == "about:home");
+                    if (!isNewTab) {
+                      this.mTabBrowser.useDefaultIcon(this.mTab);
+                    }
                   }
                 }
 
                 // For keyword URIs clear the user typed value since they will be changed into real URIs
                 if (location.scheme == "keyword")
                   this.mBrowser.userTypedValue = null;
 
                 if (this.mTab.selected)
@@ -1560,16 +1569,27 @@
           }
           this._tabAttrModified(tab, ["sharing"]);
 
           if (aBrowser == this.mCurrentBrowser)
             gIdentityHandler.updateSharingIndicator();
         ]]></body>
       </method>
 
+      <method name="getTabSharingState">
+        <parameter name="aTab"/>
+        <body><![CDATA[
+          // Normalize the state object for consumers (ie.extensions).
+          let state = Object.assign({}, aTab._sharingState);
+          // ensure bool if undefined
+          state.camera = !!state.camera;
+          state.microphone = !!state.microphone;
+          return state;
+        ]]></body>
+      </method>
 
       <!-- TODO: remove after 57, once we know add-ons can no longer use it. -->
       <method name="setTabTitleLoading">
         <parameter name="aTab"/>
         <body/>
       </method>
 
       <method name="setInitialTabTitle">
@@ -1718,17 +1738,16 @@
             var aForceNotRemote;
             var aPreferredRemoteType;
             var aNoReferrer;
             var aUserContextId;
             var aSameProcessAsFrameLoader;
             var aOriginPrincipal;
             var aOpener;
             var aOpenerBrowser;
-            var aIsPrerendered;
             var aCreateLazyBrowser;
             var aNextTabParentId;
             var aFocusUrlBar;
             var aName;
             if (arguments.length == 2 &&
                 typeof arguments[1] == "object" &&
                 !(arguments[1] instanceof Ci.nsIURI)) {
               let params = arguments[1];
@@ -1746,17 +1765,16 @@
               aForceNotRemote           = params.forceNotRemote;
               aPreferredRemoteType      = params.preferredRemoteType;
               aNoReferrer               = params.noReferrer;
               aUserContextId            = params.userContextId;
               aSameProcessAsFrameLoader = params.sameProcessAsFrameLoader;
               aOriginPrincipal          = params.originPrincipal;
               aOpener                   = params.opener;
               aOpenerBrowser            = params.openerBrowser;
-              aIsPrerendered            = params.isPrerendered;
               aCreateLazyBrowser        = params.createLazyBrowser;
               aNextTabParentId          = params.nextTabParentId;
               aFocusUrlBar              = params.focusUrlBar;
               aName                     = params.name;
             }
 
             var bgLoad = (aLoadInBackground != null) ? aLoadInBackground :
                          Services.prefs.getBoolPref("browser.tabs.loadInBackground");
@@ -1778,17 +1796,16 @@
                                   createLazyBrowser: aCreateLazyBrowser,
                                   preferredRemoteType: aPreferredRemoteType,
                                   noReferrer: aNoReferrer,
                                   userContextId: aUserContextId,
                                   originPrincipal: aOriginPrincipal,
                                   sameProcessAsFrameLoader: aSameProcessAsFrameLoader,
                                   opener: aOpener,
                                   openerBrowser: aOpenerBrowser,
-                                  isPrerendered: aIsPrerendered,
                                   nextTabParentId: aNextTabParentId,
                                   focusUrlBar: aFocusUrlBar,
                                   name: aName });
             if (!bgLoad)
               this.selectedTab = tab;
 
             return tab;
          ]]>
@@ -2122,18 +2139,21 @@
             this._preloadedBrowser = null;
 
             // Attach the nsIFormFillController now that we know the browser
             // will be used. If we do that before and the preloaded browser
             // won't be consumed until shutdown then we leak a docShell.
             // Also, we do not need to take care of attaching nsIFormFillControllers
             // in the case that the browser is remote, as remote browsers take
             // care of that themselves.
-            if (browser && this.hasAttribute("autocompletepopup")) {
-              browser.setAttribute("autocompletepopup", this.getAttribute("autocompletepopup"));
+            if (browser) {
+              browser.setAttribute("preloadedState", "consumed");
+              if (this.hasAttribute("autocompletepopup")) {
+                browser.setAttribute("autocompletepopup", this.getAttribute("autocompletepopup"));
+              }
             }
 
             return browser;
           ]]>
         </body>
       </method>
 
       <method name="_isPreloadingEnabled">
@@ -2184,32 +2204,28 @@
       </method>
 
       <method name="_createBrowser">
         <parameter name="aParams"/>
         <body>
           <![CDATA[
             // Supported parameters:
             // userContextId, remote, remoteType, isPreloadBrowser,
-            // uriIsAboutBlank, sameProcessAsFrameLoader, isPrerendered
+            // uriIsAboutBlank, sameProcessAsFrameLoader
 
             const NS_XUL = "http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul";
 
             let b = document.createElementNS(NS_XUL, "browser");
             b.permanentKey = {};
             b.setAttribute("type", "content");
             b.setAttribute("message", "true");
             b.setAttribute("messagemanagergroup", "browsers");
             b.setAttribute("contextmenu", this.getAttribute("contentcontextmenu"));
             b.setAttribute("tooltip", this.getAttribute("contenttooltip"));
 
-            if (aParams.isPrerendered) {
-              b.setAttribute("prerendered", "true");
-            }
-
             if (aParams.userContextId) {
               b.setAttribute("usercontextid", aParams.userContextId);
             }
 
             // remote parameter used by some addons, use default in this case.
             if (aParams.remote && !aParams.remoteType) {
               aParams.remoteType = E10SUtils.DEFAULT_REMOTE_TYPE;
             }
@@ -2225,18 +2241,33 @@
               }
               b.presetOpenerWindow(aParams.openerWindow);
             }
 
             if (!aParams.isPreloadBrowser && this.hasAttribute("autocompletepopup")) {
               b.setAttribute("autocompletepopup", this.getAttribute("autocompletepopup"));
             }
 
+            /*
+             * This attribute is meant to describe if the browser is the
+             * preloaded browser. There are 2 defined states: "preloaded" or
+             * "consumed". The order of events goes as follows:
+             *   1. The preloaded browser is created and the 'preloadedState'
+             *      attribute for that browser is set to "preloaded".
+             *   2. When a new tab is opened and it is time to show that
+             *      preloaded browser, the 'preloadedState' attribute for that
+             *      browser is set to "consumed"
+             *   3. When we then navigate away from about:newtab, the "consumed"
+             *      browsers will attempt to switch to a new content process,
+             *      therefore the 'preloadedState' attribute is removed from
+             *      that browser altogether
+             * See more details on Bug 1420285.
+             */
             if (aParams.isPreloadBrowser) {
-              b.setAttribute("isPreloadBrowser", "true");
+              b.setAttribute("preloadedState", "preloaded");
             }
 
             if (this.hasAttribute("selectmenulist"))
               b.setAttribute("selectmenulist", this.getAttribute("selectmenulist"));
 
             if (this.hasAttribute("datetimepicker")) {
               b.setAttribute("datetimepicker", this.getAttribute("datetimepicker"));
             }
@@ -2573,17 +2604,16 @@
             var aNoReferrer;
             var aUserContextId;
             var aEventDetail;
             var aSameProcessAsFrameLoader;
             var aOriginPrincipal;
             var aDisallowInheritPrincipal;
             var aOpener;
             var aOpenerBrowser;
-            var aIsPrerendered;
             var aCreateLazyBrowser;
             var aSkipBackgroundNotify;
             var aNextTabParentId;
             var aNoInitialLabel;
             var aFocusUrlBar;
             var aName;
             if (arguments.length == 2 &&
                 typeof arguments[1] == "object" &&
@@ -2605,17 +2635,16 @@
               aNoReferrer               = params.noReferrer;
               aUserContextId            = params.userContextId;
               aEventDetail              = params.eventDetail;
               aSameProcessAsFrameLoader = params.sameProcessAsFrameLoader;
               aOriginPrincipal          = params.originPrincipal;
               aDisallowInheritPrincipal = params.disallowInheritPrincipal;
               aOpener                   = params.opener;
               aOpenerBrowser            = params.openerBrowser;
-              aIsPrerendered            = params.isPrerendered;
               aCreateLazyBrowser        = params.createLazyBrowser;
               aSkipBackgroundNotify     = params.skipBackgroundNotify;
               aNextTabParentId          = params.nextTabParentId;
               aNoInitialLabel           = params.noInitialLabel;
               aFocusUrlBar              = params.focusUrlBar;
               aName                     = params.name;
             }
 
@@ -2663,20 +2692,16 @@
               if (isBlankPageURL(aURI)) {
                 t.setAttribute("label", gTabBrowserBundle.GetStringFromName("tabs.emptyTabTitle"));
               } else {
                 // Set URL as label so that the tab isn't empty initially.
                 this.setInitialTabTitle(t, aURI, { beforeTabOpen: true });
               }
             }
 
-            if (aIsPrerendered) {
-              t.setAttribute("hidden", "true");
-            }
-
             // Related tab inherits current tab's user context unless a different
             // usercontextid is specified
             if (aUserContextId == null && openerTab) {
               aUserContextId = openerTab.getAttribute("usercontextid") || 0;
             }
 
             if (aUserContextId) {
               t.setAttribute("usercontextid", aUserContextId);
@@ -2763,17 +2788,16 @@
 
               if (!b) {
                 // No preloaded browser found, create one.
                 b = this._createBrowser({ remoteType,
                                           uriIsAboutBlank,
                                           userContextId: aUserContextId,
                                           sameProcessAsFrameLoader: aSameProcessAsFrameLoader,
                                           openerWindow: aOpener,
-                                          isPrerendered: aIsPrerendered,
                                           nextTabParentId: aNextTabParentId,
                                           name: aName });
               }
 
               t.linkedBrowser = b;
 
               if (aFocusUrlBar) {
                 b._urlbarFocused = true;
@@ -2808,18 +2832,20 @@
                 let notificationbox = this.getNotificationBox(t.linkedBrowser);
                 notificationbox.remove();
               }
               throw e;
             }
 
             // Hack to ensure that the about:newtab favicon is loaded
             // instantaneously, to avoid flickering and improve perceived performance.
-            if (aURI == BROWSER_NEW_TAB_URL) {
+            if (aURI == "about:newtab") {
               this.setIcon(t, "chrome://branding/content/icon32.png");
+            } else if (aURI == "about:privatebrowsing") {
+              this.setIcon(t, "chrome://browser/skin/privatebrowsing/favicon.svg");
             }
 
             // Dispatch a new tab notification.  We do this once we're
             // entirely done, so that things are in a consistent state
             // even if the event listener opens or closes tabs.
             var detail = aEventDetail || {};
             var evt = new CustomEvent("TabOpen", { bubbles: true, detail });
             t.dispatchEvent(evt);
@@ -2966,19 +2992,22 @@
         ]]>
       </body>
       </method>
 
       <method name="getTabsToTheEndFrom">
         <parameter name="aTab"/>
         <body>
           <![CDATA[
-            var tabsToEnd = [];
+            let tabsToEnd = [];
             let tabs = this.visibleTabs;
-            for (let i = tabs.length - 1; tabs[i] != aTab && i >= 0; --i) {
+            for (let i = tabs.length - 1; i >= 0; --i) {
+              if (tabs[i] == aTab || tabs[i].pinned) {
+                break;
+              }
               tabsToEnd.push(tabs[i]);
             }
             return tabsToEnd;
           ]]>
         </body>
       </method>
 
       <method name="removeTabsToTheEndFrom">
@@ -3010,19 +3039,19 @@
           ]]>
         </body>
       </method>
 
       <method name="removeAllTabsBut">
         <parameter name="aTab"/>
         <body>
           <![CDATA[
-            if (aTab.pinned ||
-                !this.warnAboutClosingTabs(this.closingTabsEnum.OTHER))
+            if (!this.warnAboutClosingTabs(this.closingTabsEnum.OTHER)) {
               return;
+            }
 
             let tabs = this.visibleTabs.reverse();
             this.selectedTab = aTab;
 
             let tabsWithBeforeUnload = [];
             for (let i = tabs.length - 1; i >= 0; --i) {
               let tab = tabs[i];
               if (tab != aTab && !tab.pinned) {
@@ -3414,55 +3443,64 @@
                                       true /* aCanceledOkay */);
 
             if (aCloseWindow)
               this._windowIsClosing = closeWindow(true, window.warnAboutClosingWindow);
           ]]>
         </body>
       </method>
 
-      <method name="_blurTab">
+      <method name="_findTabToBlurTo">
         <parameter name="aTab"/>
         <body>
           <![CDATA[
-            if (!aTab.selected)
-              return;
+            if (!aTab.selected) {
+              return null;
+            }
 
             if (aTab.owner &&
                 !aTab.owner.hidden &&
                 !aTab.owner.closing &&
                 Services.prefs.getBoolPref("browser.tabs.selectOwnerOnClose")) {
-              this.selectedTab = aTab.owner;
-              return;
+              return aTab.owner;
             }
 
             // Switch to a visible tab unless there aren't any others remaining
             let remainingTabs = this.visibleTabs;
             let numTabs = remainingTabs.length;
             if (numTabs == 0 || numTabs == 1 && remainingTabs[0] == aTab) {
               remainingTabs = Array.filter(this.tabs, function(tab) {
                 return !tab.closing;
               }, this);
             }
 
             // Try to find a remaining tab that comes after the given tab
-            var tab = aTab;
+            let tab = aTab;
             do {
               tab = tab.nextSibling;
             } while (tab && remainingTabs.indexOf(tab) == -1);
 
             if (!tab) {
               tab = aTab;
 
               do {
                 tab = tab.previousSibling;
               } while (tab && remainingTabs.indexOf(tab) == -1);
             }
 
-            this.selectedTab = tab;
+            return tab;
+          ]]>
+        </body>
+      </method>
+
+      <method name="_blurTab">
+        <parameter name="aTab"/>
+        <body>
+          <![CDATA[
+            this.selectedTab = this._findTabToBlurTo(aTab);
           ]]>
         </body>
       </method>
 
       <method name="swapBrowsersAndCloseOther">
         <parameter name="aOurTab"/>
         <parameter name="aOtherTab"/>
         <body>
@@ -3851,17 +3889,17 @@
         </body>
       </method>
 
       <method name="hideTab">
         <parameter name="aTab"/>
         <body>
         <![CDATA[
           if (!aTab.hidden && !aTab.pinned && !aTab.selected &&
-              !aTab.closing) {
+              !aTab.closing && !aTab._sharingState) {
             aTab.setAttribute("hidden", "true");
             this._visibleTabs = null; // invalidate cache
 
             this.tabContainer._updateCloseButtons();
 
             this.tabContainer._setPositionalAttributes();
 
             let event = document.createEvent("Events");
@@ -4358,18 +4396,30 @@
 
             clearTimer(timer) {
               timer.cancel();
             },
 
             getTabState(tab) {
               let state = this.tabState.get(tab);
               if (state === undefined) {
-                return this.STATE_UNLOADED;
-              }
+                state = this.STATE_UNLOADED;
+
+                if (tab && tab.linkedPanel) {
+                  let b = tab.linkedBrowser;
+                  if (b.renderLayers && b.hasLayers) {
+                    state = this.STATE_LOADED;
+                  } else if (b.renderLayers && !b.hasLayers) {
+                    state = this.STATE_LOADING;
+                  } else if (!b.renderLayers && b.hasLayers) {
+                    state = this.STATE_UNLOADING;
+                  }
+                }
+              }
+
               return state;
             },
 
             setTabStateNoAction(tab, state) {
               if (state == this.STATE_UNLOADED) {
                 this.tabState.delete(tab);
               } else {
                 this.tabState.set(tab, state);
@@ -4378,26 +4428,36 @@
 
             setTabState(tab, state) {
               this.setTabStateNoAction(tab, state);
 
               let browser = tab.linkedBrowser;
               let {tabParent} = browser.frameLoader;
               if (state == this.STATE_LOADING) {
                 this.assert(!this.minimizedOrFullyOccluded);
-                browser.docShellIsActive = true;
-                if (!tabParent) {
+
+                if (!this.tabbrowser.tabWarmingEnabled) {
+                  browser.docShellIsActive = true;
+                }
+
+                if (tabParent) {
+                  browser.renderLayers = true;
+                } else {
                   this.onLayersReady(browser);
                 }
               } else if (state == this.STATE_UNLOADING) {
                 this.unwarmTab(tab);
+                // Setting the docShell to be inactive will also cause it
+                // to stop rendering layers.
                 browser.docShellIsActive = false;
                 if (!tabParent) {
                   this.onLayersCleared(browser);
                 }
+              } else if (state == this.STATE_LOADED) {
+                this.maybeActivateDocShell(tab);
               }
 
               if (!tab.linkedBrowser.isRemoteBrowser) {
                 // setTabState is potentially re-entrant in the non-remote case,
                 // so we must re-get the state for this assertion.
                 let nonRemoteState = this.getTabState(tab);
                 // Non-remote tabs can never stay in the STATE_LOADING
                 // or STATE_UNLOADING states. By the time this function
@@ -4412,39 +4472,47 @@
             get minimizedOrFullyOccluded() {
               return window.windowState == window.STATE_MINIMIZED ||
                      window.isFullyOccluded;
             },
 
             init() {
               this.log("START");
 
-              // If we minimized the window before the switcher was activated,
-              // we might have set  the preserveLayers flag for the current
-              // browser. Let's clear it.
-              this.tabbrowser.mCurrentBrowser.preserveLayers(false);
-
               window.addEventListener("MozAfterPaint", this);
               window.addEventListener("MozLayerTreeReady", this);
               window.addEventListener("MozLayerTreeCleared", this);
               window.addEventListener("TabRemotenessChange", this);
               window.addEventListener("sizemodechange", this);
               window.addEventListener("occlusionstatechange", this);
               window.addEventListener("SwapDocShells", this, true);
               window.addEventListener("EndSwapDocShells", this, true);
 
-              let tab = this.requestedTab;
-              let browser = tab.linkedBrowser;
-              let tabIsLoaded = !browser.isRemoteBrowser ||
-                                browser.frameLoader.tabParent.hasPresented;
+              let initialTab = this.requestedTab;
+              let initialBrowser = initialTab.lin